diff --git a/Gulpfile.ts b/Gulpfile.ts index 41227d2d76e..757cd4fed08 100644 --- a/Gulpfile.ts +++ b/Gulpfile.ts @@ -28,7 +28,6 @@ import minimist = require("minimist"); import browserify = require("browserify"); import through2 = require("through2"); import merge2 = require("merge2"); -import intoStream = require("into-stream"); import * as os from "os"; import fold = require("travis-fold"); const gulp = helpMaker(originalGulp); @@ -294,7 +293,7 @@ gulp.task("configure-nightly", "Runs scripts/configureNightly.ts to prepare a bu exec(host, [configureNightlyJs, packageJson, versionFile], done, done); }); gulp.task("publish-nightly", "Runs `npm publish --tag next` to create a new nightly build on npm", ["LKG"], () => { - return runSequence("clean", "useDebugMode", "runtests", (done) => { + return runSequence("clean", "useDebugMode", "runtests-parallel", (done) => { exec("npm", ["publish", "--tag", "next"], done, done); }); }); @@ -737,50 +736,75 @@ gulp.task(nodeServerOutFile, /*help*/ false, [servicesFile], () => { import convertMap = require("convert-source-map"); import sorcery = require("sorcery"); -declare module "convert-source-map" { - export function fromSource(source: string, largeSource?: boolean): SourceMapConverter; -} +import Vinyl = require("vinyl"); -gulp.task("browserify", "Runs browserify on run.js to produce a file suitable for running tests in the browser", [servicesFile, run], (done) => { - const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({ outFile: "../../built/local/bundle.js" }, /*useBuiltCompiler*/ true)); - return testProject.src() - .pipe(newer("built/local/bundle.js")) +const bundlePath = path.resolve("built/local/bundle.js"); + +gulp.task("browserify", "Runs browserify on run.js to produce a file suitable for running tests in the browser", [servicesFile], (done) => { + const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({ outFile: bundlePath, inlineSourceMap: true }, /*useBuiltCompiler*/ true)); + let originalMap: any; + let prebundledContent: string; + browserify(testProject.src() + .pipe(newer(bundlePath)) .pipe(sourcemaps.init()) .pipe(testProject()) .pipe(through2.obj((file, enc, next) => { - const originalMap = file.sourceMap; - const prebundledContent = file.contents.toString(); + if (originalMap) { + throw new Error("Should only recieve one file!"); + } + console.log(`Saving sourcemaps for ${file.path}`); + originalMap = file.sourceMap; + prebundledContent = file.contents.toString(); // Make paths absolute to help sorcery deal with all the terrible paths being thrown around originalMap.sources = originalMap.sources.map(s => path.resolve(path.join("src/harness", s))); - // intoStream (below) makes browserify think the input file is named this, so this is what it puts in the sourcemap + // browserify names input files this when they are streamed in, so this is what it puts in the sourcemap originalMap.file = "built/local/_stream_0.js"; - browserify(intoStream(file.contents), { debug: true }) - .bundle((err, res) => { - // assumes file.contents is a Buffer - const maps = JSON.parse(convertMap.fromSource(res.toString(), /*largeSource*/ true).toJSON()); - delete maps.sourceRoot; - maps.sources = maps.sources.map(s => path.resolve(s === "_stream_0.js" ? "built/local/_stream_0.js" : s)); - // Strip browserify's inline comments away (could probably just let sorcery do this, but then we couldn't fix the paths) - file.contents = new Buffer(convertMap.removeComments(res.toString())); - const chain = sorcery.loadSync("built/local/bundle.js", { - content: { - "built/local/_stream_0.js": prebundledContent, - "built/local/bundle.js": file.contents.toString() - }, - sourcemaps: { - "built/local/_stream_0.js": originalMap, - "built/local/bundle.js": maps, - "node_modules/source-map-support/source-map-support.js": undefined, - } - }); - const finalMap = chain.apply(); - file.sourceMap = finalMap; - next(/*err*/ undefined, file); - }); + next(/*err*/ undefined, file.contents); })) - .pipe(sourcemaps.write(".", { includeContent: false })) - .pipe(gulp.dest("src/harness")); + .on("error", err => { + return done(err); + }), { debug: true, basedir: __dirname }) // Attach error handler to inner stream + .bundle((err, contents) => { + if (err) { + if (err.message.match(/Cannot find module '.*_stream_0.js'/)) { + return done(); // Browserify errors when we pass in no files when `newer` filters the input, we should count that as a success, though + } + return done(err); + } + const stringContent = contents.toString(); + const file = new Vinyl({ contents, path: bundlePath }); + console.log(`Fixing sourcemaps for ${file.path}`); + // assumes contents is a Buffer, since that's what browserify yields + const maps = convertMap.fromSource(stringContent, /*largeSource*/ true).toObject(); + delete maps.sourceRoot; + maps.sources = maps.sources.map(s => path.resolve(s === "_stream_0.js" ? "built/local/_stream_0.js" : s)); + // Strip browserify's inline comments away (could probably just let sorcery do this, but then we couldn't fix the paths) + file.contents = new Buffer(convertMap.removeComments(stringContent)); + const chain = sorcery.loadSync(bundlePath, { + content: { + "built/local/_stream_0.js": prebundledContent, + [bundlePath]: stringContent + }, + sourcemaps: { + "built/local/_stream_0.js": originalMap, + [bundlePath]: maps, + "node_modules/source-map-support/source-map-support.js": undefined, + } + }); + const finalMap = chain.apply(); + file.sourceMap = finalMap; + + const stream = through2.obj((file, enc, callback) => { + return callback(/*err*/ undefined, file); + }); + stream.pipe(sourcemaps.write(".", { includeContent: false })) + .pipe(gulp.dest(".")) + .on("end", done) + .on("error", done); + stream.write(file); + stream.end(); + }); }); diff --git a/Jakefile.js b/Jakefile.js index 58779a3d8dc..31243f77c42 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -505,7 +505,7 @@ task("configure-nightly", [configureNightlyJs], function () { }, { async: true }); desc("Configure, build, test, and publish the nightly release."); -task("publish-nightly", ["configure-nightly", "LKG", "clean", "setDebugMode", "runtests"], function () { +task("publish-nightly", ["configure-nightly", "LKG", "clean", "setDebugMode", "runtests-parallel"], function () { var cmd = "npm publish --tag next"; console.log(cmd); exec(cmd); @@ -840,7 +840,8 @@ function runConsoleTests(defaultReporter, runInParallel) { testTimeout = 800000; } - var colors = process.env.colors || process.env.color || true; + var colorsFlag = process.env.color || process.env.colors; + var colors = colorsFlag !== "false" && colorsFlag !== "0"; var reporter = process.env.reporter || process.env.r || defaultReporter; var bail = process.env.bail || process.env.b; var lintFlag = process.env.lint !== 'false'; diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index ec9453bb00c..0e37b0689e0 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -69,5 +69,3 @@ function createCancellationToken(args) { } } module.exports = createCancellationToken; - -//# sourceMappingURL=cancellationToken.js.map diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 9848b920637..1a8b1d72833 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -87,8 +87,8 @@ interface PropertyDescriptor { enumerable?: boolean; value?: any; writable?: boolean; - get? (): any; - set? (v: any): void; + get?(): any; + set?(v: any): void; } interface PropertyDescriptorMap { @@ -128,7 +128,7 @@ interface Object { } interface ObjectConstructor { - new (value?: any): Object; + new(value?: any): Object; (): any; (value: any): any; @@ -286,7 +286,7 @@ interface FunctionConstructor { * Creates a new function. * @param args A list of arguments the function accepts. */ - new (...args: string[]): Function; + new(...args: string[]): Function; (...args: string[]): Function; readonly prototype: Function; } @@ -423,7 +423,7 @@ interface String { } interface StringConstructor { - new (value?: any): String; + new(value?: any): String; (value?: any): string; readonly prototype: String; fromCharCode(...codes: number[]): string; @@ -440,7 +440,7 @@ interface Boolean { } interface BooleanConstructor { - new (value?: any): Boolean; + new(value?: any): Boolean; (value?: any): boolean; readonly prototype: Boolean; } @@ -477,7 +477,7 @@ interface Number { } interface NumberConstructor { - new (value?: any): Number; + new(value?: any): Number; (value?: any): number; readonly prototype: Number; @@ -779,10 +779,10 @@ interface Date { } interface DateConstructor { - new (): Date; - new (value: number): Date; - new (value: string): Date; - new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + new(): Date; + new(value: number): Date; + new(value: string): Date; + new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; /** @@ -848,8 +848,8 @@ interface RegExp { } interface RegExpConstructor { - new (pattern: RegExp | string): RegExp; - new (pattern: string, flags?: string): RegExp; + new(pattern: RegExp | string): RegExp; + new(pattern: string, flags?: string): RegExp; (pattern: RegExp | string): RegExp; (pattern: string, flags?: string): RegExp; readonly prototype: RegExp; @@ -876,7 +876,7 @@ interface Error { } interface ErrorConstructor { - new (message?: string): Error; + new(message?: string): Error; (message?: string): Error; readonly prototype: Error; } @@ -887,7 +887,7 @@ interface EvalError extends Error { } interface EvalErrorConstructor { - new (message?: string): EvalError; + new(message?: string): EvalError; (message?: string): EvalError; readonly prototype: EvalError; } @@ -898,7 +898,7 @@ interface RangeError extends Error { } interface RangeErrorConstructor { - new (message?: string): RangeError; + new(message?: string): RangeError; (message?: string): RangeError; readonly prototype: RangeError; } @@ -909,7 +909,7 @@ interface ReferenceError extends Error { } interface ReferenceErrorConstructor { - new (message?: string): ReferenceError; + new(message?: string): ReferenceError; (message?: string): ReferenceError; readonly prototype: ReferenceError; } @@ -920,7 +920,7 @@ interface SyntaxError extends Error { } interface SyntaxErrorConstructor { - new (message?: string): SyntaxError; + new(message?: string): SyntaxError; (message?: string): SyntaxError; readonly prototype: SyntaxError; } @@ -931,7 +931,7 @@ interface TypeError extends Error { } interface TypeErrorConstructor { - new (message?: string): TypeError; + new(message?: string): TypeError; (message?: string): TypeError; readonly prototype: TypeError; } @@ -942,7 +942,7 @@ interface URIError extends Error { } interface URIErrorConstructor { - new (message?: string): URIError; + new(message?: string): URIError; (message?: string): URIError; readonly prototype: URIError; } @@ -992,12 +992,10 @@ interface ReadonlyArray { * Returns a string representation of an array. */ toString(): string; - toLocaleString(): string; /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. + * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. */ - concat>(...items: U[]): T[]; + toLocaleString(): string; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. @@ -1025,7 +1023,6 @@ interface ReadonlyArray { * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; - /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. @@ -1037,49 +1034,37 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean): boolean; - every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean): boolean; - some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => void): void; - forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => void, thisArg: Z): void; + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => U): U[]; - map(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => U, thisArg: undefined): U[]; - map(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => U, thisArg: Z): U[]; + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => value is S): S[]; - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => value is S, thisArg: undefined): S[]; - filter(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => value is S, thisArg: Z): S[]; + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => any): T[]; - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => any, thisArg: undefined): T[]; - filter(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => any, thisArg: Z): T[]; + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1117,6 +1102,9 @@ interface Array { * Returns a string representation of an array. */ toString(): string; + /** + * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. + */ toLocaleString(): string; /** * Appends new elements to an array, and returns the new length of the array. @@ -1196,73 +1184,37 @@ interface Array { * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean; - every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean; - some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void): void; - forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: T, index: number, array: T[]) => void, thisArg: Z): void; + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - map(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U, U]; - map(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U, U]; - map(this: [T, T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U, U]; + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U]; - map(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U]; - map(this: [T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U]; - map(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U]; - map(this: [T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U]; - map(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U]; - map(this: [T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (this: void, value: T, index: number, array: T[]) => U): U[]; - map(callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): U[]; - map(callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): U[]; + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any): T[]; - filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any, thisArg: undefined): T[]; - filter(callbackfn: (this: Z, value: T, index: number, array: T[]) => any, thisArg: Z): T[]; + filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1292,7 +1244,7 @@ interface Array { } interface ArrayConstructor { - new (arrayLength?: number): any[]; + new(arrayLength?: number): any[]; new (arrayLength: number): T[]; new (...items: T[]): T[]; (arrayLength?: number): any[]; @@ -1416,7 +1368,7 @@ type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; - new (byteLength: number): ArrayBuffer; + new(byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } declare const ArrayBuffer: ArrayBufferConstructor; @@ -1567,7 +1519,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; + new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1615,9 +1567,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -1636,9 +1586,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any): Int8Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any, thisArg: undefined): Int8Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => any, thisArg: Z): Int8Array; + filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -1649,9 +1597,7 @@ interface Int8Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1662,9 +1608,7 @@ interface Int8Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1673,9 +1617,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -1713,9 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number): Int8Array; - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg: undefined): Int8Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => number, thisArg: Z): Int8Array; + map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1792,9 +1732,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -1825,9 +1763,9 @@ interface Int8Array { } interface Int8ArrayConstructor { readonly prototype: Int8Array; - new (length: number): Int8Array; - new (array: ArrayLike): Int8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new(length: number): Int8Array; + new(array: ArrayLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1846,11 +1784,8 @@ interface Int8ArrayConstructor { * @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: number, k: number) => number): Int8Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; - from(arrayLike: ArrayLike): Int8Array; } declare const Int8Array: Int8ArrayConstructor; @@ -1899,9 +1834,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -1920,9 +1853,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any): Uint8Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any, thisArg: undefined): Uint8Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => any, thisArg: Z): Uint8Array; + filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -1933,9 +1864,7 @@ interface Uint8Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1946,9 +1875,7 @@ interface Uint8Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1957,9 +1884,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -1997,9 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number): Uint8Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg: undefined): Uint8Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => number, thisArg: Z): Uint8Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2076,9 +1999,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2110,9 +2031,9 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new(length: number): Uint8Array; + new(array: ArrayLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2131,11 +2052,7 @@ interface Uint8ArrayConstructor { * @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: number, k: number) => number): Uint8Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: ArrayLike): Uint8Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } declare const Uint8Array: Uint8ArrayConstructor; @@ -2184,9 +2101,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2205,9 +2120,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any): Uint8ClampedArray; - filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: undefined): Uint8ClampedArray; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: Z): Uint8ClampedArray; + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2218,9 +2131,7 @@ interface Uint8ClampedArray { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2231,9 +2142,7 @@ interface Uint8ClampedArray { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2242,9 +2151,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2282,9 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number): Uint8ClampedArray; - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: undefined): Uint8ClampedArray; - map(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: Z): Uint8ClampedArray; + map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2361,9 +2266,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2395,9 +2298,9 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; - new (length: number): Uint8ClampedArray; - new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new(length: number): Uint8ClampedArray; + new(array: ArrayLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2416,11 +2319,7 @@ interface Uint8ClampedArrayConstructor { * @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: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: ArrayLike): Uint8ClampedArray; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; @@ -2468,9 +2367,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2489,9 +2386,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any): Int16Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg: undefined): Int16Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => any, thisArg: Z): Int16Array; + filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2502,9 +2397,7 @@ interface Int16Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2515,9 +2408,7 @@ interface Int16Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2526,10 +2417,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => void, thisArg: Z): void; - + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -2566,9 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number): Int16Array; - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg: undefined): Int16Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => number, thisArg: Z): Int16Array; + map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2645,9 +2531,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2679,9 +2563,9 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; - new (length: number): Int16Array; - new (array: ArrayLike): Int16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new(length: number): Int16Array; + new(array: ArrayLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2700,11 +2584,8 @@ interface Int16ArrayConstructor { * @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: number, k: number) => number): Int16Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; - from(arrayLike: ArrayLike): Int16Array; } declare const Int16Array: Int16ArrayConstructor; @@ -2753,9 +2634,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2774,9 +2653,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any): Uint16Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any, thisArg: undefined): Uint16Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => any, thisArg: Z): Uint16Array; + filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2787,9 +2664,7 @@ interface Uint16Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2800,9 +2675,7 @@ interface Uint16Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2811,9 +2684,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2851,9 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number): Uint16Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg: undefined): Uint16Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => number, thisArg: Z): Uint16Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2930,9 +2799,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2964,9 +2831,9 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new(length: number): Uint16Array; + new(array: ArrayLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2985,11 +2852,8 @@ interface Uint16ArrayConstructor { * @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: number, k: number) => number): Uint16Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; - from(arrayLike: ArrayLike): Uint16Array; } declare const Uint16Array: Uint16ArrayConstructor; @@ -3037,9 +2901,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3058,9 +2920,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any): Int32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any, thisArg: undefined): Int32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => any, thisArg: Z): Int32Array; + filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3071,9 +2931,7 @@ interface Int32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3084,9 +2942,7 @@ interface Int32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3095,9 +2951,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3135,9 +2989,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number): Int32Array; - map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number, thisArg: undefined): Int32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => number, thisArg: Z): Int32Array; + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3214,9 +3066,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3248,9 +3098,9 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; - new (length: number): Int32Array; - new (array: ArrayLike): Int32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new(length: number): Int32Array; + new(array: ArrayLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3269,11 +3119,8 @@ interface Int32ArrayConstructor { * @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: number, k: number) => number): Int32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; - from(arrayLike: ArrayLike): Int32Array; } declare const Int32Array: Int32ArrayConstructor; @@ -3321,9 +3168,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3342,9 +3187,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any): Uint32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any, thisArg: undefined): Uint32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => any, thisArg: Z): Uint32Array; + filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3355,9 +3198,7 @@ interface Uint32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3368,9 +3209,7 @@ interface Uint32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3379,10 +3218,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => void, thisArg: Z): void; - + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -3419,9 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number): Uint32Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg: undefined): Uint32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => number, thisArg: Z): Uint32Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3498,9 +3332,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3532,9 +3364,9 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new(length: number): Uint32Array; + new(array: ArrayLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3553,11 +3385,8 @@ interface Uint32ArrayConstructor { * @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: number, k: number) => number): Uint32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; - from(arrayLike: ArrayLike): Uint32Array; } declare const Uint32Array: Uint32ArrayConstructor; @@ -3605,9 +3434,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3626,9 +3453,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any): Float32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any, thisArg: undefined): Float32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => any, thisArg: Z): Float32Array; + filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3639,9 +3464,7 @@ interface Float32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3652,9 +3475,7 @@ interface Float32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3663,9 +3484,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3703,9 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number): Float32Array; - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg: undefined): Float32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => number, thisArg: Z): Float32Array; + map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3782,9 +3599,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3816,9 +3631,9 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; - new (length: number): Float32Array; - new (array: ArrayLike): Float32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new(length: number): Float32Array; + new(array: ArrayLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3837,11 +3652,8 @@ interface Float32ArrayConstructor { * @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: number, k: number) => number): Float32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; - from(arrayLike: ArrayLike): Float32Array; } declare const Float32Array: Float32ArrayConstructor; @@ -3890,9 +3702,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3911,9 +3721,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any): Float64Array; - filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any, thisArg: undefined): Float64Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => any, thisArg: Z): Float64Array; + filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3924,9 +3732,7 @@ interface Float64Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3937,9 +3743,7 @@ interface Float64Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3948,9 +3752,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3988,9 +3790,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number): Float64Array; - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg: undefined): Float64Array; - map(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => number, thisArg: Z): Float64Array; + map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -4067,9 +3867,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -4101,9 +3899,9 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; - new (length: number): Float64Array; - new (array: ArrayLike): Float64Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new(length: number): Float64Array; + new(array: ArrayLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4122,11 +3920,8 @@ interface Float64ArrayConstructor { * @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: number, k: number) => number): Float64Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; - from(arrayLike: ArrayLike): Float64Array; } declare const Float64Array: Float64ArrayConstructor; @@ -4159,7 +3954,7 @@ declare namespace Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new (locales?: string | string[], options?: CollatorOptions): Collator; + new(locales?: string | string[], options?: CollatorOptions): Collator; (locales?: string | string[], options?: CollatorOptions): Collator; supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; }; @@ -4196,7 +3991,7 @@ declare namespace Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; }; @@ -4239,7 +4034,7 @@ declare namespace Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; }; @@ -4289,15 +4084,15 @@ interface Date { ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -4310,32 +4105,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 { @@ -4375,13 +4170,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -4395,15 +4183,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 { @@ -4412,17 +4200,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 { @@ -4432,9 +4227,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -4447,6 +4241,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -4459,17 +4254,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 { @@ -4496,11 +4291,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -4525,39 +4320,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; @@ -4569,31 +4478,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 { @@ -4611,8 +4525,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -4622,12 +4536,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 { @@ -4635,35 +4549,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 { @@ -4673,28 +4587,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; } @@ -4712,13 +4626,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -4726,241 +4640,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 { @@ -4969,39 +4764,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; @@ -5011,9 +4806,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -5022,14 +4817,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 { @@ -5038,8 +4833,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -5049,38 +4844,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 { @@ -5088,15 +4908,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 { @@ -5111,19 +4931,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 { @@ -5133,285 +4953,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 { @@ -5423,13 +5218,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 { @@ -5438,11 +5233,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 { @@ -5450,10 +5245,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -5472,19 +5267,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; @@ -5500,8 +5282,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; @@ -5511,7 +5306,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -5556,7 +5351,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -5569,7 +5364,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -5584,7 +5379,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -5607,7 +5402,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -5653,7 +5448,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -5662,7 +5457,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -5675,7 +5470,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -5694,7 +5489,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -5710,7 +5505,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -5721,7 +5516,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -5735,7 +5530,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -5758,7 +5553,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -5767,7 +5562,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -5776,13 +5571,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; } @@ -5790,7 +5585,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -5803,16 +5598,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; } @@ -5825,7 +5909,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -5834,7 +5918,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -5845,7 +5929,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -5856,7 +5940,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -5866,7 +5950,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -5879,7 +5963,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -5888,7 +5972,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -5898,7 +5982,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -5910,7 +5994,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -5920,8 +6004,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; @@ -5937,8 +6021,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; @@ -5946,7 +6030,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -5957,13 +6041,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; @@ -6039,9 +6123,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; @@ -6111,24 +6195,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; @@ -6264,9 +6348,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; @@ -6318,7 +6402,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -6329,7 +6413,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -6355,7 +6439,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -6363,296 +6447,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; @@ -6662,150 +6457,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; @@ -6816,7 +6468,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -6833,7 +6485,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -6846,7 +6498,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -6860,7 +6512,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -6873,7 +6525,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -6882,7 +6534,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -6893,7 +6545,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -6902,7 +6554,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -6915,7 +6567,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -6928,7 +6580,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -6939,7 +6591,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -7034,299 +6686,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; @@ -7346,146 +6990,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; @@ -7494,243 +7146,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; @@ -7739,7 +7391,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; @@ -7748,7 +7400,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -7762,8 +7414,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; @@ -7772,8 +7567,8 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; - new(): DragEvent; -} + new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -7787,27 +7582,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; @@ -7888,9 +7663,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]; @@ -7908,18 +7683,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; @@ -7930,9 +7705,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; @@ -7941,7 +7716,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -7955,12 +7730,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; @@ -7987,7 +7762,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; @@ -7998,8 +7773,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; @@ -8013,7 +7808,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -8021,7 +7816,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -8032,7 +7827,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; @@ -8043,7 +7838,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -8058,7 +7853,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -8068,7 +7863,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -8082,7 +7877,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; @@ -8096,7 +7891,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -8105,7 +7900,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -8120,7 +7915,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -8130,7 +7925,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -8139,7 +7934,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -8150,8 +7945,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; @@ -8162,87 +7997,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; @@ -8251,70 +8086,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; @@ -8325,66 +8160,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; @@ -8393,7 +8228,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -8401,7 +8236,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; @@ -8411,30 +8246,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; @@ -8443,16 +8264,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; @@ -8461,7 +8282,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -8520,71 +8341,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; @@ -8593,32 +8428,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; @@ -8628,42 +8463,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; @@ -8674,7 +8498,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -8685,7 +8509,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -8696,16 +8520,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; @@ -8714,8 +8538,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; @@ -8724,7 +8559,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -8897,54 +8732,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; @@ -8953,39 +8788,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; @@ -8994,12 +8829,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; @@ -9008,7 +8843,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -9017,74 +8852,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; @@ -9094,7 +8929,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -9102,68 +8937,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; @@ -9172,7 +9007,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -9199,33 +9034,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; @@ -9241,8 +9076,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; @@ -9251,29 +9086,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; @@ -9284,12 +9097,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; @@ -9298,12 +9111,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; @@ -9312,7 +9147,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -9320,79 +9155,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; @@ -9401,86 +9236,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; @@ -9492,210 +9327,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; @@ -9704,31 +9539,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; @@ -9737,16 +9557,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; @@ -9755,41 +9575,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; @@ -9800,16 +9635,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; @@ -9818,7 +9653,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -9850,7 +9685,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -9859,162 +9694,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; @@ -10041,7 +9876,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -10053,32 +9888,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; @@ -10087,7 +9922,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -10103,16 +9938,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; @@ -10121,13 +9956,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; @@ -10137,154 +10089,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; @@ -10293,37 +10128,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; @@ -10332,7 +10167,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -10344,7 +10179,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -10366,12 +10201,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; @@ -10381,24 +10216,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; @@ -10407,7 +10242,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; @@ -10417,12 +10252,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; @@ -10431,24 +10266,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; @@ -10457,12 +10292,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; @@ -10471,38 +10306,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; @@ -10512,94 +10347,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; @@ -10609,18 +10444,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; /** @@ -10634,7 +10469,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; @@ -10644,17 +10479,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; @@ -10663,16 +10498,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; @@ -10681,53 +10516,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; @@ -10736,20 +10571,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; @@ -10758,7 +10593,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; @@ -10768,111 +10603,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; @@ -10881,12 +10716,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; @@ -10895,39 +10730,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; @@ -10936,26 +10771,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; @@ -10964,7 +10799,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -10975,105 +10810,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; @@ -11082,7 +10917,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -11093,12 +10928,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; @@ -11107,7 +10942,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -11132,7 +10967,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -11144,7 +10979,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; @@ -11154,7 +10989,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -11164,8 +10999,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; @@ -11177,31 +11012,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; } @@ -11209,47 +11044,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; @@ -11273,7 +11068,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -11282,7 +11077,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -11299,7 +11094,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; @@ -11308,7 +11103,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -11319,7 +11114,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -11330,14 +11125,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; @@ -11353,7 +11148,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; @@ -11369,14 +11164,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; @@ -11393,7 +11188,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -11401,7 +11196,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; @@ -11415,7 +11210,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -11425,7 +11220,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; @@ -11445,7 +11240,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -11455,7 +11250,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -11464,7 +11259,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -11476,7 +11271,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; @@ -11491,7 +11286,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -11505,7 +11300,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -11540,7 +11335,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; @@ -11550,7 +11345,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -11571,7 +11366,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -11581,8 +11376,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; @@ -11631,7 +11808,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -11641,7 +11818,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -11651,7 +11828,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -11661,7 +11838,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -11673,7 +11850,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -11684,7 +11861,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -11693,7 +11870,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -11704,7 +11881,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -11740,7 +11917,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -11750,7 +11927,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -11784,7 +11961,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -11810,7 +11987,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -11839,7 +12016,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; @@ -11861,7 +12038,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; @@ -11871,7 +12048,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -11880,8 +12057,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; @@ -11893,19 +12082,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; @@ -11928,7 +12105,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -11939,7 +12116,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -11949,7 +12126,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -11960,7 +12137,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -11976,7 +12153,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -12011,7 +12188,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; @@ -12021,389 +12198,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; @@ -12423,7 +12218,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -12434,7 +12229,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -12451,7 +12246,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -12468,7 +12263,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -12478,7 +12273,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -12487,7 +12282,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -12496,7 +12291,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; @@ -12513,6 +12308,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; readonly hardwareConcurrency: number; + readonly languages: string[]; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; @@ -12523,7 +12319,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -12598,7 +12394,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -12621,7 +12417,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -12636,7 +12432,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -12647,7 +12443,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -12677,7 +12473,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -12685,7 +12481,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; @@ -12695,7 +12491,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 { } @@ -12703,7 +12499,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -12711,7 +12507,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; @@ -12721,7 +12517,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 { } @@ -12729,7 +12525,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; @@ -12738,7 +12534,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -12756,7 +12552,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -12777,7 +12573,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -12794,7 +12590,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -12803,7 +12599,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -12822,7 +12618,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -12830,7 +12626,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -12850,7 +12646,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -12872,7 +12668,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; @@ -12881,7 +12677,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -12898,8 +12694,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; @@ -12927,157 +12873,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 { } @@ -13085,7 +12881,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -13095,7 +12891,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -13104,7 +12900,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -13120,7 +12916,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -13133,7 +12929,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -13156,7 +12952,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -13166,7 +12962,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -13176,7 +12972,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -13193,7 +12989,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -13202,7 +12998,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -13214,7 +13010,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -13225,7 +13021,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -13238,7 +13034,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -13248,17 +13044,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; @@ -13281,7 +13174,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -13290,7 +13183,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -13311,19 +13204,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; @@ -13332,7 +13234,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -13353,7 +13255,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -13362,7 +13264,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -13391,7 +13293,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -13400,7 +13302,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -13446,7 +13348,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -13455,7 +13357,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -13479,7 +13381,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -13504,7 +13406,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -13515,7 +13417,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -13532,7 +13434,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -13541,7 +13443,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -13551,112 +13453,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; @@ -13666,7 +13877,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -13690,7 +13901,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -13700,7 +13911,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -13710,7 +13921,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -13720,7 +13931,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -13730,7 +13941,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -13740,7 +13951,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -13750,7 +13961,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -13760,7 +13971,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -13770,7 +13981,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -13780,7 +13991,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -13790,7 +14001,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -13800,7 +14011,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -13810,7 +14021,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -13823,7 +14034,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -13834,7 +14045,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -13863,7 +14074,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; @@ -13873,7 +14084,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; @@ -13883,7 +14094,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -13921,7 +14132,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -13937,7 +14148,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -13947,7 +14158,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -13961,7 +14172,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14008,7 +14219,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; @@ -14031,7 +14242,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; @@ -14042,7 +14253,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14073,7 +14284,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; @@ -14103,7 +14314,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; @@ -14118,7 +14329,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14143,7 +14354,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; @@ -14155,7 +14366,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; @@ -14165,7 +14376,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; @@ -14175,7 +14386,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; @@ -14185,7 +14396,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; @@ -14195,7 +14406,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; @@ -14205,7 +14416,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14219,7 +14430,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -14230,7 +14441,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; @@ -14240,7 +14451,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -14251,7 +14462,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14271,7 +14482,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; @@ -14284,7 +14495,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -14297,7 +14508,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14313,7 +14524,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -14331,7 +14542,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -14342,7 +14553,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -14370,7 +14581,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; @@ -14389,7 +14600,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -14403,7 +14614,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; @@ -14413,7 +14624,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -14434,7 +14645,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; @@ -14451,7 +14662,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -14466,7 +14677,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -14502,7 +14713,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -14518,21 +14729,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; @@ -14546,8 +14743,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; @@ -14558,12 +14769,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; } @@ -14571,13 +14782,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; @@ -14593,7 +14804,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -14618,7 +14829,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; @@ -14628,7 +14839,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -14637,7 +14848,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -14653,7 +14864,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -14686,7 +14897,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -14736,7 +14947,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -14751,7 +14962,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -14766,7 +14977,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -14774,7 +14985,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -14788,7 +14999,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -14802,7 +15013,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -14814,7 +15025,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -14826,7 +15037,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -14838,7 +15049,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -14850,7 +15061,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -14860,7 +15071,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -14870,7 +15081,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -14880,7 +15091,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -14889,7 +15100,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -14898,7 +15109,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -14908,7 +15119,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -14917,7 +15128,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -14926,7 +15137,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -14942,7 +15153,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -14952,7 +15163,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -14962,7 +15173,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -14979,7 +15190,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -14990,7 +15201,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -15006,7 +15217,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; @@ -15016,7 +15227,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; @@ -15026,7 +15237,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -15064,7 +15275,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; @@ -15079,7 +15290,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -15091,7 +15302,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -15107,8 +15318,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; @@ -15168,59 +15431,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; @@ -15230,7 +15441,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; @@ -15240,17 +15451,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; @@ -15277,7 +15478,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; @@ -15287,7 +15488,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -15312,7 +15513,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; @@ -15327,7 +15528,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; @@ -15337,7 +15538,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -15368,7 +15569,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -15386,8 +15587,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; @@ -15409,7 +15620,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -15420,7 +15631,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -15430,7 +15641,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; @@ -15443,420 +15654,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; @@ -15866,7 +15664,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -15877,7 +15675,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -15909,7 +15707,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; @@ -15918,7 +15716,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -15961,7 +15759,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -15985,7 +15783,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -15997,7 +15795,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -16015,7 +15813,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -16026,7 +15824,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -16042,7 +15840,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -16060,7 +15858,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -16071,7 +15869,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -16080,7 +15878,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -16091,7 +15889,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -16111,7 +15909,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -16122,8 +15920,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; @@ -16145,16 +15952,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; @@ -16172,7 +15970,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -16185,7 +15983,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -16199,7 +15997,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -16223,45 +16021,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; @@ -16271,7 +16031,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -16281,7 +16041,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -16293,8 +16053,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; @@ -16304,7 +16102,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -16312,7 +16110,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -16321,7 +16119,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -16329,7 +16127,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -16337,7 +16135,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -16345,7 +16143,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -16353,7 +16151,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -16614,13 +16412,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; @@ -16645,9 +16443,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; @@ -16677,18 +16475,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; @@ -16722,6 +16520,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; @@ -16754,23 +16566,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; @@ -16916,13 +16714,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; @@ -16947,9 +16745,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; @@ -16979,18 +16777,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; @@ -17024,6 +16822,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; @@ -17056,23 +16868,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; @@ -17096,7 +16894,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -17104,7 +16902,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -17115,7 +16913,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -17123,7 +16921,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -17131,7 +16929,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -17171,7 +16969,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -17180,7 +16978,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -17189,7 +16987,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -17202,7 +17000,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -17211,7 +17009,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -17221,7 +17019,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -17231,8 +17029,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; @@ -17268,7 +17076,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -17291,7 +17099,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; @@ -17319,6 +17127,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -17377,6 +17186,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; @@ -17390,8 +17203,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; @@ -17514,9 +17327,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; @@ -17572,7 +17385,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -17589,7 +17402,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; @@ -17599,7 +17412,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -17646,7 +17459,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; @@ -17656,7 +17469,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -17665,7 +17478,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -17676,7 +17489,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -17685,7 +17498,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -17694,7 +17507,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -17731,7 +17544,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -17747,17 +17560,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; @@ -17794,6 +17597,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; } @@ -17802,81 +17680,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; @@ -17921,16 +17724,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; } @@ -18155,38 +17958,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; @@ -18434,7 +18237,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -18484,8 +18287,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; @@ -18493,59 +18338,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; @@ -18633,48 +18436,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; @@ -18699,307 +18481,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; @@ -19007,8 +18549,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; @@ -19131,9 +18673,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; @@ -19252,6 +18794,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"; @@ -19265,6 +18808,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"; @@ -19272,12 +18821,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"; @@ -19289,6 +18832,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"; @@ -19296,9 +18847,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"; @@ -19309,14 +18860,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/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 94fb13c32ed..c96d5463b9c 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -20,15 +20,15 @@ and limitations under the License. ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -41,32 +41,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 { @@ -106,13 +106,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -126,15 +119,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 { @@ -143,17 +136,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 { @@ -163,9 +163,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -178,6 +177,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -190,17 +190,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 { @@ -227,11 +227,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -256,39 +256,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; @@ -300,31 +414,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 { @@ -342,8 +461,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -353,12 +472,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 { @@ -366,35 +485,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 { @@ -404,28 +523,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; } @@ -443,13 +562,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -457,241 +576,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 { @@ -700,39 +700,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; @@ -742,9 +742,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -753,14 +753,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 { @@ -769,8 +769,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -780,38 +780,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 { @@ -819,15 +844,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 { @@ -842,19 +867,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 { @@ -864,285 +889,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 { @@ -1154,13 +1154,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 { @@ -1169,11 +1169,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 { @@ -1181,10 +1181,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -1203,19 +1203,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; @@ -1231,8 +1218,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; @@ -1242,7 +1242,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -1287,7 +1287,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -1300,7 +1300,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -1315,7 +1315,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -1338,7 +1338,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -1384,7 +1384,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -1393,7 +1393,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -1406,7 +1406,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -1425,7 +1425,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -1441,7 +1441,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -1452,7 +1452,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -1466,7 +1466,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -1489,7 +1489,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -1498,7 +1498,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -1507,13 +1507,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; } @@ -1521,7 +1521,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -1534,16 +1534,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; } @@ -1556,7 +1845,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -1565,7 +1854,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1576,7 +1865,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -1587,7 +1876,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -1597,7 +1886,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -1610,7 +1899,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -1619,7 +1908,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -1629,7 +1918,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -1641,7 +1930,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -1651,8 +1940,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; @@ -1668,8 +1957,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; @@ -1677,7 +1966,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -1688,13 +1977,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; @@ -1770,9 +2059,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; @@ -1842,24 +2131,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; @@ -1995,9 +2284,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; @@ -2049,7 +2338,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -2060,7 +2349,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -2086,7 +2375,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -2094,296 +2383,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; @@ -2393,150 +2393,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; @@ -2547,7 +2404,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -2564,7 +2421,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -2577,7 +2434,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -2591,7 +2448,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -2604,7 +2461,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -2613,7 +2470,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -2624,7 +2481,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -2633,7 +2490,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -2646,7 +2503,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -2659,7 +2516,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -2670,7 +2527,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -2765,299 +2622,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; @@ -3077,146 +2926,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; @@ -3225,243 +3082,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; @@ -3470,7 +3327,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; @@ -3479,7 +3336,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -3493,8 +3350,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; @@ -3503,8 +3503,8 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; - new(): DragEvent; -} + new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -3518,27 +3518,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; @@ -3619,9 +3599,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]; @@ -3639,18 +3619,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; @@ -3661,9 +3641,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; @@ -3672,7 +3652,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -3686,12 +3666,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; @@ -3718,7 +3698,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; @@ -3729,8 +3709,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; @@ -3744,7 +3744,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -3752,7 +3752,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -3763,7 +3763,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; @@ -3774,7 +3774,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -3789,7 +3789,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -3799,7 +3799,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -3813,7 +3813,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; @@ -3827,7 +3827,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -3836,7 +3836,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -3851,7 +3851,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -3861,7 +3861,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -3870,7 +3870,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -3881,8 +3881,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; @@ -3893,87 +3933,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; @@ -3982,70 +4022,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; @@ -4056,66 +4096,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; @@ -4124,7 +4164,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -4132,7 +4172,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; @@ -4142,30 +4182,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; @@ -4174,16 +4200,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; @@ -4192,7 +4218,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4251,71 +4277,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; @@ -4324,32 +4364,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; @@ -4359,42 +4399,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; @@ -4405,7 +4434,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -4416,7 +4445,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -4427,16 +4456,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; @@ -4445,8 +4474,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; @@ -4455,7 +4495,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -4628,54 +4668,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; @@ -4684,39 +4724,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; @@ -4725,12 +4765,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; @@ -4739,7 +4779,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -4748,74 +4788,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; @@ -4825,7 +4865,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -4833,68 +4873,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; @@ -4903,7 +4943,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -4930,33 +4970,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; @@ -4972,8 +5012,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; @@ -4982,29 +5022,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; @@ -5015,12 +5033,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; @@ -5029,12 +5047,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; @@ -5043,7 +5083,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -5051,79 +5091,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; @@ -5132,86 +5172,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; @@ -5223,210 +5263,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; @@ -5435,31 +5475,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; @@ -5468,16 +5493,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; @@ -5486,41 +5511,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; @@ -5531,16 +5571,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; @@ -5549,7 +5589,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -5581,7 +5621,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -5590,162 +5630,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; @@ -5772,7 +5812,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -5784,32 +5824,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; @@ -5818,7 +5858,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -5834,16 +5874,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; @@ -5852,13 +5892,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; @@ -5868,154 +6025,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; @@ -6024,37 +6064,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; @@ -6063,7 +6103,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -6075,7 +6115,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -6097,12 +6137,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; @@ -6112,24 +6152,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; @@ -6138,7 +6178,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; @@ -6148,12 +6188,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; @@ -6162,24 +6202,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; @@ -6188,12 +6228,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; @@ -6202,38 +6242,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; @@ -6243,94 +6283,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; @@ -6340,18 +6380,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; /** @@ -6365,7 +6405,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; @@ -6375,17 +6415,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; @@ -6394,16 +6434,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; @@ -6412,53 +6452,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; @@ -6467,20 +6507,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; @@ -6489,7 +6529,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; @@ -6499,111 +6539,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; @@ -6612,12 +6652,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; @@ -6626,39 +6666,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; @@ -6667,26 +6707,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; @@ -6695,7 +6735,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -6706,105 +6746,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; @@ -6813,7 +6853,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -6824,12 +6864,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; @@ -6838,7 +6878,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -6863,7 +6903,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -6875,7 +6915,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; @@ -6885,7 +6925,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -6895,8 +6935,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; @@ -6908,31 +6948,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; } @@ -6940,47 +6980,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; @@ -7004,7 +7004,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -7013,7 +7013,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -7030,7 +7030,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; @@ -7039,7 +7039,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -7050,7 +7050,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -7061,14 +7061,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; @@ -7084,7 +7084,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; @@ -7100,14 +7100,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; @@ -7124,7 +7124,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -7132,7 +7132,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; @@ -7146,7 +7146,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -7156,7 +7156,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; @@ -7176,7 +7176,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -7186,7 +7186,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -7195,7 +7195,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -7207,7 +7207,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; @@ -7222,7 +7222,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -7236,7 +7236,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -7271,7 +7271,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; @@ -7281,7 +7281,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -7302,7 +7302,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -7312,8 +7312,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; @@ -7362,7 +7744,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -7372,7 +7754,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -7382,7 +7764,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -7392,7 +7774,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -7404,7 +7786,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -7415,7 +7797,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -7424,7 +7806,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -7435,7 +7817,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -7471,7 +7853,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -7481,7 +7863,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -7515,7 +7897,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -7541,7 +7923,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -7570,7 +7952,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; @@ -7592,7 +7974,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; @@ -7602,7 +7984,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -7611,8 +7993,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; @@ -7624,19 +8018,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; @@ -7659,7 +8041,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -7670,7 +8052,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -7680,7 +8062,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -7691,7 +8073,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -7707,7 +8089,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -7742,7 +8124,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; @@ -7752,389 +8134,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; @@ -8154,7 +8154,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -8165,7 +8165,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -8182,7 +8182,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -8199,7 +8199,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -8209,7 +8209,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -8218,7 +8218,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -8227,7 +8227,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; @@ -8244,6 +8244,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; readonly hardwareConcurrency: number; + readonly languages: string[]; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; @@ -8254,7 +8255,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -8329,7 +8330,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -8352,7 +8353,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -8367,7 +8368,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -8378,7 +8379,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -8408,7 +8409,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -8416,7 +8417,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; @@ -8426,7 +8427,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 { } @@ -8434,7 +8435,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -8442,7 +8443,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; @@ -8452,7 +8453,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 { } @@ -8460,7 +8461,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; @@ -8469,7 +8470,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -8487,7 +8488,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -8508,7 +8509,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -8525,7 +8526,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -8534,7 +8535,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -8553,7 +8554,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -8561,7 +8562,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -8581,7 +8582,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -8603,7 +8604,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; @@ -8612,7 +8613,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -8629,8 +8630,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; @@ -8658,157 +8809,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 { } @@ -8816,7 +8817,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -8826,7 +8827,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -8835,7 +8836,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -8851,7 +8852,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -8864,7 +8865,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -8887,7 +8888,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -8897,7 +8898,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -8907,7 +8908,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -8924,7 +8925,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -8933,7 +8934,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -8945,7 +8946,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -8956,7 +8957,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -8969,7 +8970,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -8979,17 +8980,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; @@ -9012,7 +9110,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -9021,7 +9119,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -9042,19 +9140,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; @@ -9063,7 +9170,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -9084,7 +9191,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -9093,7 +9200,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -9122,7 +9229,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -9131,7 +9238,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -9177,7 +9284,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -9186,7 +9293,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -9210,7 +9317,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -9235,7 +9342,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -9246,7 +9353,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -9263,7 +9370,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -9272,7 +9379,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -9282,112 +9389,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; @@ -9397,7 +9813,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -9421,7 +9837,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -9431,7 +9847,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -9441,7 +9857,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -9451,7 +9867,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -9461,7 +9877,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -9471,7 +9887,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -9481,7 +9897,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -9491,7 +9907,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -9501,7 +9917,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -9511,7 +9927,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -9521,7 +9937,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -9531,7 +9947,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -9541,7 +9957,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9554,7 +9970,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -9565,7 +9981,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -9594,7 +10010,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; @@ -9604,7 +10020,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; @@ -9614,7 +10030,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -9652,7 +10068,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -9668,7 +10084,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -9678,7 +10094,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -9692,7 +10108,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9739,7 +10155,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; @@ -9762,7 +10178,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; @@ -9773,7 +10189,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9804,7 +10220,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; @@ -9834,7 +10250,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; @@ -9849,7 +10265,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9874,7 +10290,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; @@ -9886,7 +10302,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; @@ -9896,7 +10312,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; @@ -9906,7 +10322,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; @@ -9916,7 +10332,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; @@ -9926,7 +10342,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; @@ -9936,7 +10352,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -9950,7 +10366,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -9961,7 +10377,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; @@ -9971,7 +10387,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -9982,7 +10398,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10002,7 +10418,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; @@ -10015,7 +10431,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -10028,7 +10444,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10044,7 +10460,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -10062,7 +10478,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -10073,7 +10489,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -10101,7 +10517,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; @@ -10120,7 +10536,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10134,7 +10550,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; @@ -10144,7 +10560,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -10165,7 +10581,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; @@ -10182,7 +10598,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10197,7 +10613,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -10233,7 +10649,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -10249,21 +10665,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; @@ -10277,8 +10679,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; @@ -10289,12 +10705,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; } @@ -10302,13 +10718,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; @@ -10324,7 +10740,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -10349,7 +10765,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; @@ -10359,7 +10775,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -10368,7 +10784,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -10384,7 +10800,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -10417,7 +10833,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -10467,7 +10883,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -10482,7 +10898,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -10497,7 +10913,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -10505,7 +10921,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -10519,7 +10935,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -10533,7 +10949,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -10545,7 +10961,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -10557,7 +10973,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -10569,7 +10985,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -10581,7 +10997,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -10591,7 +11007,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -10601,7 +11017,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -10611,7 +11027,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -10620,7 +11036,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -10629,7 +11045,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -10639,7 +11055,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -10648,7 +11064,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -10657,7 +11073,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -10673,7 +11089,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -10683,7 +11099,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -10693,7 +11109,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -10710,7 +11126,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -10721,7 +11137,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -10737,7 +11153,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; @@ -10747,7 +11163,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; @@ -10757,7 +11173,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -10795,7 +11211,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; @@ -10810,7 +11226,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -10822,7 +11238,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -10838,8 +11254,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; @@ -10899,59 +11367,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; @@ -10961,7 +11377,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; @@ -10971,17 +11387,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; @@ -11008,7 +11414,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; @@ -11018,7 +11424,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -11043,7 +11449,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; @@ -11058,7 +11464,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; @@ -11068,7 +11474,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -11099,7 +11505,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -11117,8 +11523,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; @@ -11140,7 +11556,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -11151,7 +11567,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -11161,7 +11577,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; @@ -11174,420 +11590,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; @@ -11597,7 +11600,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -11608,7 +11611,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -11640,7 +11643,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; @@ -11649,7 +11652,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -11692,7 +11695,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -11716,7 +11719,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -11728,7 +11731,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -11746,7 +11749,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -11757,7 +11760,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -11773,7 +11776,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -11791,7 +11794,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -11802,7 +11805,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -11811,7 +11814,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -11822,7 +11825,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -11842,7 +11845,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -11853,8 +11856,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; @@ -11876,16 +11888,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; @@ -11903,7 +11906,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -11916,7 +11919,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -11930,7 +11933,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -11954,45 +11957,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; @@ -12002,7 +11967,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -12012,7 +11977,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -12024,8 +11989,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; @@ -12035,7 +12038,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -12043,7 +12046,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -12052,7 +12055,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -12060,7 +12063,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -12068,7 +12071,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -12076,7 +12079,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -12084,7 +12087,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -12345,13 +12348,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; @@ -12376,9 +12379,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; @@ -12408,18 +12411,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; @@ -12453,6 +12456,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; @@ -12485,23 +12502,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; @@ -12647,13 +12650,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; @@ -12678,9 +12681,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; @@ -12710,18 +12713,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; @@ -12755,6 +12758,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; @@ -12787,23 +12804,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; @@ -12827,7 +12830,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -12835,7 +12838,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -12846,7 +12849,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -12854,7 +12857,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -12862,7 +12865,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -12902,7 +12905,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -12911,7 +12914,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -12920,7 +12923,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -12933,7 +12936,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -12942,7 +12945,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -12952,7 +12955,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -12962,8 +12965,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; @@ -12999,7 +13012,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -13022,7 +13035,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; @@ -13050,6 +13063,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -13108,6 +13122,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; @@ -13121,8 +13139,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; @@ -13245,9 +13263,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; @@ -13303,7 +13321,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -13320,7 +13338,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; @@ -13330,7 +13348,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -13377,7 +13395,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; @@ -13387,7 +13405,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -13396,7 +13414,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -13407,7 +13425,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -13416,7 +13434,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -13425,7 +13443,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -13462,7 +13480,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -13478,17 +13496,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; @@ -13525,6 +13533,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; } @@ -13533,81 +13616,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; @@ -13652,16 +13660,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; } @@ -13886,38 +13894,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; @@ -14165,7 +14173,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -14215,8 +14223,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; @@ -14224,59 +14274,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; @@ -14364,48 +14372,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; @@ -14430,307 +14417,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; @@ -14738,8 +14485,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; @@ -14862,9 +14609,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; @@ -14983,6 +14730,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"; @@ -14996,6 +14744,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"; @@ -15003,12 +14757,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"; @@ -15020,6 +14768,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"; @@ -15027,9 +14783,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"; @@ -15040,14 +14796,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/lib/lib.es2015.d.ts b/lib/lib.es2015.d.ts index a536e9c8922..d6cf43cbb7a 100644 --- a/lib/lib.es2015.d.ts +++ b/lib/lib.es2015.d.ts @@ -21,8 +21,8 @@ and limitations under the License. /// /// /// -/// /// +/// /// /// /// diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index a22ca2e9d80..09220599d5f 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -21,1841 +21,17 @@ 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 +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -1868,32 +44,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 { @@ -1933,13 +109,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -1953,15 +122,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 { @@ -1970,17 +139,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 { @@ -1990,9 +166,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -2005,6 +180,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -2017,17 +193,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 { @@ -2054,11 +230,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -2083,39 +259,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; @@ -2127,31 +417,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 { @@ -2169,8 +464,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -2180,12 +475,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 { @@ -2193,35 +488,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 { @@ -2231,28 +526,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; } @@ -2270,13 +565,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -2284,241 +579,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 { @@ -2527,39 +703,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; @@ -2569,9 +745,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -2580,14 +756,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 { @@ -2596,8 +772,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -2607,38 +783,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 { @@ -2646,15 +847,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 { @@ -2669,19 +870,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 { @@ -2691,285 +892,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 { @@ -2981,13 +1157,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 { @@ -2996,11 +1172,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 { @@ -3008,10 +1184,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -3030,19 +1206,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; @@ -3058,8 +1221,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; @@ -3069,7 +1245,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -3114,7 +1290,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -3127,7 +1303,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -3142,7 +1318,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -3165,7 +1341,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -3211,7 +1387,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -3220,7 +1396,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -3233,7 +1409,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -3252,7 +1428,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -3268,7 +1444,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -3279,7 +1455,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -3293,7 +1469,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -3316,7 +1492,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -3325,7 +1501,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -3334,13 +1510,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; } @@ -3348,7 +1524,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -3361,16 +1537,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; } @@ -3383,7 +1848,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -3392,7 +1857,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -3403,7 +1868,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -3414,7 +1879,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -3424,7 +1889,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -3437,7 +1902,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -3446,7 +1911,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -3456,7 +1921,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -3468,7 +1933,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -3478,8 +1943,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; @@ -3495,8 +1960,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; @@ -3504,7 +1969,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -3515,13 +1980,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; @@ -3597,9 +2062,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; @@ -3669,24 +2134,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; @@ -3822,9 +2287,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; @@ -3876,7 +2341,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -3887,7 +2352,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -3913,7 +2378,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -3921,296 +2386,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; @@ -4220,150 +2396,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; @@ -4374,7 +2407,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -4391,7 +2424,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -4404,7 +2437,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -4418,7 +2451,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -4431,7 +2464,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -4440,7 +2473,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -4451,7 +2484,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -4460,7 +2493,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -4473,7 +2506,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -4486,7 +2519,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -4497,7 +2530,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -4592,299 +2625,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; @@ -4904,146 +2929,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; @@ -5052,243 +3085,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; @@ -5297,7 +3330,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; @@ -5306,7 +3339,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -5320,8 +3353,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; @@ -5330,8 +3506,8 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; - new(): DragEvent; -} + new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -5345,27 +3521,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; @@ -5446,9 +3602,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]; @@ -5466,18 +3622,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; @@ -5488,9 +3644,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; @@ -5499,7 +3655,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -5513,12 +3669,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; @@ -5545,7 +3701,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; @@ -5556,8 +3712,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; @@ -5571,7 +3747,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -5579,7 +3755,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -5590,7 +3766,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; @@ -5601,7 +3777,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -5616,7 +3792,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -5626,7 +3802,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -5640,7 +3816,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; @@ -5654,7 +3830,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -5663,7 +3839,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -5678,7 +3854,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -5688,7 +3864,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -5697,7 +3873,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -5708,8 +3884,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; @@ -5720,87 +3936,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; @@ -5809,70 +4025,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; @@ -5883,66 +4099,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; @@ -5951,7 +4167,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -5959,7 +4175,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; @@ -5969,30 +4185,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; @@ -6001,16 +4203,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; @@ -6019,7 +4221,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -6078,71 +4280,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; @@ -6151,32 +4367,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; @@ -6186,42 +4402,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; @@ -6232,7 +4437,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -6243,7 +4448,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -6254,16 +4459,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; @@ -6272,8 +4477,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; @@ -6282,7 +4498,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -6455,54 +4671,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; @@ -6511,39 +4727,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; @@ -6552,12 +4768,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; @@ -6566,7 +4782,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -6575,74 +4791,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; @@ -6652,7 +4868,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -6660,68 +4876,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; @@ -6730,7 +4946,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -6757,33 +4973,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; @@ -6799,8 +5015,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; @@ -6809,29 +5025,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; @@ -6842,12 +5036,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; @@ -6856,12 +5050,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; @@ -6870,7 +5086,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -6878,79 +5094,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; @@ -6959,86 +5175,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; @@ -7050,210 +5266,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; @@ -7262,31 +5478,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; @@ -7295,16 +5496,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; @@ -7313,41 +5514,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; @@ -7358,16 +5574,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; @@ -7376,7 +5592,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -7408,7 +5624,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -7417,162 +5633,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; @@ -7599,7 +5815,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -7611,32 +5827,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; @@ -7645,7 +5861,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -7661,16 +5877,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; @@ -7679,13 +5895,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; @@ -7695,154 +6028,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; @@ -7851,37 +6067,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; @@ -7890,7 +6106,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -7902,7 +6118,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -7924,12 +6140,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; @@ -7939,24 +6155,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; @@ -7965,7 +6181,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; @@ -7975,12 +6191,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; @@ -7989,24 +6205,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; @@ -8015,12 +6231,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; @@ -8029,38 +6245,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; @@ -8070,94 +6286,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; @@ -8167,18 +6383,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; /** @@ -8192,7 +6408,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; @@ -8202,17 +6418,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; @@ -8221,16 +6437,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; @@ -8239,53 +6455,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; @@ -8294,20 +6510,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; @@ -8316,7 +6532,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; @@ -8326,111 +6542,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; @@ -8439,12 +6655,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; @@ -8453,39 +6669,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; @@ -8494,26 +6710,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; @@ -8522,7 +6738,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -8533,105 +6749,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; @@ -8640,7 +6856,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -8651,12 +6867,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; @@ -8665,7 +6881,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -8690,7 +6906,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -8702,7 +6918,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; @@ -8712,7 +6928,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -8722,8 +6938,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; @@ -8735,31 +6951,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; } @@ -8767,47 +6983,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; @@ -8831,7 +7007,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -8840,7 +7016,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -8857,7 +7033,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; @@ -8866,7 +7042,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -8877,7 +7053,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -8888,14 +7064,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; @@ -8911,7 +7087,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; @@ -8927,14 +7103,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; @@ -8951,7 +7127,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -8959,7 +7135,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; @@ -8973,7 +7149,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -8983,7 +7159,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; @@ -9003,7 +7179,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -9013,7 +7189,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -9022,7 +7198,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -9034,7 +7210,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; @@ -9049,7 +7225,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -9063,7 +7239,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -9098,7 +7274,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; @@ -9108,7 +7284,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -9129,7 +7305,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -9139,8 +7315,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; @@ -9189,7 +7747,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -9199,7 +7757,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -9209,7 +7767,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -9219,7 +7777,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -9231,7 +7789,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -9242,7 +7800,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -9251,7 +7809,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -9262,7 +7820,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -9298,7 +7856,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -9308,7 +7866,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -9342,7 +7900,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -9368,7 +7926,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -9397,7 +7955,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; @@ -9419,7 +7977,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; @@ -9429,7 +7987,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -9438,8 +7996,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; @@ -9451,19 +8021,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; @@ -9486,7 +8044,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -9497,7 +8055,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -9507,7 +8065,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -9518,7 +8076,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -9534,7 +8092,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -9569,7 +8127,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; @@ -9579,389 +8137,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; @@ -9981,7 +8157,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -9992,7 +8168,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -10009,7 +8185,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -10026,7 +8202,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -10036,7 +8212,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -10045,7 +8221,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -10054,7 +8230,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; @@ -10071,6 +8247,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; readonly hardwareConcurrency: number; + readonly languages: string[]; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; @@ -10081,7 +8258,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -10156,7 +8333,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -10179,7 +8356,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -10194,7 +8371,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -10205,7 +8382,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -10235,7 +8412,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -10243,7 +8420,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; @@ -10253,7 +8430,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 { } @@ -10261,7 +8438,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -10269,7 +8446,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; @@ -10279,7 +8456,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 { } @@ -10287,7 +8464,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; @@ -10296,7 +8473,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -10314,7 +8491,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -10335,7 +8512,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -10352,7 +8529,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -10361,7 +8538,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -10380,7 +8557,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -10388,7 +8565,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -10408,7 +8585,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -10430,7 +8607,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; @@ -10439,7 +8616,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -10456,8 +8633,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; @@ -10485,157 +8812,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 { } @@ -10643,7 +8820,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -10653,7 +8830,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -10662,7 +8839,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -10678,7 +8855,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -10691,7 +8868,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -10714,7 +8891,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -10724,7 +8901,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -10734,7 +8911,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -10751,7 +8928,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -10760,7 +8937,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -10772,7 +8949,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -10783,7 +8960,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -10796,7 +8973,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -10806,17 +8983,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; @@ -10839,7 +9113,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -10848,7 +9122,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -10869,19 +9143,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; @@ -10890,7 +9173,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -10911,7 +9194,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -10920,7 +9203,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -10949,7 +9232,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -10958,7 +9241,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -11004,7 +9287,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -11013,7 +9296,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -11037,7 +9320,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -11062,7 +9345,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -11073,7 +9356,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -11090,7 +9373,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -11099,7 +9382,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -11109,112 +9392,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; @@ -11224,7 +9816,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -11248,7 +9840,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -11258,7 +9850,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -11268,7 +9860,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -11278,7 +9870,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -11288,7 +9880,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -11298,7 +9890,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -11308,7 +9900,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -11318,7 +9910,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -11328,7 +9920,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -11338,7 +9930,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -11348,7 +9940,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -11358,7 +9950,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -11368,7 +9960,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -11381,7 +9973,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -11392,7 +9984,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -11421,7 +10013,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; @@ -11431,7 +10023,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; @@ -11441,7 +10033,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -11479,7 +10071,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -11495,7 +10087,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -11505,7 +10097,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -11519,7 +10111,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11566,7 +10158,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; @@ -11589,7 +10181,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; @@ -11600,7 +10192,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11631,7 +10223,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; @@ -11661,7 +10253,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; @@ -11676,7 +10268,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11701,7 +10293,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; @@ -11713,7 +10305,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; @@ -11723,7 +10315,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; @@ -11733,7 +10325,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; @@ -11743,7 +10335,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; @@ -11753,7 +10345,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; @@ -11763,7 +10355,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11777,7 +10369,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -11788,7 +10380,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; @@ -11798,7 +10390,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -11809,7 +10401,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11829,7 +10421,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; @@ -11842,7 +10434,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -11855,7 +10447,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11871,7 +10463,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -11889,7 +10481,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11900,7 +10492,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -11928,7 +10520,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; @@ -11947,7 +10539,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -11961,7 +10553,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; @@ -11971,7 +10563,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -11992,7 +10584,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; @@ -12009,7 +10601,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -12024,7 +10616,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -12060,7 +10652,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -12076,21 +10668,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; @@ -12104,8 +10682,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; @@ -12116,12 +10708,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; } @@ -12129,13 +10721,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; @@ -12151,7 +10743,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -12176,7 +10768,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; @@ -12186,7 +10778,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -12195,7 +10787,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -12211,7 +10803,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -12244,7 +10836,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -12294,7 +10886,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -12309,7 +10901,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -12324,7 +10916,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -12332,7 +10924,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -12346,7 +10938,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -12360,7 +10952,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -12372,7 +10964,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -12384,7 +10976,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -12396,7 +10988,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -12408,7 +11000,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -12418,7 +11010,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -12428,7 +11020,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -12438,7 +11030,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -12447,7 +11039,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -12456,7 +11048,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -12466,7 +11058,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -12475,7 +11067,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -12484,7 +11076,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -12500,7 +11092,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -12510,7 +11102,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -12520,7 +11112,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -12537,7 +11129,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -12548,7 +11140,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -12564,7 +11156,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; @@ -12574,7 +11166,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; @@ -12584,7 +11176,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -12622,7 +11214,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; @@ -12637,7 +11229,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -12649,7 +11241,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -12665,8 +11257,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; @@ -12726,59 +11370,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; @@ -12788,7 +11380,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; @@ -12798,17 +11390,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; @@ -12835,7 +11417,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; @@ -12845,7 +11427,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -12870,7 +11452,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; @@ -12885,7 +11467,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; @@ -12895,7 +11477,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -12926,7 +11508,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -12944,8 +11526,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; @@ -12967,7 +11559,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -12978,7 +11570,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -12988,7 +11580,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; @@ -13001,420 +11593,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; @@ -13424,7 +11603,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -13435,7 +11614,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -13467,7 +11646,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; @@ -13476,7 +11655,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -13519,7 +11698,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -13543,7 +11722,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -13555,7 +11734,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -13573,7 +11752,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -13584,7 +11763,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -13600,7 +11779,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -13618,7 +11797,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -13629,7 +11808,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -13638,7 +11817,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -13649,7 +11828,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -13669,7 +11848,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -13680,8 +11859,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; @@ -13703,16 +11891,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; @@ -13730,7 +11909,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -13743,7 +11922,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -13757,7 +11936,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -13781,45 +11960,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; @@ -13829,7 +11970,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -13839,7 +11980,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -13851,8 +11992,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; @@ -13862,7 +12041,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -13870,7 +12049,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -13879,7 +12058,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -13887,7 +12066,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -13895,7 +12074,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -13903,7 +12082,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -13911,7 +12090,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -14172,13 +12351,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; @@ -14203,9 +12382,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; @@ -14235,18 +12414,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; @@ -14280,6 +12459,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; @@ -14312,23 +12505,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; @@ -14474,13 +12653,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; @@ -14505,9 +12684,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; @@ -14537,18 +12716,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; @@ -14582,6 +12761,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; @@ -14614,23 +12807,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; @@ -14654,7 +12833,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -14662,7 +12841,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -14673,7 +12852,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -14681,7 +12860,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -14689,7 +12868,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -14729,7 +12908,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -14738,7 +12917,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -14747,7 +12926,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -14760,7 +12939,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -14769,7 +12948,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -14779,7 +12958,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -14789,8 +12968,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; @@ -14826,7 +13015,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -14849,7 +13038,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; @@ -14877,6 +13066,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -14935,6 +13125,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; @@ -14948,8 +13142,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; @@ -15072,9 +13266,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; @@ -15130,7 +13324,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -15147,7 +13341,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; @@ -15157,7 +13351,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -15204,7 +13398,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; @@ -15214,7 +13408,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -15223,7 +13417,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -15234,7 +13428,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -15243,7 +13437,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -15252,7 +13446,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -15289,7 +13483,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -15305,17 +13499,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; @@ -15352,6 +13536,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; } @@ -15360,81 +13619,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; @@ -15479,16 +13663,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; } @@ -15713,38 +13897,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; @@ -15992,7 +14176,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -16042,8 +14226,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; @@ -16051,59 +14277,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; @@ -16191,48 +14375,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; @@ -16257,307 +14420,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; @@ -16565,8 +14488,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; @@ -16689,9 +14612,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; @@ -16810,6 +14733,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"; @@ -16823,6 +14747,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"; @@ -16830,12 +14760,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"; @@ -16847,6 +14771,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"; @@ -16854,9 +14786,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"; @@ -16867,14 +14799,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/lib/lib.es2017.d.ts b/lib/lib.es2017.d.ts index 64ebe606847..b887f51e8c6 100644 --- a/lib/lib.es2017.d.ts +++ b/lib/lib.es2017.d.ts @@ -22,4 +22,4 @@ and limitations under the License. /// /// /// -/// \ No newline at end of file +/// diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 91bee6e9d56..6c2f2606640 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -24,1841 +24,18 @@ 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 +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -1871,32 +48,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 { @@ -1936,13 +113,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -1956,15 +126,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 { @@ -1973,17 +143,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 { @@ -1993,9 +170,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -2008,6 +184,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -2020,17 +197,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 { @@ -2057,11 +234,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -2086,39 +263,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; @@ -2130,31 +421,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 { @@ -2172,8 +468,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -2183,12 +479,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 { @@ -2196,35 +492,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 { @@ -2234,28 +530,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; } @@ -2273,13 +569,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -2287,241 +583,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 { @@ -2530,39 +707,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; @@ -2572,9 +749,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -2583,14 +760,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 { @@ -2599,8 +776,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -2610,38 +787,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 { @@ -2649,15 +851,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 { @@ -2672,19 +874,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 { @@ -2694,285 +896,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 { @@ -2984,13 +1161,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 { @@ -2999,11 +1176,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 { @@ -3011,10 +1188,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -3033,19 +1210,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; @@ -3061,8 +1225,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; @@ -3072,7 +1249,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -3117,7 +1294,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -3130,7 +1307,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -3145,7 +1322,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -3168,7 +1345,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -3214,7 +1391,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -3223,7 +1400,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -3236,7 +1413,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -3255,7 +1432,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -3271,7 +1448,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -3282,7 +1459,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -3296,7 +1473,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -3319,7 +1496,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -3328,7 +1505,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -3337,13 +1514,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; } @@ -3351,7 +1528,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -3364,16 +1541,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; } @@ -3386,7 +1852,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -3395,7 +1861,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -3406,7 +1872,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -3417,7 +1883,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -3427,7 +1893,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -3440,7 +1906,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -3449,7 +1915,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -3459,7 +1925,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -3471,7 +1937,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -3481,8 +1947,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; @@ -3498,8 +1964,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; @@ -3507,7 +1973,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -3518,13 +1984,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; @@ -3600,9 +2066,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; @@ -3672,24 +2138,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; @@ -3825,9 +2291,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; @@ -3879,7 +2345,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -3890,7 +2356,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -3916,7 +2382,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -3924,296 +2390,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; @@ -4223,150 +2400,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; @@ -4377,7 +2411,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -4394,7 +2428,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -4407,7 +2441,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -4421,7 +2455,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -4434,7 +2468,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -4443,7 +2477,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -4454,7 +2488,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -4463,7 +2497,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -4476,7 +2510,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -4489,7 +2523,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -4500,7 +2534,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -4595,299 +2629,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; @@ -4907,146 +2933,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; @@ -5055,243 +3089,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; @@ -5300,7 +3334,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; @@ -5309,7 +3343,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -5323,8 +3357,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; @@ -5333,8 +3510,8 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; - new(): DragEvent; -} + new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -5348,27 +3525,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; @@ -5449,9 +3606,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]; @@ -5469,18 +3626,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; @@ -5491,9 +3648,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; @@ -5502,7 +3659,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -5516,12 +3673,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; @@ -5548,7 +3705,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; @@ -5559,8 +3716,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; @@ -5574,7 +3751,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -5582,7 +3759,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -5593,7 +3770,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; @@ -5604,7 +3781,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -5619,7 +3796,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -5629,7 +3806,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -5643,7 +3820,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; @@ -5657,7 +3834,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -5666,7 +3843,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -5681,7 +3858,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -5691,7 +3868,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -5700,7 +3877,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -5711,8 +3888,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; @@ -5723,87 +3940,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; @@ -5812,70 +4029,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; @@ -5886,66 +4103,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; @@ -5954,7 +4171,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -5962,7 +4179,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; @@ -5972,30 +4189,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; @@ -6004,16 +4207,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; @@ -6022,7 +4225,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -6081,71 +4284,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; @@ -6154,32 +4371,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; @@ -6189,42 +4406,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; @@ -6235,7 +4441,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -6246,7 +4452,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -6257,16 +4463,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; @@ -6275,8 +4481,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; @@ -6285,7 +4502,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -6458,54 +4675,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; @@ -6514,39 +4731,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; @@ -6555,12 +4772,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; @@ -6569,7 +4786,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -6578,74 +4795,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; @@ -6655,7 +4872,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -6663,68 +4880,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; @@ -6733,7 +4950,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -6760,33 +4977,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; @@ -6802,8 +5019,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; @@ -6812,29 +5029,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; @@ -6845,12 +5040,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; @@ -6859,12 +5054,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; @@ -6873,7 +5090,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -6881,79 +5098,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; @@ -6962,86 +5179,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; @@ -7053,210 +5270,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; @@ -7265,31 +5482,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; @@ -7298,16 +5500,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; @@ -7316,41 +5518,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; @@ -7361,16 +5578,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; @@ -7379,7 +5596,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -7411,7 +5628,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -7420,162 +5637,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; @@ -7602,7 +5819,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -7614,32 +5831,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; @@ -7648,7 +5865,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -7664,16 +5881,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; @@ -7682,13 +5899,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; @@ -7698,154 +6032,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; @@ -7854,37 +6071,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; @@ -7893,7 +6110,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -7905,7 +6122,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -7927,12 +6144,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; @@ -7942,24 +6159,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; @@ -7968,7 +6185,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; @@ -7978,12 +6195,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; @@ -7992,24 +6209,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; @@ -8018,12 +6235,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; @@ -8032,38 +6249,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; @@ -8073,94 +6290,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; @@ -8170,18 +6387,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; /** @@ -8195,7 +6412,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; @@ -8205,17 +6422,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; @@ -8224,16 +6441,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; @@ -8242,53 +6459,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; @@ -8297,20 +6514,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; @@ -8319,7 +6536,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; @@ -8329,111 +6546,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; @@ -8442,12 +6659,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; @@ -8456,39 +6673,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; @@ -8497,26 +6714,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; @@ -8525,7 +6742,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -8536,105 +6753,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; @@ -8643,7 +6860,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -8654,12 +6871,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; @@ -8668,7 +6885,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -8693,7 +6910,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -8705,7 +6922,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; @@ -8715,7 +6932,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -8725,8 +6942,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; @@ -8738,31 +6955,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; } @@ -8770,47 +6987,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; @@ -8834,7 +7011,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -8843,7 +7020,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -8860,7 +7037,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; @@ -8869,7 +7046,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -8880,7 +7057,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -8891,14 +7068,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; @@ -8914,7 +7091,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; @@ -8930,14 +7107,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; @@ -8954,7 +7131,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -8962,7 +7139,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; @@ -8976,7 +7153,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -8986,7 +7163,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; @@ -9006,7 +7183,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -9016,7 +7193,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -9025,7 +7202,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -9037,7 +7214,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; @@ -9052,7 +7229,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -9066,7 +7243,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -9101,7 +7278,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; @@ -9111,7 +7288,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -9132,7 +7309,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -9142,8 +7319,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; @@ -9192,7 +7751,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -9202,7 +7761,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -9212,7 +7771,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -9222,7 +7781,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -9234,7 +7793,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -9245,7 +7804,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -9254,7 +7813,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -9265,7 +7824,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -9301,7 +7860,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -9311,7 +7870,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -9345,7 +7904,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -9371,7 +7930,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -9400,7 +7959,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; @@ -9422,7 +7981,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; @@ -9432,7 +7991,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -9441,8 +8000,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; @@ -9454,19 +8025,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; @@ -9489,7 +8048,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -9500,7 +8059,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -9510,7 +8069,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -9521,7 +8080,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -9537,7 +8096,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -9572,7 +8131,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; @@ -9582,389 +8141,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; @@ -9984,7 +8161,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -9995,7 +8172,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -10012,7 +8189,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -10029,7 +8206,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -10039,7 +8216,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -10048,7 +8225,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -10057,7 +8234,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; @@ -10074,6 +8251,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; readonly hardwareConcurrency: number; + readonly languages: string[]; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; @@ -10084,7 +8262,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -10159,7 +8337,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -10182,7 +8360,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -10197,7 +8375,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -10208,7 +8386,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -10238,7 +8416,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -10246,7 +8424,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; @@ -10256,7 +8434,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 { } @@ -10264,7 +8442,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -10272,7 +8450,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; @@ -10282,7 +8460,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 { } @@ -10290,7 +8468,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; @@ -10299,7 +8477,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -10317,7 +8495,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -10338,7 +8516,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -10355,7 +8533,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -10364,7 +8542,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -10383,7 +8561,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -10391,7 +8569,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -10411,7 +8589,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -10433,7 +8611,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; @@ -10442,7 +8620,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -10459,8 +8637,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; @@ -10488,157 +8816,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 { } @@ -10646,7 +8824,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -10656,7 +8834,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -10665,7 +8843,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -10681,7 +8859,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -10694,7 +8872,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -10717,7 +8895,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -10727,7 +8905,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -10737,7 +8915,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -10754,7 +8932,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -10763,7 +8941,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -10775,7 +8953,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -10786,7 +8964,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -10799,7 +8977,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -10809,17 +8987,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; @@ -10842,7 +9117,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -10851,7 +9126,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -10872,19 +9147,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; @@ -10893,7 +9177,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -10914,7 +9198,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -10923,7 +9207,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -10952,7 +9236,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -10961,7 +9245,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -11007,7 +9291,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -11016,7 +9300,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -11040,7 +9324,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -11065,7 +9349,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -11076,7 +9360,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -11093,7 +9377,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -11102,7 +9386,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -11112,112 +9396,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; @@ -11227,7 +9820,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -11251,7 +9844,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -11261,7 +9854,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -11271,7 +9864,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -11281,7 +9874,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -11291,7 +9884,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -11301,7 +9894,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -11311,7 +9904,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -11321,7 +9914,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -11331,7 +9924,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -11341,7 +9934,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -11351,7 +9944,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -11361,7 +9954,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -11371,7 +9964,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -11384,7 +9977,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -11395,7 +9988,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -11424,7 +10017,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; @@ -11434,7 +10027,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; @@ -11444,7 +10037,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -11482,7 +10075,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -11498,7 +10091,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -11508,7 +10101,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -11522,7 +10115,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11569,7 +10162,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; @@ -11592,7 +10185,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; @@ -11603,7 +10196,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11634,7 +10227,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; @@ -11664,7 +10257,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; @@ -11679,7 +10272,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11704,7 +10297,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; @@ -11716,7 +10309,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; @@ -11726,7 +10319,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; @@ -11736,7 +10329,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; @@ -11746,7 +10339,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; @@ -11756,7 +10349,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; @@ -11766,7 +10359,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11780,7 +10373,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -11791,7 +10384,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; @@ -11801,7 +10394,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -11812,7 +10405,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11832,7 +10425,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; @@ -11845,7 +10438,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -11858,7 +10451,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11874,7 +10467,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -11892,7 +10485,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11903,7 +10496,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -11931,7 +10524,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; @@ -11950,7 +10543,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -11964,7 +10557,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; @@ -11974,7 +10567,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -11995,7 +10588,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; @@ -12012,7 +10605,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -12027,7 +10620,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -12063,7 +10656,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -12079,21 +10672,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; @@ -12107,8 +10686,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; @@ -12119,12 +10712,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; } @@ -12132,13 +10725,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; @@ -12154,7 +10747,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -12179,7 +10772,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; @@ -12189,7 +10782,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -12198,7 +10791,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -12214,7 +10807,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -12247,7 +10840,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -12297,7 +10890,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -12312,7 +10905,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -12327,7 +10920,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -12335,7 +10928,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -12349,7 +10942,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -12363,7 +10956,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -12375,7 +10968,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -12387,7 +10980,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -12399,7 +10992,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -12411,7 +11004,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -12421,7 +11014,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -12431,7 +11024,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -12441,7 +11034,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -12450,7 +11043,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -12459,7 +11052,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -12469,7 +11062,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -12478,7 +11071,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -12487,7 +11080,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -12503,7 +11096,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -12513,7 +11106,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -12523,7 +11116,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -12540,7 +11133,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -12551,7 +11144,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -12567,7 +11160,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; @@ -12577,7 +11170,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; @@ -12587,7 +11180,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -12625,7 +11218,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; @@ -12640,7 +11233,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -12652,7 +11245,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -12668,8 +11261,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; @@ -12729,59 +11374,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; @@ -12791,7 +11384,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; @@ -12801,17 +11394,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; @@ -12838,7 +11421,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; @@ -12848,7 +11431,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -12873,7 +11456,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; @@ -12888,7 +11471,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; @@ -12898,7 +11481,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -12929,7 +11512,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -12947,8 +11530,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; @@ -12970,7 +11563,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -12981,7 +11574,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -12991,7 +11584,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; @@ -13004,420 +11597,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; @@ -13427,7 +11607,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -13438,7 +11618,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -13470,7 +11650,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; @@ -13479,7 +11659,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -13522,7 +11702,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -13546,7 +11726,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -13558,7 +11738,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -13576,7 +11756,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -13587,7 +11767,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -13603,7 +11783,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -13621,7 +11801,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -13632,7 +11812,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -13641,7 +11821,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -13652,7 +11832,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -13672,7 +11852,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -13683,8 +11863,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; @@ -13706,16 +11895,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; @@ -13733,7 +11913,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -13746,7 +11926,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -13760,7 +11940,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -13784,45 +11964,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; @@ -13832,7 +11974,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -13842,7 +11984,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -13854,8 +11996,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; @@ -13865,7 +12045,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -13873,7 +12053,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -13882,7 +12062,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -13890,7 +12070,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -13898,7 +12078,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -13906,7 +12086,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -13914,7 +12094,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -14175,13 +12355,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; @@ -14206,9 +12386,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; @@ -14238,18 +12418,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; @@ -14283,6 +12463,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; @@ -14315,23 +12509,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; @@ -14477,13 +12657,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; @@ -14508,9 +12688,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; @@ -14540,18 +12720,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; @@ -14585,6 +12765,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; @@ -14617,23 +12811,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; @@ -14657,7 +12837,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -14665,7 +12845,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -14676,7 +12856,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -14684,7 +12864,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -14692,7 +12872,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -14732,7 +12912,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -14741,7 +12921,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -14750,7 +12930,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -14763,7 +12943,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -14772,7 +12952,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -14782,7 +12962,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -14792,8 +12972,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; @@ -14829,7 +13019,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -14852,7 +13042,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; @@ -14880,6 +13070,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -14938,6 +13129,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; @@ -14951,8 +13146,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; @@ -15075,9 +13270,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; @@ -15133,7 +13328,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -15150,7 +13345,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; @@ -15160,7 +13355,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -15207,7 +13402,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; @@ -15217,7 +13412,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -15226,7 +13421,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -15237,7 +13432,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -15246,7 +13441,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -15255,7 +13450,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -15292,7 +13487,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -15308,17 +13503,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; @@ -15355,6 +13540,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; } @@ -15363,81 +13623,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; @@ -15482,16 +13667,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; } @@ -15716,38 +13901,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; @@ -15995,7 +14180,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -16045,8 +14230,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; @@ -16054,59 +14281,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; @@ -16194,48 +14379,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; @@ -16260,307 +14424,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; @@ -16568,8 +14492,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; @@ -16692,9 +14616,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; @@ -16813,6 +14737,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"; @@ -16826,6 +14751,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"; @@ -16833,12 +14764,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"; @@ -16850,6 +14775,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"; @@ -16857,9 +14790,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"; @@ -16870,14 +14803,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/lib/lib.es2017.intl.d.ts b/lib/lib.es2017.intl.d.ts new file mode 100644 index 00000000000..dd1bf6d894d --- /dev/null +++ b/lib/lib.es2017.intl.d.ts @@ -0,0 +1,30 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +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/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index f359e519ab1..f628dc4fe84 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -87,8 +87,8 @@ interface PropertyDescriptor { enumerable?: boolean; value?: any; writable?: boolean; - get? (): any; - set? (v: any): void; + get?(): any; + set?(v: any): void; } interface PropertyDescriptorMap { @@ -128,7 +128,7 @@ interface Object { } interface ObjectConstructor { - new (value?: any): Object; + new(value?: any): Object; (): any; (value: any): any; @@ -286,7 +286,7 @@ interface FunctionConstructor { * Creates a new function. * @param args A list of arguments the function accepts. */ - new (...args: string[]): Function; + new(...args: string[]): Function; (...args: string[]): Function; readonly prototype: Function; } @@ -423,7 +423,7 @@ interface String { } interface StringConstructor { - new (value?: any): String; + new(value?: any): String; (value?: any): string; readonly prototype: String; fromCharCode(...codes: number[]): string; @@ -440,7 +440,7 @@ interface Boolean { } interface BooleanConstructor { - new (value?: any): Boolean; + new(value?: any): Boolean; (value?: any): boolean; readonly prototype: Boolean; } @@ -477,7 +477,7 @@ interface Number { } interface NumberConstructor { - new (value?: any): Number; + new(value?: any): Number; (value?: any): number; readonly prototype: Number; @@ -779,10 +779,10 @@ interface Date { } interface DateConstructor { - new (): Date; - new (value: number): Date; - new (value: string): Date; - new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + new(): Date; + new(value: number): Date; + new(value: string): Date; + new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; /** @@ -848,8 +848,8 @@ interface RegExp { } interface RegExpConstructor { - new (pattern: RegExp | string): RegExp; - new (pattern: string, flags?: string): RegExp; + new(pattern: RegExp | string): RegExp; + new(pattern: string, flags?: string): RegExp; (pattern: RegExp | string): RegExp; (pattern: string, flags?: string): RegExp; readonly prototype: RegExp; @@ -876,7 +876,7 @@ interface Error { } interface ErrorConstructor { - new (message?: string): Error; + new(message?: string): Error; (message?: string): Error; readonly prototype: Error; } @@ -887,7 +887,7 @@ interface EvalError extends Error { } interface EvalErrorConstructor { - new (message?: string): EvalError; + new(message?: string): EvalError; (message?: string): EvalError; readonly prototype: EvalError; } @@ -898,7 +898,7 @@ interface RangeError extends Error { } interface RangeErrorConstructor { - new (message?: string): RangeError; + new(message?: string): RangeError; (message?: string): RangeError; readonly prototype: RangeError; } @@ -909,7 +909,7 @@ interface ReferenceError extends Error { } interface ReferenceErrorConstructor { - new (message?: string): ReferenceError; + new(message?: string): ReferenceError; (message?: string): ReferenceError; readonly prototype: ReferenceError; } @@ -920,7 +920,7 @@ interface SyntaxError extends Error { } interface SyntaxErrorConstructor { - new (message?: string): SyntaxError; + new(message?: string): SyntaxError; (message?: string): SyntaxError; readonly prototype: SyntaxError; } @@ -931,7 +931,7 @@ interface TypeError extends Error { } interface TypeErrorConstructor { - new (message?: string): TypeError; + new(message?: string): TypeError; (message?: string): TypeError; readonly prototype: TypeError; } @@ -942,7 +942,7 @@ interface URIError extends Error { } interface URIErrorConstructor { - new (message?: string): URIError; + new(message?: string): URIError; (message?: string): URIError; readonly prototype: URIError; } @@ -992,12 +992,10 @@ interface ReadonlyArray { * Returns a string representation of an array. */ toString(): string; - toLocaleString(): string; /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. + * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. */ - concat>(...items: U[]): T[]; + toLocaleString(): string; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. @@ -1025,7 +1023,6 @@ interface ReadonlyArray { * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; - /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. @@ -1037,49 +1034,37 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean): boolean; - every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean): boolean; - some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => void): void; - forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => void, thisArg: Z): void; + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => U): U[]; - map(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => U, thisArg: undefined): U[]; - map(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => U, thisArg: Z): U[]; + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => value is S): S[]; - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => value is S, thisArg: undefined): S[]; - filter(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => value is S, thisArg: Z): S[]; + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => any): T[]; - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => any, thisArg: undefined): T[]; - filter(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => any, thisArg: Z): T[]; + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1117,6 +1102,9 @@ interface Array { * Returns a string representation of an array. */ toString(): string; + /** + * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. + */ toLocaleString(): string; /** * Appends new elements to an array, and returns the new length of the array. @@ -1196,73 +1184,37 @@ interface Array { * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean; - every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean; - some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void): void; - forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: T, index: number, array: T[]) => void, thisArg: Z): void; + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - map(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U, U]; - map(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U, U]; - map(this: [T, T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U, U]; + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U]; - map(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U]; - map(this: [T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U]; - map(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U]; - map(this: [T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U]; - map(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U]; - map(this: [T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (this: void, value: T, index: number, array: T[]) => U): U[]; - map(callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): U[]; - map(callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): U[]; + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any): T[]; - filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any, thisArg: undefined): T[]; - filter(callbackfn: (this: Z, value: T, index: number, array: T[]) => any, thisArg: Z): T[]; + filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1292,7 +1244,7 @@ interface Array { } interface ArrayConstructor { - new (arrayLength?: number): any[]; + new(arrayLength?: number): any[]; new (arrayLength: number): T[]; new (...items: T[]): T[]; (arrayLength?: number): any[]; @@ -1416,7 +1368,7 @@ type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; - new (byteLength: number): ArrayBuffer; + new(byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } declare const ArrayBuffer: ArrayBufferConstructor; @@ -1567,7 +1519,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; + new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1615,9 +1567,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -1636,9 +1586,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any): Int8Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any, thisArg: undefined): Int8Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => any, thisArg: Z): Int8Array; + filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -1649,9 +1597,7 @@ interface Int8Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1662,9 +1608,7 @@ interface Int8Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1673,9 +1617,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -1713,9 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number): Int8Array; - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg: undefined): Int8Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => number, thisArg: Z): Int8Array; + map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1792,9 +1732,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -1825,9 +1763,9 @@ interface Int8Array { } interface Int8ArrayConstructor { readonly prototype: Int8Array; - new (length: number): Int8Array; - new (array: ArrayLike): Int8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new(length: number): Int8Array; + new(array: ArrayLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1846,11 +1784,8 @@ interface Int8ArrayConstructor { * @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: number, k: number) => number): Int8Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; - from(arrayLike: ArrayLike): Int8Array; } declare const Int8Array: Int8ArrayConstructor; @@ -1899,9 +1834,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -1920,9 +1853,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any): Uint8Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any, thisArg: undefined): Uint8Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => any, thisArg: Z): Uint8Array; + filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -1933,9 +1864,7 @@ interface Uint8Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1946,9 +1875,7 @@ interface Uint8Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1957,9 +1884,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -1997,9 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number): Uint8Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg: undefined): Uint8Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => number, thisArg: Z): Uint8Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2076,9 +1999,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2110,9 +2031,9 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new(length: number): Uint8Array; + new(array: ArrayLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2131,11 +2052,7 @@ interface Uint8ArrayConstructor { * @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: number, k: number) => number): Uint8Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: ArrayLike): Uint8Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } declare const Uint8Array: Uint8ArrayConstructor; @@ -2184,9 +2101,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2205,9 +2120,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any): Uint8ClampedArray; - filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: undefined): Uint8ClampedArray; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: Z): Uint8ClampedArray; + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2218,9 +2131,7 @@ interface Uint8ClampedArray { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2231,9 +2142,7 @@ interface Uint8ClampedArray { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2242,9 +2151,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2282,9 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number): Uint8ClampedArray; - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: undefined): Uint8ClampedArray; - map(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: Z): Uint8ClampedArray; + map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2361,9 +2266,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2395,9 +2298,9 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; - new (length: number): Uint8ClampedArray; - new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new(length: number): Uint8ClampedArray; + new(array: ArrayLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2416,11 +2319,7 @@ interface Uint8ClampedArrayConstructor { * @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: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: ArrayLike): Uint8ClampedArray; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; @@ -2468,9 +2367,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2489,9 +2386,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any): Int16Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg: undefined): Int16Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => any, thisArg: Z): Int16Array; + filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2502,9 +2397,7 @@ interface Int16Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2515,9 +2408,7 @@ interface Int16Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2526,10 +2417,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => void, thisArg: Z): void; - + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -2566,9 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number): Int16Array; - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg: undefined): Int16Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => number, thisArg: Z): Int16Array; + map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2645,9 +2531,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2679,9 +2563,9 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; - new (length: number): Int16Array; - new (array: ArrayLike): Int16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new(length: number): Int16Array; + new(array: ArrayLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2700,11 +2584,8 @@ interface Int16ArrayConstructor { * @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: number, k: number) => number): Int16Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; - from(arrayLike: ArrayLike): Int16Array; } declare const Int16Array: Int16ArrayConstructor; @@ -2753,9 +2634,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2774,9 +2653,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any): Uint16Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any, thisArg: undefined): Uint16Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => any, thisArg: Z): Uint16Array; + filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2787,9 +2664,7 @@ interface Uint16Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2800,9 +2675,7 @@ interface Uint16Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2811,9 +2684,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2851,9 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number): Uint16Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg: undefined): Uint16Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => number, thisArg: Z): Uint16Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2930,9 +2799,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2964,9 +2831,9 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new(length: number): Uint16Array; + new(array: ArrayLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2985,11 +2852,8 @@ interface Uint16ArrayConstructor { * @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: number, k: number) => number): Uint16Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; - from(arrayLike: ArrayLike): Uint16Array; } declare const Uint16Array: Uint16ArrayConstructor; @@ -3037,9 +2901,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3058,9 +2920,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any): Int32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any, thisArg: undefined): Int32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => any, thisArg: Z): Int32Array; + filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3071,9 +2931,7 @@ interface Int32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3084,9 +2942,7 @@ interface Int32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3095,9 +2951,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3135,9 +2989,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number): Int32Array; - map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number, thisArg: undefined): Int32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => number, thisArg: Z): Int32Array; + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3214,9 +3066,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3248,9 +3098,9 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; - new (length: number): Int32Array; - new (array: ArrayLike): Int32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new(length: number): Int32Array; + new(array: ArrayLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3269,11 +3119,8 @@ interface Int32ArrayConstructor { * @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: number, k: number) => number): Int32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; - from(arrayLike: ArrayLike): Int32Array; } declare const Int32Array: Int32ArrayConstructor; @@ -3321,9 +3168,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3342,9 +3187,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any): Uint32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any, thisArg: undefined): Uint32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => any, thisArg: Z): Uint32Array; + filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3355,9 +3198,7 @@ interface Uint32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3368,9 +3209,7 @@ interface Uint32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3379,10 +3218,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => void, thisArg: Z): void; - + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -3419,9 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number): Uint32Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg: undefined): Uint32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => number, thisArg: Z): Uint32Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3498,9 +3332,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3532,9 +3364,9 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new(length: number): Uint32Array; + new(array: ArrayLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3553,11 +3385,8 @@ interface Uint32ArrayConstructor { * @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: number, k: number) => number): Uint32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; - from(arrayLike: ArrayLike): Uint32Array; } declare const Uint32Array: Uint32ArrayConstructor; @@ -3605,9 +3434,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3626,9 +3453,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any): Float32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any, thisArg: undefined): Float32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => any, thisArg: Z): Float32Array; + filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3639,9 +3464,7 @@ interface Float32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3652,9 +3475,7 @@ interface Float32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3663,9 +3484,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3703,9 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number): Float32Array; - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg: undefined): Float32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => number, thisArg: Z): Float32Array; + map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3782,9 +3599,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3816,9 +3631,9 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; - new (length: number): Float32Array; - new (array: ArrayLike): Float32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new(length: number): Float32Array; + new(array: ArrayLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3837,11 +3652,8 @@ interface Float32ArrayConstructor { * @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: number, k: number) => number): Float32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; - from(arrayLike: ArrayLike): Float32Array; } declare const Float32Array: Float32ArrayConstructor; @@ -3890,9 +3702,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3911,9 +3721,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any): Float64Array; - filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any, thisArg: undefined): Float64Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => any, thisArg: Z): Float64Array; + filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3924,9 +3732,7 @@ interface Float64Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3937,9 +3743,7 @@ interface Float64Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3948,9 +3752,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3988,9 +3790,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number): Float64Array; - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg: undefined): Float64Array; - map(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => number, thisArg: Z): Float64Array; + map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -4067,9 +3867,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -4101,9 +3899,9 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; - new (length: number): Float64Array; - new (array: ArrayLike): Float64Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new(length: number): Float64Array; + new(array: ArrayLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4122,11 +3920,8 @@ interface Float64ArrayConstructor { * @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: number, k: number) => number): Float64Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; - from(arrayLike: ArrayLike): Float64Array; } declare const Float64Array: Float64ArrayConstructor; @@ -4159,7 +3954,7 @@ declare namespace Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new (locales?: string | string[], options?: CollatorOptions): Collator; + new(locales?: string | string[], options?: CollatorOptions): Collator; (locales?: string | string[], options?: CollatorOptions): Collator; supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; }; @@ -4196,7 +3991,7 @@ declare namespace Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; }; @@ -4239,7 +4034,7 @@ declare namespace Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; }; diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 4d2428a59ba..588c609a164 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -87,8 +87,8 @@ interface PropertyDescriptor { enumerable?: boolean; value?: any; writable?: boolean; - get? (): any; - set? (v: any): void; + get?(): any; + set?(v: any): void; } interface PropertyDescriptorMap { @@ -128,7 +128,7 @@ interface Object { } interface ObjectConstructor { - new (value?: any): Object; + new(value?: any): Object; (): any; (value: any): any; @@ -286,7 +286,7 @@ interface FunctionConstructor { * Creates a new function. * @param args A list of arguments the function accepts. */ - new (...args: string[]): Function; + new(...args: string[]): Function; (...args: string[]): Function; readonly prototype: Function; } @@ -423,7 +423,7 @@ interface String { } interface StringConstructor { - new (value?: any): String; + new(value?: any): String; (value?: any): string; readonly prototype: String; fromCharCode(...codes: number[]): string; @@ -440,7 +440,7 @@ interface Boolean { } interface BooleanConstructor { - new (value?: any): Boolean; + new(value?: any): Boolean; (value?: any): boolean; readonly prototype: Boolean; } @@ -477,7 +477,7 @@ interface Number { } interface NumberConstructor { - new (value?: any): Number; + new(value?: any): Number; (value?: any): number; readonly prototype: Number; @@ -779,10 +779,10 @@ interface Date { } interface DateConstructor { - new (): Date; - new (value: number): Date; - new (value: string): Date; - new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; + new(): Date; + new(value: number): Date; + new(value: string): Date; + new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; /** @@ -848,8 +848,8 @@ interface RegExp { } interface RegExpConstructor { - new (pattern: RegExp | string): RegExp; - new (pattern: string, flags?: string): RegExp; + new(pattern: RegExp | string): RegExp; + new(pattern: string, flags?: string): RegExp; (pattern: RegExp | string): RegExp; (pattern: string, flags?: string): RegExp; readonly prototype: RegExp; @@ -876,7 +876,7 @@ interface Error { } interface ErrorConstructor { - new (message?: string): Error; + new(message?: string): Error; (message?: string): Error; readonly prototype: Error; } @@ -887,7 +887,7 @@ interface EvalError extends Error { } interface EvalErrorConstructor { - new (message?: string): EvalError; + new(message?: string): EvalError; (message?: string): EvalError; readonly prototype: EvalError; } @@ -898,7 +898,7 @@ interface RangeError extends Error { } interface RangeErrorConstructor { - new (message?: string): RangeError; + new(message?: string): RangeError; (message?: string): RangeError; readonly prototype: RangeError; } @@ -909,7 +909,7 @@ interface ReferenceError extends Error { } interface ReferenceErrorConstructor { - new (message?: string): ReferenceError; + new(message?: string): ReferenceError; (message?: string): ReferenceError; readonly prototype: ReferenceError; } @@ -920,7 +920,7 @@ interface SyntaxError extends Error { } interface SyntaxErrorConstructor { - new (message?: string): SyntaxError; + new(message?: string): SyntaxError; (message?: string): SyntaxError; readonly prototype: SyntaxError; } @@ -931,7 +931,7 @@ interface TypeError extends Error { } interface TypeErrorConstructor { - new (message?: string): TypeError; + new(message?: string): TypeError; (message?: string): TypeError; readonly prototype: TypeError; } @@ -942,7 +942,7 @@ interface URIError extends Error { } interface URIErrorConstructor { - new (message?: string): URIError; + new(message?: string): URIError; (message?: string): URIError; readonly prototype: URIError; } @@ -992,12 +992,10 @@ interface ReadonlyArray { * Returns a string representation of an array. */ toString(): string; - toLocaleString(): string; /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. + * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. */ - concat>(...items: U[]): T[]; + toLocaleString(): string; /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. @@ -1025,7 +1023,6 @@ interface ReadonlyArray { * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; - /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. @@ -1037,49 +1034,37 @@ interface ReadonlyArray { * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean): boolean; - every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean): boolean; - some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => void): void; - forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => void, thisArg: Z): void; + forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => U): U[]; - map(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => U, thisArg: undefined): U[]; - map(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => U, thisArg: Z): U[]; + map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => value is S): S[]; - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => value is S, thisArg: undefined): S[]; - filter(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => value is S, thisArg: Z): S[]; + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => any): T[]; - filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray) => any, thisArg: undefined): T[]; - filter(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray) => any, thisArg: Z): T[]; + filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1117,6 +1102,9 @@ interface Array { * Returns a string representation of an array. */ toString(): string; + /** + * Returns a string representation of an array. The elements are converted to string using thier toLocalString methods. + */ toLocaleString(): string; /** * Appends new elements to an array, and returns the new length of the array. @@ -1196,73 +1184,37 @@ interface Array { * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean; - every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean; - some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void): void; - forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: T, index: number, array: T[]) => void, thisArg: Z): void; + forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - map(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U, U]; - map(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U, U]; - map(this: [T, T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U, U]; + map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U]; - map(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U]; - map(this: [T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U]; - map(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U]; - map(this: [T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U]; - map(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U]; - map(this: [T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U]; - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map(callbackfn: (this: void, value: T, index: number, array: T[]) => U): U[]; - map(callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): U[]; - map(callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): U[]; + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any): T[]; - filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any, thisArg: undefined): T[]; - filter(callbackfn: (this: Z, value: T, index: number, array: T[]) => any, thisArg: Z): T[]; + filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. @@ -1292,7 +1244,7 @@ interface Array { } interface ArrayConstructor { - new (arrayLength?: number): any[]; + new(arrayLength?: number): any[]; new (arrayLength: number): T[]; new (...items: T[]): T[]; (arrayLength?: number): any[]; @@ -1416,7 +1368,7 @@ type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; - new (byteLength: number): ArrayBuffer; + new(byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } declare const ArrayBuffer: ArrayBufferConstructor; @@ -1567,7 +1519,7 @@ interface DataView { } interface DataViewConstructor { - new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; + new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; @@ -1615,9 +1567,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -1636,9 +1586,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any): Int8Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any, thisArg: undefined): Int8Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => any, thisArg: Z): Int8Array; + filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -1649,9 +1597,7 @@ interface Int8Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1662,9 +1608,7 @@ interface Int8Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1673,9 +1617,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -1713,9 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number): Int8Array; - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg: undefined): Int8Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => number, thisArg: Z): Int8Array; + map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1792,9 +1732,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -1825,9 +1763,9 @@ interface Int8Array { } interface Int8ArrayConstructor { readonly prototype: Int8Array; - new (length: number): Int8Array; - new (array: ArrayLike): Int8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + new(length: number): Int8Array; + new(array: ArrayLike): Int8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; /** * The size in bytes of each element in the array. @@ -1846,11 +1784,8 @@ interface Int8ArrayConstructor { * @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: number, k: number) => number): Int8Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; - from(arrayLike: ArrayLike): Int8Array; } declare const Int8Array: Int8ArrayConstructor; @@ -1899,9 +1834,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -1920,9 +1853,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any): Uint8Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any, thisArg: undefined): Uint8Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => any, thisArg: Z): Uint8Array; + filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -1933,9 +1864,7 @@ interface Uint8Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1946,9 +1875,7 @@ interface Uint8Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1957,9 +1884,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -1997,9 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number): Uint8Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg: undefined): Uint8Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => number, thisArg: Z): Uint8Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2076,9 +1999,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2110,9 +2031,9 @@ interface Uint8Array { interface Uint8ArrayConstructor { readonly prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: ArrayLike): Uint8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + new(length: number): Uint8Array; + new(array: ArrayLike): Uint8Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; /** * The size in bytes of each element in the array. @@ -2131,11 +2052,7 @@ interface Uint8ArrayConstructor { * @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: number, k: number) => number): Uint8Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array; - - from(arrayLike: ArrayLike): Uint8Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } declare const Uint8Array: Uint8ArrayConstructor; @@ -2184,9 +2101,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2205,9 +2120,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any): Uint8ClampedArray; - filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: undefined): Uint8ClampedArray; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: Z): Uint8ClampedArray; + filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2218,9 +2131,7 @@ interface Uint8ClampedArray { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2231,9 +2142,7 @@ interface Uint8ClampedArray { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2242,9 +2151,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2282,9 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number): Uint8ClampedArray; - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: undefined): Uint8ClampedArray; - map(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: Z): Uint8ClampedArray; + map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2361,9 +2266,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2395,9 +2298,9 @@ interface Uint8ClampedArray { interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; - new (length: number): Uint8ClampedArray; - new (array: ArrayLike): Uint8ClampedArray; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + new(length: number): Uint8ClampedArray; + new(array: ArrayLike): Uint8ClampedArray; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2416,11 +2319,7 @@ interface Uint8ClampedArrayConstructor { * @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: number, k: number) => number): Uint8ClampedArray; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray; - - from(arrayLike: ArrayLike): Uint8ClampedArray; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; @@ -2468,9 +2367,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2489,9 +2386,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any): Int16Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg: undefined): Int16Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => any, thisArg: Z): Int16Array; + filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2502,9 +2397,7 @@ interface Int16Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2515,9 +2408,7 @@ interface Int16Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2526,10 +2417,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => void, thisArg: Z): void; - + forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -2566,9 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number): Int16Array; - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg: undefined): Int16Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => number, thisArg: Z): Int16Array; + map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2645,9 +2531,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2679,9 +2563,9 @@ interface Int16Array { interface Int16ArrayConstructor { readonly prototype: Int16Array; - new (length: number): Int16Array; - new (array: ArrayLike): Int16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + new(length: number): Int16Array; + new(array: ArrayLike): Int16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; /** * The size in bytes of each element in the array. @@ -2700,11 +2584,8 @@ interface Int16ArrayConstructor { * @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: number, k: number) => number): Int16Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; - from(arrayLike: ArrayLike): Int16Array; } declare const Int16Array: Int16ArrayConstructor; @@ -2753,9 +2634,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -2774,9 +2653,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any): Uint16Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any, thisArg: undefined): Uint16Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => any, thisArg: Z): Uint16Array; + filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2787,9 +2664,7 @@ interface Uint16Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2800,9 +2675,7 @@ interface Uint16Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2811,9 +2684,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2851,9 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number): Uint16Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg: undefined): Uint16Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => number, thisArg: Z): Uint16Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2930,9 +2799,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -2964,9 +2831,9 @@ interface Uint16Array { interface Uint16ArrayConstructor { readonly prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: ArrayLike): Uint16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + new(length: number): Uint16Array; + new(array: ArrayLike): Uint16Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; /** * The size in bytes of each element in the array. @@ -2985,11 +2852,8 @@ interface Uint16ArrayConstructor { * @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: number, k: number) => number): Uint16Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; - from(arrayLike: ArrayLike): Uint16Array; } declare const Uint16Array: Uint16ArrayConstructor; @@ -3037,9 +2901,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3058,9 +2920,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any): Int32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any, thisArg: undefined): Int32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => any, thisArg: Z): Int32Array; + filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3071,9 +2931,7 @@ interface Int32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3084,9 +2942,7 @@ interface Int32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3095,9 +2951,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3135,9 +2989,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number): Int32Array; - map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number, thisArg: undefined): Int32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => number, thisArg: Z): Int32Array; + map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3214,9 +3066,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3248,9 +3098,9 @@ interface Int32Array { interface Int32ArrayConstructor { readonly prototype: Int32Array; - new (length: number): Int32Array; - new (array: ArrayLike): Int32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + new(length: number): Int32Array; + new(array: ArrayLike): Int32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; /** * The size in bytes of each element in the array. @@ -3269,11 +3119,8 @@ interface Int32ArrayConstructor { * @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: number, k: number) => number): Int32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; - from(arrayLike: ArrayLike): Int32Array; } declare const Int32Array: Int32ArrayConstructor; @@ -3321,9 +3168,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3342,9 +3187,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any): Uint32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any, thisArg: undefined): Uint32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => any, thisArg: Z): Uint32Array; + filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3355,9 +3198,7 @@ interface Uint32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3368,9 +3209,7 @@ interface Uint32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3379,10 +3218,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => void, thisArg: Z): void; - + forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -3419,9 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number): Uint32Array; - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg: undefined): Uint32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => number, thisArg: Z): Uint32Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3498,9 +3332,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3532,9 +3364,9 @@ interface Uint32Array { interface Uint32ArrayConstructor { readonly prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: ArrayLike): Uint32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + new(length: number): Uint32Array; + new(array: ArrayLike): Uint32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; /** * The size in bytes of each element in the array. @@ -3553,11 +3385,8 @@ interface Uint32ArrayConstructor { * @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: number, k: number) => number): Uint32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; - from(arrayLike: ArrayLike): Uint32Array; } declare const Uint32Array: Uint32ArrayConstructor; @@ -3605,9 +3434,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3626,9 +3453,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any): Float32Array; - filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any, thisArg: undefined): Float32Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => any, thisArg: Z): Float32Array; + filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3639,9 +3464,7 @@ interface Float32Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3652,9 +3475,7 @@ interface Float32Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3663,9 +3484,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3703,9 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number): Float32Array; - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg: undefined): Float32Array; - map(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => number, thisArg: Z): Float32Array; + map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3782,9 +3599,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -3816,9 +3631,9 @@ interface Float32Array { interface Float32ArrayConstructor { readonly prototype: Float32Array; - new (length: number): Float32Array; - new (array: ArrayLike): Float32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + new(length: number): Float32Array; + new(array: ArrayLike): Float32Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; /** * The size in bytes of each element in the array. @@ -3837,11 +3652,8 @@ interface Float32ArrayConstructor { * @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: number, k: number) => number): Float32Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; - from(arrayLike: ArrayLike): Float32Array; } declare const Float32Array: Float32ArrayConstructor; @@ -3890,9 +3702,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean; - every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean; - every(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean; + every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value @@ -3911,9 +3721,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any): Float64Array; - filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any, thisArg: undefined): Float64Array; - filter(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => any, thisArg: Z): Float64Array; + filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3924,9 +3732,7 @@ interface Float64Array { * @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: number, index: number, obj: Array) => boolean): number | undefined; - find(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number | undefined; - find(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number | undefined; + find(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3937,9 +3743,7 @@ interface Float64Array { * @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: number, index: number, obj: Array) => boolean): number; - findIndex(predicate: (this: void, value: number, index: number, obj: Array) => boolean, thisArg: undefined): number; - findIndex(predicate: (this: Z, value: number, index: number, obj: Array) => boolean, thisArg: Z): number; + findIndex(predicate: (value: number, index: number, obj: Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3948,9 +3752,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void): void; - forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void, thisArg: undefined): void; - forEach(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => void, thisArg: Z): void; + forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3988,9 +3790,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number): Float64Array; - map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg: undefined): Float64Array; - map(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => number, thisArg: Z): Float64Array; + map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -4067,9 +3867,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean; - some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean; - some(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean; + some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; /** * Sorts an array. @@ -4101,9 +3899,9 @@ interface Float64Array { interface Float64ArrayConstructor { readonly prototype: Float64Array; - new (length: number): Float64Array; - new (array: ArrayLike): Float64Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + new(length: number): Float64Array; + new(array: ArrayLike): Float64Array; + new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; /** * The size in bytes of each element in the array. @@ -4122,11 +3920,8 @@ interface Float64ArrayConstructor { * @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: number, k: number) => number): Float64Array; - from(arrayLike: ArrayLike, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array; - from(arrayLike: ArrayLike, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array; + from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; - from(arrayLike: ArrayLike): Float64Array; } declare const Float64Array: Float64ArrayConstructor; @@ -4159,7 +3954,7 @@ declare namespace Intl { resolvedOptions(): ResolvedCollatorOptions; } var Collator: { - new (locales?: string | string[], options?: CollatorOptions): Collator; + new(locales?: string | string[], options?: CollatorOptions): Collator; (locales?: string | string[], options?: CollatorOptions): Collator; supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[]; }; @@ -4196,7 +3991,7 @@ declare namespace Intl { resolvedOptions(): ResolvedNumberFormatOptions; } var NumberFormat: { - new (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; + new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat; (locales?: string | string[], options?: NumberFormatOptions): NumberFormat; supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[]; }; @@ -4239,7 +4034,7 @@ declare namespace Intl { resolvedOptions(): ResolvedDateTimeFormatOptions; } var DateTimeFormat: { - new (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; + new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat; supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[]; }; @@ -6113,15 +5908,15 @@ interface Float64Array { ///////////////////////////// -/// IE DOM APIs +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -6134,32 +5929,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 { @@ -6199,13 +5994,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -6219,15 +6007,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 { @@ -6236,17 +6024,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 { @@ -6256,9 +6051,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -6271,6 +6065,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -6283,17 +6078,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 { @@ -6320,11 +6115,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -6349,39 +6144,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; @@ -6393,31 +6302,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 { @@ -6435,8 +6349,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -6446,12 +6360,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 { @@ -6459,35 +6373,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 { @@ -6497,28 +6411,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; } @@ -6536,13 +6450,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -6550,241 +6464,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 { @@ -6793,39 +6588,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; @@ -6835,9 +6630,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -6846,14 +6641,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 { @@ -6862,8 +6657,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -6873,38 +6668,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 { @@ -6912,15 +6732,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 { @@ -6935,19 +6755,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 { @@ -6957,285 +6777,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 { @@ -7247,13 +7042,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 { @@ -7262,11 +7057,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 { @@ -7274,10 +7069,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -7296,19 +7091,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; @@ -7324,8 +7106,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; @@ -7335,7 +7130,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -7380,7 +7175,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -7393,7 +7188,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -7408,7 +7203,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -7431,7 +7226,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -7477,7 +7272,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -7486,7 +7281,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -7499,7 +7294,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -7518,7 +7313,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -7534,7 +7329,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -7545,7 +7340,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -7559,7 +7354,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -7582,7 +7377,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -7591,7 +7386,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -7600,13 +7395,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; } @@ -7614,7 +7409,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -7627,16 +7422,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; } @@ -7649,7 +7733,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -7658,7 +7742,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -7669,7 +7753,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -7680,7 +7764,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -7690,7 +7774,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -7703,7 +7787,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -7712,7 +7796,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -7722,7 +7806,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -7734,7 +7818,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -7744,8 +7828,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; @@ -7761,8 +7845,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; @@ -7770,7 +7854,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -7781,13 +7865,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; @@ -7863,9 +7947,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; @@ -7935,24 +8019,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; @@ -8088,9 +8172,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; @@ -8142,7 +8226,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -8153,7 +8237,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -8179,7 +8263,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -8187,296 +8271,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; @@ -8486,150 +8281,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; @@ -8640,7 +8292,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -8657,7 +8309,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -8670,7 +8322,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -8684,7 +8336,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -8697,7 +8349,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -8706,7 +8358,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -8717,7 +8369,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -8726,7 +8378,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -8739,7 +8391,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -8752,7 +8404,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -8763,7 +8415,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -8858,299 +8510,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; @@ -9170,146 +8814,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; @@ -9318,243 +8970,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; @@ -9563,7 +9215,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; @@ -9572,7 +9224,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -9586,8 +9238,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; @@ -9596,8 +9391,8 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; - new(): DragEvent; -} + new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -9611,27 +9406,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; @@ -9712,9 +9487,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]; @@ -9732,18 +9507,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; @@ -9754,9 +9529,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; @@ -9765,7 +9540,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -9779,12 +9554,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; @@ -9811,7 +9586,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; @@ -9822,8 +9597,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; @@ -9837,7 +9632,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -9845,7 +9640,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -9856,7 +9651,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; @@ -9867,7 +9662,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -9882,7 +9677,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -9892,7 +9687,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -9906,7 +9701,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; @@ -9920,7 +9715,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -9929,7 +9724,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -9944,7 +9739,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -9954,7 +9749,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -9963,7 +9758,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -9974,8 +9769,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; @@ -9986,87 +9821,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; @@ -10075,70 +9910,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; @@ -10149,66 +9984,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; @@ -10217,7 +10052,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -10225,7 +10060,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; @@ -10235,30 +10070,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; @@ -10267,16 +10088,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; @@ -10285,7 +10106,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -10344,71 +10165,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; @@ -10417,32 +10252,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; @@ -10452,42 +10287,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; @@ -10498,7 +10322,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -10509,7 +10333,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -10520,16 +10344,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; @@ -10538,8 +10362,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; @@ -10548,7 +10383,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -10721,54 +10556,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; @@ -10777,39 +10612,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; @@ -10818,12 +10653,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; @@ -10832,7 +10667,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -10841,74 +10676,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; @@ -10918,7 +10753,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -10926,68 +10761,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; @@ -10996,7 +10831,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -11023,33 +10858,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; @@ -11065,8 +10900,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; @@ -11075,29 +10910,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; @@ -11108,12 +10921,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; @@ -11122,12 +10935,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; @@ -11136,7 +10971,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -11144,79 +10979,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; @@ -11225,86 +11060,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; @@ -11316,210 +11151,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; @@ -11528,31 +11363,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; @@ -11561,16 +11381,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; @@ -11579,41 +11399,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; @@ -11624,16 +11459,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; @@ -11642,7 +11477,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -11674,7 +11509,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -11683,162 +11518,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; @@ -11865,7 +11700,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -11877,32 +11712,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; @@ -11911,7 +11746,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -11927,16 +11762,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; @@ -11945,13 +11780,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; @@ -11961,154 +11913,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; @@ -12117,37 +11952,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; @@ -12156,7 +11991,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -12168,7 +12003,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -12190,12 +12025,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; @@ -12205,24 +12040,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; @@ -12231,7 +12066,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; @@ -12241,12 +12076,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; @@ -12255,24 +12090,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; @@ -12281,12 +12116,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; @@ -12295,38 +12130,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; @@ -12336,94 +12171,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; @@ -12433,18 +12268,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; /** @@ -12458,7 +12293,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; @@ -12468,17 +12303,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; @@ -12487,16 +12322,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; @@ -12505,53 +12340,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; @@ -12560,20 +12395,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; @@ -12582,7 +12417,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; @@ -12592,111 +12427,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; @@ -12705,12 +12540,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; @@ -12719,39 +12554,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; @@ -12760,26 +12595,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; @@ -12788,7 +12623,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -12799,105 +12634,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; @@ -12906,7 +12741,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -12917,12 +12752,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; @@ -12931,7 +12766,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -12956,7 +12791,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -12968,7 +12803,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; @@ -12978,7 +12813,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -12988,8 +12823,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; @@ -13001,31 +12836,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; } @@ -13033,47 +12868,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; @@ -13097,7 +12892,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -13106,7 +12901,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -13123,7 +12918,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; @@ -13132,7 +12927,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -13143,7 +12938,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -13154,14 +12949,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; @@ -13177,7 +12972,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; @@ -13193,14 +12988,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; @@ -13217,7 +13012,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -13225,7 +13020,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; @@ -13239,7 +13034,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -13249,7 +13044,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; @@ -13269,7 +13064,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -13279,7 +13074,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -13288,7 +13083,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -13300,7 +13095,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; @@ -13315,7 +13110,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -13329,7 +13124,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -13364,7 +13159,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; @@ -13374,7 +13169,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -13395,7 +13190,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -13405,8 +13200,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; @@ -13455,7 +13632,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -13465,7 +13642,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -13475,7 +13652,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -13485,7 +13662,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -13497,7 +13674,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -13508,7 +13685,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -13517,7 +13694,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -13528,7 +13705,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -13564,7 +13741,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -13574,7 +13751,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -13608,7 +13785,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -13634,7 +13811,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -13663,7 +13840,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; @@ -13685,7 +13862,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; @@ -13695,7 +13872,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -13704,8 +13881,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; @@ -13717,19 +13906,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; @@ -13752,7 +13929,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -13763,7 +13940,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -13773,7 +13950,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -13784,7 +13961,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -13800,7 +13977,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -13835,7 +14012,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; @@ -13845,389 +14022,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; @@ -14247,7 +14042,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -14258,7 +14053,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -14275,7 +14070,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -14292,7 +14087,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -14302,7 +14097,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -14311,7 +14106,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -14320,7 +14115,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; @@ -14337,6 +14132,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; readonly hardwareConcurrency: number; + readonly languages: string[]; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; @@ -14347,7 +14143,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -14422,7 +14218,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -14445,7 +14241,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -14460,7 +14256,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -14471,7 +14267,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -14501,7 +14297,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -14509,7 +14305,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; @@ -14519,7 +14315,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 { } @@ -14527,7 +14323,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -14535,7 +14331,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; @@ -14545,7 +14341,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 { } @@ -14553,7 +14349,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; @@ -14562,7 +14358,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -14580,7 +14376,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -14601,7 +14397,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -14618,7 +14414,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -14627,7 +14423,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -14646,7 +14442,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -14654,7 +14450,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -14674,7 +14470,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -14696,7 +14492,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; @@ -14705,7 +14501,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -14722,8 +14518,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; @@ -14751,157 +14697,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 { } @@ -14909,7 +14705,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -14919,7 +14715,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -14928,7 +14724,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -14944,7 +14740,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -14957,7 +14753,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -14980,7 +14776,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -14990,7 +14786,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -15000,7 +14796,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -15017,7 +14813,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -15026,7 +14822,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -15038,7 +14834,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -15049,7 +14845,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -15062,7 +14858,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -15072,17 +14868,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; @@ -15105,7 +14998,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -15114,7 +15007,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -15135,19 +15028,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; @@ -15156,7 +15058,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -15177,7 +15079,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -15186,7 +15088,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -15215,7 +15117,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -15224,7 +15126,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -15270,7 +15172,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -15279,7 +15181,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -15303,7 +15205,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -15328,7 +15230,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -15339,7 +15241,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -15356,7 +15258,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -15365,7 +15267,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -15375,112 +15277,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; @@ -15490,7 +15701,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -15514,7 +15725,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -15524,7 +15735,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -15534,7 +15745,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -15544,7 +15755,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -15554,7 +15765,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -15564,7 +15775,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -15574,7 +15785,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -15584,7 +15795,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -15594,7 +15805,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -15604,7 +15815,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -15614,7 +15825,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -15624,7 +15835,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -15634,7 +15845,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -15647,7 +15858,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -15658,7 +15869,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -15687,7 +15898,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; @@ -15697,7 +15908,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; @@ -15707,7 +15918,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -15745,7 +15956,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -15761,7 +15972,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -15771,7 +15982,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -15785,7 +15996,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15832,7 +16043,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; @@ -15855,7 +16066,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; @@ -15866,7 +16077,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15897,7 +16108,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; @@ -15927,7 +16138,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; @@ -15942,7 +16153,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -15967,7 +16178,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; @@ -15979,7 +16190,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; @@ -15989,7 +16200,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; @@ -15999,7 +16210,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; @@ -16009,7 +16220,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; @@ -16019,7 +16230,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; @@ -16029,7 +16240,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -16043,7 +16254,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -16054,7 +16265,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; @@ -16064,7 +16275,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -16075,7 +16286,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -16095,7 +16306,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; @@ -16108,7 +16319,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -16121,7 +16332,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -16137,7 +16348,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -16155,7 +16366,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -16166,7 +16377,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -16194,7 +16405,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; @@ -16213,7 +16424,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -16227,7 +16438,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; @@ -16237,7 +16448,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -16258,7 +16469,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; @@ -16275,7 +16486,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -16290,7 +16501,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -16326,7 +16537,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -16342,21 +16553,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; @@ -16370,8 +16567,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; @@ -16382,12 +16593,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; } @@ -16395,13 +16606,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; @@ -16417,7 +16628,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -16442,7 +16653,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; @@ -16452,7 +16663,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -16461,7 +16672,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -16477,7 +16688,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -16510,7 +16721,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -16560,7 +16771,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -16575,7 +16786,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -16590,7 +16801,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -16598,7 +16809,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -16612,7 +16823,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -16626,7 +16837,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -16638,7 +16849,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -16650,7 +16861,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -16662,7 +16873,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -16674,7 +16885,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -16684,7 +16895,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -16694,7 +16905,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -16704,7 +16915,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -16713,7 +16924,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -16722,7 +16933,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -16732,7 +16943,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -16741,7 +16952,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -16750,7 +16961,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -16766,7 +16977,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -16776,7 +16987,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -16786,7 +16997,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -16803,7 +17014,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -16814,7 +17025,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -16830,7 +17041,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; @@ -16840,7 +17051,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; @@ -16850,7 +17061,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -16888,7 +17099,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; @@ -16903,7 +17114,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -16915,7 +17126,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -16931,8 +17142,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; @@ -16992,59 +17255,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; @@ -17054,7 +17265,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; @@ -17064,17 +17275,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; @@ -17101,7 +17302,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; @@ -17111,7 +17312,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -17136,7 +17337,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; @@ -17151,7 +17352,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; @@ -17161,7 +17362,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -17192,7 +17393,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -17210,8 +17411,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; @@ -17233,7 +17444,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -17244,7 +17455,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -17254,7 +17465,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; @@ -17267,420 +17478,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; @@ -17690,7 +17488,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -17701,7 +17499,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -17733,7 +17531,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; @@ -17742,7 +17540,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -17785,7 +17583,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -17809,7 +17607,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -17821,7 +17619,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -17839,7 +17637,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -17850,7 +17648,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -17866,7 +17664,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -17884,7 +17682,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -17895,7 +17693,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -17904,7 +17702,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -17915,7 +17713,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -17935,7 +17733,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -17946,8 +17744,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; @@ -17969,16 +17776,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; @@ -17996,7 +17794,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -18009,7 +17807,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -18023,7 +17821,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -18047,45 +17845,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; @@ -18095,7 +17855,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -18105,7 +17865,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -18117,8 +17877,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; @@ -18128,7 +17926,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -18136,7 +17934,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -18145,7 +17943,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -18153,7 +17951,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -18161,7 +17959,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -18169,7 +17967,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -18177,7 +17975,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -18438,13 +18236,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; @@ -18469,9 +18267,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; @@ -18501,18 +18299,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; @@ -18546,6 +18344,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; @@ -18578,23 +18390,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; @@ -18740,13 +18538,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; @@ -18771,9 +18569,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; @@ -18803,18 +18601,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; @@ -18848,6 +18646,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; @@ -18880,23 +18692,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; @@ -18920,7 +18718,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -18928,7 +18726,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -18939,7 +18737,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -18947,7 +18745,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -18955,7 +18753,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -18995,7 +18793,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -19004,7 +18802,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -19013,7 +18811,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -19026,7 +18824,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -19035,7 +18833,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -19045,7 +18843,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -19055,8 +18853,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; @@ -19092,7 +18900,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -19115,7 +18923,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; @@ -19143,6 +18951,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -19201,6 +19010,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; @@ -19214,8 +19027,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; @@ -19338,9 +19151,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; @@ -19396,7 +19209,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -19413,7 +19226,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; @@ -19423,7 +19236,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -19470,7 +19283,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; @@ -19480,7 +19293,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -19489,7 +19302,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -19500,7 +19313,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -19509,7 +19322,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -19518,7 +19331,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -19555,7 +19368,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -19571,17 +19384,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; @@ -19618,6 +19421,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; } @@ -19626,81 +19504,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; @@ -19745,16 +19548,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; } @@ -19979,38 +19782,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; @@ -20258,7 +20061,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -20308,8 +20111,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; @@ -20317,59 +20162,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; @@ -20457,48 +20260,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; @@ -20523,307 +20305,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; @@ -20831,8 +20373,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; @@ -20955,9 +20497,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; @@ -21076,6 +20618,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"; @@ -21089,6 +20632,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"; @@ -21096,12 +20645,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"; @@ -21113,6 +20656,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"; @@ -21120,9 +20671,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"; @@ -21133,14 +20684,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/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index 70db6a78452..4d06a07f65e 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -22,1841 +22,17 @@ 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 +/// DOM APIs ///////////////////////////// interface Account { - rpDisplayName?: string; displayName?: string; id?: string; - name?: string; imageURL?: string; + name?: string; + rpDisplayName?: string; } interface Algorithm { @@ -1869,32 +45,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 { @@ -1934,13 +110,6 @@ interface CustomEventInit extends EventInit { detail?: any; } -interface DOMRectInit { - x?: any; - y?: any; - width?: any; - height?: any; -} - interface DeviceAccelerationDict { x?: number; y?: number; @@ -1954,15 +123,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 { @@ -1971,17 +140,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 { @@ -1991,9 +167,8 @@ interface EventInit { } interface EventModifierInit extends UIEventInit { - ctrlKey?: boolean; - shiftKey?: boolean; altKey?: boolean; + ctrlKey?: boolean; metaKey?: boolean; modifierAltGraph?: boolean; modifierCapsLock?: boolean; @@ -2006,6 +181,7 @@ interface EventModifierInit extends UIEventInit { modifierSuper?: boolean; modifierSymbol?: boolean; modifierSymbolLock?: boolean; + shiftKey?: boolean; } interface ExceptionInformation { @@ -2018,17 +194,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 { @@ -2055,11 +231,11 @@ interface IDBObjectStoreParameters { } interface IntersectionObserverEntryInit { - time?: number; - rootBounds?: DOMRectInit; boundingClientRect?: DOMRectInit; intersectionRect?: DOMRectInit; + rootBounds?: DOMRectInit; target?: Element; + time?: number; } interface IntersectionObserverInit { @@ -2084,39 +260,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; @@ -2128,31 +418,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 { @@ -2170,8 +465,8 @@ interface MSCredentialParameters { } interface MSCredentialSpec { - type?: MSCredentialType; id?: string; + type?: MSCredentialType; } interface MSDelay { @@ -2181,12 +476,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 { @@ -2194,35 +489,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 { @@ -2232,28 +527,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; } @@ -2271,13 +566,13 @@ interface MSPayloadBase extends RTCStats { } interface MSPortRange { - min?: number; max?: number; + min?: number; } interface MSRelayAddress { - relayAddress?: string; port?: number; + relayAddress?: string; } interface MSSignatureParameters { @@ -2285,241 +580,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 { @@ -2528,39 +704,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; @@ -2570,9 +746,9 @@ interface PaymentRequestUpdateEventInit extends EventInit { } interface PaymentShippingOption { + amount?: PaymentCurrencyAmount; id?: string; label?: string; - amount?: PaymentCurrencyAmount; selected?: boolean; } @@ -2581,14 +757,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 { @@ -2597,8 +773,8 @@ interface PopStateEventInit extends EventInit { interface PositionOptions { enableHighAccuracy?: boolean; - timeout?: number; maximumAge?: number; + timeout?: number; } interface ProgressEventInit extends EventInit { @@ -2608,38 +784,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 { @@ -2647,15 +848,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 { @@ -2670,19 +871,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 { @@ -2692,285 +893,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 { @@ -2982,13 +1158,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 { @@ -2997,11 +1173,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 { @@ -3009,10 +1185,10 @@ interface WebGLContextEventInit extends EventInit { } interface WheelEventInit extends MouseEventInit { + deltaMode?: number; deltaX?: number; deltaY?: number; deltaZ?: number; - deltaMode?: number; } interface EventListener { @@ -3031,19 +1207,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; @@ -3059,8 +1222,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; @@ -3070,7 +1246,7 @@ interface AnimationEvent extends Event { declare var AnimationEvent: { prototype: AnimationEvent; new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent; -} +}; interface ApplicationCacheEventMap { "cached": Event; @@ -3115,7 +1291,7 @@ declare var ApplicationCache: { readonly OBSOLETE: number; readonly UNCACHED: number; readonly UPDATEREADY: number; -} +}; interface Attr extends Node { readonly name: string; @@ -3128,7 +1304,7 @@ interface Attr extends Node { declare var Attr: { prototype: Attr; new(): Attr; -} +}; interface AudioBuffer { readonly duration: number; @@ -3143,7 +1319,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface AudioBufferSourceNodeEventMap { "ended": MediaStreamErrorEvent; @@ -3166,7 +1342,7 @@ interface AudioBufferSourceNode extends AudioNode { declare var AudioBufferSourceNode: { prototype: AudioBufferSourceNode; new(): AudioBufferSourceNode; -} +}; interface AudioContextEventMap { "statechange": Event; @@ -3212,7 +1388,7 @@ interface AudioContext extends AudioContextBase { declare var AudioContext: { prototype: AudioContext; new(): AudioContext; -} +}; interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; @@ -3221,7 +1397,7 @@ interface AudioDestinationNode extends AudioNode { declare var AudioDestinationNode: { prototype: AudioDestinationNode; new(): AudioDestinationNode; -} +}; interface AudioListener { dopplerFactor: number; @@ -3234,7 +1410,7 @@ interface AudioListener { declare var AudioListener: { prototype: AudioListener; new(): AudioListener; -} +}; interface AudioNode extends EventTarget { channelCount: number; @@ -3253,7 +1429,7 @@ interface AudioNode extends EventTarget { declare var AudioNode: { prototype: AudioNode; new(): AudioNode; -} +}; interface AudioParam { readonly defaultValue: number; @@ -3269,7 +1445,7 @@ interface AudioParam { declare var AudioParam: { prototype: AudioParam; new(): AudioParam; -} +}; interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; @@ -3280,7 +1456,7 @@ interface AudioProcessingEvent extends Event { declare var AudioProcessingEvent: { prototype: AudioProcessingEvent; new(): AudioProcessingEvent; -} +}; interface AudioTrack { enabled: boolean; @@ -3294,7 +1470,7 @@ interface AudioTrack { declare var AudioTrack: { prototype: AudioTrack; new(): AudioTrack; -} +}; interface AudioTrackListEventMap { "addtrack": TrackEvent; @@ -3317,7 +1493,7 @@ interface AudioTrackList extends EventTarget { declare var AudioTrackList: { prototype: AudioTrackList; new(): AudioTrackList; -} +}; interface BarProp { readonly visible: boolean; @@ -3326,7 +1502,7 @@ interface BarProp { declare var BarProp: { prototype: BarProp; new(): BarProp; -} +}; interface BeforeUnloadEvent extends Event { returnValue: any; @@ -3335,13 +1511,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; } @@ -3349,7 +1525,7 @@ interface BiquadFilterNode extends AudioNode { declare var BiquadFilterNode: { prototype: BiquadFilterNode; new(): BiquadFilterNode; -} +}; interface Blob { readonly size: number; @@ -3362,16 +1538,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; } @@ -3384,7 +1849,7 @@ interface CSSConditionRule extends CSSGroupingRule { declare var CSSConditionRule: { prototype: CSSConditionRule; new(): CSSConditionRule; -} +}; interface CSSFontFaceRule extends CSSRule { readonly style: CSSStyleDeclaration; @@ -3393,7 +1858,7 @@ interface CSSFontFaceRule extends CSSRule { declare var CSSFontFaceRule: { prototype: CSSFontFaceRule; new(): CSSFontFaceRule; -} +}; interface CSSGroupingRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -3404,7 +1869,7 @@ interface CSSGroupingRule extends CSSRule { declare var CSSGroupingRule: { prototype: CSSGroupingRule; new(): CSSGroupingRule; -} +}; interface CSSImportRule extends CSSRule { readonly href: string; @@ -3415,7 +1880,7 @@ interface CSSImportRule extends CSSRule { declare var CSSImportRule: { prototype: CSSImportRule; new(): CSSImportRule; -} +}; interface CSSKeyframeRule extends CSSRule { keyText: string; @@ -3425,7 +1890,7 @@ interface CSSKeyframeRule extends CSSRule { declare var CSSKeyframeRule: { prototype: CSSKeyframeRule; new(): CSSKeyframeRule; -} +}; interface CSSKeyframesRule extends CSSRule { readonly cssRules: CSSRuleList; @@ -3438,7 +1903,7 @@ interface CSSKeyframesRule extends CSSRule { declare var CSSKeyframesRule: { prototype: CSSKeyframesRule; new(): CSSKeyframesRule; -} +}; interface CSSMediaRule extends CSSConditionRule { readonly media: MediaList; @@ -3447,7 +1912,7 @@ interface CSSMediaRule extends CSSConditionRule { declare var CSSMediaRule: { prototype: CSSMediaRule; new(): CSSMediaRule; -} +}; interface CSSNamespaceRule extends CSSRule { readonly namespaceURI: string; @@ -3457,7 +1922,7 @@ interface CSSNamespaceRule extends CSSRule { declare var CSSNamespaceRule: { prototype: CSSNamespaceRule; new(): CSSNamespaceRule; -} +}; interface CSSPageRule extends CSSRule { readonly pseudoClass: string; @@ -3469,7 +1934,7 @@ interface CSSPageRule extends CSSRule { declare var CSSPageRule: { prototype: CSSPageRule; new(): CSSPageRule; -} +}; interface CSSRule { cssText: string; @@ -3479,8 +1944,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; @@ -3496,8 +1961,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; @@ -3505,7 +1970,7 @@ declare var CSSRule: { readonly SUPPORTS_RULE: number; readonly UNKNOWN_RULE: number; readonly VIEWPORT_RULE: number; -} +}; interface CSSRuleList { readonly length: number; @@ -3516,13 +1981,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; @@ -3598,9 +2063,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; @@ -3670,24 +2135,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; @@ -3823,9 +2288,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; @@ -3877,7 +2342,7 @@ interface CSSStyleDeclaration { declare var CSSStyleDeclaration: { prototype: CSSStyleDeclaration; new(): CSSStyleDeclaration; -} +}; interface CSSStyleRule extends CSSRule { readonly readOnly: boolean; @@ -3888,7 +2353,7 @@ interface CSSStyleRule extends CSSRule { declare var CSSStyleRule: { prototype: CSSStyleRule; new(): CSSStyleRule; -} +}; interface CSSStyleSheet extends StyleSheet { readonly cssRules: CSSRuleList; @@ -3914,7 +2379,7 @@ interface CSSStyleSheet extends StyleSheet { declare var CSSStyleSheet: { prototype: CSSStyleSheet; new(): CSSStyleSheet; -} +}; interface CSSSupportsRule extends CSSConditionRule { } @@ -3922,296 +2387,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; @@ -4221,150 +2397,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; @@ -4375,7 +2408,7 @@ interface DataCue extends TextTrackCue { declare var DataCue: { prototype: DataCue; new(): DataCue; -} +}; interface DataTransfer { dropEffect: string; @@ -4392,7 +2425,7 @@ interface DataTransfer { declare var DataTransfer: { prototype: DataTransfer; new(): DataTransfer; -} +}; interface DataTransferItem { readonly kind: string; @@ -4405,7 +2438,7 @@ interface DataTransferItem { declare var DataTransferItem: { prototype: DataTransferItem; new(): DataTransferItem; -} +}; interface DataTransferItemList { readonly length: number; @@ -4419,7 +2452,7 @@ interface DataTransferItemList { declare var DataTransferItemList: { prototype: DataTransferItemList; new(): DataTransferItemList; -} +}; interface DeferredPermissionRequest { readonly id: number; @@ -4432,7 +2465,7 @@ interface DeferredPermissionRequest { declare var DeferredPermissionRequest: { prototype: DeferredPermissionRequest; new(): DeferredPermissionRequest; -} +}; interface DelayNode extends AudioNode { readonly delayTime: AudioParam; @@ -4441,7 +2474,7 @@ interface DelayNode extends AudioNode { declare var DelayNode: { prototype: DelayNode; new(): DelayNode; -} +}; interface DeviceAcceleration { readonly x: number | null; @@ -4452,7 +2485,7 @@ interface DeviceAcceleration { declare var DeviceAcceleration: { prototype: DeviceAcceleration; new(): DeviceAcceleration; -} +}; interface DeviceLightEvent extends Event { readonly value: number; @@ -4461,7 +2494,7 @@ interface DeviceLightEvent extends Event { declare var DeviceLightEvent: { prototype: DeviceLightEvent; new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent; -} +}; interface DeviceMotionEvent extends Event { readonly acceleration: DeviceAcceleration | null; @@ -4474,7 +2507,7 @@ interface DeviceMotionEvent extends Event { declare var DeviceMotionEvent: { prototype: DeviceMotionEvent; new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent; -} +}; interface DeviceOrientationEvent extends Event { readonly absolute: boolean; @@ -4487,7 +2520,7 @@ interface DeviceOrientationEvent extends Event { declare var DeviceOrientationEvent: { prototype: DeviceOrientationEvent; new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent; -} +}; interface DeviceRotationRate { readonly alpha: number | null; @@ -4498,7 +2531,7 @@ interface DeviceRotationRate { declare var DeviceRotationRate: { prototype: DeviceRotationRate; new(): DeviceRotationRate; -} +}; interface DocumentEventMap extends GlobalEventHandlersEventMap { "abort": UIEvent; @@ -4593,299 +2626,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; @@ -4905,146 +2930,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; @@ -5053,243 +3086,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; @@ -5298,7 +3331,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; @@ -5307,7 +3340,7 @@ interface DocumentFragment extends Node, NodeSelector, ParentNode { declare var DocumentFragment: { prototype: DocumentFragment; new(): DocumentFragment; -} +}; interface DocumentType extends Node, ChildNode { readonly entities: NamedNodeMap; @@ -5321,8 +3354,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; @@ -5331,8 +3507,8 @@ interface DragEvent extends MouseEvent { declare var DragEvent: { prototype: DragEvent; - new(): DragEvent; -} + new(type: "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent; +}; interface DynamicsCompressorNode extends AudioNode { readonly attack: AudioParam; @@ -5346,27 +3522,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; @@ -5447,9 +3603,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]; @@ -5467,18 +3623,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; @@ -5489,9 +3645,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; @@ -5500,7 +3656,7 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec declare var Element: { prototype: Element; new(): Element; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -5514,12 +3670,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; @@ -5546,7 +3702,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; @@ -5557,8 +3713,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; @@ -5572,7 +3748,7 @@ interface ExtensionScriptApis { declare var ExtensionScriptApis: { prototype: ExtensionScriptApis; new(): ExtensionScriptApis; -} +}; interface External { } @@ -5580,7 +3756,7 @@ interface External { declare var External: { prototype: External; new(): External; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -5591,7 +3767,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; @@ -5602,7 +3778,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -5617,7 +3793,7 @@ interface FileReader extends EventTarget, MSBaseReader { declare var FileReader: { prototype: FileReader; new(): FileReader; -} +}; interface FocusEvent extends UIEvent { readonly relatedTarget: EventTarget; @@ -5627,7 +3803,7 @@ interface FocusEvent extends UIEvent { declare var FocusEvent: { prototype: FocusEvent; new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent; -} +}; interface FocusNavigationEvent extends Event { readonly navigationReason: NavigationReason; @@ -5641,7 +3817,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; @@ -5655,7 +3831,7 @@ interface FormData { declare var FormData: { prototype: FormData; new (form?: HTMLFormElement): FormData; -} +}; interface GainNode extends AudioNode { readonly gain: AudioParam; @@ -5664,7 +3840,7 @@ interface GainNode extends AudioNode { declare var GainNode: { prototype: GainNode; new(): GainNode; -} +}; interface Gamepad { readonly axes: number[]; @@ -5679,7 +3855,7 @@ interface Gamepad { declare var Gamepad: { prototype: Gamepad; new(): Gamepad; -} +}; interface GamepadButton { readonly pressed: boolean; @@ -5689,7 +3865,7 @@ interface GamepadButton { declare var GamepadButton: { prototype: GamepadButton; new(): GamepadButton; -} +}; interface GamepadEvent extends Event { readonly gamepad: Gamepad; @@ -5698,7 +3874,7 @@ interface GamepadEvent extends Event { declare var GamepadEvent: { prototype: GamepadEvent; new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent; -} +}; interface Geolocation { clearWatch(watchId: number): void; @@ -5709,8 +3885,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; @@ -5721,87 +3937,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; @@ -5810,70 +4026,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; @@ -5884,66 +4100,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; @@ -5952,7 +4168,7 @@ interface HTMLAreaElement extends HTMLElement { declare var HTMLAreaElement: { prototype: HTMLAreaElement; new(): HTMLAreaElement; -} +}; interface HTMLAreasCollection extends HTMLCollectionBase { } @@ -5960,7 +4176,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; @@ -5970,30 +4186,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; @@ -6002,16 +4204,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; @@ -6020,7 +4222,7 @@ interface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty declare var HTMLBaseFontElement: { prototype: HTMLBaseFontElement; new(): HTMLBaseFontElement; -} +}; interface HTMLBodyElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -6079,71 +4281,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; @@ -6152,32 +4368,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; @@ -6187,42 +4403,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; @@ -6233,7 +4438,7 @@ interface HTMLDataElement extends HTMLElement { declare var HTMLDataElement: { prototype: HTMLDataElement; new(): HTMLDataElement; -} +}; interface HTMLDataListElement extends HTMLElement { options: HTMLCollectionOf; @@ -6244,7 +4449,7 @@ interface HTMLDataListElement extends HTMLElement { declare var HTMLDataListElement: { prototype: HTMLDataListElement; new(): HTMLDataListElement; -} +}; interface HTMLDirectoryElement extends HTMLElement { compact: boolean; @@ -6255,16 +4460,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; @@ -6273,8 +4478,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; @@ -6283,7 +4499,7 @@ interface HTMLDocument extends Document { declare var HTMLDocument: { prototype: HTMLDocument; new(): HTMLDocument; -} +}; interface HTMLElementEventMap extends ElementEventMap { "abort": UIEvent; @@ -6456,54 +4672,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; @@ -6512,39 +4728,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; @@ -6553,12 +4769,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; @@ -6567,7 +4783,7 @@ interface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOM declare var HTMLFontElement: { prototype: HTMLFontElement; new(): HTMLFontElement; -} +}; interface HTMLFormControlsCollection extends HTMLCollectionBase { namedItem(name: string): HTMLCollection | Element | null; @@ -6576,74 +4792,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; @@ -6653,7 +4869,7 @@ interface HTMLFormElement extends HTMLElement { declare var HTMLFormElement: { prototype: HTMLFormElement; new(): HTMLFormElement; -} +}; interface HTMLFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -6661,68 +4877,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; @@ -6731,7 +4947,7 @@ interface HTMLFrameElement extends HTMLElement, GetSVGDocument { declare var HTMLFrameElement: { prototype: HTMLFrameElement; new(): HTMLFrameElement; -} +}; interface HTMLFrameSetElementEventMap extends HTMLElementEventMap { "afterprint": Event; @@ -6758,33 +4974,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; @@ -6800,8 +5016,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; @@ -6810,29 +5026,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; @@ -6843,12 +5037,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; @@ -6857,12 +5051,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; @@ -6871,7 +5087,7 @@ interface HTMLHtmlElement extends HTMLElement { declare var HTMLHtmlElement: { prototype: HTMLHtmlElement; new(): HTMLHtmlElement; -} +}; interface HTMLIFrameElementEventMap extends HTMLElementEventMap { "load": Event; @@ -6879,79 +5095,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; @@ -6960,86 +5176,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; @@ -7051,210 +5267,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; @@ -7263,31 +5479,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; @@ -7296,16 +5497,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; @@ -7314,41 +5515,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; @@ -7359,16 +5575,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; @@ -7377,7 +5593,7 @@ interface HTMLMapElement extends HTMLElement { declare var HTMLMapElement: { prototype: HTMLMapElement; new(): HTMLMapElement; -} +}; interface HTMLMarqueeElementEventMap extends HTMLElementEventMap { "bounce": Event; @@ -7409,7 +5625,7 @@ interface HTMLMarqueeElement extends HTMLElement { declare var HTMLMarqueeElement: { prototype: HTMLMarqueeElement; new(): HTMLMarqueeElement; -} +}; interface HTMLMediaElementEventMap extends HTMLElementEventMap { "encrypted": MediaEncryptedEvent; @@ -7418,162 +5634,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; @@ -7600,7 +5816,7 @@ declare var HTMLMediaElement: { readonly NETWORK_IDLE: number; readonly NETWORK_LOADING: number; readonly NETWORK_NO_SOURCE: number; -} +}; interface HTMLMenuElement extends HTMLElement { compact: boolean; @@ -7612,32 +5828,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; @@ -7646,7 +5862,7 @@ interface HTMLMetaElement extends HTMLElement { declare var HTMLMetaElement: { prototype: HTMLMetaElement; new(): HTMLMetaElement; -} +}; interface HTMLMeterElement extends HTMLElement { high: number; @@ -7662,16 +5878,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; @@ -7680,13 +5896,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; @@ -7696,154 +6029,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; @@ -7852,37 +6068,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; @@ -7891,7 +6107,7 @@ interface HTMLOptionElement extends HTMLElement { declare var HTMLOptionElement: { prototype: HTMLOptionElement; new(): HTMLOptionElement; -} +}; interface HTMLOptionsCollection extends HTMLCollectionOf { length: number; @@ -7903,7 +6119,7 @@ interface HTMLOptionsCollection extends HTMLCollectionOf { declare var HTMLOptionsCollection: { prototype: HTMLOptionsCollection; new(): HTMLOptionsCollection; -} +}; interface HTMLOutputElement extends HTMLElement { defaultValue: string; @@ -7925,12 +6141,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; @@ -7940,24 +6156,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; @@ -7966,7 +6182,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; @@ -7976,12 +6192,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; @@ -7990,24 +6206,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; @@ -8016,12 +6232,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; @@ -8030,38 +6246,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; @@ -8071,94 +6287,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; @@ -8168,18 +6384,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; /** @@ -8193,7 +6409,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; @@ -8203,17 +6419,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; @@ -8222,16 +6438,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; @@ -8240,53 +6456,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; @@ -8295,20 +6511,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; @@ -8317,7 +6533,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; @@ -8327,111 +6543,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; @@ -8440,12 +6656,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; @@ -8454,39 +6670,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; @@ -8495,26 +6711,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; @@ -8523,7 +6739,7 @@ interface HTMLTableSectionElement extends HTMLElement, HTMLTableAlignment { declare var HTMLTableSectionElement: { prototype: HTMLTableSectionElement; new(): HTMLTableSectionElement; -} +}; interface HTMLTemplateElement extends HTMLElement { readonly content: DocumentFragment; @@ -8534,105 +6750,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; @@ -8641,7 +6857,7 @@ interface HTMLTextAreaElement extends HTMLElement { declare var HTMLTextAreaElement: { prototype: HTMLTextAreaElement; new(): HTMLTextAreaElement; -} +}; interface HTMLTimeElement extends HTMLElement { dateTime: string; @@ -8652,12 +6868,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; @@ -8666,7 +6882,7 @@ interface HTMLTitleElement extends HTMLElement { declare var HTMLTitleElement: { prototype: HTMLTitleElement; new(): HTMLTitleElement; -} +}; interface HTMLTrackElement extends HTMLElement { default: boolean; @@ -8691,7 +6907,7 @@ declare var HTMLTrackElement: { readonly LOADED: number; readonly LOADING: number; readonly NONE: number; -} +}; interface HTMLUListElement extends HTMLElement { compact: boolean; @@ -8703,7 +6919,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; @@ -8713,7 +6929,7 @@ interface HTMLUnknownElement extends HTMLElement { declare var HTMLUnknownElement: { prototype: HTMLUnknownElement; new(): HTMLUnknownElement; -} +}; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { "MSVideoFormatChanged": Event; @@ -8723,8 +6939,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; @@ -8736,31 +6952,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; } @@ -8768,47 +6984,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; @@ -8832,7 +7008,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -8841,7 +7017,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -8858,7 +7034,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; @@ -8867,7 +7043,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -8878,7 +7054,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -8889,14 +7065,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; @@ -8912,7 +7088,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; @@ -8928,14 +7104,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; @@ -8952,7 +7128,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -8960,7 +7136,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; @@ -8974,7 +7150,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -8984,7 +7160,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; @@ -9004,7 +7180,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -9014,7 +7190,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface IIRFilterNode extends AudioNode { getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void; @@ -9023,7 +7199,7 @@ interface IIRFilterNode extends AudioNode { declare var IIRFilterNode: { prototype: IIRFilterNode; new(): IIRFilterNode; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -9035,7 +7211,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; @@ -9050,7 +7226,7 @@ interface IntersectionObserver { declare var IntersectionObserver: { prototype: IntersectionObserver; new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; -} +}; interface IntersectionObserverEntry { readonly boundingClientRect: ClientRect; @@ -9064,7 +7240,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; -} +}; interface KeyboardEvent extends UIEvent { readonly altKey: boolean; @@ -9099,7 +7275,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; @@ -9109,7 +7285,7 @@ interface ListeningStateChangedEvent extends Event { declare var ListeningStateChangedEvent: { prototype: ListeningStateChangedEvent; new(): ListeningStateChangedEvent; -} +}; interface Location { hash: string; @@ -9130,7 +7306,7 @@ interface Location { declare var Location: { prototype: Location; new(): Location; -} +}; interface LongRunningScriptDetectedEvent extends Event { readonly executionTime: number; @@ -9140,8 +7316,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; @@ -9190,7 +7748,7 @@ declare var MSAppAsyncOperation: { readonly COMPLETED: number; readonly ERROR: number; readonly STARTED: number; -} +}; interface MSAssertion { readonly id: string; @@ -9200,7 +7758,7 @@ interface MSAssertion { declare var MSAssertion: { prototype: MSAssertion; new(): MSAssertion; -} +}; interface MSBlobBuilder { append(data: any, endings?: string): void; @@ -9210,7 +7768,7 @@ interface MSBlobBuilder { declare var MSBlobBuilder: { prototype: MSBlobBuilder; new(): MSBlobBuilder; -} +}; interface MSCredentials { getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise; @@ -9220,7 +7778,7 @@ interface MSCredentials { declare var MSCredentials: { prototype: MSCredentials; new(): MSCredentials; -} +}; interface MSFIDOCredentialAssertion extends MSAssertion { readonly algorithm: string | Algorithm; @@ -9232,7 +7790,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion { declare var MSFIDOCredentialAssertion: { prototype: MSFIDOCredentialAssertion; new(): MSFIDOCredentialAssertion; -} +}; interface MSFIDOSignature { readonly authnrData: string; @@ -9243,7 +7801,7 @@ interface MSFIDOSignature { declare var MSFIDOSignature: { prototype: MSFIDOSignature; new(): MSFIDOSignature; -} +}; interface MSFIDOSignatureAssertion extends MSAssertion { readonly signature: MSFIDOSignature; @@ -9252,7 +7810,7 @@ interface MSFIDOSignatureAssertion extends MSAssertion { declare var MSFIDOSignatureAssertion: { prototype: MSFIDOSignatureAssertion; new(): MSFIDOSignatureAssertion; -} +}; interface MSGesture { target: Element; @@ -9263,7 +7821,7 @@ interface MSGesture { declare var MSGesture: { prototype: MSGesture; new(): MSGesture; -} +}; interface MSGestureEvent extends UIEvent { readonly clientX: number; @@ -9299,7 +7857,7 @@ declare var MSGestureEvent: { readonly MSGESTURE_FLAG_END: number; readonly MSGESTURE_FLAG_INERTIA: number; readonly MSGESTURE_FLAG_NONE: number; -} +}; interface MSGraphicsTrust { readonly constrictionActive: boolean; @@ -9309,7 +7867,7 @@ interface MSGraphicsTrust { declare var MSGraphicsTrust: { prototype: MSGraphicsTrust; new(): MSGraphicsTrust; -} +}; interface MSHTMLWebViewElement extends HTMLElement { readonly canGoBack: boolean; @@ -9343,7 +7901,7 @@ interface MSHTMLWebViewElement extends HTMLElement { declare var MSHTMLWebViewElement: { prototype: MSHTMLWebViewElement; new(): MSHTMLWebViewElement; -} +}; interface MSInputMethodContextEventMap { "MSCandidateWindowHide": Event; @@ -9369,7 +7927,7 @@ interface MSInputMethodContext extends EventTarget { declare var MSInputMethodContext: { prototype: MSInputMethodContext; new(): MSInputMethodContext; -} +}; interface MSManipulationEvent extends UIEvent { readonly currentState: number; @@ -9398,7 +7956,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; @@ -9420,7 +7978,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; @@ -9430,7 +7988,7 @@ interface MSMediaKeyMessageEvent extends Event { declare var MSMediaKeyMessageEvent: { prototype: MSMediaKeyMessageEvent; new(): MSMediaKeyMessageEvent; -} +}; interface MSMediaKeyNeededEvent extends Event { readonly initData: Uint8Array | null; @@ -9439,8 +7997,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; @@ -9452,19 +8022,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; @@ -9487,7 +8045,7 @@ interface MSPointerEvent extends MouseEvent { declare var MSPointerEvent: { prototype: MSPointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent; -} +}; interface MSRangeCollection { readonly length: number; @@ -9498,7 +8056,7 @@ interface MSRangeCollection { declare var MSRangeCollection: { prototype: MSRangeCollection; new(): MSRangeCollection; -} +}; interface MSSiteModeEvent extends Event { readonly actionURL: string; @@ -9508,7 +8066,7 @@ interface MSSiteModeEvent extends Event { declare var MSSiteModeEvent: { prototype: MSSiteModeEvent; new(): MSSiteModeEvent; -} +}; interface MSStream { readonly type: string; @@ -9519,7 +8077,7 @@ interface MSStream { declare var MSStream: { prototype: MSStream; new(): MSStream; -} +}; interface MSStreamReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -9535,7 +8093,7 @@ interface MSStreamReader extends EventTarget, MSBaseReader { declare var MSStreamReader: { prototype: MSStreamReader; new(): MSStreamReader; -} +}; interface MSWebViewAsyncOperationEventMap { "complete": Event; @@ -9570,7 +8128,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; @@ -9580,389 +8138,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; @@ -9982,7 +8158,7 @@ declare var MutationEvent: { readonly ADDITION: number; readonly MODIFICATION: number; readonly REMOVAL: number; -} +}; interface MutationObserver { disconnect(): void; @@ -9993,7 +8169,7 @@ interface MutationObserver { declare var MutationObserver: { prototype: MutationObserver; new(callback: MutationCallback): MutationObserver; -} +}; interface MutationRecord { readonly addedNodes: NodeList; @@ -10010,7 +8186,7 @@ interface MutationRecord { declare var MutationRecord: { prototype: MutationRecord; new(): MutationRecord; -} +}; interface NamedNodeMap { readonly length: number; @@ -10027,7 +8203,7 @@ interface NamedNodeMap { declare var NamedNodeMap: { prototype: NamedNodeMap; new(): NamedNodeMap; -} +}; interface NavigationCompletedEvent extends NavigationEvent { readonly isSuccess: boolean; @@ -10037,7 +8213,7 @@ interface NavigationCompletedEvent extends NavigationEvent { declare var NavigationCompletedEvent: { prototype: NavigationCompletedEvent; new(): NavigationCompletedEvent; -} +}; interface NavigationEvent extends Event { readonly uri: string; @@ -10046,7 +8222,7 @@ interface NavigationEvent extends Event { declare var NavigationEvent: { prototype: NavigationEvent; new(): NavigationEvent; -} +}; interface NavigationEventWithReferrer extends NavigationEvent { readonly referer: string; @@ -10055,7 +8231,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; @@ -10072,6 +8248,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte readonly serviceWorker: ServiceWorkerContainer; readonly webdriver: boolean; readonly hardwareConcurrency: number; + readonly languages: string[]; getGamepads(): Gamepad[]; javaEnabled(): boolean; msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void; @@ -10082,7 +8259,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte declare var Navigator: { prototype: Navigator; new(): Navigator; -} +}; interface Node extends EventTarget { readonly attributes: NamedNodeMap; @@ -10157,7 +8334,7 @@ declare var Node: { readonly NOTATION_NODE: number; readonly PROCESSING_INSTRUCTION_NODE: number; readonly TEXT_NODE: number; -} +}; interface NodeFilter { acceptNode(n: Node): number; @@ -10180,7 +8357,7 @@ declare var NodeFilter: { readonly SHOW_NOTATION: number; readonly SHOW_PROCESSING_INSTRUCTION: number; readonly SHOW_TEXT: number; -} +}; interface NodeIterator { readonly expandEntityReferences: boolean; @@ -10195,7 +8372,7 @@ interface NodeIterator { declare var NodeIterator: { prototype: NodeIterator; new(): NodeIterator; -} +}; interface NodeList { readonly length: number; @@ -10206,7 +8383,7 @@ interface NodeList { declare var NodeList: { prototype: NodeList; new(): NodeList; -} +}; interface NotificationEventMap { "click": Event; @@ -10236,7 +8413,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface OES_element_index_uint { } @@ -10244,7 +8421,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; @@ -10254,7 +8431,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 { } @@ -10262,7 +8439,7 @@ interface OES_texture_float { declare var OES_texture_float: { prototype: OES_texture_float; new(): OES_texture_float; -} +}; interface OES_texture_float_linear { } @@ -10270,7 +8447,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; @@ -10280,7 +8457,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 { } @@ -10288,7 +8465,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; @@ -10297,7 +8474,7 @@ interface OfflineAudioCompletionEvent extends Event { declare var OfflineAudioCompletionEvent: { prototype: OfflineAudioCompletionEvent; new(): OfflineAudioCompletionEvent; -} +}; interface OfflineAudioContextEventMap extends AudioContextEventMap { "complete": OfflineAudioCompletionEvent; @@ -10315,7 +8492,7 @@ interface OfflineAudioContext extends AudioContextBase { declare var OfflineAudioContext: { prototype: OfflineAudioContext; new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; -} +}; interface OscillatorNodeEventMap { "ended": MediaStreamErrorEvent; @@ -10336,7 +8513,7 @@ interface OscillatorNode extends AudioNode { declare var OscillatorNode: { prototype: OscillatorNode; new(): OscillatorNode; -} +}; interface OverflowEvent extends UIEvent { readonly horizontalOverflow: boolean; @@ -10353,7 +8530,7 @@ declare var OverflowEvent: { readonly BOTH: number; readonly HORIZONTAL: number; readonly VERTICAL: number; -} +}; interface PageTransitionEvent extends Event { readonly persisted: boolean; @@ -10362,7 +8539,7 @@ interface PageTransitionEvent extends Event { declare var PageTransitionEvent: { prototype: PageTransitionEvent; new(): PageTransitionEvent; -} +}; interface PannerNode extends AudioNode { coneInnerAngle: number; @@ -10381,7 +8558,7 @@ interface PannerNode extends AudioNode { declare var PannerNode: { prototype: PannerNode; new(): PannerNode; -} +}; interface Path2D extends Object, CanvasPathMethods { } @@ -10389,7 +8566,7 @@ interface Path2D extends Object, CanvasPathMethods { declare var Path2D: { prototype: Path2D; new(path?: Path2D): Path2D; -} +}; interface PaymentAddress { readonly addressLine: string[]; @@ -10409,7 +8586,7 @@ interface PaymentAddress { declare var PaymentAddress: { prototype: PaymentAddress; new(): PaymentAddress; -} +}; interface PaymentRequestEventMap { "shippingaddresschange": Event; @@ -10431,7 +8608,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; @@ -10440,7 +8617,7 @@ interface PaymentRequestUpdateEvent extends Event { declare var PaymentRequestUpdateEvent: { prototype: PaymentRequestUpdateEvent; new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; -} +}; interface PaymentResponse { readonly details: any; @@ -10457,8 +8634,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; @@ -10486,157 +8813,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 { } @@ -10644,7 +8821,7 @@ interface PeriodicWave { declare var PeriodicWave: { prototype: PeriodicWave; new(): PeriodicWave; -} +}; interface PermissionRequest extends DeferredPermissionRequest { readonly state: MSWebViewPermissionState; @@ -10654,7 +8831,7 @@ interface PermissionRequest extends DeferredPermissionRequest { declare var PermissionRequest: { prototype: PermissionRequest; new(): PermissionRequest; -} +}; interface PermissionRequestedEvent extends Event { readonly permissionRequest: PermissionRequest; @@ -10663,7 +8840,7 @@ interface PermissionRequestedEvent extends Event { declare var PermissionRequestedEvent: { prototype: PermissionRequestedEvent; new(): PermissionRequestedEvent; -} +}; interface Plugin { readonly description: string; @@ -10679,7 +8856,7 @@ interface Plugin { declare var Plugin: { prototype: Plugin; new(): Plugin; -} +}; interface PluginArray { readonly length: number; @@ -10692,7 +8869,7 @@ interface PluginArray { declare var PluginArray: { prototype: PluginArray; new(): PluginArray; -} +}; interface PointerEvent extends MouseEvent { readonly currentPoint: any; @@ -10715,7 +8892,7 @@ interface PointerEvent extends MouseEvent { declare var PointerEvent: { prototype: PointerEvent; new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent; -} +}; interface PopStateEvent extends Event { readonly state: any; @@ -10725,7 +8902,7 @@ interface PopStateEvent extends Event { declare var PopStateEvent: { prototype: PopStateEvent; new(typeArg: string, eventInitDict?: PopStateEventInit): PopStateEvent; -} +}; interface Position { readonly coords: Coordinates; @@ -10735,7 +8912,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -10752,7 +8929,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProcessingInstruction extends CharacterData { readonly target: string; @@ -10761,7 +8938,7 @@ interface ProcessingInstruction extends CharacterData { declare var ProcessingInstruction: { prototype: ProcessingInstruction; new(): ProcessingInstruction; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -10773,7 +8950,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -10784,7 +8961,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -10797,7 +8974,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -10807,17 +8984,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; @@ -10840,7 +9114,7 @@ interface RTCDtlsTransport extends RTCStatsProvider { declare var RTCDtlsTransport: { prototype: RTCDtlsTransport; new(transport: RTCIceTransport): RTCDtlsTransport; -} +}; interface RTCDtlsTransportStateChangedEvent extends Event { readonly state: RTCDtlsTransportState; @@ -10849,7 +9123,7 @@ interface RTCDtlsTransportStateChangedEvent extends Event { declare var RTCDtlsTransportStateChangedEvent: { prototype: RTCDtlsTransportStateChangedEvent; new(): RTCDtlsTransportStateChangedEvent; -} +}; interface RTCDtmfSenderEventMap { "tonechange": RTCDTMFToneChangeEvent; @@ -10870,19 +9144,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; @@ -10891,7 +9174,7 @@ interface RTCIceCandidatePairChangedEvent extends Event { declare var RTCIceCandidatePairChangedEvent: { prototype: RTCIceCandidatePairChangedEvent; new(): RTCIceCandidatePairChangedEvent; -} +}; interface RTCIceGathererEventMap { "error": Event; @@ -10912,7 +9195,7 @@ interface RTCIceGatherer extends RTCStatsProvider { declare var RTCIceGatherer: { prototype: RTCIceGatherer; new(options: RTCIceGatherOptions): RTCIceGatherer; -} +}; interface RTCIceGathererEvent extends Event { readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete; @@ -10921,7 +9204,7 @@ interface RTCIceGathererEvent extends Event { declare var RTCIceGathererEvent: { prototype: RTCIceGathererEvent; new(): RTCIceGathererEvent; -} +}; interface RTCIceTransportEventMap { "candidatepairchange": RTCIceCandidatePairChangedEvent; @@ -10950,7 +9233,7 @@ interface RTCIceTransport extends RTCStatsProvider { declare var RTCIceTransport: { prototype: RTCIceTransport; new(): RTCIceTransport; -} +}; interface RTCIceTransportStateChangedEvent extends Event { readonly state: RTCIceTransportState; @@ -10959,7 +9242,7 @@ interface RTCIceTransportStateChangedEvent extends Event { declare var RTCIceTransportStateChangedEvent: { prototype: RTCIceTransportStateChangedEvent; new(): RTCIceTransportStateChangedEvent; -} +}; interface RTCPeerConnectionEventMap { "addstream": MediaStreamEvent; @@ -11005,7 +9288,7 @@ interface RTCPeerConnection extends EventTarget { declare var RTCPeerConnection: { prototype: RTCPeerConnection; new(configuration: RTCConfiguration): RTCPeerConnection; -} +}; interface RTCPeerConnectionIceEvent extends Event { readonly candidate: RTCIceCandidate; @@ -11014,7 +9297,7 @@ interface RTCPeerConnectionIceEvent extends Event { declare var RTCPeerConnectionIceEvent: { prototype: RTCPeerConnectionIceEvent; new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent; -} +}; interface RTCRtpReceiverEventMap { "error": Event; @@ -11038,7 +9321,7 @@ declare var RTCRtpReceiver: { prototype: RTCRtpReceiver; new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCRtpSenderEventMap { "error": Event; @@ -11063,7 +9346,7 @@ declare var RTCRtpSender: { prototype: RTCRtpSender; new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender; getCapabilities(kind?: string): RTCRtpCapabilities; -} +}; interface RTCSessionDescription { sdp: string | null; @@ -11074,7 +9357,7 @@ interface RTCSessionDescription { declare var RTCSessionDescription: { prototype: RTCSessionDescription; new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; -} +}; interface RTCSrtpSdesTransportEventMap { "error": Event; @@ -11091,7 +9374,7 @@ declare var RTCSrtpSdesTransport: { prototype: RTCSrtpSdesTransport; new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport; getLocalParameters(): RTCSrtpSdesParameters[]; -} +}; interface RTCSsrcConflictEvent extends Event { readonly ssrc: number; @@ -11100,7 +9383,7 @@ interface RTCSsrcConflictEvent extends Event { declare var RTCSsrcConflictEvent: { prototype: RTCSsrcConflictEvent; new(): RTCSsrcConflictEvent; -} +}; interface RTCStatsProvider extends EventTarget { getStats(): Promise; @@ -11110,112 +9393,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; @@ -11225,7 +9817,7 @@ interface SVGAElement extends SVGGraphicsElement, SVGURIReference { declare var SVGAElement: { prototype: SVGAElement; new(): SVGAElement; -} +}; interface SVGAngle { readonly unitType: number; @@ -11249,7 +9841,7 @@ declare var SVGAngle: { readonly SVG_ANGLETYPE_RAD: number; readonly SVG_ANGLETYPE_UNKNOWN: number; readonly SVG_ANGLETYPE_UNSPECIFIED: number; -} +}; interface SVGAnimatedAngle { readonly animVal: SVGAngle; @@ -11259,7 +9851,7 @@ interface SVGAnimatedAngle { declare var SVGAnimatedAngle: { prototype: SVGAnimatedAngle; new(): SVGAnimatedAngle; -} +}; interface SVGAnimatedBoolean { readonly animVal: boolean; @@ -11269,7 +9861,7 @@ interface SVGAnimatedBoolean { declare var SVGAnimatedBoolean: { prototype: SVGAnimatedBoolean; new(): SVGAnimatedBoolean; -} +}; interface SVGAnimatedEnumeration { readonly animVal: number; @@ -11279,7 +9871,7 @@ interface SVGAnimatedEnumeration { declare var SVGAnimatedEnumeration: { prototype: SVGAnimatedEnumeration; new(): SVGAnimatedEnumeration; -} +}; interface SVGAnimatedInteger { readonly animVal: number; @@ -11289,7 +9881,7 @@ interface SVGAnimatedInteger { declare var SVGAnimatedInteger: { prototype: SVGAnimatedInteger; new(): SVGAnimatedInteger; -} +}; interface SVGAnimatedLength { readonly animVal: SVGLength; @@ -11299,7 +9891,7 @@ interface SVGAnimatedLength { declare var SVGAnimatedLength: { prototype: SVGAnimatedLength; new(): SVGAnimatedLength; -} +}; interface SVGAnimatedLengthList { readonly animVal: SVGLengthList; @@ -11309,7 +9901,7 @@ interface SVGAnimatedLengthList { declare var SVGAnimatedLengthList: { prototype: SVGAnimatedLengthList; new(): SVGAnimatedLengthList; -} +}; interface SVGAnimatedNumber { readonly animVal: number; @@ -11319,7 +9911,7 @@ interface SVGAnimatedNumber { declare var SVGAnimatedNumber: { prototype: SVGAnimatedNumber; new(): SVGAnimatedNumber; -} +}; interface SVGAnimatedNumberList { readonly animVal: SVGNumberList; @@ -11329,7 +9921,7 @@ interface SVGAnimatedNumberList { declare var SVGAnimatedNumberList: { prototype: SVGAnimatedNumberList; new(): SVGAnimatedNumberList; -} +}; interface SVGAnimatedPreserveAspectRatio { readonly animVal: SVGPreserveAspectRatio; @@ -11339,7 +9931,7 @@ interface SVGAnimatedPreserveAspectRatio { declare var SVGAnimatedPreserveAspectRatio: { prototype: SVGAnimatedPreserveAspectRatio; new(): SVGAnimatedPreserveAspectRatio; -} +}; interface SVGAnimatedRect { readonly animVal: SVGRect; @@ -11349,7 +9941,7 @@ interface SVGAnimatedRect { declare var SVGAnimatedRect: { prototype: SVGAnimatedRect; new(): SVGAnimatedRect; -} +}; interface SVGAnimatedString { readonly animVal: string; @@ -11359,7 +9951,7 @@ interface SVGAnimatedString { declare var SVGAnimatedString: { prototype: SVGAnimatedString; new(): SVGAnimatedString; -} +}; interface SVGAnimatedTransformList { readonly animVal: SVGTransformList; @@ -11369,7 +9961,7 @@ interface SVGAnimatedTransformList { declare var SVGAnimatedTransformList: { prototype: SVGAnimatedTransformList; new(): SVGAnimatedTransformList; -} +}; interface SVGCircleElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -11382,7 +9974,7 @@ interface SVGCircleElement extends SVGGraphicsElement { declare var SVGCircleElement: { prototype: SVGCircleElement; new(): SVGCircleElement; -} +}; interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { readonly clipPathUnits: SVGAnimatedEnumeration; @@ -11393,7 +9985,7 @@ interface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes { declare var SVGClipPathElement: { prototype: SVGClipPathElement; new(): SVGClipPathElement; -} +}; interface SVGComponentTransferFunctionElement extends SVGElement { readonly amplitude: SVGAnimatedNumber; @@ -11422,7 +10014,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; @@ -11432,7 +10024,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; @@ -11442,7 +10034,7 @@ interface SVGDescElement extends SVGElement { declare var SVGDescElement: { prototype: SVGDescElement; new(): SVGDescElement; -} +}; interface SVGElementEventMap extends ElementEventMap { "click": MouseEvent; @@ -11480,7 +10072,7 @@ interface SVGElement extends Element { declare var SVGElement: { prototype: SVGElement; new(): SVGElement; -} +}; interface SVGElementInstance extends EventTarget { readonly childNodes: SVGElementInstanceList; @@ -11496,7 +10088,7 @@ interface SVGElementInstance extends EventTarget { declare var SVGElementInstance: { prototype: SVGElementInstance; new(): SVGElementInstance; -} +}; interface SVGElementInstanceList { readonly length: number; @@ -11506,7 +10098,7 @@ interface SVGElementInstanceList { declare var SVGElementInstanceList: { prototype: SVGElementInstanceList; new(): SVGElementInstanceList; -} +}; interface SVGEllipseElement extends SVGGraphicsElement { readonly cx: SVGAnimatedLength; @@ -11520,7 +10112,7 @@ interface SVGEllipseElement extends SVGGraphicsElement { declare var SVGEllipseElement: { prototype: SVGEllipseElement; new(): SVGEllipseElement; -} +}; interface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11567,7 +10159,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; @@ -11590,7 +10182,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; @@ -11601,7 +10193,7 @@ interface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveSt declare var SVGFEComponentTransferElement: { prototype: SVGFEComponentTransferElement; new(): SVGFEComponentTransferElement; -} +}; interface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11632,7 +10224,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; @@ -11662,7 +10254,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; @@ -11677,7 +10269,7 @@ interface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStan declare var SVGFEDiffuseLightingElement: { prototype: SVGFEDiffuseLightingElement; new(): SVGFEDiffuseLightingElement; -} +}; interface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11702,7 +10294,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; @@ -11714,7 +10306,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; @@ -11724,7 +10316,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; @@ -11734,7 +10326,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; @@ -11744,7 +10336,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; @@ -11754,7 +10346,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; @@ -11764,7 +10356,7 @@ interface SVGFEFuncRElement extends SVGComponentTransferFunctionElement { declare var SVGFEFuncRElement: { prototype: SVGFEFuncRElement; new(): SVGFEFuncRElement; -} +}; interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11778,7 +10370,7 @@ interface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandar declare var SVGFEGaussianBlurElement: { prototype: SVGFEGaussianBlurElement; new(): SVGFEGaussianBlurElement; -} +}; interface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference { readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio; @@ -11789,7 +10381,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; @@ -11799,7 +10391,7 @@ interface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttrib declare var SVGFEMergeElement: { prototype: SVGFEMergeElement; new(): SVGFEMergeElement; -} +}; interface SVGFEMergeNodeElement extends SVGElement { readonly in1: SVGAnimatedString; @@ -11810,7 +10402,7 @@ interface SVGFEMergeNodeElement extends SVGElement { declare var SVGFEMergeNodeElement: { prototype: SVGFEMergeNodeElement; new(): SVGFEMergeNodeElement; -} +}; interface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11830,7 +10422,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; @@ -11843,7 +10435,7 @@ interface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttri declare var SVGFEOffsetElement: { prototype: SVGFEOffsetElement; new(): SVGFEOffsetElement; -} +}; interface SVGFEPointLightElement extends SVGElement { readonly x: SVGAnimatedNumber; @@ -11856,7 +10448,7 @@ interface SVGFEPointLightElement extends SVGElement { declare var SVGFEPointLightElement: { prototype: SVGFEPointLightElement; new(): SVGFEPointLightElement; -} +}; interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11872,7 +10464,7 @@ interface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveSta declare var SVGFESpecularLightingElement: { prototype: SVGFESpecularLightingElement; new(): SVGFESpecularLightingElement; -} +}; interface SVGFESpotLightElement extends SVGElement { readonly limitingConeAngle: SVGAnimatedNumber; @@ -11890,7 +10482,7 @@ interface SVGFESpotLightElement extends SVGElement { declare var SVGFESpotLightElement: { prototype: SVGFESpotLightElement; new(): SVGFESpotLightElement; -} +}; interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; @@ -11901,7 +10493,7 @@ interface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttribu declare var SVGFETileElement: { prototype: SVGFETileElement; new(): SVGFETileElement; -} +}; interface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly baseFrequencyX: SVGAnimatedNumber; @@ -11929,7 +10521,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; @@ -11948,7 +10540,7 @@ interface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference { declare var SVGFilterElement: { prototype: SVGFilterElement; new(): SVGFilterElement; -} +}; interface SVGForeignObjectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -11962,7 +10554,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; @@ -11972,7 +10564,7 @@ interface SVGGElement extends SVGGraphicsElement { declare var SVGGElement: { prototype: SVGGElement; new(): SVGGElement; -} +}; interface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference { readonly gradientTransform: SVGAnimatedTransformList; @@ -11993,7 +10585,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; @@ -12010,7 +10602,7 @@ interface SVGGraphicsElement extends SVGElement, SVGTests { declare var SVGGraphicsElement: { prototype: SVGGraphicsElement; new(): SVGGraphicsElement; -} +}; interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { readonly height: SVGAnimatedLength; @@ -12025,7 +10617,7 @@ interface SVGImageElement extends SVGGraphicsElement, SVGURIReference { declare var SVGImageElement: { prototype: SVGImageElement; new(): SVGImageElement; -} +}; interface SVGLength { readonly unitType: number; @@ -12061,7 +10653,7 @@ declare var SVGLength: { readonly SVG_LENGTHTYPE_PT: number; readonly SVG_LENGTHTYPE_PX: number; readonly SVG_LENGTHTYPE_UNKNOWN: number; -} +}; interface SVGLengthList { readonly numberOfItems: number; @@ -12077,21 +10669,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; @@ -12105,8 +10683,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; @@ -12117,12 +10709,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; } @@ -12130,13 +10722,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; @@ -12152,7 +10744,7 @@ interface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes { declare var SVGMaskElement: { prototype: SVGMaskElement; new(): SVGMaskElement; -} +}; interface SVGMatrix { a: number; @@ -12177,7 +10769,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; @@ -12187,7 +10779,7 @@ interface SVGMetadataElement extends SVGElement { declare var SVGMetadataElement: { prototype: SVGMetadataElement; new(): SVGMetadataElement; -} +}; interface SVGNumber { value: number; @@ -12196,7 +10788,7 @@ interface SVGNumber { declare var SVGNumber: { prototype: SVGNumber; new(): SVGNumber; -} +}; interface SVGNumberList { readonly numberOfItems: number; @@ -12212,7 +10804,7 @@ interface SVGNumberList { declare var SVGNumberList: { prototype: SVGNumberList; new(): SVGNumberList; -} +}; interface SVGPathElement extends SVGGraphicsElement { readonly pathSegList: SVGPathSegList; @@ -12245,7 +10837,7 @@ interface SVGPathElement extends SVGGraphicsElement { declare var SVGPathElement: { prototype: SVGPathElement; new(): SVGPathElement; -} +}; interface SVGPathSeg { readonly pathSegType: number; @@ -12295,7 +10887,7 @@ declare var SVGPathSeg: { readonly PATHSEG_MOVETO_ABS: number; readonly PATHSEG_MOVETO_REL: number; readonly PATHSEG_UNKNOWN: number; -} +}; interface SVGPathSegArcAbs extends SVGPathSeg { angle: number; @@ -12310,7 +10902,7 @@ interface SVGPathSegArcAbs extends SVGPathSeg { declare var SVGPathSegArcAbs: { prototype: SVGPathSegArcAbs; new(): SVGPathSegArcAbs; -} +}; interface SVGPathSegArcRel extends SVGPathSeg { angle: number; @@ -12325,7 +10917,7 @@ interface SVGPathSegArcRel extends SVGPathSeg { declare var SVGPathSegArcRel: { prototype: SVGPathSegArcRel; new(): SVGPathSegArcRel; -} +}; interface SVGPathSegClosePath extends SVGPathSeg { } @@ -12333,7 +10925,7 @@ interface SVGPathSegClosePath extends SVGPathSeg { declare var SVGPathSegClosePath: { prototype: SVGPathSegClosePath; new(): SVGPathSegClosePath; -} +}; interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { x: number; @@ -12347,7 +10939,7 @@ interface SVGPathSegCurvetoCubicAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicAbs: { prototype: SVGPathSegCurvetoCubicAbs; new(): SVGPathSegCurvetoCubicAbs; -} +}; interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { x: number; @@ -12361,7 +10953,7 @@ interface SVGPathSegCurvetoCubicRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicRel: { prototype: SVGPathSegCurvetoCubicRel; new(): SVGPathSegCurvetoCubicRel; -} +}; interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { x: number; @@ -12373,7 +10965,7 @@ interface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothAbs: { prototype: SVGPathSegCurvetoCubicSmoothAbs; new(): SVGPathSegCurvetoCubicSmoothAbs; -} +}; interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { x: number; @@ -12385,7 +10977,7 @@ interface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoCubicSmoothRel: { prototype: SVGPathSegCurvetoCubicSmoothRel; new(): SVGPathSegCurvetoCubicSmoothRel; -} +}; interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { x: number; @@ -12397,7 +10989,7 @@ interface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticAbs: { prototype: SVGPathSegCurvetoQuadraticAbs; new(): SVGPathSegCurvetoQuadraticAbs; -} +}; interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { x: number; @@ -12409,7 +11001,7 @@ interface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticRel: { prototype: SVGPathSegCurvetoQuadraticRel; new(): SVGPathSegCurvetoQuadraticRel; -} +}; interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { x: number; @@ -12419,7 +11011,7 @@ interface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothAbs: { prototype: SVGPathSegCurvetoQuadraticSmoothAbs; new(): SVGPathSegCurvetoQuadraticSmoothAbs; -} +}; interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { x: number; @@ -12429,7 +11021,7 @@ interface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg { declare var SVGPathSegCurvetoQuadraticSmoothRel: { prototype: SVGPathSegCurvetoQuadraticSmoothRel; new(): SVGPathSegCurvetoQuadraticSmoothRel; -} +}; interface SVGPathSegLinetoAbs extends SVGPathSeg { x: number; @@ -12439,7 +11031,7 @@ interface SVGPathSegLinetoAbs extends SVGPathSeg { declare var SVGPathSegLinetoAbs: { prototype: SVGPathSegLinetoAbs; new(): SVGPathSegLinetoAbs; -} +}; interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { x: number; @@ -12448,7 +11040,7 @@ interface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalAbs: { prototype: SVGPathSegLinetoHorizontalAbs; new(): SVGPathSegLinetoHorizontalAbs; -} +}; interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { x: number; @@ -12457,7 +11049,7 @@ interface SVGPathSegLinetoHorizontalRel extends SVGPathSeg { declare var SVGPathSegLinetoHorizontalRel: { prototype: SVGPathSegLinetoHorizontalRel; new(): SVGPathSegLinetoHorizontalRel; -} +}; interface SVGPathSegLinetoRel extends SVGPathSeg { x: number; @@ -12467,7 +11059,7 @@ interface SVGPathSegLinetoRel extends SVGPathSeg { declare var SVGPathSegLinetoRel: { prototype: SVGPathSegLinetoRel; new(): SVGPathSegLinetoRel; -} +}; interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { y: number; @@ -12476,7 +11068,7 @@ interface SVGPathSegLinetoVerticalAbs extends SVGPathSeg { declare var SVGPathSegLinetoVerticalAbs: { prototype: SVGPathSegLinetoVerticalAbs; new(): SVGPathSegLinetoVerticalAbs; -} +}; interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { y: number; @@ -12485,7 +11077,7 @@ interface SVGPathSegLinetoVerticalRel extends SVGPathSeg { declare var SVGPathSegLinetoVerticalRel: { prototype: SVGPathSegLinetoVerticalRel; new(): SVGPathSegLinetoVerticalRel; -} +}; interface SVGPathSegList { readonly numberOfItems: number; @@ -12501,7 +11093,7 @@ interface SVGPathSegList { declare var SVGPathSegList: { prototype: SVGPathSegList; new(): SVGPathSegList; -} +}; interface SVGPathSegMovetoAbs extends SVGPathSeg { x: number; @@ -12511,7 +11103,7 @@ interface SVGPathSegMovetoAbs extends SVGPathSeg { declare var SVGPathSegMovetoAbs: { prototype: SVGPathSegMovetoAbs; new(): SVGPathSegMovetoAbs; -} +}; interface SVGPathSegMovetoRel extends SVGPathSeg { x: number; @@ -12521,7 +11113,7 @@ interface SVGPathSegMovetoRel extends SVGPathSeg { declare var SVGPathSegMovetoRel: { prototype: SVGPathSegMovetoRel; new(): SVGPathSegMovetoRel; -} +}; interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference { readonly height: SVGAnimatedLength; @@ -12538,7 +11130,7 @@ interface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitTo declare var SVGPatternElement: { prototype: SVGPatternElement; new(): SVGPatternElement; -} +}; interface SVGPoint { x: number; @@ -12549,7 +11141,7 @@ interface SVGPoint { declare var SVGPoint: { prototype: SVGPoint; new(): SVGPoint; -} +}; interface SVGPointList { readonly numberOfItems: number; @@ -12565,7 +11157,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; @@ -12575,7 +11167,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; @@ -12585,7 +11177,7 @@ interface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints { declare var SVGPolylineElement: { prototype: SVGPolylineElement; new(): SVGPolylineElement; -} +}; interface SVGPreserveAspectRatio { align: number; @@ -12623,7 +11215,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; @@ -12638,7 +11230,7 @@ interface SVGRadialGradientElement extends SVGGradientElement { declare var SVGRadialGradientElement: { prototype: SVGRadialGradientElement; new(): SVGRadialGradientElement; -} +}; interface SVGRect { height: number; @@ -12650,7 +11242,7 @@ interface SVGRect { declare var SVGRect: { prototype: SVGRect; new(): SVGRect; -} +}; interface SVGRectElement extends SVGGraphicsElement { readonly height: SVGAnimatedLength; @@ -12666,8 +11258,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; @@ -12727,59 +11371,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; @@ -12789,7 +11381,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; @@ -12799,17 +11391,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; @@ -12836,7 +11418,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; @@ -12846,7 +11428,7 @@ interface SVGTextElement extends SVGTextPositioningElement { declare var SVGTextElement: { prototype: SVGTextElement; new(): SVGTextElement; -} +}; interface SVGTextPathElement extends SVGTextContentElement, SVGURIReference { readonly method: SVGAnimatedEnumeration; @@ -12871,7 +11453,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; @@ -12886,7 +11468,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; @@ -12896,7 +11478,7 @@ interface SVGTitleElement extends SVGElement { declare var SVGTitleElement: { prototype: SVGTitleElement; new(): SVGTitleElement; -} +}; interface SVGTransform { readonly angle: number; @@ -12927,7 +11509,7 @@ declare var SVGTransform: { readonly SVG_TRANSFORM_SKEWY: number; readonly SVG_TRANSFORM_TRANSLATE: number; readonly SVG_TRANSFORM_UNKNOWN: number; -} +}; interface SVGTransformList { readonly numberOfItems: number; @@ -12945,8 +11527,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; @@ -12968,7 +11560,7 @@ interface SVGUseElement extends SVGGraphicsElement, SVGURIReference { declare var SVGUseElement: { prototype: SVGUseElement; new(): SVGUseElement; -} +}; interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { readonly viewTarget: SVGStringList; @@ -12979,7 +11571,7 @@ interface SVGViewElement extends SVGElement, SVGZoomAndPan, SVGFitToViewBox { declare var SVGViewElement: { prototype: SVGViewElement; new(): SVGViewElement; -} +}; interface SVGZoomAndPan { readonly zoomAndPan: number; @@ -12989,7 +11581,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; @@ -13002,420 +11594,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; @@ -13425,7 +11604,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface Text extends CharacterData { readonly wholeText: string; @@ -13436,7 +11615,7 @@ interface Text extends CharacterData { declare var Text: { prototype: Text; new(data?: string): Text; -} +}; interface TextEvent extends UIEvent { readonly data: string; @@ -13468,7 +11647,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; @@ -13477,7 +11656,7 @@ interface TextMetrics { declare var TextMetrics: { prototype: TextMetrics; new(): TextMetrics; -} +}; interface TextTrackEventMap { "cuechange": Event; @@ -13520,7 +11699,7 @@ declare var TextTrack: { readonly LOADING: number; readonly NONE: number; readonly SHOWING: number; -} +}; interface TextTrackCueEventMap { "enter": Event; @@ -13544,7 +11723,7 @@ interface TextTrackCue extends EventTarget { declare var TextTrackCue: { prototype: TextTrackCue; new(startTime: number, endTime: number, text: string): TextTrackCue; -} +}; interface TextTrackCueList { readonly length: number; @@ -13556,7 +11735,7 @@ interface TextTrackCueList { declare var TextTrackCueList: { prototype: TextTrackCueList; new(): TextTrackCueList; -} +}; interface TextTrackListEventMap { "addtrack": TrackEvent; @@ -13574,7 +11753,7 @@ interface TextTrackList extends EventTarget { declare var TextTrackList: { prototype: TextTrackList; new(): TextTrackList; -} +}; interface TimeRanges { readonly length: number; @@ -13585,7 +11764,7 @@ interface TimeRanges { declare var TimeRanges: { prototype: TimeRanges; new(): TimeRanges; -} +}; interface Touch { readonly clientX: number; @@ -13601,7 +11780,7 @@ interface Touch { declare var Touch: { prototype: Touch; new(): Touch; -} +}; interface TouchEvent extends UIEvent { readonly altKey: boolean; @@ -13619,7 +11798,7 @@ interface TouchEvent extends UIEvent { declare var TouchEvent: { prototype: TouchEvent; new(type: string, touchEventInit?: TouchEventInit): TouchEvent; -} +}; interface TouchList { readonly length: number; @@ -13630,7 +11809,7 @@ interface TouchList { declare var TouchList: { prototype: TouchList; new(): TouchList; -} +}; interface TrackEvent extends Event { readonly track: VideoTrack | AudioTrack | TextTrack | null; @@ -13639,7 +11818,7 @@ interface TrackEvent extends Event { declare var TrackEvent: { prototype: TrackEvent; new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent; -} +}; interface TransitionEvent extends Event { readonly elapsedTime: number; @@ -13650,7 +11829,7 @@ interface TransitionEvent extends Event { declare var TransitionEvent: { prototype: TransitionEvent; new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent; -} +}; interface TreeWalker { currentNode: Node; @@ -13670,7 +11849,7 @@ interface TreeWalker { declare var TreeWalker: { prototype: TreeWalker; new(): TreeWalker; -} +}; interface UIEvent extends Event { readonly detail: number; @@ -13681,8 +11860,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; @@ -13704,16 +11892,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; @@ -13731,7 +11910,7 @@ interface ValidityState { declare var ValidityState: { prototype: ValidityState; new(): ValidityState; -} +}; interface VideoPlaybackQuality { readonly corruptedVideoFrames: number; @@ -13744,7 +11923,7 @@ interface VideoPlaybackQuality { declare var VideoPlaybackQuality: { prototype: VideoPlaybackQuality; new(): VideoPlaybackQuality; -} +}; interface VideoTrack { readonly id: string; @@ -13758,7 +11937,7 @@ interface VideoTrack { declare var VideoTrack: { prototype: VideoTrack; new(): VideoTrack; -} +}; interface VideoTrackListEventMap { "addtrack": TrackEvent; @@ -13782,45 +11961,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; @@ -13830,7 +11971,7 @@ interface WaveShaperNode extends AudioNode { declare var WaveShaperNode: { prototype: WaveShaperNode; new(): WaveShaperNode; -} +}; interface WebAuthentication { getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; @@ -13840,7 +11981,7 @@ interface WebAuthentication { declare var WebAuthentication: { prototype: WebAuthentication; new(): WebAuthentication; -} +}; interface WebAuthnAssertion { readonly authenticatorData: ArrayBuffer; @@ -13852,8 +11993,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; @@ -13863,7 +12042,7 @@ interface WebGLActiveInfo { declare var WebGLActiveInfo: { prototype: WebGLActiveInfo; new(): WebGLActiveInfo; -} +}; interface WebGLBuffer extends WebGLObject { } @@ -13871,7 +12050,7 @@ interface WebGLBuffer extends WebGLObject { declare var WebGLBuffer: { prototype: WebGLBuffer; new(): WebGLBuffer; -} +}; interface WebGLContextEvent extends Event { readonly statusMessage: string; @@ -13880,7 +12059,7 @@ interface WebGLContextEvent extends Event { declare var WebGLContextEvent: { prototype: WebGLContextEvent; new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent; -} +}; interface WebGLFramebuffer extends WebGLObject { } @@ -13888,7 +12067,7 @@ interface WebGLFramebuffer extends WebGLObject { declare var WebGLFramebuffer: { prototype: WebGLFramebuffer; new(): WebGLFramebuffer; -} +}; interface WebGLObject { } @@ -13896,7 +12075,7 @@ interface WebGLObject { declare var WebGLObject: { prototype: WebGLObject; new(): WebGLObject; -} +}; interface WebGLProgram extends WebGLObject { } @@ -13904,7 +12083,7 @@ interface WebGLProgram extends WebGLObject { declare var WebGLProgram: { prototype: WebGLProgram; new(): WebGLProgram; -} +}; interface WebGLRenderbuffer extends WebGLObject { } @@ -13912,7 +12091,7 @@ interface WebGLRenderbuffer extends WebGLObject { declare var WebGLRenderbuffer: { prototype: WebGLRenderbuffer; new(): WebGLRenderbuffer; -} +}; interface WebGLRenderingContext { readonly canvas: HTMLCanvasElement; @@ -14173,13 +12352,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; @@ -14204,9 +12383,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; @@ -14236,18 +12415,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; @@ -14281,6 +12460,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; @@ -14313,23 +12506,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; @@ -14475,13 +12654,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; @@ -14506,9 +12685,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; @@ -14538,18 +12717,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; @@ -14583,6 +12762,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; @@ -14615,23 +12808,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; @@ -14655,7 +12834,7 @@ declare var WebGLRenderingContext: { readonly VERTEX_SHADER: number; readonly VIEWPORT: number; readonly ZERO: number; -} +}; interface WebGLShader extends WebGLObject { } @@ -14663,7 +12842,7 @@ interface WebGLShader extends WebGLObject { declare var WebGLShader: { prototype: WebGLShader; new(): WebGLShader; -} +}; interface WebGLShaderPrecisionFormat { readonly precision: number; @@ -14674,7 +12853,7 @@ interface WebGLShaderPrecisionFormat { declare var WebGLShaderPrecisionFormat: { prototype: WebGLShaderPrecisionFormat; new(): WebGLShaderPrecisionFormat; -} +}; interface WebGLTexture extends WebGLObject { } @@ -14682,7 +12861,7 @@ interface WebGLTexture extends WebGLObject { declare var WebGLTexture: { prototype: WebGLTexture; new(): WebGLTexture; -} +}; interface WebGLUniformLocation { } @@ -14690,7 +12869,7 @@ interface WebGLUniformLocation { declare var WebGLUniformLocation: { prototype: WebGLUniformLocation; new(): WebGLUniformLocation; -} +}; interface WebKitCSSMatrix { a: number; @@ -14730,7 +12909,7 @@ interface WebKitCSSMatrix { declare var WebKitCSSMatrix: { prototype: WebKitCSSMatrix; new(text?: string): WebKitCSSMatrix; -} +}; interface WebKitDirectoryEntry extends WebKitEntry { createReader(): WebKitDirectoryReader; @@ -14739,7 +12918,7 @@ interface WebKitDirectoryEntry extends WebKitEntry { declare var WebKitDirectoryEntry: { prototype: WebKitDirectoryEntry; new(): WebKitDirectoryEntry; -} +}; interface WebKitDirectoryReader { readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void; @@ -14748,7 +12927,7 @@ interface WebKitDirectoryReader { declare var WebKitDirectoryReader: { prototype: WebKitDirectoryReader; new(): WebKitDirectoryReader; -} +}; interface WebKitEntry { readonly filesystem: WebKitFileSystem; @@ -14761,7 +12940,7 @@ interface WebKitEntry { declare var WebKitEntry: { prototype: WebKitEntry; new(): WebKitEntry; -} +}; interface WebKitFileEntry extends WebKitEntry { file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void; @@ -14770,7 +12949,7 @@ interface WebKitFileEntry extends WebKitEntry { declare var WebKitFileEntry: { prototype: WebKitFileEntry; new(): WebKitFileEntry; -} +}; interface WebKitFileSystem { readonly name: string; @@ -14780,7 +12959,7 @@ interface WebKitFileSystem { declare var WebKitFileSystem: { prototype: WebKitFileSystem; new(): WebKitFileSystem; -} +}; interface WebKitPoint { x: number; @@ -14790,8 +12969,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; @@ -14827,7 +13016,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WheelEvent extends MouseEvent { readonly deltaMode: number; @@ -14850,7 +13039,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; @@ -14878,6 +13067,7 @@ interface WindowEventMap extends GlobalEventHandlersEventMap { "durationchange": Event; "emptied": Event; "ended": MediaStreamErrorEvent; + "error": ErrorEvent; "focus": FocusEvent; "hashchange": HashChangeEvent; "input": Event; @@ -14936,6 +13126,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; @@ -14949,8 +13143,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; @@ -15073,9 +13267,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; @@ -15131,7 +13325,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window declare var Window: { prototype: Window; new(): Window; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -15148,7 +13342,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; @@ -15158,7 +13352,7 @@ interface XMLDocument extends Document { declare var XMLDocument: { prototype: XMLDocument; new(): XMLDocument; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -15205,7 +13399,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; @@ -15215,7 +13409,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface XMLSerializer { serializeToString(target: Node): string; @@ -15224,7 +13418,7 @@ interface XMLSerializer { declare var XMLSerializer: { prototype: XMLSerializer; new(): XMLSerializer; -} +}; interface XPathEvaluator { createExpression(expression: string, resolver: XPathNSResolver): XPathExpression; @@ -15235,7 +13429,7 @@ interface XPathEvaluator { declare var XPathEvaluator: { prototype: XPathEvaluator; new(): XPathEvaluator; -} +}; interface XPathExpression { evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult; @@ -15244,7 +13438,7 @@ interface XPathExpression { declare var XPathExpression: { prototype: XPathExpression; new(): XPathExpression; -} +}; interface XPathNSResolver { lookupNamespaceURI(prefix: string): string; @@ -15253,7 +13447,7 @@ interface XPathNSResolver { declare var XPathNSResolver: { prototype: XPathNSResolver; new(): XPathNSResolver; -} +}; interface XPathResult { readonly booleanValue: boolean; @@ -15290,7 +13484,7 @@ declare var XPathResult: { readonly STRING_TYPE: number; readonly UNORDERED_NODE_ITERATOR_TYPE: number; readonly UNORDERED_NODE_SNAPSHOT_TYPE: number; -} +}; interface XSLTProcessor { clearParameters(): void; @@ -15306,17 +13500,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; @@ -15353,6 +13537,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; } @@ -15361,81 +13620,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; @@ -15480,16 +13664,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; } @@ -15714,38 +13898,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; @@ -15993,7 +14177,7 @@ interface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment { } interface ShadowRootInit { - mode: 'open'|'closed'; + mode: "open" | "closed"; delegatesFocus?: boolean; } @@ -16043,8 +14227,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; @@ -16052,59 +14278,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; @@ -16192,48 +14376,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; @@ -16258,307 +14421,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; @@ -16566,8 +14489,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; @@ -16690,9 +14613,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; @@ -16811,6 +14734,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"; @@ -16824,6 +14748,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"; @@ -16831,12 +14761,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"; @@ -16848,6 +14772,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"; @@ -16855,9 +14787,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"; @@ -16868,14 +14800,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/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 4e7672f7973..997b007a879 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -20,7 +20,7 @@ and limitations under the License. ///////////////////////////// -/// IE Worker APIs +/// Worker APIs ///////////////////////////// interface Algorithm { @@ -28,16 +28,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 { @@ -69,16 +69,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 { @@ -86,29 +86,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 { @@ -176,7 +176,7 @@ interface AudioBuffer { declare var AudioBuffer: { prototype: AudioBuffer; new(): AudioBuffer; -} +}; interface Blob { readonly size: number; @@ -189,7 +189,7 @@ interface Blob { declare var Blob: { prototype: Blob; new (blobParts?: any[], options?: BlobPropertyBag): Blob; -} +}; interface Cache { add(request: RequestInfo): Promise; @@ -204,7 +204,7 @@ interface Cache { declare var Cache: { prototype: Cache; new(): Cache; -} +}; interface CacheStorage { delete(cacheName: string): Promise; @@ -217,7 +217,7 @@ interface CacheStorage { declare var CacheStorage: { prototype: CacheStorage; new(): CacheStorage; -} +}; interface CloseEvent extends Event { readonly code: number; @@ -229,7 +229,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; @@ -240,8 +240,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; @@ -259,7 +259,7 @@ interface Console { declare var Console: { prototype: Console; new(): Console; -} +}; interface Coordinates { readonly accuracy: number; @@ -274,7 +274,7 @@ interface Coordinates { declare var Coordinates: { prototype: Coordinates; new(): Coordinates; -} +}; interface CryptoKey { readonly algorithm: KeyAlgorithm; @@ -286,7 +286,7 @@ interface CryptoKey { declare var CryptoKey: { prototype: CryptoKey; new(): CryptoKey; -} +}; interface DOMError { readonly name: string; @@ -296,7 +296,7 @@ interface DOMError { declare var DOMError: { prototype: DOMError; new(): DOMError; -} +}; interface DOMException { readonly code: number; @@ -316,10 +316,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; @@ -348,10 +348,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; @@ -362,7 +362,7 @@ declare var DOMException: { readonly URL_MISMATCH_ERR: number; readonly VALIDATION_ERR: number; readonly WRONG_DOCUMENT_ERR: number; -} +}; interface DOMStringList { readonly length: number; @@ -374,7 +374,7 @@ interface DOMStringList { declare var DOMStringList: { prototype: DOMStringList; new(): DOMStringList; -} +}; interface ErrorEvent extends Event { readonly colno: number; @@ -388,12 +388,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; @@ -420,7 +420,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; @@ -431,7 +431,7 @@ interface EventTarget { declare var EventTarget: { prototype: EventTarget; new(): EventTarget; -} +}; interface File extends Blob { readonly lastModifiedDate: any; @@ -442,7 +442,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; @@ -453,7 +453,7 @@ interface FileList { declare var FileList: { prototype: FileList; new(): FileList; -} +}; interface FileReader extends EventTarget, MSBaseReader { readonly error: DOMError; @@ -468,8 +468,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; @@ -482,7 +491,7 @@ interface Headers { declare var Headers: { prototype: Headers; new(init?: any): Headers; -} +}; interface IDBCursor { readonly direction: IDBCursorDirection; @@ -506,7 +515,7 @@ declare var IDBCursor: { readonly NEXT_NO_DUPLICATE: string; readonly PREV: string; readonly PREV_NO_DUPLICATE: string; -} +}; interface IDBCursorWithValue extends IDBCursor { readonly value: any; @@ -515,7 +524,7 @@ interface IDBCursorWithValue extends IDBCursor { declare var IDBCursorWithValue: { prototype: IDBCursorWithValue; new(): IDBCursorWithValue; -} +}; interface IDBDatabaseEventMap { "abort": Event; @@ -532,7 +541,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; @@ -541,7 +550,7 @@ interface IDBDatabase extends EventTarget { declare var IDBDatabase: { prototype: IDBDatabase; new(): IDBDatabase; -} +}; interface IDBFactory { cmp(first: any, second: any): number; @@ -552,7 +561,7 @@ interface IDBFactory { declare var IDBFactory: { prototype: IDBFactory; new(): IDBFactory; -} +}; interface IDBIndex { keyPath: string | string[]; @@ -563,14 +572,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; @@ -586,7 +595,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; @@ -602,14 +611,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; @@ -626,7 +635,7 @@ interface IDBOpenDBRequest extends IDBRequest { declare var IDBOpenDBRequest: { prototype: IDBOpenDBRequest; new(): IDBOpenDBRequest; -} +}; interface IDBRequestEventMap { "error": Event; @@ -634,7 +643,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; @@ -648,7 +657,7 @@ interface IDBRequest extends EventTarget { declare var IDBRequest: { prototype: IDBRequest; new(): IDBRequest; -} +}; interface IDBTransactionEventMap { "abort": Event; @@ -658,7 +667,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; @@ -678,7 +687,7 @@ declare var IDBTransaction: { readonly READ_ONLY: string; readonly READ_WRITE: string; readonly VERSION_CHANGE: string; -} +}; interface IDBVersionChangeEvent extends Event { readonly newVersion: number | null; @@ -688,7 +697,7 @@ interface IDBVersionChangeEvent extends Event { declare var IDBVersionChangeEvent: { prototype: IDBVersionChangeEvent; new(): IDBVersionChangeEvent; -} +}; interface ImageData { data: Uint8ClampedArray; @@ -700,7 +709,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; @@ -710,7 +719,7 @@ interface MessageChannel { declare var MessageChannel: { prototype: MessageChannel; new(): MessageChannel; -} +}; interface MessageEvent extends Event { readonly data: any; @@ -723,7 +732,7 @@ interface MessageEvent extends Event { declare var MessageEvent: { prototype: MessageEvent; new(type: string, eventInitDict?: MessageEventInit): MessageEvent; -} +}; interface MessagePortEventMap { "message": MessageEvent; @@ -741,7 +750,7 @@ interface MessagePort extends EventTarget { declare var MessagePort: { prototype: MessagePort; new(): MessagePort; -} +}; interface NotificationEventMap { "click": Event; @@ -771,7 +780,7 @@ declare var Notification: { prototype: Notification; new(title: string, options?: NotificationOptions): Notification; requestPermission(callback?: NotificationPermissionCallback): Promise; -} +}; interface Performance { readonly navigation: PerformanceNavigation; @@ -794,7 +803,7 @@ interface Performance { declare var Performance: { prototype: Performance; new(): Performance; -} +}; interface PerformanceNavigation { readonly redirectCount: number; @@ -813,18 +822,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; @@ -844,7 +853,7 @@ interface PerformanceTiming { declare var PerformanceTiming: { prototype: PerformanceTiming; new(): PerformanceTiming; -} +}; interface Position { readonly coords: Coordinates; @@ -854,7 +863,7 @@ interface Position { declare var Position: { prototype: Position; new(): Position; -} +}; interface PositionError { readonly code: number; @@ -871,7 +880,7 @@ declare var PositionError: { readonly PERMISSION_DENIED: number; readonly POSITION_UNAVAILABLE: number; readonly TIMEOUT: number; -} +}; interface ProgressEvent extends Event { readonly lengthComputable: boolean; @@ -883,7 +892,7 @@ interface ProgressEvent extends Event { declare var ProgressEvent: { prototype: ProgressEvent; new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent; -} +}; interface PushManager { getSubscription(): Promise; @@ -894,7 +903,7 @@ interface PushManager { declare var PushManager: { prototype: PushManager; new(): PushManager; -} +}; interface PushSubscription { readonly endpoint: USVString; @@ -907,7 +916,7 @@ interface PushSubscription { declare var PushSubscription: { prototype: PushSubscription; new(): PushSubscription; -} +}; interface PushSubscriptionOptions { readonly applicationServerKey: ArrayBuffer | null; @@ -917,7 +926,7 @@ interface PushSubscriptionOptions { declare var PushSubscriptionOptions: { prototype: PushSubscriptionOptions; new(): PushSubscriptionOptions; -} +}; interface ReadableStream { readonly locked: boolean; @@ -928,7 +937,7 @@ interface ReadableStream { declare var ReadableStream: { prototype: ReadableStream; new(): ReadableStream; -} +}; interface ReadableStreamReader { cancel(): Promise; @@ -939,7 +948,7 @@ interface ReadableStreamReader { declare var ReadableStreamReader: { prototype: ReadableStreamReader; new(): ReadableStreamReader; -} +}; interface Request extends Object, Body { readonly cache: RequestCache; @@ -961,7 +970,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; @@ -977,7 +986,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; @@ -995,7 +1006,7 @@ interface ServiceWorker extends EventTarget, AbstractWorker { declare var ServiceWorker: { prototype: ServiceWorker; new(): ServiceWorker; -} +}; interface ServiceWorkerRegistrationEventMap { "updatefound": Event; @@ -1020,7 +1031,7 @@ interface ServiceWorkerRegistration extends EventTarget { declare var ServiceWorkerRegistration: { prototype: ServiceWorkerRegistration; new(): ServiceWorkerRegistration; -} +}; interface SyncManager { getTags(): any; @@ -1030,7 +1041,7 @@ interface SyncManager { declare var SyncManager: { prototype: SyncManager; new(): SyncManager; -} +}; interface URL { hash: string; @@ -1053,7 +1064,7 @@ declare var URL: { new(url: string, base?: string): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; -} +}; interface WebSocketEventMap { "close": CloseEvent; @@ -1090,7 +1101,7 @@ declare var WebSocket: { readonly CLOSING: number; readonly CONNECTING: number; readonly OPEN: number; -} +}; interface WorkerEventMap extends AbstractWorkerEventMap { "message": MessageEvent; @@ -1107,7 +1118,7 @@ interface Worker extends EventTarget, AbstractWorker { declare var Worker: { prototype: Worker; new(stringUrl: string): Worker; -} +}; interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { "readystatechange": Event; @@ -1153,7 +1164,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; @@ -1163,7 +1174,7 @@ interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { declare var XMLHttpRequestUpload: { prototype: XMLHttpRequestUpload; new(): XMLHttpRequestUpload; -} +}; interface AbstractWorkerEventMap { "error": ErrorEvent; @@ -1278,7 +1289,7 @@ interface Client { declare var Client: { prototype: Client; new(): Client; -} +}; interface Clients { claim(): Promise; @@ -1290,7 +1301,7 @@ interface Clients { declare var Clients: { prototype: Clients; new(): Clients; -} +}; interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "message": MessageEvent; @@ -1307,7 +1318,7 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope { declare var DedicatedWorkerGlobalScope: { prototype: DedicatedWorkerGlobalScope; new(): DedicatedWorkerGlobalScope; -} +}; interface ExtendableEvent extends Event { waitUntil(f: Promise): void; @@ -1316,7 +1327,7 @@ interface ExtendableEvent extends Event { declare var ExtendableEvent: { prototype: ExtendableEvent; new(type: string, eventInitDict?: ExtendableEventInit): ExtendableEvent; -} +}; interface ExtendableMessageEvent extends ExtendableEvent { readonly data: any; @@ -1329,7 +1340,7 @@ interface ExtendableMessageEvent extends ExtendableEvent { declare var ExtendableMessageEvent: { prototype: ExtendableMessageEvent; new(type: string, eventInitDict?: ExtendableMessageEventInit): ExtendableMessageEvent; -} +}; interface FetchEvent extends ExtendableEvent { readonly clientId: string | null; @@ -1341,7 +1352,7 @@ interface FetchEvent extends ExtendableEvent { declare var FetchEvent: { prototype: FetchEvent; new(type: string, eventInitDict: FetchEventInit): FetchEvent; -} +}; interface FileReaderSync { readAsArrayBuffer(blob: Blob): any; @@ -1353,7 +1364,7 @@ interface FileReaderSync { declare var FileReaderSync: { prototype: FileReaderSync; new(): FileReaderSync; -} +}; interface NotificationEvent extends ExtendableEvent { readonly action: string; @@ -1363,7 +1374,7 @@ interface NotificationEvent extends ExtendableEvent { declare var NotificationEvent: { prototype: NotificationEvent; new(type: string, eventInitDict: NotificationEventInit): NotificationEvent; -} +}; interface PushEvent extends ExtendableEvent { readonly data: PushMessageData | null; @@ -1372,7 +1383,7 @@ interface PushEvent extends ExtendableEvent { declare var PushEvent: { prototype: PushEvent; new(type: string, eventInitDict?: PushEventInit): PushEvent; -} +}; interface PushMessageData { arrayBuffer(): ArrayBuffer; @@ -1384,7 +1395,7 @@ interface PushMessageData { declare var PushMessageData: { prototype: PushMessageData; new(): PushMessageData; -} +}; interface ServiceWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "activate": ExtendableEvent; @@ -1418,7 +1429,7 @@ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { declare var ServiceWorkerGlobalScope: { prototype: ServiceWorkerGlobalScope; new(): ServiceWorkerGlobalScope; -} +}; interface SyncEvent extends ExtendableEvent { readonly lastChance: boolean; @@ -1428,7 +1439,7 @@ interface SyncEvent extends ExtendableEvent { declare var SyncEvent: { prototype: SyncEvent; new(type: string, init: SyncEventInit): SyncEvent; -} +}; interface WindowClient extends Client { readonly focused: boolean; @@ -1440,7 +1451,7 @@ interface WindowClient extends Client { declare var WindowClient: { prototype: WindowClient; new(): WindowClient; -} +}; interface WorkerGlobalScopeEventMap { "error": ErrorEvent; @@ -1463,7 +1474,7 @@ interface WorkerGlobalScope extends EventTarget, WorkerUtils, WindowConsole, Glo declare var WorkerGlobalScope: { prototype: WorkerGlobalScope; new(): WorkerGlobalScope; -} +}; interface WorkerLocation { readonly hash: string; @@ -1481,7 +1492,7 @@ interface WorkerLocation { declare var WorkerLocation: { prototype: WorkerLocation; new(): WorkerLocation; -} +}; interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, NavigatorBeacon, NavigatorConcurrentHardware { readonly hardwareConcurrency: number; @@ -1490,7 +1501,7 @@ interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine, Navigato declare var WorkerNavigator: { prototype: WorkerNavigator; new(): WorkerNavigator; -} +}; interface WorkerUtils extends Object, WindowBase64 { readonly indexedDB: IDBFactory; @@ -1533,38 +1544,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; @@ -1771,8 +1782,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; @@ -1780,21 +1806,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/lib/protocol.d.ts b/lib/protocol.d.ts index 9e26197e21d..7b4bdfe4718 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -2,51 +2,53 @@ * Declaration module describing the TypeScript Server protocol */ declare namespace ts.server.protocol { - namespace CommandTypes { - type Brace = "brace"; - type BraceCompletion = "braceCompletion"; - type Change = "change"; - type Close = "close"; - type Completions = "completions"; - type CompletionDetails = "completionEntryDetails"; - type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - type Configure = "configure"; - type Definition = "definition"; - type Implementation = "implementation"; - type Exit = "exit"; - type Format = "format"; - type Formatonkey = "formatonkey"; - type Geterr = "geterr"; - type GeterrForProject = "geterrForProject"; - type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - type NavBar = "navbar"; - type Navto = "navto"; - type NavTree = "navtree"; - type NavTreeFull = "navtree-full"; - type Occurrences = "occurrences"; - type DocumentHighlights = "documentHighlights"; - type Open = "open"; - type Quickinfo = "quickinfo"; - type References = "references"; - type Reload = "reload"; - type Rename = "rename"; - type Saveto = "saveto"; - type SignatureHelp = "signatureHelp"; - type TypeDefinition = "typeDefinition"; - type ProjectInfo = "projectInfo"; - type ReloadProjects = "reloadProjects"; - type Unknown = "unknown"; - type OpenExternalProject = "openExternalProject"; - type OpenExternalProjects = "openExternalProjects"; - type CloseExternalProject = "closeExternalProject"; - type TodoComments = "todoComments"; - type Indentation = "indentation"; - type DocCommentTemplate = "docCommentTemplate"; - type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - type GetCodeFixes = "getCodeFixes"; - type GetSupportedCodeFixes = "getSupportedCodeFixes"; + const enum CommandTypes { + Brace = "brace", + BraceCompletion = "braceCompletion", + Change = "change", + Close = "close", + Completions = "completions", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", + Implementation = "implementation", + Exit = "exit", + Format = "format", + Formatonkey = "formatonkey", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + NavBar = "navbar", + Navto = "navto", + NavTree = "navtree", + NavTreeFull = "navtree-full", + Occurrences = "occurrences", + DocumentHighlights = "documentHighlights", + Open = "open", + Quickinfo = "quickinfo", + References = "references", + Reload = "reload", + Rename = "rename", + Saveto = "saveto", + SignatureHelp = "signatureHelp", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", + GetSupportedCodeFixes = "getSupportedCodeFixes", + GetApplicableRefactors = "getApplicableRefactors", + GetEditsForRefactor = "getEditsForRefactor", } /** * A TypeScript Server message @@ -287,6 +289,85 @@ declare namespace ts.server.protocol { */ offset: number; } + type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; + /** + * Request refactorings at a given position or selection area. + */ + interface GetApplicableRefactorsRequest extends Request { + command: CommandTypes.GetApplicableRefactors; + arguments: GetApplicableRefactorsRequestArgs; + } + type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs; + /** + * Response is a list of available refactorings. + * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring + */ + interface GetApplicableRefactorsResponse extends Response { + body?: ApplicableRefactorInfo[]; + } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ + interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ + name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ + description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; + } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + type RefactorActionInfo = { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + }; + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; + arguments: GetEditsForRefactorRequestArgs; + } + /** + * Request the edits that a particular refactoring action produces. + * Callers must specify the name of the refactor and the name of the action. + */ + type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { + refactor: string; + action: string; + }; + interface GetEditsForRefactorResponse extends Response { + body?: RefactorEditInfo; + } + type RefactorEditInfo = { + edits: FileCodeEdits[]; + /** + * An optional location where the editor should start a rename operation once + * the refactoring edits have been applied + */ + renameLocation?: Location; + renameFilename?: string; + }; /** * Request for the available codefixes at a specific position. */ @@ -294,10 +375,7 @@ declare namespace ts.server.protocol { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } - /** - * Instances of this interface specify errorcodes on a specific location in a sourcefile. - */ - interface CodeFixRequestArgs extends FileRequestArgs { + interface FileRangeRequestArgs extends FileRequestArgs { /** * The line number for the request (1-based). */ @@ -314,6 +392,11 @@ declare namespace ts.server.protocol { * The character offset (on the line) for the request (1-based). */ endOffset: number; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRangeRequestArgs { /** * Errorcodes we want to get the fixes for. */ @@ -394,7 +477,7 @@ declare namespace ts.server.protocol { command: CommandTypes.Implementation; } /** - * Location in source code expressed as (one-based) line and character offset. + * Location in source code expressed as (one-based) line and (one-based) column offset. */ interface Location { line: number; @@ -488,10 +571,9 @@ declare 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. */ interface HighlightSpan extends TextSpan { - kind: string; + kind: HighlightSpanKind; } /** * Represents a set of highligh spans for a give name @@ -609,7 +691,7 @@ declare 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'). */ @@ -957,7 +1039,7 @@ declare 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'). */ @@ -1143,7 +1225,7 @@ declare 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'). */ @@ -1170,7 +1252,7 @@ declare 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'). */ @@ -1417,6 +1499,12 @@ declare namespace ts.server.protocol { */ source?: string; } + interface DiagnosticWithFileName extends Diagnostic { + /** + * Name of the file the diagnostic is in + */ + fileName: string; + } interface DiagnosticEventBody { /** * The file for which diagnostic information is reported. @@ -1446,7 +1534,7 @@ declare namespace ts.server.protocol { /** * An arry of diagnostic information items for the found config file. */ - diagnostics: Diagnostic[]; + diagnostics: DiagnosticWithFileName[]; } /** * Event message for "configFileDiag" event type. @@ -1563,7 +1651,7 @@ declare namespace ts.server.protocol { /** * The symbol's kind (such as 'className' or 'parameterName'). */ - kind: string; + kind: ScriptElementKind; /** * exact, substring, or prefix. */ @@ -1596,7 +1684,7 @@ declare namespace ts.server.protocol { /** * Kind of symbol's container symbol (if any). */ - containerKind?: string; + containerKind?: ScriptElementKind; } /** * Navto response message. Body is an array of navto items. Each @@ -1660,7 +1748,7 @@ declare 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'). */ @@ -1681,7 +1769,7 @@ declare namespace ts.server.protocol { /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ interface NavigationTree { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems?: NavigationTree[]; @@ -1756,12 +1844,11 @@ declare namespace ts.server.protocol { interface NavTreeResponse extends Response { body?: NavigationTree; } - namespace IndentStyle { - type None = "None"; - type Block = "Block"; - type Smart = "Smart"; + const enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart", } - type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; interface EditorSettings { baseIndentSize?: number; indentSize?: number; @@ -1782,6 +1869,7 @@ declare namespace ts.server.protocol { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; @@ -1854,40 +1942,35 @@ declare namespace ts.server.protocol { typeRoots?: string[]; [option: string]: CompilerOptionsValue | undefined; } - namespace JsxEmit { - type None = "None"; - type Preserve = "Preserve"; - type ReactNative = "ReactNative"; - type React = "React"; + const enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React", } - type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React | JsxEmit.ReactNative; - namespace ModuleKind { - type None = "None"; - type CommonJS = "CommonJS"; - type AMD = "AMD"; - type UMD = "UMD"; - type System = "System"; - type ES6 = "ES6"; - type ES2015 = "ES2015"; + const enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", } - type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; - namespace ModuleResolutionKind { - type Classic = "Classic"; - type Node = "Node"; + const enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node", } - type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; - namespace NewLineKind { - type Crlf = "Crlf"; - type Lf = "Lf"; + const enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf", } - type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; - namespace ScriptTarget { - type ES3 = "ES3"; - type ES5 = "ES5"; - type ES6 = "ES6"; - type ES2015 = "ES2015"; + const enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", } - type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; } declare namespace ts.server.protocol { @@ -1943,6 +2026,8 @@ declare namespace ts.server.protocol { } declare namespace ts { // these types are empty stubs for types from services and should not be used directly + export type HighlightSpanKind = never; + export type ScriptElementKind = never; export type ScriptKind = never; export type IndentStyle = never; export type JsxEmit = never; diff --git a/lib/tsc.js b/lib/tsc.js index 4c846c034f8..9ad790d1385 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -13,451 +13,15 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +"use strict"; 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"; @@ -482,45 +46,6 @@ var ts; 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"; @@ -535,196 +60,6 @@ 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"; @@ -744,309 +79,8 @@ var ts; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(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"; - Extension[Extension["Tsx"] = 1] = "Tsx"; - Extension[Extension["Dts"] = 2] = "Dts"; - Extension[Extension["Js"] = 3] = "Js"; - 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) { @@ -1109,15 +143,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.0"; + ts.versionMajorMinor = "2.5"; + ts.version = ts.versionMajorMinor + ".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() { @@ -1130,12 +159,28 @@ var ts; return new MapCtr(); } ts.createMap = createMap; + function createUnderscoreEscapedMap() { + return new MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function createSymbolTable(symbols) { + var result = createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; function createMapFromTemplate(template) { var map = new MapCtr(); - for (var key in template) + for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); } + } return map; } ts.createMapFromTemplate = createMapFromTemplate; @@ -1205,45 +250,6 @@ var ts; return class_1; }()); } - function createFileMap(keyMapper) { - var files = createMap(); - return { - get: get, - set: set, - contains: contains, - remove: remove, - forEachValue: forEachValueInMap, - getKeys: getKeys, - clear: clear, - }; - function forEachValueInMap(f) { - files.forEach(function (file, key) { - f(key, file); - }); - } - function getKeys() { - return arrayFrom(files.keys()); - } - function get(path) { - return files.get(toKey(path)); - } - function set(path, value) { - files.set(toKey(path), value); - } - function contains(path) { - return files.has(toKey(path)); - } - function remove(path) { - files.delete(toKey(path)); - } - function clear() { - files.clear(); - } - function toKey(path) { - return keyMapper ? keyMapper(path) : path; - } - } - ts.createFileMap = createFileMap; function toPath(fileName, basePath, getCanonicalFileName) { var nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) @@ -1251,12 +257,6 @@ 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; } @@ -1438,6 +438,10 @@ var ts; array.length = outIndex; } ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; function map(array, f) { var result; if (array) { @@ -1507,6 +511,19 @@ var ts; return result; } ts.flatMap = flatMap; + function flatMapIter(iter, mapfn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapfn(value); + if (res) + result.push.apply(result, res); + } + return result; + } + ts.flatMapIter = flatMapIter; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1529,6 +546,18 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapDefined(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } + } + return result; + } + ts.mapDefined = mapDefined; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1722,12 +751,21 @@ var ts; return to; } ts.append = append; - function addRange(to, from) { + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { if (from === undefined) return to; - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - to = append(to, v); + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + var v = from[i]; + if (v !== undefined) { + to.push(from[i]); + } } return to; } @@ -1750,16 +788,22 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; function firstOrUndefined(array) { - return array && array.length > 0 - ? array[0] - : undefined; + return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { @@ -1864,10 +908,11 @@ var ts; ts.getProperty = getProperty; function getOwnKeys(map) { var keys = []; - for (var key in map) + for (var key in map) { if (hasOwnProperty.call(map, key)) { keys.push(key); } + } return keys; } ts.getOwnKeys = getOwnKeys; @@ -1880,15 +925,6 @@ var ts; var _b; } ts.arrayFrom = arrayFrom; - function convertToArray(iterator, f) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(f(value)); - } - return result; - var _b; - } - ts.convertToArray = convertToArray; function forEachEntry(map, callback) { var iterator = map.entries(); for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { @@ -1927,10 +963,11 @@ var ts; } for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var arg = args_1[_a]; - for (var p in arg) + for (var p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; } + } } return t; } @@ -1940,18 +977,20 @@ var ts; return true; if (!left || !right) return false; - for (var key in left) + for (var key in left) { if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } - for (var key in right) + } + for (var key in right) { if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } + } return true; } ts.equalOwnProperties = equalOwnProperties; @@ -1964,6 +1003,10 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToSet(array, makeKey) { + return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -1982,14 +1025,16 @@ var ts; ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) + for (var id in second) { if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - for (var id in first) + } + for (var id in first) { if (hasOwnProperty.call(first, id)) { result[id] = first[id]; } + } return result; } ts.extend = extend; @@ -2023,6 +1068,16 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; function noop() { } ts.noop = noop; function notImplemented() { @@ -2340,10 +1395,18 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); + return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function moduleHasNonRelativeName(moduleName) { + return !isExternalModuleNameRelative(moduleName); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2446,7 +1509,7 @@ var ts; var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - directoryComponents.length--; + directoryComponents.pop(); } var joinStartIndex; for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { @@ -2570,7 +1633,7 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsAny(path, extensions) { + function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; if (fileExtensionIs(path, extension)) { @@ -2579,7 +1642,7 @@ var ts; } return false; } - ts.fileExtensionIsAny = fileExtensionIsAny; + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; @@ -2682,7 +1745,7 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -2694,17 +1757,16 @@ var ts; var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } return flatten(results); - function visitDirectory(path, absolutePath) { + function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; files = files.slice().sort(comparer); - directories = directories.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; @@ -2722,13 +1784,20 @@ var ts; var current = files_1[_i]; _loop_1(current); } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + directories = directories.slice().sort(comparer); for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { var current = directories_1[_b]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName); + visitDirectory(name, absoluteName, depth); } } } @@ -2766,7 +1835,7 @@ var ts; return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } function ensureScriptKind(fileName, scriptKind) { - return (scriptKind || getScriptKindFromFileName(fileName)) || 3; + return scriptKind || getScriptKindFromFileName(fileName) || 3; } ts.ensureScriptKind = ensureScriptKind; function getScriptKindFromFileName(fileName) { @@ -2780,6 +1849,8 @@ var ts; return 3; case ".tsx": return 4; + case ".json": + return 6; default: return 0; } @@ -2825,13 +1896,6 @@ 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])) { @@ -2888,11 +1952,14 @@ var ts; ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; this.declarations = undefined; } - function Type(_checker, flags) { + function Type(checker, flags) { this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } } function Signature() { } @@ -2907,6 +1974,11 @@ var ts; this.parent = undefined; this.original = undefined; } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, getTokenConstructor: function () { return Node; }, @@ -2914,37 +1986,49 @@ var ts; getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, - getSignatureConstructor: function () { return Signature; } + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - 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; + Debug.isDebugging = false; function shouldAssert(level) { return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo) { + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { - var verboseDebugString = ""; if (verboseDebugInfo) { - verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); } - debugger; - throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; - function fail(message) { - Debug.assert(false, message); + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; } Debug.fail = fail; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; })(Debug = ts.Debug || (ts.Debug = {})); function orderedRemoveItem(array, item) { for (var i = 0; i < array.length; i++) { @@ -3045,7 +2129,7 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; function extensionIsTypeScript(ext) { - return ext <= ts.Extension.LastTypeScriptExtension; + return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } ts.extensionIsTypeScript = extensionIsTypeScript; function extensionFromPath(path) { @@ -3057,21 +2141,7 @@ var ts; } ts.extensionFromPath = extensionFromPath; function tryGetExtensionFromPath(path) { - if (fileExtensionIs(path, ".d.ts")) { - return ts.Extension.Dts; - } - if (fileExtensionIs(path, ".ts")) { - return ts.Extension.Ts; - } - if (fileExtensionIs(path, ".tsx")) { - return ts.Extension.Tsx; - } - if (fileExtensionIs(path, ".js")) { - return ts.Extension.Js; - } - if (fileExtensionIs(path, ".jsx")) { - return ts.Extension.Jsx; - } + return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3081,6 +2151,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -3153,7 +2229,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName); + fileCallback(fileName, FileWatcherEventKind.Changed); } } } @@ -3166,7 +2242,13 @@ var ts; if (platform === "win32" || platform === "win64") { return false; } - return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + return !fileExists(swapCase(__filename)); + } + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); @@ -3239,14 +2321,9 @@ var ts; return { files: [], directories: [] }; } } - function readDirectory(path, extensions, excludes, includes) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, 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); @@ -3292,10 +2369,19 @@ var ts; }; } function fileChanged(curr, prev) { - if (+curr.mtime <= +prev.mtime) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { return; } - callback(fileName); + callback(fileName, eventKind); } }, watchDirectory: function (directoryName, callback, recursive) { @@ -3315,9 +2401,7 @@ var ts; } }); }, - resolvePath: function (path) { - return _path.resolve(path); - }, + resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { @@ -3371,6 +2455,7 @@ var ts; realpath: function (path) { return _fs.realpathSync(path); }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { try { require("source-map-support").install(); @@ -3407,7 +2492,7 @@ var ts; getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), - readDirectory: function (path, extensions, excludes, includes) { + readDirectory: function (path, extensions, excludes, includes, _depth) { var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, @@ -3449,910 +2534,933 @@ var ts; ? 1 : 0; } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } })(ts || (ts = {})); var ts; (function (ts) { + function diag(code, category, key, message) { + return { code: code, category: category, key: key, message: message }; + } ts.Diagnostics = { - Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated_string_literal_1002", message: "Unterminated string literal." }, - Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_1003", message: "Identifier expected." }, - _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "_0_expected_1005", message: "'{0}' expected." }, - A_file_cannot_have_a_reference_to_itself: { code: 1006, category: ts.DiagnosticCategory.Error, key: "A_file_cannot_have_a_reference_to_itself_1006", message: "A file cannot have a reference to itself." }, - Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing_comma_not_allowed_1009", message: "Trailing comma not allowed." }, - Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "Asterisk_Slash_expected_1010", message: "'*/' expected." }, - Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_1012", message: "Unexpected token." }, - A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_last_in_a_parameter_list_1014", message: "A rest parameter must be last in a parameter list." }, - Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: ts.DiagnosticCategory.Error, key: "Parameter_cannot_have_question_mark_and_initializer_1015", message: "Parameter cannot have question mark and initializer." }, - A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: ts.DiagnosticCategory.Error, key: "A_required_parameter_cannot_follow_an_optional_parameter_1016", message: "A required parameter cannot follow an optional parameter." }, - An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: ts.DiagnosticCategory.Error, key: "An_index_signature_cannot_have_a_rest_parameter_1017", message: "An index signature cannot have a rest parameter." }, - An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", message: "An index signature parameter cannot have an accessibility modifier." }, - An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_a_question_mark_1019", message: "An index signature parameter cannot have a question mark." }, - An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_initializer_1020", message: "An index signature parameter cannot have an initializer." }, - An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, - An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, - An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, - readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, - Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, - _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, - _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, - _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_class_element_1031", message: "'{0}' modifier cannot appear on a class element." }, - super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: ts.DiagnosticCategory.Error, key: "super_must_be_followed_by_an_argument_list_or_member_access_1034", message: "'super' must be followed by an argument list or member access." }, - Only_ambient_modules_can_use_quoted_names: { code: 1035, category: ts.DiagnosticCategory.Error, key: "Only_ambient_modules_can_use_quoted_names_1035", message: "Only ambient modules can use quoted names." }, - Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: ts.DiagnosticCategory.Error, key: "Statements_are_not_allowed_in_ambient_contexts_1036", message: "Statements are not allowed in ambient contexts." }, - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", message: "A 'declare' modifier cannot be used in an already ambient context." }, - Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: ts.DiagnosticCategory.Error, key: "Initializers_are_not_allowed_in_ambient_contexts_1039", message: "Initializers are not allowed in ambient contexts." }, - _0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_in_an_ambient_context_1040", message: "'{0}' modifier cannot be used in an ambient context." }, - _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, - _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, - _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, - A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, - A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, - A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, - A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_have_an_initializer_1048", message: "A rest parameter cannot have an initializer." }, - A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_must_have_exactly_one_parameter_1049", message: "A 'set' accessor must have exactly one parameter." }, - A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_an_optional_parameter_1051", message: "A 'set' accessor cannot have an optional parameter." }, - A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, - A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, - A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, - An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, - The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", message: "The return type of an async function must either be a valid promise or must not contain a callable 'then' member." }, - A_promise_must_have_a_then_method: { code: 1059, category: ts.DiagnosticCategory.Error, key: "A_promise_must_have_a_then_method_1059", message: "A promise must have a 'then' method." }, - The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: { code: 1060, category: ts.DiagnosticCategory.Error, key: "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", message: "The first parameter of the 'then' method of a promise must be a callback." }, - Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, - Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, - An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, - In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, - Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, - _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, - _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, - A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, - Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." }, - An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_be_declared_in_an_ambient_context_1086", message: "An accessor cannot be declared in an ambient context." }, - _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", message: "'{0}' modifier cannot appear on a constructor declaration." }, - _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_parameter_1090", message: "'{0}' modifier cannot appear on a parameter." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", message: "Only a single variable declaration is allowed in a 'for...in' statement." }, - Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: ts.DiagnosticCategory.Error, key: "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", message: "Type parameters cannot appear on a constructor declaration." }, - Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: ts.DiagnosticCategory.Error, key: "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", message: "Type annotation cannot appear on a constructor declaration." }, - An_accessor_cannot_have_type_parameters: { code: 1094, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_have_type_parameters_1094", message: "An accessor cannot have type parameters." }, - A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_a_return_type_annotation_1095", message: "A 'set' accessor cannot have a return type annotation." }, - An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_exactly_one_parameter_1096", message: "An index signature must have exactly one parameter." }, - _0_list_cannot_be_empty: { code: 1097, category: ts.DiagnosticCategory.Error, key: "_0_list_cannot_be_empty_1097", message: "'{0}' list cannot be empty." }, - Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type_parameter_list_cannot_be_empty_1098", message: "Type parameter list cannot be empty." }, - Type_argument_list_cannot_be_empty: { code: 1099, category: ts.DiagnosticCategory.Error, key: "Type_argument_list_cannot_be_empty_1099", message: "Type argument list cannot be empty." }, - Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_in_strict_mode_1100", message: "Invalid use of '{0}' in strict mode." }, - with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_strict_mode_1101", message: "'with' statements are not allowed in strict mode." }, - delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", message: "'delete' cannot be called on an identifier in strict mode." }, - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: { code: 1103, category: ts.DiagnosticCategory.Error, key: "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", message: "A 'for-await-of' statement is only allowed within an async function or async generator." }, - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", message: "A 'continue' statement can only be used within an enclosing iteration statement." }, - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", message: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, - Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump_target_cannot_cross_function_boundary_1107", message: "Jump target cannot cross function boundary." }, - A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: ts.DiagnosticCategory.Error, key: "A_return_statement_can_only_be_used_within_a_function_body_1108", message: "A 'return' statement can only be used within a function body." }, - Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." }, - Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." }, - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", message: "A 'default' clause cannot appear more than once in a 'switch' statement." }, - Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'." }, - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", message: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", message: "A 'break' statement can only jump to a label of an enclosing statement." }, - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", message: "An object literal cannot have multiple properties with the same name in strict mode." }, - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", message: "An object literal cannot have multiple get/set accessors with the same name." }, - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", message: "An object literal cannot have property and accessor with the same name." }, - An_export_assignment_cannot_have_modifiers: { code: 1120, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_have_modifiers_1120", message: "An export assignment cannot have modifiers." }, - Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_strict_mode_1121", message: "Octal literals are not allowed in strict mode." }, - A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: ts.DiagnosticCategory.Error, key: "A_tuple_type_element_list_cannot_be_empty_1122", message: "A tuple type element list cannot be empty." }, - Variable_declaration_list_cannot_be_empty: { code: 1123, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_list_cannot_be_empty_1123", message: "Variable declaration list cannot be empty." }, - Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit_expected_1124", message: "Digit expected." }, - Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal_digit_expected_1125", message: "Hexadecimal digit expected." }, - Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected_end_of_text_1126", message: "Unexpected end of text." }, - Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid_character_1127", message: "Invalid character." }, - Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration_or_statement_expected_1128", message: "Declaration or statement expected." }, - Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement_expected_1129", message: "Statement expected." }, - case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "case_or_default_expected_1130", message: "'case' or 'default' expected." }, - Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property_or_signature_expected_1131", message: "Property or signature expected." }, - Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum_member_expected_1132", message: "Enum member expected." }, - Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_expected_1134", message: "Variable declaration expected." }, - Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument_expression_expected_1135", message: "Argument expression expected." }, - Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property_assignment_expected_1136", message: "Property assignment expected." }, - Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression_or_comma_expected_1137", message: "Expression or comma expected." }, - Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter_declaration_expected_1138", message: "Parameter declaration expected." }, - Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type_parameter_declaration_expected_1139", message: "Type parameter declaration expected." }, - Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type_argument_expected_1140", message: "Type argument expected." }, - String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, - Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, - or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, - Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, - File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing." }, - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, - const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized." }, - const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "const_declarations_can_only_be_declared_inside_a_block_1156", message: "'const' declarations can only be declared inside a block." }, - let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "let_declarations_can_only_be_declared_inside_a_block_1157", message: "'let' declarations can only be declared inside a block." }, - Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." }, - Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated_regular_expression_literal_1161", message: "Unterminated regular expression literal." }, - An_object_member_cannot_be_declared_optional: { code: 1162, category: ts.DiagnosticCategory.Error, key: "An_object_member_cannot_be_declared_optional_1162", message: "An object member cannot be declared optional." }, - A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: ts.DiagnosticCategory.Error, key: "A_yield_expression_is_only_allowed_in_a_generator_body_1163", message: "A 'yield' expression is only allowed in a generator body." }, - Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "Computed_property_names_are_not_allowed_in_enums_1164", message: "Computed property names are not allowed in enums." }, - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", message: "A computed property name in an ambient context must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", message: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", message: "A computed property name in a method overload must directly refer to a built-in symbol." }, - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", message: "A computed property name in an interface must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", message: "A computed property name in a type literal must directly refer to a built-in symbol." }, - A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: ts.DiagnosticCategory.Error, key: "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", message: "A comma expression is not allowed in a computed property name." }, - extends_clause_already_seen: { code: 1172, category: ts.DiagnosticCategory.Error, key: "extends_clause_already_seen_1172", message: "'extends' clause already seen." }, - extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "extends_clause_must_precede_implements_clause_1173", message: "'extends' clause must precede 'implements' clause." }, - Classes_can_only_extend_a_single_class: { code: 1174, category: ts.DiagnosticCategory.Error, key: "Classes_can_only_extend_a_single_class_1174", message: "Classes can only extend a single class." }, - implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "implements_clause_already_seen_1175", message: "'implements' clause already seen." }, - Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface_declaration_cannot_have_implements_clause_1176", message: "Interface declaration cannot have 'implements' clause." }, - Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary_digit_expected_1177", message: "Binary digit expected." }, - Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal_digit_expected_1178", message: "Octal digit expected." }, - Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_expected_1179", message: "Unexpected token. '{' expected." }, - Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property_destructuring_pattern_expected_1180", message: "Property destructuring pattern expected." }, - Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array_element_destructuring_pattern_expected_1181", message: "Array element destructuring pattern expected." }, - A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: ts.DiagnosticCategory.Error, key: "A_destructuring_declaration_must_have_an_initializer_1182", message: "A destructuring declaration must have an initializer." }, - An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1183, category: ts.DiagnosticCategory.Error, key: "An_implementation_cannot_be_declared_in_ambient_contexts_1183", message: "An implementation cannot be declared in ambient contexts." }, - Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, - Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, - A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, - The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, - The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, - An_import_declaration_cannot_have_modifiers: { code: 1191, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_cannot_have_modifiers_1191", message: "An import declaration cannot have modifiers." }, - Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, - An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, - Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, - Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, - An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, - Unterminated_Unicode_escape_sequence: { code: 1199, category: ts.DiagnosticCategory.Error, key: "Unterminated_Unicode_escape_sequence_1199", message: "Unterminated Unicode escape sequence." }, - 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." }, - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", message: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." }, - Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", message: "Invalid use of '{0}'. Class definitions are automatically in strict mode." }, - A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, - Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, - Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, - Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, - Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, - Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: ts.DiagnosticCategory.Error, key: "Generators_are_not_allowed_in_an_ambient_context_1221", message: "Generators are not allowed in an ambient context." }, - An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, - _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "_0_tag_already_specified_1223", message: "'{0}' tag already specified." }, - Signature_0_must_have_a_type_predicate: { code: 1224, category: ts.DiagnosticCategory.Error, key: "Signature_0_must_have_a_type_predicate_1224", message: "Signature '{0}' must have a type predicate." }, - Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot_find_parameter_0_1225", message: "Cannot find parameter '{0}'." }, - Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: ts.DiagnosticCategory.Error, key: "Type_predicate_0_is_not_assignable_to_1_1226", message: "Type predicate '{0}' is not assignable to '{1}'." }, - Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: ts.DiagnosticCategory.Error, key: "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", message: "Parameter '{0}' is not in the same position as parameter '{1}'." }, - A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", message: "A type predicate is only allowed in return type position for functions and methods." }, - A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_a_rest_parameter_1229", message: "A type predicate cannot reference a rest parameter." }, - A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", message: "A type predicate cannot reference element '{0}' in a binding pattern." }, - An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_can_only_be_used_in_a_module_1231", message: "An export assignment can only be used in a module." }, - An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", message: "An import declaration can only be used in a namespace or module." }, - An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_can_only_be_used_in_a_module_1233", message: "An export declaration can only be used in a module." }, - An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", message: "An ambient module declaration is only allowed at the top level in a file." }, - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", message: "A namespace declaration is only allowed in a namespace or module." }, - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", message: "The return type of a property decorator function must be either 'void' or 'any'." }, - The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", message: "The return type of a parameter decorator function must be either 'void' or 'any'." }, - Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", message: "Unable to resolve signature of class decorator when called as an expression." }, - Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, - Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, - Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, - _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, - Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, - Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, - An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, - A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, - A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, - A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: { code: 1250, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, - _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, - with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, - await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, - The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, - Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, - Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, - Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, - A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, - An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, - A_default_export_can_only_be_used_in_an_ECMAScript_style_module: { code: 1319, category: ts.DiagnosticCategory.Error, key: "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", message: "A default export can only be used in an ECMAScript-style module." }, - Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1320, category: ts.DiagnosticCategory.Error, key: "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", message: "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1321, category: ts.DiagnosticCategory.Error, key: "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", message: "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1322, category: ts.DiagnosticCategory.Error, key: "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", message: "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member." }, - Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, - Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, - Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, - Circular_definition_of_import_alias_0: { code: 2303, category: ts.DiagnosticCategory.Error, key: "Circular_definition_of_import_alias_0_2303", message: "Circular definition of import alias '{0}'." }, - Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_2304", message: "Cannot find name '{0}'." }, - Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, - File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, - Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, - Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, - An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, - Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, - A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, - An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, - Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, - Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, - Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, - Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_have_1_type_parameter_s_2317", message: "Global type '{0}' must have {1} type parameter(s)." }, - Cannot_find_global_type_0: { code: 2318, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_type_0_2318", message: "Cannot find global type '{0}'." }, - Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: ts.DiagnosticCategory.Error, key: "Named_property_0_of_types_1_and_2_are_not_identical_2319", message: "Named property '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, - Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, - Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, - Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, - Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, - Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: ts.DiagnosticCategory.Error, key: "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", message: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: ts.DiagnosticCategory.Error, key: "Types_of_parameters_0_and_1_are_incompatible_2328", message: "Types of parameters '{0}' and '{1}' are incompatible." }, - Index_signature_is_missing_in_type_0: { code: 2329, category: ts.DiagnosticCategory.Error, key: "Index_signature_is_missing_in_type_0_2329", message: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index_signatures_are_incompatible_2330", message: "Index signatures are incompatible." }, - this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", message: "'this' cannot be referenced in a module or namespace body." }, - this_cannot_be_referenced_in_current_location: { code: 2332, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_current_location_2332", message: "'this' cannot be referenced in current location." }, - this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_constructor_arguments_2333", message: "'this' cannot be referenced in constructor arguments." }, - this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_static_property_initializer_2334", message: "'this' cannot be referenced in a static property initializer." }, - super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_a_derived_class_2335", message: "'super' can only be referenced in a derived class." }, - super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_constructor_arguments_2336", message: "'super' cannot be referenced in constructor arguments." }, - Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: ts.DiagnosticCategory.Error, key: "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", message: "Super calls are not permitted outside constructors or in nested functions inside constructors." }, - super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: ts.DiagnosticCategory.Error, key: "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", message: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." }, - Property_0_does_not_exist_on_type_1: { code: 2339, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_2339", message: "Property '{0}' does not exist on type '{1}'." }, - Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, - Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, - An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, - 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}'." }, - 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." }, - Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, - Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, - Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, - Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, - The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, - The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter." }, - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, - Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, - Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, - Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'." }, - A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", message: "A parameter property is only allowed in a constructor implementation." }, - A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_of_an_array_type_2370", message: "A rest parameter must be of an array type." }, - A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", message: "A parameter initializer is only allowed in a function or constructor implementation." }, - Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: ts.DiagnosticCategory.Error, key: "Parameter_0_cannot_be_referenced_in_its_initializer_2372", message: "Parameter '{0}' cannot be referenced in its initializer." }, - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: ts.DiagnosticCategory.Error, key: "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", message: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, - Duplicate_string_index_signature: { code: 2374, category: ts.DiagnosticCategory.Error, key: "Duplicate_string_index_signature_2374", message: "Duplicate string index signature." }, - Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, - Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, - Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, - get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, - A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, - Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, - Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, - Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, - Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, - Function_overload_must_be_static: { code: 2387, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_be_static_2387", message: "Function overload must be static." }, - Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_not_be_static_2388", message: "Function overload must not be static." }, - Function_implementation_name_must_be_0: { code: 2389, category: ts.DiagnosticCategory.Error, key: "Function_implementation_name_must_be_0_2389", message: "Function implementation name must be '{0}'." }, - Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor_implementation_is_missing_2390", message: "Constructor implementation is missing." }, - Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: ts.DiagnosticCategory.Error, key: "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", message: "Function implementation is missing or not immediately following the declaration." }, - Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: ts.DiagnosticCategory.Error, key: "Multiple_constructor_implementations_are_not_allowed_2392", message: "Multiple constructor implementations are not allowed." }, - Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate_function_implementation_2393", message: "Duplicate function implementation." }, - Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, - Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, - Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, - Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, - Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, - Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, - Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", message: "Expression resolves to '_super' that compiler uses to capture base class reference." }, - Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, - The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, - The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, - Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, - Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class." }, - The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, - Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, - Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, - Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, - Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'." }, - Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, - A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, - Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'." }, - All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, - Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'." }, - In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, - A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged." }, - A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged." }, - Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", message: "Ambient modules cannot be nested in other modules or namespaces." }, - Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient_module_declaration_cannot_specify_relative_module_name_2436", message: "Ambient module declaration cannot specify relative module name." }, - Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name." }, - Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'." }, - Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", message: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." }, - Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." }, - Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types_have_separate_declarations_of_a_private_property_0_2442", message: "Types have separate declarations of a private property '{0}'." }, - Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", message: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." }, - Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", message: "Property '{0}' is protected in type '{1}' but public in type '{2}'." }, - Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", message: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, - The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, - Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - Class_0_used_before_its_declaration: { code: 2449, category: ts.DiagnosticCategory.Error, key: "Class_0_used_before_its_declaration_2449", message: "Class '{0}' used before its declaration." }, - Enum_0_used_before_its_declaration: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Enum_0_used_before_its_declaration_2450", message: "Enum '{0}' used before its declaration." }, - Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, - An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, - The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, - Variable_0_is_used_before_being_assigned: { code: 2454, category: ts.DiagnosticCategory.Error, key: "Variable_0_is_used_before_being_assigned_2454", message: "Variable '{0}' is used before being assigned." }, - Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", message: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, - Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type_alias_0_circularly_references_itself_2456", message: "Type alias '{0}' circularly references itself." }, - Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'." }, - An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An_AMD_module_cannot_have_multiple_name_assignments_2458", message: "An AMD module cannot have multiple name assignments." }, - Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, - Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, - Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern." }, - A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, - A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, - this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, - super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_a_computed_property_name_2466", message: "'super' cannot be referenced in a computed property name." }, - A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", message: "A computed property name cannot reference a type parameter from its containing type." }, - Cannot_find_global_value_0: { code: 2468, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_value_0_2468", message: "Cannot find global value '{0}'." }, - The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: ts.DiagnosticCategory.Error, key: "The_0_operator_cannot_be_applied_to_type_symbol_2469", message: "The '{0}' operator cannot be applied to type 'symbol'." }, - Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: ts.DiagnosticCategory.Error, key: "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", message: "'Symbol' reference does not refer to the global Symbol constructor object." }, - A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", message: "A computed property name of the form '{0}' must be of type 'symbol'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", message: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." }, - Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: ts.DiagnosticCategory.Error, key: "Enum_declarations_must_all_be_const_or_non_const_2473", message: "Enum declarations must all be const or non-const." }, - In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: ts.DiagnosticCategory.Error, key: "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", message: "In 'const' enum declarations member initializer must be constant expression." }, - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: ts.DiagnosticCategory.Error, key: "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", message: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." }, - A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: ts.DiagnosticCategory.Error, key: "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", message: "A const enum member can only be accessed using a string literal." }, - const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", message: "'const' enum member initializer was evaluated to a non-finite value." }, - const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", message: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, - Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_const_enum_1_2479", message: "Property '{0}' does not exist on 'const' enum '{1}'." }, - let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", message: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." }, - Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, - The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, - Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'." }, - The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, - An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, - The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", message: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." }, - Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause." }, - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", message: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." }, - Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", message: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." }, - Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_2495", message: "Type '{0}' is not an array type or a string type." }, - The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", message: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." }, - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: ts.DiagnosticCategory.Error, key: "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", message: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." }, - Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: ts.DiagnosticCategory.Error, key: "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", message: "Module '{0}' uses 'export =' and cannot be used with 'export *'." }, - An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", message: "An interface can only extend an identifier/qualified-name with optional type arguments." }, - A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", message: "A class can only implement an identifier/qualified-name with optional type arguments." }, - A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, - _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, - Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: { code: 2504, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", message: "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator." }, - A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, - _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, - Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, - No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: ts.DiagnosticCategory.Error, key: "No_base_constructor_has_the_specified_number_of_type_arguments_2508", message: "No base constructor has the specified number of type arguments." }, - Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, - Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, - Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, - Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, - Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, - Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, - All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, - Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, - A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, - An_async_iterator_must_have_a_next_method: { code: 2519, category: ts.DiagnosticCategory.Error, key: "An_async_iterator_must_have_a_next_method_2519", message: "An async iterator must have a 'next()' method." }, - Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, - Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, - yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, - await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, - A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, - A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, - Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, - Object_is_possibly_null: { code: 2531, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_2531", message: "Object is possibly 'null'." }, - Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, - Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, - A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, - Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, - Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, - Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, - Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, - The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, - Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, - Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, - Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, - A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, - The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: { code: 2547, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", message: "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property." }, - Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { 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." }, - Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'." }, - JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", message: "JSX element type '{0}' does not have any construct or call signatures." }, - JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", message: "JSX element type '{0}' is not a constructor function for JSX elements." }, - Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", message: "Property '{0}' of JSX spread attribute is not assignable to target property." }, - JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property." }, - The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property." }, - JSX_spread_child_must_be_an_array_type: { code: 2609, category: ts.DiagnosticCategory.Error, key: "JSX_spread_child_must_be_an_array_type_2609", message: "JSX spread child must be an array type." }, - Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: { code: 2649, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", message: "Cannot augment module '{0}' with value exports because it resolves to a non-module entity." }, - Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React." }, - A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", message: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." }, - Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", message: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, - Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", message: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." }, - Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, - Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, - JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element." }, - Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'." }, - super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, - super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, - Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", message: "Cannot export '{0}'. Only local declarations can be exported from a module." }, - Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, - Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, - Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, - Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, - Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, - Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, - export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, - Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, - Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, - Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, - Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, - Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, - Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, - Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, - Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, - A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: { code: 2677, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", message: "A type predicate's type must be assignable to its parameter's type." }, - Type_0_is_not_comparable_to_type_1: { code: 2678, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_comparable_to_type_1_2678", message: "Type '{0}' is not comparable to type '{1}'." }, - A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: { code: 2679, category: ts.DiagnosticCategory.Error, key: "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", message: "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'." }, - A_this_parameter_must_be_the_first_parameter: { code: 2680, category: ts.DiagnosticCategory.Error, key: "A_this_parameter_must_be_the_first_parameter_2680", message: "A 'this' parameter must be the first parameter." }, - A_constructor_cannot_have_a_this_parameter: { code: 2681, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_have_a_this_parameter_2681", message: "A constructor cannot have a 'this' parameter." }, - get_and_set_accessor_must_have_the_same_this_type: { code: 2682, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_this_type_2682", message: "'get' and 'set' accessor must have the same 'this' type." }, - this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, - The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, - The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, - All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, - Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, - Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, - Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, - The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, - Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, - Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: { code: 2699, category: ts.DiagnosticCategory.Error, key: "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", message: "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'." }, - Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, - The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, - The_operand_of_a_delete_operator_must_be_a_property_reference: { code: 2703, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", message: "The operand of a delete operator must be a property reference." }, - The_operand_of_a_delete_operator_cannot_be_a_read_only_property: { code: 2704, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", message: "The operand of a delete operator cannot be a read-only property." }, - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: { code: 2705, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", message: "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option." }, - Required_type_parameters_may_not_follow_optional_type_parameters: { code: 2706, category: ts.DiagnosticCategory.Error, key: "Required_type_parameters_may_not_follow_optional_type_parameters_2706", message: "Required type parameters may not follow optional type parameters." }, - Generic_type_0_requires_between_1_and_2_type_arguments: { code: 2707, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_between_1_and_2_type_arguments_2707", message: "Generic type '{0}' requires between {1} and {2} type arguments." }, - Cannot_use_namespace_0_as_a_value: { code: 2708, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_value_2708", message: "Cannot use namespace '{0}' as a value." }, - Cannot_use_namespace_0_as_a_type: { code: 2709, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_type_2709", message: "Cannot use namespace '{0}' as a type." }, - _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: { code: 2710, category: ts.DiagnosticCategory.Error, key: "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", message: "'{0}' are specified twice. The attribute named '{0}' will be overwritten." }, - Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, - Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, - Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", message: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", message: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", message: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", message: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", message: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", message: "Type parameter '{0}' of exported function has or is using private name '{1}'." }, - Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", message: "Implements clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "'extends' clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "'extends' clause of exported interface '{0}' has or is using private name '{1}'." }, - Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", message: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." }, - Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", message: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." }, - Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_private_name_1_4025", message: "Exported variable '{0}' has or is using private name '{1}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", message: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", message: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", message: "Public static property '{0}' of exported class has or is using private name '{1}'." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", message: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", message: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", message: "Public property '{0}' of exported class has or is using private name '{1}'." }, - Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", message: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." }, - Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", message: "Property '{0}' of exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", message: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", message: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", message: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", message: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", message: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", message: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", message: "Return type of public static property getter from exported class has or is using private name '{0}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", message: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", message: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", message: "Return type of public property getter from exported class has or is using private name '{0}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", message: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", message: "Return type of constructor signature from exported interface has or is using private name '{0}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", message: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", message: "Return type of call signature from exported interface has or is using private name '{0}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", message: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", message: "Return type of index signature from exported interface has or is using private name '{0}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", message: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", message: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", message: "Return type of public static method from exported class has or is using private name '{0}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", message: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", message: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", message: "Return type of public method from exported class has or is using private name '{0}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", message: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", message: "Return type of method from exported interface has or is using private name '{0}'." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", message: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", message: "Return type of exported function has or is using name '{0}' from private module '{1}'." }, - Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", message: "Return type of exported function has or is using private name '{0}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", message: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", message: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", message: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", message: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", message: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", message: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", message: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", message: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", message: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", message: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", message: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, - Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, - Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced: { code: 4093, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced_4093", message: "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced." }, - The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, - Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, - File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, - Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}." }, - Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, - Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "Unknown compiler option '{0}'." }, - Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_requires_a_value_of_type_1_5024", message: "Compiler option '{0}' requires a value of type {1}." }, - Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}." }, - Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", message: "Option 'project' cannot be mixed with source files on a command line." }, - Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher." }, - Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", message: "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." }, - Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, - Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, - A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, - Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, - Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, - Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'." }, - The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'." }, - Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, - Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, - Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character." }, - Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character." }, - Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, - Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, - File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, - Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, - Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, - Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, - Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, - Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", message: "Specify the location where debugger should locate TypeScript files instead of source locations." }, - Watch_input_files: { code: 6005, category: ts.DiagnosticCategory.Message, key: "Watch_input_files_6005", message: "Watch input files." }, - Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect_output_structure_to_the_directory_6006", message: "Redirect output structure to the directory." }, - Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: ts.DiagnosticCategory.Message, key: "Do_not_erase_const_enum_declarations_in_generated_code_6007", message: "Do not erase const enum declarations in generated code." }, - Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, - Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, - Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, - Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, - Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'." }, - Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'." }, - Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, - Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, - Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", message: "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'." }, - Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" }, - options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" }, - file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" }, - Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples_Colon_0_6026", message: "Examples: {0}" }, - Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options_Colon_6027", message: "Options:" }, - Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version_0_6029", message: "Version {0}" }, - Insert_command_line_options_and_files_from_a_file: { code: 6030, category: ts.DiagnosticCategory.Message, key: "Insert_command_line_options_and_files_from_a_file_6030", message: "Insert command line options and files from a file." }, - File_change_detected_Starting_incremental_compilation: { code: 6032, category: ts.DiagnosticCategory.Message, key: "File_change_detected_Starting_incremental_compilation_6032", message: "File change detected. Starting incremental compilation..." }, - KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND_6034", message: "KIND" }, - FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE_6035", message: "FILE" }, - VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, - LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, - DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, - STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, - FILE_OR_DIRECTORY: { code: 6040, category: ts.DiagnosticCategory.Message, key: "FILE_OR_DIRECTORY_6040", message: "FILE OR DIRECTORY" }, - Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, - Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, - Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, - Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}." }, - Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, - Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, - Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." }, - Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted_locale_file_0_6051", message: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", message: "Raise error on expressions and declarations with an implied 'any' type." }, - File_0_not_found: { code: 6053, category: ts.DiagnosticCategory.Error, key: "File_0_not_found_6053", message: "File '{0}' not found." }, - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: ts.DiagnosticCategory.Error, key: "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", message: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, - Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: ts.DiagnosticCategory.Message, key: "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", message: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, - Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", message: "Do not emit declarations for code that has an '@internal' annotation." }, - Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: ts.DiagnosticCategory.Message, key: "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", message: "Specify the root directory of input files. Use to control the output directory structure with --outDir." }, - File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", message: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, - Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", message: "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, - NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, - Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, - Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, - Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, - Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, - Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: { code: 6069, category: ts.DiagnosticCategory.Message, key: "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", message: "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)." }, - Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, - Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, - Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context (experimental)." }, - Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, - Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, - Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, - Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, - Specify_library_files_to_be_included_in_the_compilation_Colon: { code: 6079, category: ts.DiagnosticCategory.Message, key: "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", message: "Specify library files to be included in the compilation: " }, - Specify_JSX_code_generation_Colon_preserve_react_native_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", message: "Specify JSX code generation: 'preserve', 'react-native', or 'react'." }, - File_0_has_an_unsupported_extension_so_skipping_it: { code: 6081, category: ts.DiagnosticCategory.Message, key: "File_0_has_an_unsupported_extension_so_skipping_it_6081", message: "File '{0}' has an unsupported extension, so skipping it." }, - Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, - Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, - Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", message: "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit" }, - Enable_tracing_of_the_name_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_name_resolution_process_6085", message: "Enable tracing of the name resolution process." }, - Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, - Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, - Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, - Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, - Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, - paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, - Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, - Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, - Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, - Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", message: "Loading module as file / folder, candidate module location '{0}', target file type '{1}'." }, - File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, - File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, - Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, - Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, - package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, - Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, - Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, - Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, - Expected_type_of_0_field_in_package_json_to_be_string_got_1: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", message: "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'." }, - baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'." }, - rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'." }, - Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'." }, - Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'." }, - Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'." }, - Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed." }, - Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, - Enable_strict_null_checks: { code: 6113, category: ts.DiagnosticCategory.Message, key: "Enable_strict_null_checks_6113", message: "Enable strict null checks." }, - Unknown_option_excludes_Did_you_mean_exclude: { code: 6114, category: ts.DiagnosticCategory.Error, key: "Unknown_option_excludes_Did_you_mean_exclude_6114", message: "Unknown option 'excludes'. Did you mean 'exclude'?" }, - Raise_error_on_this_expressions_with_an_implied_any_type: { code: 6115, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_this_expressions_with_an_implied_any_type_6115", message: "Raise error on 'this' expressions with an implied 'any' type." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_2: { code: 6116, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========" }, - Resolving_using_primary_search_paths: { code: 6117, category: ts.DiagnosticCategory.Message, key: "Resolving_using_primary_search_paths_6117", message: "Resolving using primary search paths..." }, - Resolving_from_node_modules_folder: { code: 6118, category: ts.DiagnosticCategory.Message, key: "Resolving_from_node_modules_folder_6118", message: "Resolving from node_modules folder..." }, - Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: { code: 6119, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", message: "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========" }, - Type_reference_directive_0_was_not_resolved: { code: 6120, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_not_resolved_6120", message: "======== Type reference directive '{0}' was not resolved. ========" }, - Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'." }, - Root_directory_cannot_be_determined_skipping_primary_search_paths: { code: 6122, category: ts.DiagnosticCategory.Message, key: "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", message: "Root directory cannot be determined, skipping primary search paths." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: { code: 6123, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========" }, - Type_declaration_files_to_be_included_in_compilation: { code: 6124, category: ts.DiagnosticCategory.Message, key: "Type_declaration_files_to_be_included_in_compilation_6124", message: "Type declaration files to be included in compilation." }, - Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'." }, - Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: { code: 6126, category: ts.DiagnosticCategory.Message, key: "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", message: "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder." }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: { code: 6127, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", message: "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========" }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, - The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, - Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'." }, - Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, - File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it." }, - _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - 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}'." }, - Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file." }, - Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, - Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, - Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, - Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, - Resolution_for_module_0_was_found_in_cache: { code: 6147, category: ts.DiagnosticCategory.Message, key: "Resolution_for_module_0_was_found_in_cache_6147", message: "Resolution for module '{0}' was found in cache." }, - Directory_0_does_not_exist_skipping_all_lookups_in_it: { code: 6148, category: ts.DiagnosticCategory.Message, key: "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", message: "Directory '{0}' does not exist, skipping all lookups in it." }, - Show_diagnostic_information: { code: 6149, category: ts.DiagnosticCategory.Message, key: "Show_diagnostic_information_6149", message: "Show diagnostic information." }, - Show_verbose_diagnostic_information: { code: 6150, category: ts.DiagnosticCategory.Message, key: "Show_verbose_diagnostic_information_6150", message: "Show verbose diagnostic information." }, - Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: { code: 6151, category: ts.DiagnosticCategory.Message, key: "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", message: "Emit a single file with source maps instead of having a separate file." }, - Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: { code: 6152, category: ts.DiagnosticCategory.Message, key: "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", message: "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set." }, - Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: { code: 6153, category: ts.DiagnosticCategory.Message, key: "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", message: "Transpile each file as a separate module (similar to 'ts.transpileModule')." }, - Print_names_of_generated_files_part_of_the_compilation: { code: 6154, category: ts.DiagnosticCategory.Message, key: "Print_names_of_generated_files_part_of_the_compilation_6154", message: "Print names of generated files part of the compilation." }, - Print_names_of_files_part_of_the_compilation: { code: 6155, category: ts.DiagnosticCategory.Message, key: "Print_names_of_files_part_of_the_compilation_6155", message: "Print names of files part of the compilation." }, - The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: { code: 6156, category: ts.DiagnosticCategory.Message, key: "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", message: "The locale used when displaying messages to the user (e.g. 'en-us')" }, - Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: { code: 6157, category: ts.DiagnosticCategory.Message, key: "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", message: "Do not generate custom helper functions like '__extends' in compiled output." }, - Do_not_include_the_default_library_file_lib_d_ts: { code: 6158, category: ts.DiagnosticCategory.Message, key: "Do_not_include_the_default_library_file_lib_d_ts_6158", message: "Do not include the default library file (lib.d.ts)." }, - Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: { code: 6159, category: ts.DiagnosticCategory.Message, key: "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", message: "Do not add triple-slash references or imported modules to the list of compiled files." }, - Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: { code: 6160, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", message: "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files." }, - List_of_folders_to_include_type_definitions_from: { code: 6161, category: ts.DiagnosticCategory.Message, key: "List_of_folders_to_include_type_definitions_from_6161", message: "List of folders to include type definitions from." }, - Disable_size_limitations_on_JavaScript_projects: { code: 6162, category: ts.DiagnosticCategory.Message, key: "Disable_size_limitations_on_JavaScript_projects_6162", message: "Disable size limitations on JavaScript projects." }, - The_character_set_of_the_input_files: { code: 6163, category: ts.DiagnosticCategory.Message, key: "The_character_set_of_the_input_files_6163", message: "The character set of the input files." }, - Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: { code: 6164, category: ts.DiagnosticCategory.Message, key: "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", message: "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files." }, - Do_not_truncate_error_messages: { code: 6165, category: ts.DiagnosticCategory.Message, key: "Do_not_truncate_error_messages_6165", message: "Do not truncate error messages." }, - Output_directory_for_generated_declaration_files: { code: 6166, category: ts.DiagnosticCategory.Message, key: "Output_directory_for_generated_declaration_files_6166", message: "Output directory for generated declaration files." }, - A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: { code: 6167, category: ts.DiagnosticCategory.Message, key: "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", message: "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'." }, - List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: { code: 6168, category: ts.DiagnosticCategory.Message, key: "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", message: "List of root folders whose combined content represents the structure of the project at runtime." }, - Show_all_compiler_options: { code: 6169, category: ts.DiagnosticCategory.Message, key: "Show_all_compiler_options_6169", message: "Show all compiler options." }, - Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: { code: 6170, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", message: "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file" }, - Command_line_Options: { code: 6171, category: ts.DiagnosticCategory.Message, key: "Command_line_Options_6171", message: "Command-line Options" }, - Basic_Options: { code: 6172, category: ts.DiagnosticCategory.Message, key: "Basic_Options_6172", message: "Basic Options" }, - Strict_Type_Checking_Options: { code: 6173, category: ts.DiagnosticCategory.Message, key: "Strict_Type_Checking_Options_6173", message: "Strict Type-Checking Options" }, - Module_Resolution_Options: { code: 6174, category: ts.DiagnosticCategory.Message, key: "Module_Resolution_Options_6174", message: "Module Resolution Options" }, - Source_Map_Options: { code: 6175, category: ts.DiagnosticCategory.Message, key: "Source_Map_Options_6175", message: "Source Map Options" }, - Additional_Checks: { code: 6176, category: ts.DiagnosticCategory.Message, key: "Additional_Checks_6176", message: "Additional Checks" }, - Experimental_Options: { code: 6177, category: ts.DiagnosticCategory.Message, key: "Experimental_Options_6177", message: "Experimental Options" }, - Advanced_Options: { code: 6178, category: ts.DiagnosticCategory.Message, key: "Advanced_Options_6178", message: "Advanced Options" }, - Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: { code: 6179, category: ts.DiagnosticCategory.Message, key: "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", message: "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'." }, - 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." }, - new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: ts.DiagnosticCategory.Error, key: "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", message: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, - _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, - Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, - Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, - Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, - Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, - Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, - Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", message: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." }, - _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: { code: 7023, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", message: "'{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." }, - 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: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "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." }, - Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, - JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists." }, - Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, - Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, - Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, - Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, - Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, - Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: { code: 7035, category: ts.DiagnosticCategory.Error, key: "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", message: "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`" }, - You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, - You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, - import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, - export_can_only_be_used_in_a_ts_file: { code: 8003, category: ts.DiagnosticCategory.Error, key: "export_can_only_be_used_in_a_ts_file_8003", message: "'export=' can only be used in a .ts file." }, - type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: ts.DiagnosticCategory.Error, key: "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", message: "'type parameter declarations' can only be used in a .ts file." }, - implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: ts.DiagnosticCategory.Error, key: "implements_clauses_can_only_be_used_in_a_ts_file_8005", message: "'implements clauses' can only be used in a .ts file." }, - interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: ts.DiagnosticCategory.Error, key: "interface_declarations_can_only_be_used_in_a_ts_file_8006", message: "'interface declarations' can only be used in a .ts file." }, - module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: ts.DiagnosticCategory.Error, key: "module_declarations_can_only_be_used_in_a_ts_file_8007", message: "'module declarations' can only be used in a .ts file." }, - type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: ts.DiagnosticCategory.Error, key: "type_aliases_can_only_be_used_in_a_ts_file_8008", message: "'type aliases' can only be used in a .ts file." }, - _0_can_only_be_used_in_a_ts_file: { code: 8009, category: ts.DiagnosticCategory.Error, key: "_0_can_only_be_used_in_a_ts_file_8009", message: "'{0}' can only be used in a .ts file." }, - types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, - type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, - parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, - type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, - Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, - JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, - JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, - Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, - JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "JSX attribute expected." }, - Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, - A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'." }, - An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, - super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, - super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, - _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: { code: 17012, category: ts.DiagnosticCategory.Error, key: "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", message: "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" }, - Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: { code: 17013, category: ts.DiagnosticCategory.Error, key: "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", message: "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." }, - Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, - The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, - No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, - Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, - Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, - Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'." }, - Remove_declaration_for_Colon_0: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_declaration_for_Colon_0_90004", message: "Remove declaration for: '{0}'." }, - Implement_interface_0: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_0_90006", message: "Implement interface '{0}'." }, - Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class." }, - Add_this_to_unresolved_variable: { code: 90008, category: ts.DiagnosticCategory.Message, key: "Add_this_to_unresolved_variable_90008", message: "Add 'this.' to unresolved variable." }, - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig." }, - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, - Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}." }, - Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}." }, - Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}." }, - Add_declaration_for_missing_property_0: { code: 90016, category: ts.DiagnosticCategory.Message, key: "Add_declaration_for_missing_property_0_90016", message: "Add declaration for missing property '{0}'." }, - Add_index_signature_for_missing_property_0: { code: 90017, category: ts.DiagnosticCategory.Message, key: "Add_index_signature_for_missing_property_0_90017", message: "Add index signature for missing property '{0}'." }, - Disable_checking_for_this_file: { code: 90018, category: ts.DiagnosticCategory.Message, key: "Disable_checking_for_this_file_90018", message: "Disable checking for this file." }, - 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." }, + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), + A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), + A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), + A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), + A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "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: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "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: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "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: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "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: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), + Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "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: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _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: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{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."), + 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), }; })(ts || (ts = {})); var ts; @@ -4570,12 +3678,19 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; - function computePositionOfLineAndCharacter(lineStarts, line, character) { + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { ts.Debug.assert(line >= 0 && line < lineStarts.length); - return lineStarts[line] + character; + var res = lineStarts[line] + character; + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res < debugText.length); + } + return res; } ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; function getLineStarts(sourceFile) { @@ -4642,6 +3757,7 @@ var ts; case 32: case 47: case 60: + case 124: case 61: case 62: return true; @@ -4703,6 +3819,7 @@ var ts; } break; case 60: + case 124: case 61: case 62: if (isConflictMarkerTrivia(text, pos)) { @@ -4756,10 +3873,10 @@ var ts; } } else { - ts.Debug.assert(ch === 61); + ts.Debug.assert(ch === 124 || ch === 61); while (pos < len) { - var ch_1 = text.charCodeAt(pos); - if (ch_1 === 62 && isConflictMarkerTrivia(text, pos)) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 || currentChar === 62) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { break; } pos++; @@ -5439,13 +4556,13 @@ var ts; pos += 2; var commentClosed = false; while (pos < end) { - var ch_2 = text.charCodeAt(pos); - if (ch_2 === 42 && text.charCodeAt(pos + 1) === 47) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) { pos += 2; commentClosed = true; break; } - if (isLineBreak(ch_2)) { + if (isLineBreak(ch_1)) { precedingLineBreak = true; } pos++; @@ -5600,6 +4717,15 @@ var ts; pos++; return token = 17; case 124: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 54; } @@ -5935,6 +5061,8 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.emptyArray = []; + ts.emptyMap = ts.createMap(); ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -5962,48 +5090,49 @@ var ts; return undefined; } ts.findDeclaration = findDeclaration; - var stringWriters = []; - function getSingleLineStringWriter() { - if (stringWriters.length === 0) { - var str_1 = ""; - var writeText = function (text) { return str_1 += text; }; - return { - string: function () { return str_1; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { return str_1 = ""; }, - trackSymbol: ts.noop, - reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop - }; + var stringWriter = createSingleLineStringWriter(); + var stringWriterAcquired = false; + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + string: function () { return str; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function usingSingleLineStringWriter(action) { + try { + ts.Debug.assert(!stringWriterAcquired); + stringWriterAcquired = true; + action(stringWriter); + return stringWriter.string(); + } + finally { + stringWriter.clear(); + stringWriterAcquired = false; } - return stringWriters.pop(); } - ts.getSingleLineStringWriter = getSingleLineStringWriter; - function releaseStringWriter(writer) { - writer.clear(); - stringWriters.push(writer); - } - ts.releaseStringWriter = releaseStringWriter; + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; function getFullWidth(node) { return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText)); - } - ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { - return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined; + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); } ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { @@ -6128,34 +5257,22 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function isToken(n) { - return n.kind >= 0 && n.kind <= 142; - } - ts.isToken = isToken; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; } - if (isJSDocNode(node)) { + if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 294 && node._children.length > 0) { + if (node.kind === 286 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; - function isJSDocNode(node) { - return node.kind >= 267 && node.kind <= 293; - } - ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 283 && node.kind <= 293; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -6184,11 +5301,16 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: return '"' + escapeText(node.text) + '"'; @@ -6210,8 +5332,12 @@ var ts; return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; function escapeIdentifier(identifier) { - return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; + return identifier; } ts.escapeIdentifier = escapeIdentifier; function makeIdentifierFromModuleName(moduleName) { @@ -6233,6 +5359,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } @@ -6243,7 +5373,7 @@ var ts; function isBlockScopedContainerTopLevel(node) { return node.kind === 265 || node.kind === 233 || - isFunctionLike(node); + ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { @@ -6285,7 +5415,7 @@ var ts; case 187: return true; case 207: - return parentNode && !isFunctionLike(parentNode); + return parentNode && !ts.isFunctionLike(parentNode); } return false; } @@ -6311,13 +5441,13 @@ var ts; function getTextOfPropertyName(name) { switch (name.kind) { case 71: - return name.text; + return name.escapedText; case 9: case 8: - return name.text; + return escapeLeadingUnderscores(name.text); case 144: if (isStringOrNumericLiteral(name.expression)) { - return name.expression.text; + return escapeLeadingUnderscores(name.expression.text); } } return undefined; @@ -6326,7 +5456,7 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71: - return getFullWidth(name) === 0 ? ts.unescapeIdentifier(name.text) : getTextOfNode(name); + return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); case 143: return entityNameToString(name.left) + "." + entityNameToString(name.right); case 179: @@ -6433,6 +5563,10 @@ var ts; return n.kind === 181 && n.expression.kind === 97; } ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 181 && n.expression.kind === 91; + } + ts.isImportCall = isImportCall; function isPrologueDirective(node) { return node.kind === 210 && node.expression.kind === 9; @@ -6450,7 +5584,8 @@ var ts; var commentRanges = (node.kind === 146 || node.kind === 145 || node.kind === 186 || - node.kind === 187) ? + node.kind === 187 || + node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); return ts.filter(commentRanges, function (comment) { @@ -6543,10 +5678,6 @@ var ts; return false; } ts.isChildOfNodeWithKind = isChildOfNodeWithKind; - function isPrefixUnaryExpression(node) { - return node.kind === 192; - } - ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { @@ -6592,7 +5723,7 @@ var ts; case 199: return; default: - if (isFunctionLike(node)) { + if (ts.isFunctionLike(node)) { var name = node.name; if (name && name.kind === 144) { traverse(name.expression); @@ -6635,47 +5766,6 @@ var ts; return false; } ts.isVariableLike = isVariableLike; - function isAccessor(node) { - return node && (node.kind === 153 || node.kind === 154); - } - ts.isAccessor = isAccessor; - function isClassLike(node) { - return node && (node.kind === 229 || node.kind === 199); - } - ts.isClassLike = isClassLike; - function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); - } - ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { - switch (kind) { - case 152: - case 186: - case 228: - case 187: - case 151: - case 150: - case 153: - case 154: - case 155: - case 156: - case 157: - case 160: - case 161: - return true; - } - 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: @@ -6690,20 +5780,6 @@ var ts; return false; } ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; - function isIterationStatement(node, lookInLabeledStatements) { - switch (node.kind) { - case 214: - case 215: - case 216: - case 212: - case 213: - return true; - case 222: - return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); - } - return false; - } - ts.isIterationStatement = isIterationStatement; function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { while (true) { if (beforeUnwrapLabelCallback) { @@ -6717,7 +5793,7 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 && isFunctionLike(node.parent); + return node && node.kind === 207 && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { @@ -6738,10 +5814,19 @@ var ts; return predicate && predicate.kind === 0; } ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return ts.filter(objectLiteral.properties, function (property) { + if (property.kind === 261) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (key2 && key2 === propName); + } + }); + } + ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { while (true) { node = node.parent; - if (!node || isFunctionLike(node)) { + if (!node || ts.isFunctionLike(node)) { return node; } } @@ -6750,7 +5835,7 @@ var ts; function getContainingClass(node) { while (true) { node = node.parent; - if (!node || isClassLike(node)) { + if (!node || ts.isClassLike(node)) { return node; } } @@ -6764,16 +5849,16 @@ var ts; } switch (node.kind) { case 144: - if (isClassLike(node.parent.parent)) { + if (ts.isClassLike(node.parent.parent)) { return node; } node = node.parent; break; case 147: - if (node.parent.kind === 146 && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { node = node.parent; } break; @@ -6839,10 +5924,10 @@ var ts; case 154: return node; case 147: - if (node.parent.kind === 146 && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { node = node.parent; } break; @@ -6873,7 +5958,6 @@ var ts; function getEntityNameFromTypeNode(node) { switch (node.kind) { case 159: - case 277: return node.typeName; case 201: return isEntityNameExpression(node.expression) @@ -6886,29 +5970,11 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; - function isCallLikeExpression(node) { - switch (node.kind) { - case 251: - case 250: - case 181: - case 182: - case 183: - case 147: - return true; - default: - return false; - } - } - 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; } - else if (isJsxOpeningLikeElement(node)) { + else if (ts.isJsxOpeningLikeElement(node)) { return node.tagName; } return node.expression; @@ -6966,7 +6032,6 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 99: case 97: case 95: case 101: @@ -7034,7 +6099,6 @@ var ts; case 221: case 257: case 223: - case 221: return parent.expression === node; case 214: var forStatement = parent; @@ -7069,12 +6133,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isInstantiatedModule(node, preserveConstEnums) { - var moduleState = ts.getModuleInstanceState(node); - return moduleState === 1 || - (preserveConstEnums && moduleState === 2); - } - ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 && node.moduleReference.kind === 248; } @@ -7096,12 +6154,16 @@ var ts; return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJSDoc(node) { + return node && !!(node.flags & 1048576); + } + ts.isInJSDoc = isInJSDoc; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 181) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 || expression.text !== "require") { + if (expression.kind !== 71 || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -7131,11 +6193,11 @@ var ts; } ts.getRightMostAssignedExpression = getRightMostAssignedExpression; function isExportsIdentifier(node) { - return isIdentifier(node) && node.text === "exports"; + return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; function isModuleExportsPropertyAccessExpression(node) { - return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports"; + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; function getSpecialPropertyAssignmentKind(expression) { @@ -7149,10 +6211,10 @@ var ts; var lhs = expr.left; if (lhs.expression.kind === 71) { var lhsId = lhs.expression; - if (lhsId.text === "exports") { + if (lhsId.escapedText === "exports") { return 1; } - else if (lhsId.text === "module" && lhs.name.text === "exports") { + else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { return 2; } else { @@ -7166,10 +6228,10 @@ var ts; var innerPropertyAccess = lhs.expression; if (innerPropertyAccess.expression.kind === 71) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { + if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { return 1; } - if (innerPropertyAccess.name.text === "prototype") { + if (innerPropertyAccess.name.escapedText === "prototype") { return 3; } } @@ -7228,52 +6290,40 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 279 && + return node.kind === 273 && node.parameters.length > 0 && - node.parameters[0].type.kind === 281; + node.parameters[0].name && + node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getCommentsFromJSDoc(node) { - return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); - } - ts.getCommentsFromJSDoc = getCommentsFromJSDoc; function hasJSDocParameterTags(node) { - var parameterTags = getJSDocTags(node, 286); - return parameterTags && parameterTags.length > 0; + return !!getFirstJSDocTag(node, 279); } ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getJSDocTags(node, kind) { - var docs = getJSDocs(node); - if (docs) { - var result = []; - for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { - var doc = docs_1[_i]; - if (doc.kind === 286) { - if (doc.kind === kind) { - result.push(doc); - } - } - else { - var tags = doc.tags; - if (tags) { - result.push.apply(result, ts.filter(tags, function (tag) { return tag.kind === kind; })); - } - } - } - return result; - } - } function getFirstJSDocTag(node, kind) { - return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); } - function getJSDocs(node) { - var cache = node.jsDocCache; - if (!cache) { - getJSDocsWorker(node); - node.jsDocCache = cache; + function getAllJSDocs(node) { + if (ts.isJSDocTypedefTag(node)) { + return [node.parent]; } - return cache; - function getJSDocsWorker(node) { + return getJSDocCommentsAndTags(node); + } + ts.getAllJSDocs = getAllJSDocs; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getJSDocCommentsAndTags(node) { + var result; + getJSDocCommentsAndTagsWorker(node); + return result || ts.emptyArray; + function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && parent.initializer === node && @@ -7284,55 +6334,65 @@ var ts; isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - getJSDocsWorker(variableStatementNode); + getJSDocCommentsAndTagsWorker(variableStatementNode); } var isSourceOfAssignmentExpressionStatement = parent && parent.parent && parent.kind === 194 && parent.operatorToken.kind === 58 && parent.parent.kind === 210; if (isSourceOfAssignmentExpressionStatement) { - getJSDocsWorker(parent.parent); + getJSDocCommentsAndTagsWorker(parent.parent); } var isModuleDeclaration = node.kind === 233 && parent && parent.kind === 233; var isPropertyAssignmentExpression = parent && parent.kind === 261; if (isModuleDeclaration || isPropertyAssignmentExpression) { - getJSDocsWorker(parent); + getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 146) { - cache = ts.concatenate(cache, getJSDocParameterTags(node)); + result = ts.addRange(result, getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer) { - cache = ts.concatenate(cache, node.initializer.jsDoc); + result = ts.addRange(result, node.initializer.jsDoc); } - cache = ts.concatenate(cache, node.jsDoc); + result = ts.addRange(result, node.jsDoc); } } - ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } - var func = param.parent; - var tags = getJSDocTags(func, 286); - if (!param.name) { - var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 286; }); - if (paramTags && 0 <= i && i < paramTags.length) { - return [paramTags[i]]; - } - } - else if (param.name.kind === 71) { - var name_1 = param.name.text; - return ts.filter(tags, function (tag) { return tag.kind === 286 && tag.parameterName.text === name_1; }); - } - else { - return undefined; + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); } + return undefined; } ts.getJSDocParameterTags = getJSDocParameterTags; + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + ts.Debug.assert(node.parent.kind === 275); + var func = node.parent.parent; + if (!ts.isFunctionLike(func)) { + return undefined; + } + var parameter = ts.find(func.parameters, function (p) { + return p.name.kind === 71 && p.name.escapedText === name; + }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 288); + var tag = getFirstJSDocTag(node, 281); if (!tag && node.kind === 146) { var paramTags = getJSDocParameterTags(node); if (paramTags) { @@ -7343,15 +6403,24 @@ var ts; } ts.getJSDocType = getJSDocType; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285); + return getFirstJSDocTag(node, 277); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 287); + return getFirstJSDocTag(node, 280); } ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 289); + return getFirstJSDocTag(node, 282); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { @@ -7363,9 +6432,9 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 65536)) { - if (node.type && node.type.kind === 280 || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 280; })) { + if (isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 274 || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { return true; } } @@ -7376,12 +6445,6 @@ 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) { @@ -7461,46 +6524,31 @@ var ts; case 71: case 9: case 8: - return isDeclaration(name.parent) && name.parent.name === name; + return ts.isDeclaration(name.parent) && name.parent.name === name; default: 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; + function isAnyDeclarationName(name) { + switch (name.kind) { + case 71: + case 9: + case 8: + if (ts.isDeclaration(name.parent)) { + return name.parent.name === name; + } + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + default: + return false; } } - ts.getNameOfDeclaration = getNameOfDeclaration; + ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && - isDeclaration(node.parent.parent); + ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { @@ -7528,6 +6576,7 @@ var ts; case 242: return parent.propertyName === node; case 246: + case 253: return true; } return false; @@ -7631,14 +6680,6 @@ 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; @@ -7676,10 +6717,6 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isNumericLiteral(node) { - return node.kind === 8; - } - ts.isNumericLiteral = isNumericLiteral; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 9 @@ -7687,7 +6724,7 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - var name = getNameOfDeclaration(declaration); + var name = ts.getNameOfDeclaration(declaration); return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; @@ -7698,56 +6735,67 @@ var ts; } ts.isDynamicName = isDynamicName; function isWellKnownSymbolSyntactically(node) { - return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 || name.kind === 9 || name.kind === 8 || name.kind === 146) { - return name.text; + if (name.kind === 71) { + return name.escapedText; + } + if (name.kind === 9 || name.kind === 8) { + return escapeLeadingUnderscores(name.text); } if (name.kind === 144) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.text; - return getPropertyNameForKnownSymbolName(rightHandSideName); + var rightHandSideName = nameExpression.name.escapedText; + return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); } else if (nameExpression.kind === 9 || nameExpression.kind === 8) { - return nameExpression.text; + return escapeLeadingUnderscores(nameExpression.text); } } return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return ts.unescapeLeadingUnderscores(node.escapedText); + } + if (node.kind === 9 || + node.kind === 8) { + return node.text; + } + } + return undefined; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return node.escapedText; + } + if (node.kind === 9 || + node.kind === 8) { + return escapeLeadingUnderscores(node.text); + } + } + return undefined; + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function isESSymbolIdentifier(node) { - return node.kind === 71 && node.text === "Symbol"; + return node.kind === 71 && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { - return node.text === "push" || node.text === "unshift"; + return node.escapedText === "push" || node.escapedText === "unshift"; } ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; - function isModifierKind(token) { - switch (token) { - case 117: - case 120: - case 76: - case 124: - case 79: - case 84: - case 114: - case 112: - case 113: - case 131: - case 115: - return true; - } - return false; - } - ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 146; @@ -7778,30 +6826,14 @@ var ts; || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile)); - } - return getOriginalSourceFile(sourceFileOrBundle); - } - ts.getOriginalSourceFileOrBundle = getOriginalSourceFileOrBundle; function getOriginalSourceFile(sourceFile) { - return ts.getParseTreeNode(sourceFile, isSourceFile) || sourceFile; + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } + ts.getOriginalSourceFile = getOriginalSourceFile; function getOriginalSourceFiles(sourceFiles) { return ts.sameMap(sourceFiles, getOriginalSourceFile); } ts.getOriginalSourceFiles = getOriginalSourceFiles; - function getOriginalNodeId(node) { - node = ts.getOriginalNode(node); - 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; @@ -7963,7 +6995,7 @@ var ts; return 2; case 198: return 1; - case 297: + case 289: return 0; default: return -1; @@ -8218,44 +7250,6 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { - var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); - var options = host.getCompilerOptions(); - if (options.outFile || options.out) { - if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); - } - } - else { - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); - } - } - } - ts.forEachEmittedFile = forEachEmittedFile; - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } - function getOutputExtension(sourceFile, options) { - if (options.jsx === 1) { - if (isSourceFileJavaScript(sourceFile)) { - if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { - return ".jsx"; - } - } - else if (sourceFile.languageVariant === 1) { - return ".jsx"; - } - } - return ".js"; - } function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); var commonSourceDirectory = host.getCommonSourceDirectory(); @@ -8286,12 +7280,16 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; - function getSetAccessorTypeAnnotationNode(accessor) { + function getSetAccessorValueParameter(accessor) { if (accessor && accessor.parameters.length > 0) { var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); - return accessor.parameters[hasThis ? 1 : 0].type; + return accessor.parameters[hasThis ? 1 : 0]; } } + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { if (signature.parameters.length) { @@ -8362,6 +7360,39 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + function getEffectiveTypeAnnotationNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocType(node); + } + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getEffectiveReturnTypeNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocReturnType(node); + } + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getEffectiveTypeParameterDeclarations(node) { + if (node.typeParameters) { + return node.typeParameters; + } + if (isInJavaScriptFile(node)) { + var templateTag = getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); } @@ -8523,6 +7554,12 @@ var ts; if (node.modifierFlagsCache & 536870912) { return node.modifierFlagsCache & ~536870912; } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { var flags = 0; if (node.modifiers) { for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { @@ -8533,10 +7570,9 @@ var ts; if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) { flags |= 1; } - node.modifierFlagsCache = flags | 536870912; return flags; } - ts.getModifierFlags = getModifierFlags; + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { case 115: return 32; @@ -8567,17 +7603,17 @@ var ts; function tryGetClassExtendingExpressionWithTypeArguments(node) { if (node.kind === 201 && node.parent.token === 85 && - isClassLike(node.parent.parent)) { + ts.isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { - return isBinaryExpression(node) + return ts.isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 58 : isAssignmentOperator(node.operatorToken.kind)) - && isLeftHandSideExpression(node.left); + && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { @@ -8597,7 +7633,7 @@ var ts; if (node.kind === 71) { return true; } - else if (isPropertyAccessExpression(node)) { + else if (ts.isPropertyAccessExpression(node)) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -8614,7 +7650,7 @@ var ts; && node.parent && node.parent.token === 108 && node.parent.parent - && isClassLike(node.parent.parent); + && ts.isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { @@ -8638,11 +7674,11 @@ var ts; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined; + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isExportDefaultSymbol(symbol) { - return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512); + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); } function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -8782,27 +7818,74 @@ var ts; } return false; } - var syntaxKindCache = []; - function formatSyntaxKind(kind) { - var syntaxKindEnum = ts.SyntaxKind; - if (syntaxKindEnum) { - var cached = syntaxKindCache[kind]; - if (cached !== undefined) { - return cached; - } - for (var name in syntaxKindEnum) { - if (syntaxKindEnum[name] === kind) { - var result = kind + " (" + name + ")"; - syntaxKindCache[kind] = result; - return result; + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; } } + if (remainingFlags === 0) { + return result; + } } else { - return kind.toString(); + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, false); } ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, true); + } + ts.formatObjectFlags = formatObjectFlags; function getRangePos(range) { return range ? range.pos : -1; } @@ -8919,630 +8002,12 @@ var ts; return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; } ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; - function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); - } - ts.isNodeArray = isNodeArray; - function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13; - } - ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; - function isLiteralKind(kind) { - return 8 <= kind && kind <= 13; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 || kind === 13; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isLiteralExpression(node) { - return isLiteralKind(node.kind); - } - ts.isLiteralExpression = isLiteralExpression; - function isTemplateLiteralKind(kind) { - return 13 <= kind && kind <= 16; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateHead(node) { - return node.kind === 14; - } - ts.isTemplateHead = isTemplateHead; - function isTemplateMiddleOrTemplateTail(node) { - var kind = node.kind; - return kind === 15 - || kind === 16; - } - ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; - function isIdentifier(node) { - return node.kind === 71; - } - ts.isIdentifier = isIdentifier; - function isGeneratedIdentifier(node) { - return isIdentifier(node) && node.autoGenerateKind > 0; - } - ts.isGeneratedIdentifier = isGeneratedIdentifier; - function isModifier(node) { - return isModifierKind(node.kind); - } - ts.isModifier = isModifier; - function isQualifiedName(node) { - return node.kind === 143; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 144; - } - ts.isComputedPropertyName = isComputedPropertyName; - function isEntityName(node) { - var kind = node.kind; - return kind === 143 - || kind === 71; - } - ts.isEntityName = isEntityName; - function isPropertyName(node) { - var kind = node.kind; - return kind === 71 - || kind === 9 - || kind === 8 - || kind === 144; - } - ts.isPropertyName = isPropertyName; - function isModuleName(node) { - var kind = node.kind; - return kind === 71 - || kind === 9; - } - ts.isModuleName = isModuleName; - function isBindingName(node) { - var kind = node.kind; - return kind === 71 - || kind === 174 - || kind === 175; - } - ts.isBindingName = isBindingName; - function isTypeParameter(node) { - return node.kind === 145; - } - ts.isTypeParameter = isTypeParameter; - function isParameter(node) { - return node.kind === 146; - } - ts.isParameter = isParameter; - function isDecorator(node) { - return node.kind === 147; - } - ts.isDecorator = isDecorator; - function isMethodDeclaration(node) { - return node.kind === 151; - } - ts.isMethodDeclaration = isMethodDeclaration; - function isClassElement(node) { - var kind = node.kind; - return kind === 152 - || kind === 149 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 157 - || 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 - || kind === 262 - || kind === 263 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 247; - } - ts.isObjectLiteralElementLike = isObjectLiteralElementLike; - function isTypeNodeKind(kind) { - return (kind >= 158 && kind <= 173) - || kind === 119 - || kind === 133 - || kind === 134 - || kind === 122 - || kind === 136 - || kind === 137 - || kind === 99 - || kind === 105 - || kind === 139 - || kind === 95 - || kind === 130 - || kind === 201; - } - function isTypeNode(node) { - return isTypeNodeKind(node.kind); - } - ts.isTypeNode = isTypeNode; - function isArrayBindingPattern(node) { - return node.kind === 175; - } - ts.isArrayBindingPattern = isArrayBindingPattern; - function isObjectBindingPattern(node) { - return node.kind === 174; - } - ts.isObjectBindingPattern = isObjectBindingPattern; - function isBindingPattern(node) { - if (node) { - var kind = node.kind; - return kind === 175 - || kind === 174; - } - return false; - } - ts.isBindingPattern = isBindingPattern; - function isAssignmentPattern(node) { - var kind = node.kind; - return kind === 177 - || kind === 178; - } - ts.isAssignmentPattern = isAssignmentPattern; - function isBindingElement(node) { - return node.kind === 176; - } - ts.isBindingElement = isBindingElement; - function isArrayBindingElement(node) { - var kind = node.kind; - return kind === 176 - || kind === 200; - } - ts.isArrayBindingElement = isArrayBindingElement; - function isDeclarationBindingElement(bindingElement) { - switch (bindingElement.kind) { - case 226: - case 146: - case 176: - return true; - } - return false; - } - ts.isDeclarationBindingElement = isDeclarationBindingElement; - function isBindingOrAssignmentPattern(node) { - return isObjectBindingOrAssignmentPattern(node) - || isArrayBindingOrAssignmentPattern(node); - } - ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; - function isObjectBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 174: - case 178: - return true; - } - return false; - } - ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; - function isArrayBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 175: - case 177: - return true; - } - return false; - } - ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; - function isArrayLiteralExpression(node) { - return node.kind === 177; - } - ts.isArrayLiteralExpression = isArrayLiteralExpression; - function isObjectLiteralExpression(node) { - return node.kind === 178; - } - ts.isObjectLiteralExpression = isObjectLiteralExpression; - function isPropertyAccessExpression(node) { - return node.kind === 179; - } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isPropertyAccessOrQualifiedName(node) { - var kind = node.kind; - return kind === 179 - || kind === 143; - } - ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; - function isElementAccessExpression(node) { - return node.kind === 180; - } - ts.isElementAccessExpression = isElementAccessExpression; - function isBinaryExpression(node) { - return node.kind === 194; - } - ts.isBinaryExpression = isBinaryExpression; - function isConditionalExpression(node) { - return node.kind === 195; - } - ts.isConditionalExpression = isConditionalExpression; - function isCallExpression(node) { - return node.kind === 181; - } - ts.isCallExpression = isCallExpression; - function isTemplateLiteral(node) { - var kind = node.kind; - return kind === 196 - || kind === 13; - } - ts.isTemplateLiteral = isTemplateLiteral; - function isSpreadExpression(node) { - return node.kind === 198; - } - ts.isSpreadExpression = isSpreadExpression; - function isExpressionWithTypeArguments(node) { - return node.kind === 201; - } - ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 - || kind === 180 - || kind === 182 - || kind === 181 - || kind === 249 - || kind === 250 - || kind === 183 - || kind === 177 - || kind === 185 - || kind === 178 - || kind === 199 - || kind === 186 - || kind === 71 - || kind === 12 - || kind === 8 - || kind === 9 - || kind === 13 - || kind === 196 - || kind === 86 - || kind === 95 - || kind === 99 - || kind === 101 - || kind === 97 - || kind === 203 - || kind === 204; - } - function isLeftHandSideExpression(node) { - return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 - || kind === 193 - || kind === 188 - || kind === 189 - || kind === 190 - || kind === 191 - || kind === 184 - || isLeftHandSideExpressionKind(kind); - } - function isUnaryExpression(node) { - return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isUnaryExpression = isUnaryExpression; - function isExpressionKind(kind) { - return kind === 195 - || kind === 197 - || kind === 187 - || kind === 194 - || kind === 198 - || kind === 202 - || kind === 200 - || kind === 297 - || isUnaryExpressionKind(kind); - } - function isExpression(node) { - return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isExpression = isExpression; - function isAssertionExpression(node) { - var kind = node.kind; - return kind === 184 - || kind === 202; - } - ts.isAssertionExpression = isAssertionExpression; - function isPartiallyEmittedExpression(node) { - return node.kind === 296; - } - ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; - function isNotEmittedStatement(node) { - return node.kind === 295; - } - ts.isNotEmittedStatement = isNotEmittedStatement; - function isNotEmittedOrPartiallyEmittedNode(node) { - return isNotEmittedStatement(node) - || isPartiallyEmittedExpression(node); - } - ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - function isOmittedExpression(node) { - return node.kind === 200; - } - ts.isOmittedExpression = isOmittedExpression; - function isTemplateSpan(node) { - return node.kind === 205; - } - ts.isTemplateSpan = isTemplateSpan; - function isBlock(node) { - return node.kind === 207; - } - ts.isBlock = isBlock; - function isConciseBody(node) { - return isBlock(node) - || isExpression(node); - } - ts.isConciseBody = isConciseBody; - function isFunctionBody(node) { - return isBlock(node); - } - ts.isFunctionBody = isFunctionBody; - function isForInitializer(node) { - return isVariableDeclarationList(node) - || isExpression(node); - } - ts.isForInitializer = isForInitializer; - function isVariableDeclaration(node) { - return node.kind === 226; - } - ts.isVariableDeclaration = isVariableDeclaration; - function isVariableDeclarationList(node) { - return node.kind === 227; - } - ts.isVariableDeclarationList = isVariableDeclarationList; - function isCaseBlock(node) { - return node.kind === 235; - } - ts.isCaseBlock = isCaseBlock; - function isModuleBody(node) { - var kind = node.kind; - return kind === 234 - || kind === 233 - || kind === 71; - } - ts.isModuleBody = isModuleBody; - function isNamespaceBody(node) { - var kind = node.kind; - return kind === 234 - || kind === 233; - } - ts.isNamespaceBody = isNamespaceBody; - function isJSDocNamespaceBody(node) { - var kind = node.kind; - return kind === 71 - || kind === 233; - } - ts.isJSDocNamespaceBody = isJSDocNamespaceBody; - function isImportEqualsDeclaration(node) { - return node.kind === 237; - } - ts.isImportEqualsDeclaration = isImportEqualsDeclaration; - function isImportDeclaration(node) { - return node.kind === 238; - } - ts.isImportDeclaration = isImportDeclaration; - function isImportClause(node) { - return node.kind === 239; - } - ts.isImportClause = isImportClause; - function isNamedImportBindings(node) { - var kind = node.kind; - return kind === 241 - || kind === 240; - } - ts.isNamedImportBindings = isNamedImportBindings; - function isImportSpecifier(node) { - return node.kind === 242; - } - ts.isImportSpecifier = isImportSpecifier; - function isNamedExports(node) { - return node.kind === 245; - } - ts.isNamedExports = isNamedExports; - function isExportSpecifier(node) { - 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; - } - ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; - function isDeclarationKind(kind) { - return kind === 187 - || kind === 176 - || kind === 229 - || kind === 199 - || kind === 152 - || kind === 232 - || kind === 264 - || kind === 246 - || kind === 228 - || kind === 186 - || kind === 153 - || kind === 239 - || kind === 237 - || kind === 242 - || kind === 230 - || kind === 253 - || kind === 151 - || kind === 150 - || kind === 233 - || kind === 236 - || kind === 240 - || kind === 146 - || kind === 261 - || kind === 149 - || kind === 148 - || kind === 154 - || kind === 262 - || kind === 231 - || kind === 145 - || kind === 226 - || kind === 290; - } - function isDeclarationStatementKind(kind) { - return kind === 228 - || kind === 247 - || kind === 229 - || kind === 230 - || kind === 231 - || kind === 232 - || kind === 233 - || kind === 238 - || kind === 237 - || kind === 244 - || kind === 243 - || kind === 236; - } - function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 - || kind === 217 - || kind === 225 - || kind === 212 - || kind === 210 - || kind === 209 - || kind === 215 - || kind === 216 - || kind === 214 - || kind === 211 - || kind === 222 - || kind === 219 - || kind === 221 - || kind === 223 - || kind === 224 - || kind === 208 - || kind === 213 - || kind === 220 - || kind === 295 - || kind === 299 - || kind === 298; - } - function isDeclaration(node) { - return isDeclarationKind(node.kind); - } - ts.isDeclaration = isDeclaration; - function isDeclarationStatement(node) { - return isDeclarationStatementKind(node.kind); - } - ts.isDeclarationStatement = isDeclarationStatement; - function isStatementButNotDeclaration(node) { - return isStatementKindButNotDeclarationKind(node.kind); - } - ts.isStatementButNotDeclaration = isStatementButNotDeclaration; - function isStatement(node) { - var kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) - || isDeclarationStatementKind(kind) - || kind === 207; - } - ts.isStatement = isStatement; - function isModuleReference(node) { - var kind = node.kind; - return kind === 248 - || kind === 143 - || kind === 71; - } - ts.isModuleReference = isModuleReference; - function isJsxOpeningElement(node) { - return node.kind === 251; - } - ts.isJsxOpeningElement = isJsxOpeningElement; - function isJsxClosingElement(node) { - return node.kind === 252; - } - ts.isJsxClosingElement = isJsxClosingElement; - function isJsxTagNameExpression(node) { - var kind = node.kind; - return kind === 99 - || kind === 71 - || kind === 179; - } - ts.isJsxTagNameExpression = isJsxTagNameExpression; - function isJsxChild(node) { - var kind = node.kind; - return kind === 249 - || kind === 256 - || kind === 250 - || kind === 10; - } - ts.isJsxChild = isJsxChild; - function isJsxAttributes(node) { - var kind = node.kind; - return kind === 254; - } - ts.isJsxAttributes = isJsxAttributes; - function isJsxAttributeLike(node) { - var kind = node.kind; - return kind === 253 - || kind === 255; - } - ts.isJsxAttributeLike = isJsxAttributeLike; - function isJsxSpreadAttribute(node) { - return node.kind === 255; - } - ts.isJsxSpreadAttribute = isJsxSpreadAttribute; - function isJsxAttribute(node) { - return node.kind === 253; - } - ts.isJsxAttribute = isJsxAttribute; - function isStringLiteralOrJsxExpression(node) { - var kind = node.kind; - return kind === 9 - || kind === 256; - } - ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; - function isJsxOpeningLikeElement(node) { - var kind = node.kind; - return kind === 251 - || kind === 250; - } - ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; - function isCaseOrDefaultClause(node) { - var kind = node.kind; - return kind === 257 - || kind === 258; - } - ts.isCaseOrDefaultClause = isCaseOrDefaultClause; - function isHeritageClause(node) { - return node.kind === 259; - } - ts.isHeritageClause = isHeritageClause; - function isCatchClause(node) { - return node.kind === 260; - } - ts.isCatchClause = isCatchClause; - function isPropertyAssignment(node) { - return node.kind === 261; - } - ts.isPropertyAssignment = isPropertyAssignment; - function isShorthandPropertyAssignment(node) { - return node.kind === 262; - } - ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; - function isEnumMember(node) { - return node.kind === 264; - } - ts.isEnumMember = isEnumMember; - function isSourceFile(node) { - return node.kind === 265; - } - ts.isSourceFile = isSourceFile; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; + return symbol.flags & 33554432 ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; function getDeclarationModifierFlagsFromSymbol(s) { @@ -9558,7 +8023,7 @@ var ts; var staticModifier = checkFlags & 512 ? 32 : 0; return accessModifier | staticModifier; } - if (s.flags & 16777216) { + if (s.flags & 4194304) { return 4 | 32; } return 0; @@ -9583,6 +8048,14 @@ var ts; return previous[previous.length - 1]; } ts.levenshtein = levenshtein; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9838,10 +8311,29209 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; - function unescapeIdentifier(identifier) { - return identifier.length >= 3 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 && identifier.charCodeAt(2) === 95 ? identifier.substr(1) : identifier; + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function unescapeIdentifier(id) { + return id; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { + return declaration.name.right; + } + if (declaration.kind === 194) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; +})(ts || (ts = {})); +(function (ts) { + function isNumericLiteral(node) { + return node.kind === 8; + } + ts.isNumericLiteral = isNumericLiteral; + function isStringLiteral(node) { + return node.kind === 9; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 10; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 12; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 13; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isTemplateHead(node) { + return node.kind === 14; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 15; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 16; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 71; + } + ts.isIdentifier = isIdentifier; + function isQualifiedName(node) { + return node.kind === 143; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 144; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isTypeParameterDeclaration(node) { + return node.kind === 145; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 146; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 147; + } + ts.isDecorator = isDecorator; + function isPropertySignature(node) { + return node.kind === 148; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 149; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 150; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 151; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 152; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 153; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 154; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 155; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 156; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 157; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isTypePredicateNode(node) { + return node.kind === 158; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 159; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 160; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 161; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 162; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 163; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 164; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 165; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 166; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 167; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 168; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 169; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 170; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 171; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 172; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 173; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isObjectBindingPattern(node) { + return node.kind === 174; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 175; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 176; + } + ts.isBindingElement = isBindingElement; + function isArrayLiteralExpression(node) { + return node.kind === 177; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 178; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 179; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 180; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 181; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 182; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 183; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 184; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 185; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 186; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 187; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 188; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 191; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 190; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 191; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 192; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 193; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 194; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 195; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 196; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 197; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 198; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 199; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 200; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 201; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 202; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 203; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 204; + } + ts.isMetaProperty = isMetaProperty; + function isTemplateSpan(node) { + return node.kind === 205; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 206; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + function isBlock(node) { + return node.kind === 207; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 208; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 209; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 210; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 211; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 212; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 213; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 214; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 215; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 216; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 217; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 218; + } + ts.isBreakStatement = isBreakStatement; + function isReturnStatement(node) { + return node.kind === 219; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 220; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 221; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 222; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 223; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 224; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 225; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 226; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 227; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 228; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 229; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 230; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 231; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 232; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 233; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 234; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 235; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 236; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 237; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 239; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 240; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 241; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 242; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 244; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 245; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 246; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 247; + } + ts.isMissingDeclaration = isMissingDeclaration; + function isExternalModuleReference(node) { + return node.kind === 248; + } + ts.isExternalModuleReference = isExternalModuleReference; + function isJsxElement(node) { + return node.kind === 249; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 250; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 251; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 252; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxAttribute(node) { + return node.kind === 253; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 254; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 255; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 256; + } + ts.isJsxExpression = isJsxExpression; + function isCaseClause(node) { + return node.kind === 257; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 258; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 259; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 260; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 261; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 262; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 263; + } + ts.isSpreadAssignment = isSpreadAssignment; + function isEnumMember(node) { + return node.kind === 264; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 265; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 266; + } + ts.isBundle = isBundle; + function isJSDocTypeExpression(node) { + return node.kind === 267; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 268; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 269; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 270; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 271; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 272; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 273; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 274; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 275; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 277; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocParameterTag(node) { + return node.kind === 279; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 280; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 281; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 282; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 283; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 284; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 284 || node.kind === 279; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 285; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; +})(ts || (ts = {})); +(function (ts) { + function isSyntaxList(n) { + return n.kind === 286; + } + ts.isSyntaxList = isSyntaxList; + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + function isNodeKind(kind) { + return kind >= 143; + } + ts.isNodeKind = isNodeKind; + function isToken(n) { + return n.kind >= 0 && n.kind <= 142; + } + ts.isToken = isToken; + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 13; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 13 <= kind && kind <= 16; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 15 + || kind === 16; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isStringTextContainingNode(node) { + switch (node.kind) { + case 9: + case 14: + case 15: + case 16: + case 13: + return true; + default: + return false; + } + } + ts.isStringTextContainingNode = isStringTextContainingNode; + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && node.autoGenerateKind > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifierKind(token) { + switch (token) { + case 117: + case 120: + case 76: + case 124: + case 79: + case 84: + case 114: + case 112: + case 113: + case 131: + case 115: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 143 + || kind === 71; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 71 + || kind === 9 + || kind === 8 + || kind === 144; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 71 + || kind === 174 + || kind === 175; + } + ts.isBindingName = isBindingName; + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 152: + case 186: + case 228: + case 187: + case 151: + case 150: + case 153: + case 154: + case 155: + case 156: + case 157: + case 160: + case 273: + case 161: + return true; + } + return false; + } + ts.isFunctionLikeKind = isFunctionLikeKind; + function isClassElement(node) { + var kind = node.kind; + return kind === 152 + || kind === 149 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 157 + || kind === 206 + || kind === 247; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 229 || node.kind === 199); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 153 || node.kind === 154); + } + ts.isAccessor = isAccessor; + 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 + || kind === 262 + || kind === 263 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 247; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNodeKind(kind) { + return (kind >= 158 && kind <= 173) + || kind === 119 + || kind === 133 + || kind === 134 + || kind === 122 + || kind === 136 + || kind === 137 + || kind === 99 + || kind === 105 + || kind === 139 + || kind === 95 + || kind === 130 + || kind === 201; + } + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 175 + || kind === 174; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 177 + || kind === 178; + } + ts.isAssignmentPattern = isAssignmentPattern; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 176 + || kind === 200; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 226: + case 146: + case 176: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 174: + case 178: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 175: + case 177: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 179 + || kind === 143; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 251: + case 250: + case 181: + case 182: + case 183: + case 147: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 196 + || kind === 13; + } + ts.isTemplateLiteral = isTemplateLiteral; + function isLeftHandSideExpressionKind(kind) { + return kind === 179 + || kind === 180 + || kind === 182 + || kind === 181 + || kind === 249 + || kind === 250 + || kind === 183 + || kind === 177 + || kind === 185 + || kind === 178 + || kind === 199 + || kind === 186 + || kind === 71 + || kind === 12 + || kind === 8 + || kind === 9 + || kind === 13 + || kind === 196 + || kind === 86 + || kind === 95 + || kind === 99 + || kind === 101 + || kind === 97 + || kind === 91 + || kind === 203 + || kind === 204; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 192 + || kind === 193 + || kind === 188 + || kind === 189 + || kind === 190 + || kind === 191 + || kind === 184 + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 195 + || kind === 197 + || kind === 187 + || kind === 194 + || kind === 198 + || kind === 202 + || kind === 200 + || kind === 289 + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 184 + || kind === 202; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 214: + case 215: + case 216: + case 212: + case 213: + return true; + case 222: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + function isForInOrOfStatement(node) { + return node.kind === 215 || node.kind === 216; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isModuleBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233 + || kind === 71; + } + ts.isModuleBody = isModuleBody; + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233; + } + ts.isNamespaceBody = isNamespaceBody; + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 71 + || kind === 233; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 241 + || kind === 240; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isModuleOrEnumDeclaration(node) { + return node.kind === 233 || node.kind === 232; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 187 + || kind === 176 + || kind === 229 + || kind === 199 + || kind === 152 + || kind === 232 + || kind === 264 + || kind === 246 + || kind === 228 + || kind === 186 + || kind === 153 + || kind === 239 + || kind === 237 + || kind === 242 + || kind === 230 + || kind === 253 + || kind === 151 + || kind === 150 + || kind === 233 + || kind === 236 + || kind === 240 + || kind === 146 + || kind === 261 + || kind === 149 + || kind === 148 + || kind === 154 + || kind === 262 + || kind === 231 + || kind === 145 + || kind === 226 + || kind === 283; + } + function isDeclarationStatementKind(kind) { + return kind === 228 + || kind === 247 + || kind === 229 + || kind === 230 + || kind === 231 + || kind === 232 + || kind === 233 + || kind === 238 + || kind === 237 + || kind === 244 + || kind === 243 + || kind === 236; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 218 + || kind === 217 + || kind === 225 + || kind === 212 + || kind === 210 + || kind === 209 + || kind === 215 + || kind === 216 + || kind === 214 + || kind === 211 + || kind === 222 + || kind === 219 + || kind === 221 + || kind === 223 + || kind === 224 + || kind === 208 + || kind === 213 + || kind === 220 + || kind === 287 + || kind === 291 + || kind === 290; + } + function isDeclaration(node) { + if (node.kind === 145) { + return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 207; + } + ts.isStatement = isStatement; + function isModuleReference(node) { + var kind = node.kind; + return kind === 248 + || kind === 143 + || kind === 71; + } + ts.isModuleReference = isModuleReference; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 99 + || kind === 71 + || kind === 179; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 249 + || kind === 256 + || kind === 250 + || kind === 10; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 253 + || kind === 255; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 + || kind === 256; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 251 + || kind === 250; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 257 + || kind === 258; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isJSDocNode(node) { + return node.kind >= 267 && node.kind <= 285; + } + ts.isJSDocNode = isJSDocNode; + function isJSDocCommentContainingNode(node) { + return node.kind === 275 || isJSDocTag(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + function isJSDocTag(node) { + return node.kind >= 276 && node.kind <= 285; + } + ts.isJSDocTag = isJSDocTag; +})(ts || (ts = {})); +var ts; +(function (ts) { + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 265) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 71) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 142) { + return; + } + switch (node.kind) { + case 143: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 145: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 262: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 263: + return visitNode(cbNode, node.expression); + case 146: + case 149: + case 148: + case 261: + case 226: + case 176: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 160: + case 161: + case 155: + case 156: + case 157: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 151: + case 150: + case 152: + case 153: + case 154: + case 186: + case 228: + case 187: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 159: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 158: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 162: + return visitNode(cbNode, node.exprName); + case 163: + return visitNodes(cbNode, cbNodes, node.members); + case 164: + return visitNode(cbNode, node.elementType); + case 165: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 166: + case 167: + return visitNodes(cbNode, cbNodes, node.types); + case 168: + case 170: + return visitNode(cbNode, node.type); + case 171: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 172: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 173: + return visitNode(cbNode, node.literal); + case 174: + case 175: + return visitNodes(cbNode, cbNodes, node.elements); + case 177: + return visitNodes(cbNode, cbNodes, node.elements); + case 178: + return visitNodes(cbNode, cbNodes, node.properties); + case 179: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 180: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 181: + case 182: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 183: + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.template); + case 184: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 185: + return visitNode(cbNode, node.expression); + case 188: + return visitNode(cbNode, node.expression); + case 189: + return visitNode(cbNode, node.expression); + case 190: + return visitNode(cbNode, node.expression); + case 192: + return visitNode(cbNode, node.operand); + case 197: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 191: + return visitNode(cbNode, node.expression); + case 193: + return visitNode(cbNode, node.operand); + case 194: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 202: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 203: + return visitNode(cbNode, node.expression); + case 204: + return visitNode(cbNode, node.name); + case 195: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 198: + return visitNode(cbNode, node.expression); + case 207: + case 234: + return visitNodes(cbNode, cbNodes, node.statements); + case 265: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 208: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 227: + return visitNodes(cbNode, cbNodes, node.declarations); + case 210: + return visitNode(cbNode, node.expression); + case 211: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 212: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 213: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 215: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 216: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 217: + case 218: + return visitNode(cbNode, node.label); + case 219: + return visitNode(cbNode, node.expression); + case 220: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 221: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 235: + return visitNodes(cbNode, cbNodes, node.clauses); + case 257: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 258: + return visitNodes(cbNode, cbNodes, node.statements); + case 222: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 223: + return visitNode(cbNode, node.expression); + case 224: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 260: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 147: + return visitNode(cbNode, node.expression); + case 229: + case 199: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 230: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 231: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 232: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 264: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 233: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 237: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 238: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 239: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 236: + return visitNode(cbNode, node.name); + case 240: + return visitNode(cbNode, node.name); + case 241: + case 245: + return visitNodes(cbNode, cbNodes, node.elements); + case 244: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 242: + case 246: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 243: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 196: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 205: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 144: + return visitNode(cbNode, node.expression); + case 259: + return visitNodes(cbNode, cbNodes, node.types); + case 201: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 248: + return visitNode(cbNode, node.expression); + case 247: + return visitNodes(cbNode, cbNodes, node.decorators); + case 289: + return visitNodes(cbNode, cbNodes, node.elements); + case 249: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 250: + case 251: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.attributes); + case 254: + return visitNodes(cbNode, cbNodes, node.properties); + case 253: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 255: + return visitNode(cbNode, node.expression); + case 256: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 252: + return visitNode(cbNode, node.tagName); + case 267: + return visitNode(cbNode, node.type); + case 271: + return visitNode(cbNode, node.type); + case 270: + return visitNode(cbNode, node.type); + case 272: + return visitNode(cbNode, node.type); + case 273: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 274: + return visitNode(cbNode, node.type); + case 275: + return visitNodes(cbNode, cbNodes, node.tags); + case 279: + case 284: + if (node.isNameFirst) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression); + } + else { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name); + } + case 280: + return visitNode(cbNode, node.typeExpression); + case 281: + return visitNode(cbNode, node.typeExpression); + case 277: + return visitNode(cbNode, node.typeExpression); + case 282: + return visitNodes(cbNode, cbNodes, node.typeParameters); + case 283: + if (node.typeExpression && + node.typeExpression.kind === 267) { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName); + } + else { + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + } + case 285: + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } + return; + case 288: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + newSourceFile.flags |= (sourceFile.flags & 524288); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + var Parser; + (function (Parser) { + var scanner = ts.createScanner(5, true); + var disallowInAndDecoratorContext = 2048 | 8192; + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + var contextFlags; + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + initializeState(sourceText, 2, undefined, 6); + sourceFile = createSourceFile(fileName, 2, 6); + var result = sourceFile; + nextToken(); + if (token() === 1) { + sourceFile.endOfFileToken = parseTokenNode(); + } + else if (token() === 17 || + lookAhead(function () { return token() === 9; })) { + result.jsonObject = parseObjectLiteralExpression(); + sourceFile.endOfFileToken = parseExpectedToken(1, false, ts.Diagnostics.Unexpected_token); + } + else { + parseExpected(17); + } + sourceFile.parseDiagnostics = parseDiagnostics; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 || scriptKind === 6 ? 1 : 0; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + parseErrorBeforeNextFinishedNode = false; + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + scanner.setText(""); + scanner.setOnError(undefined); + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; + nextToken(); + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0, parseStatement); + ts.Debug.assert(token() === 1); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + } + function addJSDocComment(node) { + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; + } + if (!node.jsDoc) { + node.jsDoc = []; + } + node.jsDoc.push(jsDoc); + } + } + return node; + } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind) { + var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048); + } + function setYieldContext(val) { + setContextFlag(val, 4096); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192); + } + function setAwaitContext(val) { + setContextFlag(val, 16384); + } + function doOutsideOfContext(context, func) { + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + setContextFlag(false, contextFlagsToClear); + var result = func(); + setContextFlag(true, contextFlagsToClear); + return result; + } + return func(); + } + function doInsideOfContext(context, func) { + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + setContextFlag(true, contextFlagsToSet); + var result = func(); + setContextFlag(false, contextFlagsToSet); + return result; + } + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 | 16384, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096); + } + function inDisallowInContext() { + return inContext(2048); + } + function inDecoratorContext() { + return inContext(8192); + } + function inAwaitContext() { + return inContext(16384); + } + function parseErrorAtCurrentToken(message, arg0) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + parseErrorAtPosition(start, length, message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + parseErrorBeforeNextFinishedNode = true; + } + function scanError(message, length) { + var pos = scanner.getTextPos(); + parseErrorAtPosition(pos, length || 0, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var saveContextFlags = contextFlags; + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, true); + } + function tryParse(callback) { + return speculationHelper(callback, false); + } + function isIdentifier() { + if (token() === 71) { + return true; + } + if (token() === 116 && inYieldContext()) { + return false; + } + if (token() === 121 && inAwaitContext()) { + return false; + } + return token() > 107; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + if (token() === 25) { + return true; + } + return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 25) { + nextToken(); + } + return true; + } + else { + return parseExpected(25); + } + } + function createNode(kind, pos) { + nodeCount++; + if (!(pos >= 0)) { + pos = scanner.getStartPos(); + } + return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : + kind === 71 ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind, scanner.getStartPos()); + if (kind === 71) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(71); + if (token() !== 71) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName() { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 9 || token() === 8) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 21) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseComputedPropertyName() { + var node = createNode(144); + parseExpected(21); + node.expression = allowInAnd(parseExpression); + parseExpected(22); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + if (token() === 76) { + return nextToken() === 83; + } + if (token() === 84) { + nextToken(); + if (token() === 79) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + } + if (token() === 79) { + return nextTokenCanFollowDefaultKeyword(); + } + if (token() === 115) { + nextToken(); + return canFollowModifier(); + } + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 21 + || token() === 17 + || token() === 39 + || token() === 24 + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 75 || token() === 89 || + token() === 109 || + (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0: + case 1: + case 3: + return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); + case 2: + return token() === 73 || token() === 79; + case 4: + return lookAhead(isTypeMemberStart); + case 5: + return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); + case 6: + return token() === 21 || isLiteralPropertyName(); + case 12: + return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); + case 17: + return isLiteralPropertyName(); + case 9: + return token() === 21 || token() === 24 || isLiteralPropertyName(); + case 7: + if (token() === 17) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8: + return isIdentifierOrPattern(); + case 10: + return token() === 26 || token() === 24 || isIdentifierOrPattern(); + case 18: + return isIdentifier(); + case 11: + case 15: + return token() === 26 || token() === 24 || isStartOfExpression(); + case 16: + return isStartOfParameter(); + case 19: + case 20: + return token() === 26 || isStartOfType(); + case 21: + return isHeritageClause(); + case 22: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; + case 14: + return true; + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 17); + if (nextToken() === 18) { + var next = nextToken(); + return next === 26 || next === 17 || next === 85 || next === 108; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 108 || + token() === 85) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function isListTerminator(kind) { + if (token() === 1) { + return true; + } + switch (kind) { + case 1: + case 2: + case 4: + case 5: + case 6: + case 12: + case 9: + case 22: + return token() === 18; + case 3: + return token() === 18 || token() === 73 || token() === 79; + case 7: + return token() === 17 || token() === 85 || token() === 108; + case 8: + return isVariableDeclaratorListTerminator(); + case 18: + return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; + case 11: + return token() === 20 || token() === 25; + case 15: + case 20: + case 10: + return token() === 22; + case 16: + case 17: + return token() === 20 || token() === 22; + case 19: + return token() !== 26; + case 21: + return token() === 17 || token() === 18; + case 13: + return token() === 29 || token() === 41; + case 14: + return token() === 27 && lookAhead(nextTokenIsSlash); + } + } + function isVariableDeclaratorListTerminator() { + if (canParseSemicolon()) { + return true; + } + if (isInOrOfKeyword(token())) { + return true; + } + if (token() === 36) { + return true; + } + return false; + } + function isInSomeParsingContext() { + for (var kind = 0; kind < 23; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + while (!isListTerminator(kind)) { + if (isListElement(kind, false)) { + var element = parseListElement(kind, parseElement); + result.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + if (ts.nodeIsMissing(node)) { + return undefined; + } + if (node.intersectsChange) { + return undefined; + } + if (ts.containsParseError(node)) { + return undefined; + } + var nodeContextFlags = node.flags & 96256; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5: + return isReusableClassMember(node); + case 2: + return isReusableSwitchClause(node); + case 0: + case 1: + case 3: + return isReusableStatement(node); + case 6: + return isReusableEnumMember(node); + case 4: + return isReusableTypeMember(node); + case 8: + return isReusableVariableDeclaration(node); + case 16: + return isReusableParameter(node); + case 17: + return false; + case 21: + case 18: + case 20: + case 19: + case 11: + case 12: + case 7: + case 13: + case 14: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 152: + case 157: + case 153: + case 154: + case 149: + case 206: + return true; + case 151: + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 71 && + methodDeclaration.name.originalKeywordKind === 123; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 257: + case 258: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 228: + case 208: + case 207: + case 211: + case 210: + case 223: + case 219: + case 221: + case 218: + case 217: + case 215: + case 216: + case 214: + case 213: + case 220: + case 209: + case 224: + case 222: + case 212: + case 225: + case 238: + case 237: + case 244: + case 243: + case 233: + case 229: + case 230: + case 232: + case 231: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 264; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 156: + case 150: + case 157: + case 148: + case 155: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 226) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.initializer === undefined; + } + function isReusableParameter(node) { + if (node.kind !== 146) { + return false; + } + var parameter = node; + return parameter.initializer === undefined; + } + function abortParsingListOrMoveToNextToken(kind) { + parseErrorAtCurrentToken(parsingContextErrors(kind)); + if (isInSomeParsingContext()) { + return true; + } + nextToken(); + return false; + } + function parsingContextErrors(context) { + switch (context) { + case 0: return ts.Diagnostics.Declaration_or_statement_expected; + case 1: return ts.Diagnostics.Declaration_or_statement_expected; + case 2: return ts.Diagnostics.case_or_default_expected; + case 3: return ts.Diagnostics.Statement_expected; + case 17: + case 4: return ts.Diagnostics.Property_or_signature_expected; + case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 6: return ts.Diagnostics.Enum_member_expected; + case 7: return ts.Diagnostics.Expression_expected; + case 8: return ts.Diagnostics.Variable_declaration_expected; + case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; + case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; + case 11: return ts.Diagnostics.Argument_expression_expected; + case 12: return ts.Diagnostics.Property_assignment_expected; + case 15: return ts.Diagnostics.Expression_or_comma_expected; + case 16: return ts.Diagnostics.Parameter_declaration_expected; + case 18: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_argument_expected; + case 20: return ts.Diagnostics.Type_expected; + case 21: return ts.Diagnostics.Unexpected_token_expected; + case 22: return ts.Diagnostics.Identifier_expected; + case 13: return ts.Diagnostics.Identifier_expected; + case 14: return ts.Diagnostics.Identifier_expected; + } + } + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + var commaStart = -1; + while (true) { + if (isListElement(kind, false)) { + var startPos = scanner.getStartPos(); + result.push(parseListElement(kind, parseElement)); + commaStart = scanner.getTokenPos(); + if (parseOptional(26)) { + continue; + } + commaStart = -1; + if (isListTerminator(kind)) { + break; + } + parseExpected(26); + if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + } + if (startPos === scanner.getStartPos()) { + nextToken(); + } + continue; + } + if (isListTerminator(kind)) { + break; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + if (commaStart >= 0) { + result.hasTrailingComma = true; + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + return createNodeArray(); + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(23)) { + if (token() === 27) { + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(143, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(196); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); + var templateSpans = createNodeArray(); + do { + templateSpans.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); + templateSpans.end = getNodeEnd(); + template.templateSpans = templateSpans; + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(205); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 18) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + var text = scanner.getTokenValue(); + node.text = text; + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + if (node.kind === 8) { + node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + } + nextToken(); + finishNode(node); + return node; + } + function parseTypeReference() { + var node = createNode(159); + node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(158, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(169); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType() { + var result = createNode(268); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + nextToken(); + if (token() === 26 || + token() === 18 || + token() === 20 || + token() === 29 || + token() === 58 || + token() === 49) { + var result = createNode(269, pos); + return finishNode(result); + } + else { + var result = createNode(270, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNode(273); + nextToken(); + fillSignature(56, 4 | 32, result); + return finishNode(result); + } + var node = createNode(159); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(146); + if (token() === 99 || token() === 94) { + parameter.name = parseIdentifierName(); + parseExpected(56); + } + parameter.type = parseType(); + return finishNode(parameter); + } + function parseJSDocNodeWithType(kind) { + var result = createNode(kind); + nextToken(); + result.type = parseType(); + return finishNode(result); + } + function parseTypeQuery() { + var node = createNode(162); + parseExpected(103); + node.exprName = parseEntityName(true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + if (parseOptional(85)) { + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(58)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 27) { + return parseBracketedList(18, parseTypeParameter, 27, 29); + } + } + function parseParameterType() { + if (parseOptional(56)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter() { + return token() === 24 || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 57 || isStartOfType(); + } + function parseParameter() { + var node = createNode(146); + if (token() === 99) { + node.name = createIdentifier(true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + nextToken(); + } + node.questionToken = parseOptionalToken(55); + node.type = parseParameterType(); + node.initializer = parseBindingElementInitializer(true); + return addJSDocComment(finishNode(node)); + } + function parseBindingElementInitializer(inParameter) { + return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); + } + function parseParameterInitializer() { + return parseInitializer(true); + } + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32)) { + signature.typeParameters = parseTypeParameters(); + } + signature.parameters = parseParameterList(flags); + var returnTokenRequired = returnToken === 36; + if (returnTokenRequired) { + parseExpected(returnToken); + signature.type = parseTypeOrTypePredicate(); + } + else if (parseOptional(returnToken)) { + signature.type = parseTypeOrTypePredicate(); + } + else if (flags & 4) { + var start = scanner.getTokenPos(); + var length_1 = scanner.getTextPos() - start; + var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); + if (backwardToken) { + signature.type = parseTypeOrTypePredicate(); + parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); + } + } + } + function parseParameterList(flags) { + if (parseExpected(19)) { + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + if (!parseExpected(20) && (flags & 8)) { + return undefined; + } + return result; + } + return (flags & 8) ? undefined : createMissingList(); + } + function parseTypeMemberSemicolon() { + if (parseOptional(26)) { + return; + } + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNode(kind); + if (kind === 156) { + parseExpected(94); + } + fillSignature(56, 4, node); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(node)); + } + function isIndexSignature() { + if (token() !== 21) { + return false; + } + return lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + nextToken(); + if (token() === 24 || token() === 22) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + nextToken(); + } + if (token() === 56 || token() === 26) { + return true; + } + if (token() !== 55) { + return false; + } + nextToken(); + return token() === 56 || token() === 26 || token() === 22; + } + function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { + var node = createNode(157, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.parameters = parseBracketedList(16, parseParameter, 21, 22); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(fullStart, modifiers) { + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (token() === 19 || token() === 27) { + var method = createNode(150, fullStart); + method.modifiers = modifiers; + method.name = name; + method.questionToken = questionToken; + fillSignature(56, 4, method); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(method)); + } + else { + var property = createNode(148, fullStart); + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + if (token() === 58) { + property.initializer = parseNonParameterInitializer(); + } + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(property)); + } + } + function isTypeMemberStart() { + if (token() === 19 || token() === 27) { + return true; + } + var idToken; + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + if (token() === 21) { + return true; + } + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + if (idToken) { + return token() === 19 || + token() === 27 || + token() === 55 || + token() === 56 || + token() === 26 || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 19 || token() === 27) { + return parseSignatureMember(155); + } + if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(156); + } + var fullStart = getNodePos(); + var modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 19 || token() === 27; + } + function parseTypeLiteral() { + var node = createNode(163); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(17)) { + members = parseList(4, parseTypeMember); + parseExpected(18); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 131) { + nextToken(); + } + return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; + } + function parseMappedTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + parseExpected(92); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(172); + parseExpected(17); + node.readonlyToken = parseOptionalToken(131); + parseExpected(21); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(22); + node.questionToken = parseOptionalToken(55); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(18); + return finishNode(node); + } + function parseTupleType() { + var node = createNode(165); + node.elementTypes = parseBracketedList(20, parseType, 21, 22); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(168); + parseExpected(19); + node.type = parseType(); + parseExpected(20); + return finishNode(node); + } + function parseFunctionOrConstructorType(kind) { + var node = createNode(kind); + if (kind === 161) { + parseExpected(94); + } + fillSignature(36, 4, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 23 ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(173); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8; + } + function parseNonArrayType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 139: + case 130: + case 134: + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 39: + return parseJSDocAllType(); + case 55: + return parseJSDocUnknownOrNullableType(); + case 89: + return parseJSDocFunctionType(); + case 24: + return parseJSDocNodeWithType(274); + case 51: + return parseJSDocNodeWithType(271); + case 9: + case 8: + case 101: + case 86: + return parseLiteralTypeNode(); + case 38: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + case 105: + case 95: + return parseTokenNode(); + case 99: { + var thisKeyword = parseThisTypeNode(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 103: + return parseTypeQuery(); + case 17: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 21: + return parseTupleType(); + case 19: + return parseParenthesizedType(); + default: + return parseTypeReference(); + } + } + function isStartOfType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 105: + case 139: + case 95: + case 99: + case 103: + case 130: + case 17: + case 21: + case 27: + case 49: + case 48: + case 94: + case 9: + case 8: + case 101: + case 86: + case 134: + return true; + case 38: + return lookAhead(nextTokenIsNumericLiteral); + case 19: + return lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 20 || isStartOfParameter() || isStartOfType(); + } + function parseJSDocPostfixTypeOrHigher() { + var type = parseNonArrayType(); + var kind = getKind(token()); + if (!kind) + return type; + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + function getKind(tokenKind) { + switch (tokenKind) { + case 58: + return contextFlags & 1048576 ? 272 : undefined; + case 51: + return 271; + case 55: + return 270; + } + } + } + function parseArrayTypeOrHigher() { + var type = parseJSDocPostfixTypeOrHigher(); + while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { + if (isStartOfType()) { + var node = createNode(171, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22); + type = finishNode(node); + } + else { + var node = createNode(164, type.pos); + node.elementType = type; + parseExpected(22); + type = finishNode(node); + } + } + return type; + } + function parseTypeOperator(operator) { + var node = createNode(170); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 127: + return parseTypeOperator(127); + } + return parseArrayTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = createNodeArray([type], type.pos); + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + types.end = getNodeEnd(); + var node = createNode(kind, type.pos); + node.types = types; + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + } + function isStartOfFunctionType() { + if (token() === 27) { + return true; + } + return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + parseModifiers(); + } + if (isIdentifier() || token() === 99) { + nextToken(); + return true; + } + if (token() === 21 || token() === 17) { + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 20 || token() === 24) { + return true; + } + if (skipParameterStart()) { + if (token() === 56 || token() === 26 || + token() === 55 || token() === 58) { + return true; + } + if (token() === 20) { + nextToken(); + if (token() === 36) { + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(158, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + return doOutsideOfContext(20480, parseTypeWorker); + } + function parseTypeWorker() { + if (isStartOfFunctionType()) { + return parseFunctionOrConstructorType(160); + } + if (token() === 94) { + return parseFunctionOrConstructorType(161); + } + return parseUnionTypeOrHigher(); + } + function parseTypeAnnotation() { + return parseOptional(56) ? parseType() : undefined; + } + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 99: + case 97: + case 95: + case 101: + case 86: + case 8: + case 9: + case 13: + case 14: + case 19: + case 21: + case 17: + case 89: + case 75: + case 94: + case 41: + case 63: + case 71: + return true; + case 91: + return lookAhead(nextTokenIsOpenParenOrLessThan); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 43: + case 44: + case 27: + case 121: + case 116: + return true; + default: + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + return token() !== 17 && + token() !== 89 && + token() !== 75 && + token() !== 57 && + isStartOfExpression(); + } + function parseExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(26))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return expr; + } + function parseInitializer(inParameter) { + if (token() !== 58) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { + return undefined; + } + } + parseExpected(58); + return parseAssignmentExpressionOrHigher(); + } + function parseAssignmentExpressionOrHigher() { + if (isYieldExpression()) { + return parseYieldExpression(); + } + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + var expr = parseBinaryExpressionOrHigher(0); + if (expr.kind === 71 && token() === 36) { + return parseSimpleArrowFunctionExpression(expr); + } + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 116) { + if (inYieldContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(197); + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 39 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(39); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(187, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(187, identifier.pos); + } + var parameter = createNode(146, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos); + node.parameters.end = parameter.end; + node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(!!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0) { + return undefined; + } + var arrowFunction = triState === 1 + ? parseParenthesizedArrowFunctionExpressionHead(true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + return undefined; + } + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 36 || lastToken === 17) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return addJSDocComment(finishNode(arrowFunction)); + } + function isParenthesizedArrowFunctionExpression() { + if (token() === 19 || token() === 27 || token() === 120) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 36) { + return 1; + } + return 0; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0; + } + if (token() !== 19 && token() !== 27) { + return 0; + } + } + var first = token(); + var second = nextToken(); + if (first === 19) { + if (second === 20) { + var third = nextToken(); + switch (third) { + case 36: + case 56: + case 17: + return 1; + default: + return 0; + } + } + if (second === 21 || second === 17) { + return 2; + } + if (second === 24) { + return 1; + } + if (!isIdentifier()) { + return 0; + } + if (nextToken() === 56) { + return 1; + } + return 2; + } + else { + ts.Debug.assert(first === 27); + if (!isIdentifier()) { + return 0; + } + if (sourceFile.languageVariant === 1) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 85) { + var fourth = nextToken(); + switch (fourth) { + case 58: + case 29: + return false; + default: + return true; + } + } + else if (third === 26) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1; + } + return 0; + } + return 2; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + if (token() === 120) { + var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); + if (isUnParenthesizedAsyncArrowFunction === 1) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak() || token() === 36) { + return 0; + } + var expr = parseBinaryExpressionOrHigher(0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { + return 1; + } + } + return 0; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNode(187); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + if (!node.parameters) { + return undefined; + } + if (!allowAmbiguity && token() !== 36 && token() !== 17) { + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 17) { + return parseFunctionBlock(isAsync ? 2 : 0); + } + if (token() !== 25 && + token() !== 89 && + token() !== 75 && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + return parseFunctionBlock(16 | (isAsync ? 2 : 0)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + var questionToken = parseOptionalToken(55); + if (!questionToken) { + return leftOperand; + } + var node = createNode(195, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); + node.whenFalse = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 92 || t === 142; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + reScanGreaterToken(); + var newPrecedence = getBinaryOperatorPrecedence(); + var consumeCurrentOperator = token() === 40 ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 92 && inDisallowInContext()) { + break; + } + if (token() === 118) { + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 92) { + return false; + } + return getBinaryOperatorPrecedence() > 0; + } + function getBinaryOperatorPrecedence() { + switch (token()) { + case 54: + return 1; + case 53: + return 2; + case 49: + return 3; + case 50: + return 4; + case 48: + return 5; + case 32: + case 33: + case 34: + case 35: + return 6; + case 27: + case 29: + case 30: + case 31: + case 93: + case 92: + case 118: + return 7; + case 45: + case 46: + case 47: + return 8; + case 37: + case 38: + return 9; + case 39: + case 41: + case 42: + return 10; + case 40: + return 11; + } + return -1; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(194, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(202, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(188); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(189); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(190); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 121) { + if (inAwaitContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(191); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseUnaryExpressionOrHigher() { + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 40 ? + parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + updateExpression; + } + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 40) { + var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + if (simpleUnaryExpression.kind === 184) { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + function parseSimpleUnaryExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + return parsePrefixUnaryExpression(); + case 80: + return parseDeleteExpression(); + case 103: + return parseTypeOfExpression(); + case 105: + return parseVoidExpression(); + case 27: + return parseTypeAssertion(); + case 121: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + default: + return parseUpdateExpression(); + } + } + function isUpdateExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 121: + return false; + case 27: + if (sourceFile.languageVariant !== 1) { + return false; + } + default: + return true; + } + } + function parseUpdateExpression() { + if (token() === 43 || token() === 44) { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + return parseJsxElementOrSelfClosingElement(true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(193, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + var expression; + if (token() === 91 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + sourceFile.flags |= 524288; + expression = parseTokenNode(); + } + else { + expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 19 || token() === 23 || token() === 21) { + return expression; + } + var node = createNode(179, expression.pos); + node.expression = expression; + parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(true); + return finishNode(node); + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 71) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 99) { + return true; + } + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + function parseJsxElementOrSelfClosingElement(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + var result; + if (opening.kind === 251) { + var node = createNode(249, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement.tagName); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 250); + result = opening; + } + if (inExpressionContext && token() === 27) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(194, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(26, false, undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(10, scanner.getStartPos()); + node.containsOnlyWhiteSpaces = currentToken === 11; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild() { + switch (token()) { + case 10: + case 11: + return parseJsxText(); + case 17: + return parseJsxExpression(false); + case 27: + return parseJsxElementOrSelfClosingElement(false); + } + ts.Debug.fail("Unknown JSX child kind " + token()); + } + function parseJsxChildren(openingTagName) { + var result = createNodeArray(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14; + while (true) { + currentToken = scanner.reScanJsxToken(); + if (token() === 28) { + break; + } + else if (token() === 1) { + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + break; + } + else if (token() === 7) { + break; + } + var child = parseJsxChild(); + if (child) { + result.push(child); + } + } + result.end = scanner.getTokenPos(); + parsingContext = saveParsingContext; + return result; + } + function parseJsxAttributes() { + var jsxAttributes = createNode(254); + jsxAttributes.properties = parseList(13, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(27); + var tagName = parseJsxElementName(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 29) { + node = createNode(251, fullStart); + scanJsxText(); + } + else { + parseExpected(41); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + node = createNode(250, fullStart); + } + node.tagName = tagName; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + var expression = token() === 99 ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(23)) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(256); + parseExpected(17); + if (token() !== 18) { + node.dotDotDotToken = parseOptionalToken(24); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(18); + } + else { + parseExpected(18, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 17) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(253); + node.name = parseIdentifierName(); + if (token() === 58) { + switch (scanJsxAttributeValue()) { + case 9: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(255); + parseExpected(17); + parseExpected(24); + node.expression = parseExpression(); + parseExpected(18); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(252); + parseExpected(28); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(184); + parseExpected(27); + node.type = parseType(); + parseExpected(29); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(23); + if (dotToken) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 51 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(203, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + if (!inDecoratorContext() && parseOptional(21)) { + var indexedAccess = createNode(180, expression.pos); + indexedAccess.expression = expression; + if (token() !== 22) { + indexedAccess.argumentExpression = allowInAnd(parseExpression); + if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { + var literal = indexedAccess.argumentExpression; + literal.text = internIdentifier(literal.text); + } + } + parseExpected(22); + expression = finishNode(indexedAccess); + continue; + } + if (token() === 13 || token() === 14) { + var tagExpression = createNode(183, expression.pos); + tagExpression.tag = expression; + tagExpression.template = token() === 13 + ? parseLiteralNode() + : parseTemplateExpression(); + expression = finishNode(tagExpression); + continue; + } + return expression; + } + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 27) { + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 19) { + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(19); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(20); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(27)) { + return undefined; + } + var typeArguments = parseDelimitedList(19, parseType); + if (!parseExpected(29)) { + return undefined; + } + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 19: + case 23: + case 20: + case 22: + case 56: + case 25: + case 55: + case 32: + case 34: + case 33: + case 35: + case 53: + case 54: + case 50: + case 48: + case 49: + case 18: + case 1: + return true; + case 26: + case 17: + default: + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8: + case 9: + case 13: + return parseLiteralNode(); + case 99: + case 97: + case 95: + case 101: + case 86: + return parseTokenNode(); + case 19: + return parseParenthesizedExpression(); + case 21: + return parseArrayLiteralExpression(); + case 17: + return parseObjectLiteralExpression(); + case 120: + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 75: + return parseClassExpression(); + case 89: + return parseFunctionExpression(); + case 94: + return parseNewExpression(); + case 41: + case 63: + if (reScanSlashToken() === 12) { + return parseLiteralNode(); + } + break; + case 14: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNode(185); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + return addJSDocComment(finishNode(node)); + } + function parseSpreadElement() { + var node = createNode(198); + parseExpected(24); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 24 ? parseSpreadElement() : + token() === 26 ? createNode(200) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(177); + parseExpected(21); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); + parseExpected(22); + return finishNode(node); + } + function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + } + else if (parseContextualModifier(135)) { + return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + } + return undefined; + } + function parseObjectLiteralElement() { + var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(24); + if (dotDotDotToken) { + var spreadElement = createNode(263, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + var asteriskToken = parseOptionalToken(39); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + } + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); + if (isShorthandPropertyAssignment) { + var shorthandDeclaration = createNode(262, fullStart); + shorthandDeclaration.name = propertyName; + shorthandDeclaration.questionToken = questionToken; + var equalsToken = parseOptionalToken(58); + if (equalsToken) { + shorthandDeclaration.equalsToken = equalsToken; + shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return addJSDocComment(finishNode(shorthandDeclaration)); + } + else { + var propertyAssignment = createNode(261, fullStart); + propertyAssignment.modifiers = modifiers; + propertyAssignment.name = propertyName; + propertyAssignment.questionToken = questionToken; + parseExpected(56); + propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + return addJSDocComment(finishNode(propertyAssignment)); + } + } + function parseObjectLiteralExpression() { + var node = createNode(178); + parseExpected(17); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); + parseExpected(18); + return finishNode(node); + } + function parseFunctionExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var node = createNode(186); + node.modifiers = parseModifiers(); + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return addJSDocComment(finishNode(node)); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpression() { + var fullStart = scanner.getStartPos(); + parseExpected(94); + if (parseOptional(23)) { + var node_1 = createNode(204, fullStart); + node_1.keywordToken = 94; + node_1.name = parseIdentifierName(); + return finishNode(node_1); + } + var node = createNode(182, fullStart); + node.expression = parseMemberExpressionOrHigher(); + node.typeArguments = tryParse(parseTypeArgumentsInExpression); + if (node.typeArguments || token() === 19) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(207); + if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2)); + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var block = parseBlock(!!(flags & 16), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(209); + parseExpected(25); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(211); + parseExpected(90); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(82) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(212); + parseExpected(81); + node.statement = parseStatement(); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + parseOptional(25); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(213); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(88); + var awaitToken = parseOptionalToken(121); + parseExpected(19); + var initializer = undefined; + if (token() !== 25) { + if (token() === 104 || token() === 110 || token() === 76) { + initializer = parseVariableDeclarationList(true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(142) : parseOptional(142)) { + var forOfStatement = createNode(216, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(20); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(92)) { + var forInStatement = createNode(215, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(20); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(214, pos); + forStatement.initializer = initializer; + parseExpected(25); + if (token() !== 25 && token() !== 20) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(25); + if (token() !== 20) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(20); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 218 ? 72 : 77); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(219); + parseExpected(96); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(220); + parseExpected(107); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(257); + parseExpected(73); + node.expression = allowInAnd(parseExpression); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(258); + parseExpected(79); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 73 ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(221); + parseExpected(98); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + var caseBlock = createNode(235, scanner.getStartPos()); + parseExpected(17); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(18); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + var node = createNode(223); + parseExpected(100); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + function parseTryStatement() { + var node = createNode(224); + parseExpected(102); + node.tryBlock = parseBlock(false); + node.catchClause = token() === 74 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 87) { + parseExpected(87); + node.finallyBlock = parseBlock(false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(260); + parseExpected(74); + if (parseExpected(19)) { + result.variableDeclaration = parseVariableDeclaration(); + } + parseExpected(20); + result.block = parseBlock(false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(225); + parseExpected(78); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + var fullStart = scanner.getStartPos(); + var expression = allowInAnd(parseExpression); + if (expression.kind === 71 && parseOptional(56)) { + var labeledStatement = createNode(222, fullStart); + labeledStatement.label = expression; + labeledStatement.statement = parseStatement(); + return addJSDocComment(finishNode(labeledStatement)); + } + else { + var expressionStatement = createNode(210, fullStart); + expressionStatement.expression = expression; + parseSemicolon(); + return addJSDocComment(finishNode(expressionStatement)); + } + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 75 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 89 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 104: + case 110: + case 76: + case 89: + case 75: + case 83: + return true; + case 109: + case 138: + return nextTokenIsIdentifierOnSameLine(); + case 128: + case 129: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 117: + case 120: + case 124: + case 112: + case 113: + case 114: + case 131: + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 141: + nextToken(); + return token() === 17 || token() === 71 || token() === 84; + case 91: + nextToken(); + return token() === 9 || token() === 39 || + token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); + case 84: + nextToken(); + if (token() === 58 || token() === 39 || + token() === 17 || token() === 79 || + token() === 118) { + return true; + } + continue; + case 115: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 57: + case 25: + case 17: + case 104: + case 110: + case 89: + case 75: + case 83: + case 90: + case 81: + case 106: + case 88: + case 77: + case 72: + case 96: + case 107: + case 98: + case 100: + case 102: + case 78: + case 74: + case 87: + return true; + case 91: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + case 76: + case 84: + return isStartOfDeclaration(); + case 120: + case 124: + case 109: + case 128: + case 129: + case 138: + case 141: + return true; + case 114: + case 112: + case 113: + case 115: + case 131: + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 17 || token() === 21; + } + function isLetDeclaration() { + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 25: + return parseEmptyStatement(); + case 17: + return parseBlock(false); + case 104: + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 110: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; + case 89: + return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); + case 75: + return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); + case 90: + return parseIfStatement(); + case 81: + return parseDoStatement(); + case 106: + return parseWhileStatement(); + case 88: + return parseForOrForInOrForOfStatement(); + case 77: + return parseBreakOrContinueStatement(217); + case 72: + return parseBreakOrContinueStatement(218); + case 96: + return parseReturnStatement(); + case 107: + return parseWithStatement(); + case 98: + return parseSwitchStatement(); + case 100: + return parseThrowStatement(); + case 102: + case 74: + case 87: + return parseTryStatement(); + case 78: + return parseDebuggerStatement(); + case 57: + return parseDeclaration(); + case 120: + case 109: + case 138: + case 128: + case 129: + case 124: + case 76: + case 83: + case 84: + case 91: + case 112: + case 113: + case 114: + case 117: + case 115: + case 131: + case 141: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function parseDeclaration() { + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + switch (token()) { + case 104: + case 110: + case 76: + return parseVariableStatement(fullStart, decorators, modifiers); + case 89: + return parseFunctionDeclaration(fullStart, decorators, modifiers); + case 75: + return parseClassDeclaration(fullStart, decorators, modifiers); + case 109: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 138: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 83: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 141: + case 128: + case 129: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 91: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 84: + nextToken(); + switch (token()) { + case 79: + case 58: + return parseExportAssignment(fullStart, decorators, modifiers); + case 118: + return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + default: + return parseExportDeclaration(fullStart, decorators, modifiers); + } + default: + if (decorators || modifiers) { + var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + node.modifiers = modifiers; + return finishNode(node); + } + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 17 && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + function parseArrayBindingElement() { + if (token() === 26) { + return createNode(200); + } + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 56) { + node.name = propertyName; + } + else { + parseExpected(56); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(174); + parseExpected(17); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(18); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(175); + parseExpected(21); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(22); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 17 || token() === 21 || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 21) { + return parseArrayBindingPattern(); + } + if (token() === 17) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclaration() { + var node = createNode(226); + node.name = parseIdentifierOrPattern(); + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(false); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(227); + switch (token()) { + case 104: + break; + case 110: + node.flags |= 1; + break; + case 76: + node.flags |= 2; + break; + default: + ts.Debug.fail(); + } + nextToken(); + if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 20; + } + function parseVariableStatement(fullStart, decorators, modifiers) { + var node = createNode(208, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.declarationList = parseVariableDeclarationList(false); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseFunctionDeclaration(fullStart, decorators, modifiers) { + var node = createNode(228, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseConstructorDeclaration(pos, decorators, modifiers) { + var node = createNode(152, pos); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(123); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { + var method = createNode(151, fullStart); + method.decorators = decorators; + method.modifiers = modifiers; + method.asteriskToken = asteriskToken; + method.name = name; + method.questionToken = questionToken; + var isGenerator = asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(method, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, method); + method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return addJSDocComment(finishNode(method)); + } + function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { + var property = createNode(149, fullStart); + property.decorators = decorators; + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + property.initializer = ts.hasModifier(property, 32) + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); + parseSemicolon(); + return addJSDocComment(finishNode(property)); + } + function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + var asteriskToken = parseOptionalToken(39); + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + } + else { + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + } + } + function parseNonParameterInitializer() { + return parseInitializer(false); + } + function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.name = parsePropertyName(); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0); + return addJSDocComment(finishNode(node)); + } + function isClassMemberModifier(idToken) { + switch (idToken) { + case 114: + case 112: + case 113: + case 115: + case 131: + return true; + default: + return false; + } + } + function isClassMemberStart() { + var idToken; + if (token() === 57) { + return true; + } + while (ts.isModifierKind(token())) { + idToken = token(); + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 39) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + if (token() === 21) { + return true; + } + if (idToken !== undefined) { + if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { + return true; + } + switch (token()) { + case 19: + case 27: + case 56: + case 58: + case 55: + return true; + default: + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var decorators; + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(57)) { + break; + } + var decorator = createNode(147, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } + } + if (decorators) { + decorators.end = getNodeEnd(); + } + return decorators; + } + function parseModifiers(permitInvalidConstAsModifier) { + var modifiers; + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 76 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + if (!modifiers) { + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); + } + } + if (modifiers) { + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 120) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseClassElement() { + if (token() === 25) { + var result = createNode(206); + nextToken(); + return finishNode(result); + } + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(true); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + if (token() === 123) { + return parseConstructorDeclaration(fullStart, decorators, modifiers); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + } + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8 || + token() === 39 || + token() === 21) { + return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + } + if (decorators || modifiers) { + var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + } + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + } + function parseClassDeclaration(fullStart, decorators, modifiers) { + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + } + function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(75); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(17)) { + node.members = parseClassMembers(); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseNameOfClassDeclarationOrExpression() { + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + if (isHeritageClause()) { + return parseList(21, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + if (tok === 85 || tok === 108) { + var node = createNode(259); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); + } + return undefined; + } + function parseExpressionWithTypeArguments() { + var node = createNode(201); + node.expression = parseLeftHandSideExpressionOrHigher(); + if (token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function isHeritageClause() { + return token() === 85 || token() === 108; + } + function parseClassMembers() { + return parseList(5, parseClassElement); + } + function parseInterfaceDeclaration(fullStart, decorators, modifiers) { + var node = createNode(230, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(109); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return addJSDocComment(finishNode(node)); + } + function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { + var node = createNode(231, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(138); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(58); + node.type = parseType(); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseEnumMember() { + var node = createNode(264, scanner.getStartPos()); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseNonParameterInitializer); + return addJSDocComment(finishNode(node)); + } + function parseEnumDeclaration(fullStart, decorators, modifiers) { + var node = createNode(232, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(83); + node.name = parseIdentifier(); + if (parseExpected(17)) { + node.members = parseDelimitedList(6, parseEnumMember); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseModuleBlock() { + var node = createNode(234, scanner.getStartPos()); + if (parseExpected(17)) { + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { + var node = createNode(233, fullStart); + var namespaceFlag = flags & 16; + node.decorators = decorators; + node.modifiers = modifiers; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(23) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + : parseModuleBlock(); + return addJSDocComment(finishNode(node)); + } + function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { + var node = createNode(233, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (token() === 141) { + node.name = parseIdentifier(); + node.flags |= 512; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 17) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(fullStart, decorators, modifiers) { + var flags = 0; + if (token() === 141) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(129)) { + flags |= 16; + } + else { + parseExpected(128); + if (token() === 9) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + } + return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + } + function isExternalModuleReference() { + return token() === 132 && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 19; + } + function nextTokenIsSlash() { + return nextToken() === 41; + } + function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { + var exportDeclaration = createNode(236, fullStart); + exportDeclaration.decorators = decorators; + exportDeclaration.modifiers = modifiers; + parseExpected(118); + parseExpected(129); + exportDeclaration.name = parseIdentifier(); + parseSemicolon(); + return finishNode(exportDeclaration); + } + function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + parseExpected(91); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 26 && token() !== 140) { + return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + } + } + var importDeclaration = createNode(238, fullStart); + importDeclaration.decorators = decorators; + importDeclaration.modifiers = modifiers; + if (identifier || + token() === 39 || + token() === 17) { + importDeclaration.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(140); + } + importDeclaration.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(importDeclaration); + } + function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { + var importEqualsDeclaration = createNode(237, fullStart); + importEqualsDeclaration.decorators = decorators; + importEqualsDeclaration.modifiers = modifiers; + importEqualsDeclaration.name = identifier; + parseExpected(58); + importEqualsDeclaration.moduleReference = parseModuleReference(); + parseSemicolon(); + return addJSDocComment(finishNode(importEqualsDeclaration)); + } + function parseImportClause(identifier, fullStart) { + var importClause = createNode(239, fullStart); + if (identifier) { + importClause.name = identifier; + } + if (!importClause.name || + parseOptional(26)) { + importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(false); + } + function parseExternalModuleReference() { + var node = createNode(248); + parseExpected(132); + parseExpected(19); + node.expression = parseModuleSpecifier(); + parseExpected(20); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 9) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + return parseExpression(); + } + } + function parseNamespaceImport() { + var namespaceImport = createNode(240); + parseExpected(39); + parseExpected(118); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(246); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(242); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 118) { + node.propertyName = identifierName; + parseExpected(118); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 242 && checkIdentifierIsKeyword) { + parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(fullStart, decorators, modifiers) { + var node = createNode(244, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(39)) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(245); + if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(fullStart, decorators, modifiers) { + var node = createNode(243, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(58)) { + node.isExportEquals = true; + } + else { + parseExpected(79); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function processReferenceComments(sourceFile) { + var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); + var referencedFiles = []; + var typeReferenceDirectives = []; + var amdDependencies = []; + var amdModuleName; + var checkJsDirective = undefined; + while (true) { + var kind = triviaScanner.scan(); + if (kind !== 2) { + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); + if (referencePathMatchResult) { + var fileReference = referencePathMatchResult.fileReference; + sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + if (fileReference) { + if (referencePathMatchResult.isTypeReferenceDirective) { + typeReferenceDirectives.push(fileReference); + } + else { + referencedFiles.push(fileReference); + } + } + if (diagnosticMessage) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + } + } + else { + var amdModuleNameRegEx = /^\/\/\/\s*= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + var tags; + var comments = []; + var result; + if (!isJsDocStart(content, start)) { + return result; + } + scanner.scanRange(start + 3, length - 5, function () { + var advanceToken = true; + var state = 1; + var margin = undefined; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5) { + nextJSDocToken(); + } + if (token() === 4) { + state = 0; + indent = 0; + nextJSDocToken(); + } + while (token() !== 1) { + switch (token()) { + case 57: + if (state === 0 || state === 1) { + removeTrailingNewlines(comments); + parseTag(indent); + state = 0; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 39: + var asterisk = scanner.getTokenText(); + if (state === 1 || state === 2) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 71: + pushComment(scanner.getTokenText()); + state = 2; + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break; + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { + nextJSDocToken(); + } + else { + advanceToken = true; + } + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42; + } + function createJSDocComment() { + var result = createNode(275, start); + result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function skipWhitespace() { + while (token() === 5 || token() === 4) { + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return; + } + var tag; + if (tagName) { + switch (tagName.escapedText) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + tag = parseParameterOrPropertyTag(atToken, tagName, 1); + break; + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; + } + } + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + } + function parseTagComments(indent) { + var comments = []; + var state = 0; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 57 && token() !== 1) { + switch (token()) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 57: + break; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 39: + if (state === 0) { + state = 1; + indent += scanner.getTokenText().length; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (token() === 57) { + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { + var result = createNode(276, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); + } + else { + tags.push(tag); + } + tags.end = tag.end; + } + function tryParseTypeExpression() { + return tryParse(function () { + skipWhitespace(); + if (token() !== 17) { + return undefined; + } + return parseJSDocTypeExpression(); + }); + } + function parseBracketNameInPropertyAndParamTag() { + var isBracketed = parseOptional(21); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + if (parseOptionalToken(58)) { + parseExpression(); + } + parseExpected(22); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 134: + return true; + case 164: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(atToken, tagName, target) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespace(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 ? + createNode(279, atToken.pos) : + createNode(284, atToken.pos); + var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { + if (!children) { + children = []; + } + children.push(child); + } + if (children) { + jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(280, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(281, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(277, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } + function parseClassTag(atToken, tagName) { + var tag = createNode(278, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var typedefTag = createNode(283, atToken.pos); + typedefTag.atToken = atToken; + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (true) { + if (rightNode.kind === 71 || !rightNode.body) { + typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; + break; + } + rightNode = rightNode.body; + } + } + skipWhitespace(); + typedefTag.typeExpression = typeExpression; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var alreadyHasTypeTag = false; + var start_3 = scanner.getStartPos(); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(285, start_3); + } + if (child.kind === 281) { + if (alreadyHasTypeTag) { + break; + } + else { + jsdocTypeLiteral.jsDocTypeTag = child; + alreadyHasTypeTag = true; + } + } + else { + if (!jsdocTypeLiteral.jsDocPropertyTags) { + jsdocTypeLiteral.jsDocPropertyTags = []; + } + jsdocTypeLiteral.jsDocPropertyTags.push(child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + } + } + return finishNode(typedefTag); + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23)) { + var jsDocNamespaceNode = createNode(233, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && flags & 4) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildParameterOrPropertyTag(target, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + nextJSDocToken(); + switch (token()) { + case 57: + if (canParseTag) { + var child = tryParseChildTag(target); + if (child && child.kind === 279 && + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4: + canParseTag = true; + seenAsterisk = false; + break; + case 39: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 71: + canParseTag = false; + break; + case 1: + return false; + } + } + } + function tryParseChildTag(target) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getStartPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return false; + } + switch (tagName.escapedText) { + case "type": + return target === 0 && parseTypeTag(atToken, tagName); + case "prop": + case "property": + return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + case "arg": + case "argument": + case "param": + return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + } + return false; + } + function parseTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var typeParameters = createNodeArray(); + while (true) { + var name = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(145, name.pos); + typeParameter.name = name; + finishNode(typeParameter); + typeParameters.push(typeParameter); + if (token() === 26) { + nextJSDocToken(); + skipWhitespace(); + } + else { + break; + } + } + var result = createNode(282, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + finishNode(result); + typeParameters.end = result.end; + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + while (parseOptional(23)) { + var name = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(createIfMissing) { + if (createIfMissing === void 0) { createIfMissing = false; } + if (!ts.tokenIsIdentifierOrKeyword(token())) { + if (createIfMissing) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); + return undefined; + } + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(71, pos); + result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); + } + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + forEachChild(jsDocComment, visitNode, visitArray); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 9: + case 8: + case 71: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + element.pos = Math.min(element.pos, changeRangeNewEnd); + if (element.end >= changeRangeOldEnd) { + element.end += delta; + } + else { + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + checkNodePositions(child, aggressiveChecks); + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; + visitNode(node); + } + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + var maxLookahead = 1; + var start = changeRange.span.start; + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } + else { + ts.Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1; + return { + currentNode: function (position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = undefined; + currentArrayIndex = -1; + current = undefined; + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode, visitArray); + return true; + } + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + return false; + } + } + } + })(IncrementalParser || (IncrementalParser = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function getModuleInstanceState(node) { + if (node.kind === 230 || node.kind === 231) { + return 0; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2; + } + else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { + return 0; + } + else if (node.kind === 234) { + var state_1 = 0; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0: + return false; + case 2: + state_1 = 2; + return false; + case 1: + state_1 = 1; + return true; + } + }); + return state_1; + } + else if (node.kind === 233) { + var body = node.body; + return body ? getModuleInstanceState(body) : 1; + } + else if (node.kind === 71 && node.isInJSDocNamespace) { + return 0; + } + else { + return 1; + } + } + ts.getModuleInstanceState = getModuleInstanceState; + var binder = createBinder(); + function bindSourceFile(file, options) { + ts.performance.mark("beforeBind"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + var emitFlags; + var inStrictMode; + var symbolCount = 0; + var Symbol; + var classifiableNames; + var unreachableFlow = { flags: 1 }; + var reportedUnreachableFlow = { flags: 1 }; + var subtreeTransformFlags = 0; + var skipTransformFlagAggregation; + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0; + subtreeTransformFlags = 0; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & 6240 && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { + symbol.valueDeclaration = node; + } + } + } + function getDeclarationName(node) { + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 144) { + var nameExpression = name.expression; + if (ts.isStringOrNumericLiteral(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + } + return ts.getEscapedTextOfIdentifierOrLiteral(name); + } + switch (node.kind) { + case 152: + return "__constructor"; + case 160: + case 155: + return "__call"; + case 161: + case 156: + return "__new"; + case 157: + return "__index"; + case 244: + return "__export"; + case 243: + return node.isExportEquals ? "export=" : "default"; + case 194: + if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + return "export="; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 228: + case 229: + return (ts.hasModifier(node, 512) ? "default" : undefined); + case 273: + return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); + case 146: + ts.Debug.assert(node.parent.kind === 273); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "arg" + index; + case 283: + var parentNode = node.parent && node.parent.parent; + var nameFromParentNode = void 0; + if (parentNode && parentNode.kind === 208) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (ts.isIdentifier(nameIdentifier)) { + nameFromParentNode = nameIdentifier.escapedText; + } + } + } + return nameFromParentNode; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + } + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512); + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0, "__missing"); + } + else { + symbol = symbolTable.get(name); + if (includes & 788448) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + symbolTable.set(name, symbol = createSymbol(0, name)); + } + else { + if (node.name) { + node.name.parent = node; + } + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; + if (symbolFlags & 2097152) { + if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + if (node.kind === 283) + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var isJSDocTypedefInJSDocNamespace = node.kind === 283 && + node.name && + node.name.kind === 71 && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { + var exportKind = symbolFlags & 107455 ? 1048576 : 0; + var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + } + function bindContainer(node, containerFlags) { + var saveContainer = container; + var savedBlockScopeContainer = blockScopeContainer; + if (containerFlags & 1) { + container = blockScopeContainer = node; + if (containerFlags & 32) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); + if (isIIFE) { + currentReturnTarget = createBranchLabel(); + } + else { + currentFlow = { flags: 2 }; + if (containerFlags & (16 | 128)) { + currentFlow.container = node; + } + currentReturnTarget = undefined; + } + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + node.flags &= ~1408; + if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { + node.flags |= 128; + if (hasExplicitReturn) + node.flags |= 256; + } + if (node.kind === 265) { + node.flags |= emitFlags; + } + if (isIIFE) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + } + else { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; + } + else { + bindChildren(node); + } + container = saveContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (node.jsDoc) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + if (checkUnreachable(node)) { + bindEachChild(node); + return; + } + switch (node.kind) { + case 213: + bindWhileStatement(node); + break; + case 212: + bindDoStatement(node); + break; + case 214: + bindForStatement(node); + break; + case 215: + case 216: + bindForInOrForOfStatement(node); + break; + case 211: + bindIfStatement(node); + break; + case 219: + case 223: + bindReturnOrThrow(node); + break; + case 218: + case 217: + bindBreakOrContinueStatement(node); + break; + case 224: + bindTryStatement(node); + break; + case 221: + bindSwitchStatement(node); + break; + case 235: + bindCaseBlock(node); + break; + case 257: + bindCaseClause(node); + break; + case 222: + bindLabeledStatement(node); + break; + case 192: + bindPrefixUnaryExpressionFlow(node); + break; + case 193: + bindPostfixUnaryExpressionFlow(node); + break; + case 194: + bindBinaryExpressionFlow(node); + break; + case 188: + bindDeleteExpressionFlow(node); + break; + case 195: + bindConditionalExpressionFlow(node); + break; + case 226: + bindVariableDeclarationFlow(node); + break; + case 181: + bindCallExpressionFlow(node); + break; + case 275: + bindJSDocComment(node); + break; + case 283: + bindJSDocTypedefTag(node); + break; + default: + bindEachChild(node); + break; + } + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 71: + case 99: + case 179: + return isNarrowableReference(expr); + case 181: + return hasNarrowableArgument(expr); + case 185: + return isNarrowingExpression(expr.expression); + case 194: + return isNarrowingBinaryExpression(expr); + case 192: + return expr.operator === 51 && isNarrowingExpression(expr.operand); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 71 || + expr.kind === 99 || + expr.kind === 97 || + expr.kind === 179 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 179 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 58: + return isNarrowableReference(expr.left); + case 32: + case 33: + case 34: + case 35: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 93: + return isNarrowableOperand(expr.left); + case 26: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 185: + return isNarrowableOperand(expr.expression); + case 194: + switch (expr.operatorToken.kind) { + case 58: + return isNarrowableOperand(expr.left); + case 26: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + flow.flags |= flow.flags & 512 ? 1024 : 512; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1) { + return antecedent; + } + if (!expression) { + return flags & 32 ? antecedent : unreachableFlow; + } + if (expression.kind === 101 && flags & 64 || + expression.kind === 86 && flags & 32) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: flags, + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent + }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 16, + antecedent: antecedent, + node: node + }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256, + antecedent: antecedent, + node: node + }; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 211: + case 213: + case 212: + return parent.expression === node; + case 214: + case 195: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 185) { + node = node.expression; + } + else if (node.kind === 192 && node.operator === 51) { + node = node.operand; + } + else { + return node.kind === 194 && (node.operatorToken.kind === 53 || + node.operatorToken.kind === 54); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 185 || + node.parent.kind === 192 && + node.parent.operator === 51) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 222 + ? ts.lastOrUndefined(activeLabels) + : undefined; + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 216) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 227) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 219) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 218 ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + if (!(currentFlow.flags & 1)) { + if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1)) { + var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + } + if (!node.statement || node.statement.kind !== 212) { + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 194 && node.operatorToken.kind === 58) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 177) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 198) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 178) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 261) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 262) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 263) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 53) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 51) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 43 || node.operator === 44) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 43 || node.operator === 44) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 53 || operator === 54) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 58 && node.left.kind === 180) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 179) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocComment(node) { + ts.forEachChild(node, function (n) { + if (n.kind !== 283) { + bind(n); + } + }); + } + function bindJSDocTypedefTag(node) { + ts.forEachChild(node, function (n) { + if (node.fullName && n === node.name && node.fullName.kind !== 71) { + return; + } + bind(n); + }); + } + function bindCallExpressionFlow(node) { + var expr = node.expression; + while (expr.kind === 185) { + expr = expr.expression; + } + if (expr.kind === 186 || expr.kind === 187) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 179) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 199: + case 229: + case 232: + case 178: + case 163: + case 285: + case 254: + return 1; + case 230: + return 1 | 64; + case 233: + case 231: + case 172: + return 1 | 32; + case 265: + return 1 | 4 | 32; + case 151: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } + case 152: + case 228: + case 150: + case 153: + case 154: + case 155: + case 273: + case 160: + case 156: + case 157: + case 161: + return 1 | 4 | 32 | 8; + case 186: + case 187: + return 1 | 4 | 32 | 8 | 16; + case 234: + return 4; + case 149: + return node.initializer ? 4 : 0; + case 260: + case 214: + case 215: + case 216: + case 235: + return 2; + case 207: + return ts.isFunctionLike(node.parent) ? 0 : 2; + } + return 0; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + case 233: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 265: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 199: + case 229: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 232: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 163: + case 285: + case 178: + case 230: + case 254: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 160: + case 161: + case 155: + case 156: + case 157: + case 151: + case 150: + case 152: + case 153: + case 154: + case 228: + case 186: + case 187: + case 273: + case 231: + case 172: + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 265 ? node : node.body; + if (body && (body.kind === 265 || body.kind === 234)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 244 || stat.kind === 243) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 32; + } + else { + node.flags &= ~32; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isExternalModuleAugmentation(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 9) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); + if (pattern) { + (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); + } + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0) { + if (node.symbol.flags & (16 | 32 | 256)) { + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2; + if (node.symbol.constEnumOnlyModule === undefined) { + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); + return state; + } + function bindFunctionOrConstructorType(node) { + var symbol = createSymbol(131072, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072); + var typeLiteralSymbol = createSymbol(2048, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); + } + function bindObjectLiteralExpression(node) { + if (inStrictMode) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263 || prop.name.kind !== 71) { + continue; + } + var identifier = prop.name; + var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 + ? 1 + : 2; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 && existingKind === 1) { + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096, "__object"); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 233: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 265: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2, 107455); + } + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 108 && + node.originalKeywordKind <= 116 && + !ts.isIdentifierName(node) && + !ts.isInAmbientContext(node)) { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + if (inStrictMode && node.expression.kind === 71) { + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 71) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2) { + if (blockScopeContainer.kind !== 265 && + blockScopeContainer.kind !== 233 && + !ts.isFunctionLike(blockScopeContainer)) { + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 4) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + if (inStrictMode) { + if (node.operator === 43 || node.operator === 44) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + if (ts.isInJavaScriptFile(node)) + bindJSDocTypedefTagIfAny(node); + bindWorker(node); + if (node.kind > 142) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } + inStrictMode = saveInStrictMode; + } + function bindJSDocTypedefTagIfAny(node) { + if (!node.jsDoc) { + return; + } + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (!jsDoc.tags) { + continue; + } + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.kind === 283) { + var savedParent = parent; + parent = jsDoc; + bind(tag); + parent = savedParent; + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + case 71: + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 283) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288, 793064); + break; + } + case 99: + if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 179: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + break; + case 194: + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 5: + bindStaticPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 260: + return checkStrictModeCatchClause(node); + case 188: + return checkStrictModeDeleteExpression(node); + case 8: + return checkStrictModeNumericLiteral(node); + case 193: + return checkStrictModePostfixUnaryExpression(node); + case 192: + return checkStrictModePrefixUnaryExpression(node); + case 220: + return checkStrictModeWithStatement(node); + case 169: + seenThisKeyword = true; + return; + case 158: + return checkTypePredicate(node); + case 145: + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + case 146: + return bindParameter(node); + case 226: + return bindVariableDeclarationOrBindingElement(node); + case 176: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 149: + case 148: + return bindPropertyWorker(node); + case 261: + case 262: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 264: + return bindPropertyOrMethodOrAccessor(node, 8, 900095); + case 155: + case 156: + case 157: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 151: + case 150: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + case 228: + return bindFunctionDeclaration(node); + case 152: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 153: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 154: + return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + case 160: + case 273: + case 161: + return bindFunctionOrConstructorType(node); + case 163: + case 285: + case 172: + return bindAnonymousTypeWorker(node); + case 178: + return bindObjectLiteralExpression(node); + case 186: + case 187: + return bindFunctionExpression(node); + case 181: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + case 199: + case 229: + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 230: + return bindBlockScopedDeclaration(node, 64, 792968); + case 231: + return bindBlockScopedDeclaration(node, 524288, 793064); + case 232: + return bindEnumDeclaration(node); + case 233: + return bindModuleDeclaration(node); + case 254: + return bindJsxAttributes(node); + case 253: + return bindJsxAttribute(node, 4, 0); + case 237: + case 240: + case 242: + case 246: + return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + case 236: + return bindNamespaceExportDeclaration(node); + case 239: + return bindImportClause(node); + case 244: + return bindExportDeclaration(node); + case 243: + return bindExportAssignment(node); + case 265: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 207: + if (!ts.isFunctionLike(node.parent)) { + return; + } + case 234: + return updateStrictModeStatementList(node.statements); + case 279: + if (node.parent.kind !== 285) { + break; + } + case 284: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? + 4 | 16777216 : + 4; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0); + case 283: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048, "__type"); + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 71) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 169) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); + } + else { + var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) + ? 2097152 + : 4; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 2097152 | 32 | 16); + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + if (node.parent.kind !== 265) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + } + else if (!node.exportClause) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + } + } + function setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } + } + } + function bindExportsPropertyAssignment(node) { + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); + } + function isExportsOrModuleExportsOrAlias(node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + isNameOfExportsOrModuleExportsAliasDeclaration(node); + } + function isNameOfExportsOrModuleExportsAliasDeclaration(node) { + if (ts.isIdentifier(node)) { + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); + } + return false; + } + function isExportsOrModuleExportsOrAliasOrAssignment(node) { + return isExportsOrModuleExportsOrAlias(node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); + } + function bindModuleExportsAssignment(node) { + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + setCommonJsModuleIndicator(node); + return; + } + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node, 4 | 1048576 | 512, 0); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var container = ts.getThisContainer(node, false); + switch (container.kind) { + case 228: + case 186: + container.symbol.members = container.symbol.members || ts.createSymbolTable(); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + break; + case 152: + case 149: + case 151: + case 153: + case 154: + var containingClass = container.parent; + var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); + break; + } + } + function bindPrototypePropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); + } + function bindStaticPropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var target = leftSideOfAssignment.expression; + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + } + } + function lookupSymbolForName(name) { + return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); + } + function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { + var targetSymbol = lookupSymbolForName(functionName); + if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { + targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + } + if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { + return; + } + var symbolTable = isPrototypeProperty ? + (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : + (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); + declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); + } + function bindCallExpression(node) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 229) { + bindBlockScopedDeclaration(node, 32, 899519); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class"; + bindAnonymousDeclaration(node, 32, bindingName); + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + var prototypeSymbol = createSymbol(4 | 4194304, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isConst(node) + ? bindBlockScopedDeclaration(node, 128, 899967) + : bindBlockScopedDeclaration(node, 256, 899327); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + declareSymbolAndAddToSymbolTable(node, 1, 107455); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 107454); + } + } + } + function bindParameter(node) { + if (inStrictMode && !ts.isInAmbientContext(node)) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 107455); + } + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16, 106927); + } + else { + declareSymbolAndAddToSymbolTable(node, 16, 106927); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function"; + return bindAnonymousDeclaration(node, 16, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || + node.kind === 229 || + (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 208 || + ts.getCombinedNodeFlags(node.declarationList) & 3 || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + } + return true; + } + } + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 181: + return computeCallExpression(node, subtreeFlags); + case 182: + return computeNewExpression(node, subtreeFlags); + case 233: + return computeModuleDeclaration(node, subtreeFlags); + case 185: + return computeParenthesizedExpression(node, subtreeFlags); + case 194: + return computeBinaryExpression(node, subtreeFlags); + case 210: + return computeExpressionStatement(node, subtreeFlags); + case 146: + return computeParameter(node, subtreeFlags); + case 187: + return computeArrowFunction(node, subtreeFlags); + case 186: + return computeFunctionExpression(node, subtreeFlags); + case 228: + return computeFunctionDeclaration(node, subtreeFlags); + case 226: + return computeVariableDeclaration(node, subtreeFlags); + case 227: + return computeVariableDeclarationList(node, subtreeFlags); + case 208: + return computeVariableStatement(node, subtreeFlags); + case 222: + return computeLabeledStatement(node, subtreeFlags); + case 229: + return computeClassDeclaration(node, subtreeFlags); + case 199: + return computeClassExpression(node, subtreeFlags); + case 259: + return computeHeritageClause(node, subtreeFlags); + case 260: + return computeCatchClause(node, subtreeFlags); + case 201: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 152: + return computeConstructor(node, subtreeFlags); + case 149: + return computePropertyDeclaration(node, subtreeFlags); + case 151: + return computeMethod(node, subtreeFlags); + case 153: + case 154: + return computeAccessor(node, subtreeFlags); + case 237: + return computeImportEquals(node, subtreeFlags); + case 179: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288 + || isSuperOrSuperProperty(expression, expressionKind)) { + transformFlags |= 192; + } + if (expression.kind === 91) { + transformFlags |= 67108864; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 97: + return true; + case 179: + case 180: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 97; + } + return false; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 58 && leftKind === 178) { + transformFlags |= 8 | 192 | 3072; + } + else if (operatorTokenKind === 58 && leftKind === 177) { + transformFlags |= 192 | 3072; + } + else if (operatorTokenKind === 40 + || operatorTokenKind === 62) { + transformFlags |= 32; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + if (node.questionToken + || node.type + || subtreeFlags & 4096 + || ts.isThisIdentifier(name)) { + transformFlags |= 3; + } + if (modifierFlags & 92) { + transformFlags |= 3 | 262144; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { + transformFlags |= 192 | 131072; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + if (expressionKind === 202 + || expressionKind === 184) { + transformFlags |= 3; + } + if (expressionTransformFlags & 1024) { + transformFlags |= 1024; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 192; + if ((subtreeFlags & 274432) + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~539358529; + } + function computeClassExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (subtreeFlags & 274432 + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~539358529; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 85: + transformFlags |= 192; + break; + case 108: + transformFlags |= 3; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537920833; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.typeArguments) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computeMethod(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.typeParameters + || node.type + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.type + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computePropertyDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags | 3; + if (node.initializer) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 33554432; + if (modifierFlags & 2270 + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (modifierFlags & 256) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601281857; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601281857; + } + function computeArrowFunction(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 16384) { + transformFlags |= 32768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601249089; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (expressionKind === 97) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 | 8388608; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (node.type) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 8388608) { + transformFlags |= 192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (subtreeFlags & 4194304 + && ts.isIterationStatement(node, true)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.expression.transformFlags & 1024) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~574674241; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 33554432; + if (subtreeFlags & 8388608) { + transformFlags |= 192; + } + if (node.flags & 3) { + transformFlags |= 192 | 4194304; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~546309441; + } + function computeOther(node, kind, subtreeFlags) { + var transformFlags = subtreeFlags; + var excludeFlags = 536872257; + switch (kind) { + case 120: + case 191: + transformFlags |= 8 | 16; + break; + case 114: + case 112: + case 113: + case 117: + case 124: + case 76: + case 232: + case 264: + case 184: + case 202: + case 203: + case 131: + transformFlags |= 3; + break; + case 249: + case 250: + case 251: + case 10: + case 252: + case 253: + case 254: + case 255: + case 256: + transformFlags |= 4; + break; + case 13: + case 14: + case 15: + case 16: + case 196: + case 183: + case 262: + case 115: + case 204: + transformFlags |= 192; + break; + case 9: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192; + } + break; + case 8: + if (node.numericLiteralFlags & 48) { + transformFlags |= 192; + } + break; + case 216: + if (node.awaitModifier) { + transformFlags |= 8; + } + transformFlags |= 192; + break; + case 197: + transformFlags |= 8 | 192 | 16777216; + break; + case 119: + case 133: + case 130: + case 134: + case 136: + case 122: + case 137: + case 105: + case 145: + case 148: + case 150: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 161: + case 162: + case 163: + case 164: + case 165: + case 166: + case 167: + case 168: + case 230: + case 231: + case 169: + case 170: + case 171: + case 172: + case 173: + case 236: + transformFlags = 3; + excludeFlags = -3; + break; + case 144: + transformFlags |= 2097152; + if (subtreeFlags & 16384) { + transformFlags |= 65536; + } + break; + case 198: + transformFlags |= 192 | 524288; + break; + case 263: + transformFlags |= 8 | 1048576; + break; + case 97: + transformFlags |= 192; + break; + case 99: + transformFlags |= 16384; + break; + case 174: + transformFlags |= 192 | 8388608; + if (subtreeFlags & 524288) { + transformFlags |= 8 | 1048576; + } + excludeFlags = 537396545; + break; + case 175: + transformFlags |= 192 | 8388608; + excludeFlags = 537396545; + break; + case 176: + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 524288; + } + break; + case 147: + transformFlags |= 3 | 4096; + break; + case 178: + excludeFlags = 540087617; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + break; + case 177: + case 182: + excludeFlags = 537396545; + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + break; + case 212: + case 213: + case 214: + case 215: + if (subtreeFlags & 4194304) { + transformFlags |= 192; + } + break; + case 265: + if (subtreeFlags & 32768) { + transformFlags |= 192; + } + break; + case 219: + case 217: + case 218: + transformFlags |= 33554432; + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~excludeFlags; + } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 158 && kind <= 173) { + return -3; + } + switch (kind) { + case 181: + case 182: + case 177: + return 537396545; + case 233: + return 574674241; + case 146: + return 536872257; + case 187: + return 601249089; + case 186: + case 228: + return 601281857; + case 227: + return 546309441; + case 229: + case 199: + return 539358529; + case 152: + return 601015617; + case 151: + case 153: + case 154: + return 601015617; + case 119: + case 133: + case 130: + case 136: + case 134: + case 122: + case 137: + case 105: + case 145: + case 148: + case 150: + case 155: + case 156: + case 157: + case 230: + case 231: + return -3; + case 178: + return 540087617; + case 260: + return 537920833; + case 174: + case 175: + return 537396545; + default: + return 536872257; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; + })(Extensions || (Extensions = {})); + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; + } + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); + function tryReadFromField(fieldName) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); + resolvedFile = resolvedTypeScriptOnly(result && result.value); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + var directoryToModuleNameMap = ts.createMap(); + var moduleNameToDirectoryMap = ts.createMap(); + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + var perFolderCache = directoryToModuleNameMap.get(path); + if (!perFolderCache) { + perFolderCache = ts.createMap(); + directoryToModuleNameMap.set(path, perFolderCache); + } + return perFolderCache; + } + function getOrCreateCacheForModuleName(nonRelativeModuleName) { + if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { + return undefined; + } + var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); + if (!perModuleNameCache) { + perModuleNameCache = createPerModuleNameCache(); + moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + } + return perModuleNameCache; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + var commonPrefix = getCommonPrefix(path, resolvedFileName); + var current = path; + while (true) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + if (current === commonPrefix) { + break; + } + } + } + function getCommonPrefix(directory, resolution) { + if (resolution === undefined) { + return undefined; + } + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + var i = 0; + while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + var sep = directory.lastIndexOf(ts.directorySeparator, i); + if (sep < 0) { + return undefined; + } + return directory.substr(0, sep); + } + } + } + ts.createModuleResolutionCache = createModuleResolutionCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + break; + 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); + var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); + if (perModuleNameCache) { + perModuleNameCache.set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, false, state); + if (path_1 !== undefined) { + return { path: path_1, extension: extension }; + } + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + 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 }; + var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + } + } + } + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + if (resolvedFromFile) { + return resolvedFromFile; + } + } + if (!onlyRecordFailures) { + var candidateExists = directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts"); + case Extensions.TypeScript: + return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); + case Extensions.JavaScript: + return tryExtension(".js") || tryExtension(".jsx"); + } + function tryExtension(extension) { + var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } + } + else { + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocations.push(packageJsonPath); + } + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + } + function resolvedIfExtensionMatches(extensions, path) { + var extension = ts.tryGetExtensionFromPath(path); + return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + } + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" || extension === ".jsx"; + case Extensions.TypeScript: + return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; + case Extensions.DtsOnly: + return extension === ".d.ts"; + } + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, true, undefined); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + } + }); + } + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== Extensions.JavaScript) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + } + } + var mangledScopedPackageSeparator = "__"; + function mangleScopedPackage(moduleName, state) { + if (ts.startsWith(moduleName, "@")) { + var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== moduleName) { + var mangled = replaceSlash.slice(1); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + } + return moduleName; + } + function getPackageNameFromAtTypesDirectory(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + var result = cache && cache.get(containingDirectory); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + } + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + if (!ts.isExternalModuleNameRelative(moduleName)) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 || + (preserveConstEnums && moduleState === 2); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var symbolInstantiationDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); + var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; + var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; + var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; + var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4, "arguments"); + var apparentArgumentCount; + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { + parameter = ts.getParseTreeNode(parameter, ts.isParameter); + ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (node) { + node = ts.getParseTreeNode(node, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : unknownType; + }, + getParameterType: getTypeAtPosition, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (node) { + node = ts.getParseTreeNode(node, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : unknownType; + }, + getPropertySymbolOfDestructuringAssignment: function (location) { + location = ts.getParseTreeNode(location, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, + symbolToString: function (symbol, enclosingDeclaration, meaning) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (node) { + node = ts.getParseTreeNode(node, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { + node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + apparentArgumentCount = theArgumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; + apparentArgumentCount = undefined; + return res; + }, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (node, propertyName) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); + return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + }, + getSignatureFromDeclaration: function (declaration) { + declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: function (symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + links.immediateTarget = getTargetOfAliasDeclaration(node, true); + } + return links.immediateTarget; + }, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getAmbientModules: getAmbientModules, + getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { + node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; + }, + getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + isOptionalParameter: function (node) { + node = ts.getParseTreeNode(node, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + return tryFindAmbientModule(moduleName, false); + }, + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + resolveNameAtLocation: function (location, name, meaning) { + location = ts.getParseTreeNode(location); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, ts.escapeLeadingUnderscores(name)); + }, + }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var unknownSymbol = createSymbol(4, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); + var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); + var unknownType = createIntrinsicType(1, "unknown"); + var undefinedType = createIntrinsicType(2048, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); + var nullType = createIntrinsicType(4096, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); + var stringType = createIntrinsicType(2, "string"); + var numberType = createIntrinsicType(4, "number"); + var trueType = createIntrinsicType(128, "true"); + var falseType = createIntrinsicType(128, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512, "symbol"); + var voidType = createIntrinsicType(1024, "void"); + var neverType = createIntrinsicType(8192, "never"); + var silentNeverType = createIntrinsicType(8192, "never"); + var nonPrimitiveType = createIntrinsicType(16777216, "object"); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + anyFunctionType.flags |= 8388608; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var enumNumberIndexInfo = createIndexInfo(stringType, true); + var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); + var globals = ts.createSymbolTable(); + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredJsxElementClassType; + var deferredJsxElementType; + var deferredJsxStatelessElementType; + var deferredNodes; + var deferredUnusedIdentifierNodes; + var flowLoopStart = 0; + var flowLoopCount = 0; + var visitedFlowCount = 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 = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var visitedFlowNodes = []; + var visitedFlowTypes = []; + var potentialThisCollisions = []; + var potentialNewTargetCollisions = []; + var awaitedTypeStack = []; + var diagnostics = ts.createDiagnosticCollection(); + var typeofEQFacts = ts.createMapFromTemplate({ + "string": 1, + "number": 2, + "boolean": 4, + "symbol": 8, + "undefined": 16384, + "object": 16, + "function": 32 + }); + var typeofNEFacts = ts.createMapFromTemplate({ + "string": 128, + "number": 256, + "boolean": 512, + "symbol": 1024, + "undefined": 131072, + "object": 2048, + "function": 4096 + }); + var typeofTypesByName = ts.createMapFromTemplate({ + "string": stringType, + "number": numberType, + "boolean": booleanType, + "symbol": esSymbolType, + "undefined": undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var _jsxElementPropertiesName; + var _hasComputedJsxElementPropertiesName = false; + var _jsxElementChildrenPropertyName; + var _hasComputedJsxElementChildrenPropertyName = false; + var jsxTypes = ts.createUnderscoreEscapedMap(); + var JsxNames = { + JSX: "JSX", + IntrinsicElements: "IntrinsicElements", + ElementClass: "ElementClass", + ElementAttributesPropertyNameContainer: "ElementAttributesProperty", + ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" + }; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + var _displayBuilder; + var builtinGlobals = ts.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + initializeTypeChecker(); + return checker; + function getJsxNamespace() { + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function error(location, message, arg0, arg1, arg2) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + diagnostics.add(diagnostic); + } + function createSymbol(flags, name) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432, name)); + symbol.checkFlags = 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2) + result |= 107455; + if (flags & 1) + result |= 107454; + if (flags & 4) + result |= 0; + if (flags & 8) + result |= 900095; + if (flags & 16) + result |= 106927; + if (flags & 32) + result |= 899519; + if (flags & 64) + result |= 792968; + if (flags & 256) + result |= 899327; + if (flags & 128) + result |= 899967; + if (flags & 512) + result |= 106639; + if (flags & 8192) + result |= 99263; + if (flags & 32768) + result |= 41919; + if (flags & 65536) + result |= 74687; + if (flags & 262144) + result |= 530920; + if (flags & 524288) + result |= 793064; + if (flags & 2097152) + result |= 2097152; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations.slice(0); + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024) { + 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + ts.forEach(target.declarations, function (node) { + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + } + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + } + else { + if (!(targetSymbol.flags & 33554432)) { + targetSymbol = cloneSymbol(targetSymbol); + target.set(id, targetSymbol); + } + mergeSymbol(targetSymbol, sourceSymbol); + } + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); + if (!mainModule) { + return; + } + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920) { + mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function getObjectFlags(type) { + return type.flags & 32768 ? type.objectFlags : 0; + } + function isGlobalSourceFile(node) { + return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + ts.isInAmbientContext(declaration)) { + return true; + } + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + } + if (declaration.pos <= usage.pos) { + if (declaration.kind === 176) { + var errorBindingElement = ts.getAncestor(usage, 176); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); + } + else if (declaration.kind === 226) { + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + return true; + } + if (usage.parent.kind === 246) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 208: + case 214: + case 216: + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 149 && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.getModifierFlags(current.parent) & 32) { + if (declaration.kind === 151) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + }); + } + } + 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; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + 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 !== 275) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 146 || + lastLocation.kind === 145 + : false; + } + if (meaning & 107455 && result.flags & 1) { + useResult = + lastLocation.kind === 146 || + (lastLocation === location.type && + result.valueDeclaration.kind === 146); + } + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 265: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + case 233: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 265 || ts.isAmbientModule(location)) { + if (result = moduleExports.get("default")) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 && + ts.getDeclarationOfKind(moduleExport, 246)) { + break; + } + } + if (result = lookup(moduleExports, name, meaning & 2623475)) { + break loop; + } + break; + case 232: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { + break loop; + } + break; + case 149: + case 148: + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 107455)) { + propertyWithInvalidInitializer = location; + } + } + } + break; + case 229: + case 199: + case 230: + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + result = undefined; + break; + } + if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 199 && meaning & 32) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 144: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 230) { + 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; + } + } + break; + case 151: + case 150: + case 152: + case 153: + case 154: + case 228: + case 187: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 186: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 147: + if (location.parent && location.parent.kind === 146) { + location = location.parent; + } + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (result && nameNotFoundMessage && noUnusedIdentifiers) { + result.isReferenced = true; + } + if (!result) { + result = lookup(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + if (errorLocation && + (meaning & 2 || + ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + if (result && isInExternalModule && (meaning & 107455) === 107455) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 236) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + } + } + } + return result; + } + function diagnosticName(nameArg) { + return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 145 && decl.parent === container) { + return true; + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if ((errorLocation.kind === 71 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + if (location === container && !(ts.getModifierFlags(location) & 32)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64, true)); + if (isError) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + } + return isError; + } + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 71: + case 179: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 201: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + 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, ts.unescapeLeadingUnderscores(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, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (107455 & ~1024 & ~793064)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (793064 & ~1024 & ~107455)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); + 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(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 32) { + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + } + } + function isSameScopeDescendentOf(initial, parent, stopAt) { + return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + if (ts.isAliasSymbolDeclaration(node)) { + if (node.kind === 237) { + return node; + } + return ts.findAncestor(node, ts.isImportDeclaration); + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 248) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + var exportValue = moduleSymbol.exports.get("export="); + exportDefaultSymbol = exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") + : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + } + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (793064 | 1920)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + switch (node.kind) { + case 237: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 239: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 240: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 242: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 246: + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); + case 243: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 236: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + } + } + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 107455 | 793064 | 1920; } + return symbol && (symbol.flags & (2097152 | excludes)) === 2097152; + } + function resolveSymbol(symbol, dontResolveAlias) { + var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); + return shouldResolve ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + if (node.kind === 243) { + checkExpressionCached(node.expression); + } + else if (node.kind === 246) { + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + checkExpressionCached(node.moduleReference); + } + } + } + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (entityName.kind === 71 || entityName.parent.kind === 143) { + return resolveEntityName(entityName, 1920, false, dontResolveAlias); + } + else { + ts.Debug.assert(entityName.parent.kind === 237); + return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol) { + return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + } + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var symbol; + if (name.kind === 71) { + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + if (!symbol) { + return undefined; + } + } + else if (name.kind === 143 || name.kind === 179) { + var left = void 0; + if (name.kind === 143) { + left = name.left; + } + else if (name.kind === 179 && + (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { + left = name.expression; + } + else { + return undefined; + } + var right = name.kind === 143 ? name.right : name.name; + var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else if (name.kind === 185) { + return ts.isEntityNameExpression(name.expression) ? + resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : + undefined; + } + else { + ts.Debug.fail("Unknown entity name kind."); + } + 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) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReferenceExpression.kind !== 9 && moduleReferenceExpression.kind !== 13) { + return; + } + var moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === 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(moduleReference, true); + if (ambientModule) { + return ambientModule; + } + var isRelative = ts.isExternalModuleNameRelative(moduleReference); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (noImplicitAny && moduleNotFoundError) { + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return undefined; + } + if (moduleNotFoundError) { + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + } + function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { + 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)); + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=") !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (!symbol) { + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); + } + } + return symbol; + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + function extendExportSymbols(target, source, lookupTable, exportNode) { + source && source.forEach(function (sourceSymbol, id) { + if (id === "default") + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + function visit(symbol) { + if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + return; + } + visitedSymbols.push(symbol); + var symbols = ts.cloneMap(symbol.exports); + var exportStars = symbol.exports.get("__export"); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent); + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return symbol && (symbol.flags & 1048576) !== 0 + ? getMergedSymbol(symbol.exportSymbol) + : symbol; + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 107455 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 107455); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 152 && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(32768); + type.objectFlags = objectFlags; + type.symbol = symbol; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 && + name.charCodeAt(1) === 95 && + name.charCodeAt(2) !== 95 && + name.charCodeAt(2) !== 64; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + if (symbolIsValue(symbol)) { + result.push(symbol); + } + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 265: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + case 233: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + return rightMeaning === 107455 ? 107455 : 1920; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; + function canQualifySymbol(symbolFromSymbolTable, meaning) { + if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { + return true; + } + var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + return !!accessibleParent; + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + } + function trySymbolTable(symbols) { + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; + } + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + } + }); + } + } + if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + if (!symbolFromSymbolTable) { + return false; + } + if (symbolFromSymbolTable === symbol) { + return true; + } + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 149: + case 151: + case 153: + case 154: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { + var initialSymbol = symbol; + var meaningToLook = meaning; + while (symbol) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); + if (accessibleSymbolChain) { + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (!hasAccessibleDeclarations) { + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, + }; + } + return hasAccessibleDeclarations; + } + meaningToLook = getQualifiedLeftMeaning(meaning); + symbol = getParentOfSymbol(symbol); + } + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + return { + accessibility: 2, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 }; + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + return undefined; + } + return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !(ts.getModifierFlags(anyImportSyntax) & 1) && + isDeclarationVisible(anyImportSyntax.parent)) { + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; + } + } + return true; + } + return false; + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + var meaning; + if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning = 107455 | 1048576; + } + else if (entityName.kind === 143 || entityName.kind === 179 || + entityName.parent.kind === 237) { + meaning = 1920; + } + else { + meaning = 793064; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined); + return (symbol && hasVisibleDeclarations(symbol, true)) || { + accessibility: 1, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function writeKeyword(writer, kind) { + writer.writeKeyword(ts.tokenToString(kind)); + } + function writePunctuation(writer, kind) { + writer.writePunctuation(ts.tokenToString(kind)); + } + function writeSpace(writer) { + writer.writeSpace(" "); + } + function symbolToString(symbol, enclosingDeclaration, meaning) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); + }); + } + function signatureToString(signature, enclosingDeclaration, flags, kind) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); + }); + } + function typeToString(type, enclosingDeclaration, flags) { + 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); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); + var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; + if (maxLength && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 8) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 256) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 4096) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 64) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + 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) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + } + }; + function createNodeBuilderContext(enclosingDeclaration, flags) { + return { + enclosingDeclaration: enclosingDeclaration, + flags: flags, + encounteredError: false, + symbolStack: undefined + }; + } + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + if (!type) { + context.encounteredError = true; + return undefined; + } + if (type.flags & 1) { + return ts.createKeywordTypeNode(119); + } + if (type.flags & 2) { + return ts.createKeywordTypeNode(136); + } + if (type.flags & 4) { + return ts.createKeywordTypeNode(133); + } + if (type.flags & 8) { + return ts.createKeywordTypeNode(122); + } + 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.setEmitFlags(ts.createLiteral(type.value), 16777216)); + } + if (type.flags & (64)) { + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 128) { + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 1024) { + return ts.createKeywordTypeNode(105); + } + if (type.flags & 2048) { + return ts.createKeywordTypeNode(139); + } + if (type.flags & 4096) { + return ts.createKeywordTypeNode(95); + } + if (type.flags & 8192) { + return ts.createKeywordTypeNode(130); + } + if (type.flags & 512) { + return ts.createKeywordTypeNode(137); + } + if (type.flags & 16777216) { + return ts.createKeywordTypeNode(134); + } + if (type.flags & 16384 && type.isThisType) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + context.encounteredError = true; + } + } + return ts.createThis(); + } + var objectFlags = getObjectFlags(type); + if (objectFlags & 4) { + ts.Debug.assert(!!(type.flags & 32768)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); + return ts.createTypeReferenceNode(name, undefined); + } + 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); + } + 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)) { + context.encounteredError = true; + } + return undefined; + } + } + 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, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 524288) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 32768)); + var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; + var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; + 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; + if (symbol) { + if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || + symbol.flags & (384 | 512) || + shouldWriteTypeOfFunctionSymbol()) { + return createTypeQueryNodeFromSymbol(symbol, 107455); + } + else if (ts.contains(context.symbolStack, symbol)) { + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + var entityName = symbolToName(typeAlias, context, 793064, false); + return ts.createTypeReferenceNode(entityName, undefined); + } + else { + return ts.createKeywordTypeNode(119); + } + } + else { + if (!context.symbolStack) { + context.symbolStack = []; + } + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } + } + else { + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 || declaration.parent.kind === 234; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return ts.contains(context.symbolStack, symbol); + } + } + } + function createTypeNodeFromObjectType(type) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + return createMappedTypeNodeFromType(type); + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); + } + 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.escapedName) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var qualifiedName = void 0; + if (outerTypeParameters) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + 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 { + qualifiedName = ts.createQualifiedName(namePart, undefined); + } + } + } + } + var entityName = undefined; + var nameIdentifier = symbolToTypeReferenceName(type.symbol); + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); + entityName = qualifiedName; + } + else { + entityName = nameIdentifier; + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.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, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); + } + if (resolvedType.stringIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + var propertyType = getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 ? 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, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + typeElements.push(methodDeclaration); + } + } + else { + 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 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 ? 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.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, context); + } + 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, context) { + var name = symbolToName(type.symbol, context, 793064, true); + var constraint = getConstraintFromTypeParameter(type); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function symbolToParameterDeclaration(parameterSymbol, context) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { + return ts.createParameter(undefined, undefined, parameterSymbol.isRestParameter ? ts.createToken(24) : undefined, "args", undefined, typeToTypeNodeHelper(anyArrayType, context), undefined); + } + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name) : + ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; + var parameterType = getTypeOfSymbol(parameterSymbol); + 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, context, meaning, expectsIdentifier) { + var chain; + var isTypeParameter = symbol.flags & 262144; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(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 typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { + var parentSymbol = chain[index - 1]; + var typeParameters = void 0; + if (ts.getCheckFlags(symbol) & 1) { + typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); + } + else { + var targetSymbol = getTargetSymbol(parentSymbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + } + } + typeParameterNodes = mapToTypeNodes(typeParameters, context); + } + 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) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var parentSymbol; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); + if (parentChain) { + parentSymbol = parent; + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + return [symbol]; + } + } + } + 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 ts.unescapeLeadingUnderscores(symbol.escapedName); + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + }); + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144)) { + if (t.flags & (128 | 256)) { + 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); + } + } + if (flags & 4096) + result.push(nullType); + if (flags & 2048) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8) { + return "private"; + } + if (flags === 16) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); + if (node.kind === 231) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 234 && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function literalTypeToString(type) { + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + } + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; + } + } + return ts.unescapeLeadingUnderscores(symbol.escapedName); + } + function getSymbolDisplayBuilder() { + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); + } + function appendPropertyOrElementAccessForSymbol(symbol, writer) { + var symbolName = getNameOfSymbol(symbol); + var firstChar = symbolName.charCodeAt(0); + var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); + if (needsElementAccess) { + writePunctuation(writer, 21); + if (ts.isSingleOrDoubleQuote(firstChar)) { + writer.writeStringLiteral(symbolName); + } + else { + writer.writeSymbol(symbolName, symbol); + } + writePunctuation(writer, 22); + } + else { + writePunctuation(writer, 23); + writer.writeSymbol(symbolName, symbol); + } + } + function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { + var parentSymbol; + function appendParentTypeArgumentsAndSymbolName(symbol) { + if (parentSymbol) { + if (flags & 1) { + if (ts.getCheckFlags(symbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); + } + else { + buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); + } + } + appendPropertyOrElementAccessForSymbol(symbol, writer); + } + else { + appendSymbolNameOnly(symbol, writer); + } + parentSymbol = symbol; + } + writer.trackSymbol(symbol, enclosingDeclaration, meaning); + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); + } + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + } + } + else if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + var isTypeParameter = symbol.flags & 262144; + var typeFormatFlag = 256 & typeFlags; + if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { + walkSymbol(symbol, meaning, true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { + var globalFlagsToPass = globalFlags & (32 | 16384); + var inObjectTypeLiteral = false; + return writeType(type, globalFlags); + function writeType(type, flags) { + var nextFlags = flags & ~1024; + if (type.flags & 16793231) { + writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } + else if (type.flags & 16384 && type.isThisType) { + if (inObjectTypeLiteral) { + writer.reportInaccessibleThisError(); + } + writer.writeKeyword("this"); + } + else if (getObjectFlags(type) & 4) { + writeTypeReference(type, nextFlags); + } + 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 & (272 | 16384)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); + } + else if (!(flags & 1024) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); + } + else if (type.flags & 196608) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (getObjectFlags(type) & (16 | 32)) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96) { + writer.writeStringLiteral(literalTypeToString(type)); + } + else if (type.flags & 262144) { + if (flags & 128) { + writePunctuation(writer, 19); + } + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 128); + if (flags & 128) { + writePunctuation(writer, 20); + } + } + else if (type.flags & 524288) { + writeType(type.objectType, 128); + writePunctuation(writer, 21); + writeType(type.indexType, 0); + writePunctuation(writer, 22); + } + else { + writePunctuation(writer, 17); + writeSpace(writer); + writePunctuation(writer, 24); + writeSpace(writer); + writePunctuation(writer, 18); + } + } + function writeTypeList(types, delimiter) { + for (var i = 0; i < types.length; i++) { + if (i > 0) { + if (delimiter !== 26) { + writeSpace(writer); + } + writePunctuation(writer, delimiter); + writeSpace(writer); + } + writeType(types[i], delimiter === 26 ? 0 : 128); + } + } + function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { + if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); + } + if (pos < end) { + writePunctuation(writer, 27); + writeType(typeArguments[pos], 512); + pos++; + while (pos < end) { + writePunctuation(writer, 26); + writeSpace(writer); + writeType(typeArguments[pos], 0); + pos++; + } + writePunctuation(writer, 29); + } + } + function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType && !(flags & 1)) { + writeType(typeArguments[0], 128 | 32768); + writePunctuation(writer, 21); + writePunctuation(writer, 22); + } + else if (type.target.objectFlags & 8) { + writePunctuation(writer, 21); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); + writePunctuation(writer, 22); + } + else if (flags & 16384 && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 199) { + writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_3 = outerTypeParameters.length; + while (i < length_3) { + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + writeSymbolTypeReference(parent, typeArguments, start, i, flags); + writePunctuation(writer, 23); + } + } + } + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); + } + } + function writeUnionOrIntersectionType(type, flags) { + if (flags & 128) { + writePunctuation(writer, 19); + } + if (type.flags & 65536) { + writeTypeList(formatUnionTypes(type.types), 49); + } + else { + writeTypeList(type.types, 48); + } + if (flags & 128) { + writePunctuation(writer, 20); + } + } + function writeAnonymousType(type, flags) { + var symbol = type.symbol; + if (symbol) { + if (symbol.flags & 32 && + !getBaseTypeVariableOfClass(symbol) && + !(symbol.valueDeclaration.kind === 199 && flags & 16384) || + symbol.flags & (384 | 512)) { + writeTypeOfSymbol(type, flags); + } + else if (shouldWriteTypeOfFunctionSymbol()) { + writeTypeOfSymbol(type, flags); + } + else if (ts.contains(symbolStack, symbol)) { + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); + } + else { + writeKeyword(writer, 119); + } + } + else { + if (!symbolStack) { + symbolStack = []; + } + var isConstructorObject = type.flags & 32768 && + getObjectFlags(type) & 16 && + type.symbol && type.symbol.flags & 32; + if (isConstructorObject) { + writeLiteralType(type, flags); + } + else { + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } + } + } + else { + writeLiteralType(type, flags); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 || declaration.parent.kind === 234; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return !!(flags & 4) || + (ts.contains(symbolStack, symbol)); + } + } + } + function writeTypeOfSymbol(type, typeFormatFlags) { + if (typeFormatFlags & 32768) { + writePunctuation(writer, 19); + } + writeKeyword(writer, 103); + writeSpace(writer); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); + if (typeFormatFlags & 32768) { + writePunctuation(writer, 20); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 131); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 16777216) { + writePunctuation(writer, 55); + } + } + function shouldAddParenthesisAroundFunctionType(callSignature, flags) { + if (flags & 128) { + return true; + } + else if (flags & 512) { + var typeParameters = callSignature.target && (flags & 64) ? + callSignature.target.typeParameters : callSignature.typeParameters; + return typeParameters && typeParameters.length !== 0; + } + return false; + } + function writeLiteralType(type, flags) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + writeMappedType(type); + return; + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + writePunctuation(writer, 17); + writePunctuation(writer, 18); + return; + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); + if (parenthesizeSignature) { + writePunctuation(writer, 19); + } + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); + if (parenthesizeSignature) { + writePunctuation(writer, 20); + } + return; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + if (flags & 128) { + writePunctuation(writer, 19); + } + writeKeyword(writer, 94); + writeSpace(writer); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); + if (flags & 128) { + writePunctuation(writer, 20); + } + return; + } + } + var saveInObjectTypeLiteral = inObjectTypeLiteral; + inObjectTypeLiteral = true; + writePunctuation(writer, 17); + writer.writeLine(); + writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 18); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); + buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + if (globalFlags & 16384) { + if (p.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { + writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + } + } + var t = getTypeOfSymbol(p); + if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { + var signatures = getSignaturesOfType(t, 0); + for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { + var signature = signatures_2[_f]; + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + else { + writePropertyWithModifiers(p); + writePunctuation(writer, 56); + writeSpace(writer); + writeType(t, globalFlags & 16384); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + } + function writeMappedType(type) { + writePunctuation(writer, 17); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 131); + writeSpace(writer); + } + writePunctuation(writer, 21); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 92); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0); + writePunctuation(writer, 22); + if (type.declaration.questionToken) { + writePunctuation(writer, 55); + } + writePunctuation(writer, 56); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0); + writePunctuation(writer, 25); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 18); + } + } + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); + } + } + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { + appendSymbolNameOnly(tp.symbol, writer); + var constraint = getConstraintOfTypeParameter(tp); + if (constraint) { + writeSpace(writer); + writeKeyword(writer, 85); + writeSpace(writer); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); + } + var defaultType = getDefaultFromTypeParameter(tp); + if (defaultType) { + writeSpace(writer); + writePunctuation(writer, 58); + writeSpace(writer); + buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { + writePunctuation(writer, 24); + } + if (parameterNode && ts.isBindingPattern(parameterNode.name)) { + buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + appendSymbolNameOnly(p, writer); + } + if (parameterNode && isOptionalParameter(parameterNode)) { + writePunctuation(writer, 55); + } + writePunctuation(writer, 56); + writeSpace(writer); + var type = getTypeOfSymbol(p); + if (parameterNode && isRequiredInitializedParameter(parameterNode)) { + type = getNullableType(type, 2048); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { + if (bindingPattern.kind === 174) { + writePunctuation(writer, 17); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 18); + } + else if (bindingPattern.kind === 175) { + writePunctuation(writer, 21); + var elements = bindingPattern.elements; + buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (elements && elements.hasTrailingComma) { + writePunctuation(writer, 26); + } + writePunctuation(writer, 22); + } + } + function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isOmittedExpression(bindingElement)) { + return; + } + ts.Debug.assert(bindingElement.kind === 176); + if (bindingElement.propertyName) { + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 56); + writeSpace(writer); + } + if (ts.isBindingPattern(bindingElement.name)) { + buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + if (bindingElement.dotDotDotToken) { + writePunctuation(writer, 24); + } + appendSymbolNameOnly(bindingElement.symbol, writer); + } + } + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27); + buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 29); + } + } + function buildDisplayForCommaSeparatedList(list, writer, action) { + for (var i = 0; i < list.length; i++) { + if (i > 0) { + writePunctuation(writer, 26); + writeSpace(writer); + } + action(list[i]); + } + } + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27); + var flags = 512; + for (var i = 0; i < typeParameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 26); + writeSpace(writer); + flags = 0; + } + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); + } + writePunctuation(writer, 29); + } + } + function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { + writePunctuation(writer, 19); + if (thisParameter) { + buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); + } + for (var i = 0; i < parameters.length; i++) { + if (i > 0 || thisParameter) { + writePunctuation(writer, 26); + writeSpace(writer); + } + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); + } + writePunctuation(writer, 20); + } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 99); + } + writeSpace(writer); + writeKeyword(writer, 126); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + var returnType = getReturnTypeOfSignature(signature); + if (flags & 4096 && isTypeAny(returnType)) { + return; + } + if (flags & 16) { + writeSpace(writer); + writePunctuation(writer, 36); + } + else { + writePunctuation(writer, 56); + } + writeSpace(writer); + if (signature.typePredicate) { + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); + } + else { + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1) { + writeKeyword(writer, 94); + writeSpace(writer); + } + if (signature.target && (flags & 64)) { + buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); + } + else { + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); + } + buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); + } + function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 131); + writeSpace(writer); + } + writePunctuation(writer, 21); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 56); + writeSpace(writer); + switch (kind) { + case 1: + writeKeyword(writer, 133); + break; + case 0: + writeKeyword(writer, 136); + break; + } + writePunctuation(writer, 22); + writePunctuation(writer, 56); + writeSpace(writer); + buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + return _displayBuilder || (_displayBuilder = { + buildSymbolDisplay: buildSymbolDisplay, + buildTypeDisplay: buildTypeDisplay, + buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, + buildParameterDisplay: buildParameterDisplay, + buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, + buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, + buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, + buildSignatureDisplay: buildSignatureDisplay, + buildIndexSignatureDisplay: buildIndexSignatureDisplay, + buildReturnTypeDisplay: buildReturnTypeDisplay + }); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 176: + return isDeclarationVisible(node.parent.parent); + case 226: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + return false; + } + case 233: + case 229: + case 230: + case 231: + case 228: + case 232: + case 237: + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + if (!(ts.getCombinedModifierFlags(node) & 1) && + !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { + return isGlobalSourceFile(parent); + } + return isDeclarationVisible(parent); + case 149: + case 148: + case 153: + case 154: + case 151: + case 150: + if (ts.getModifierFlags(node) & (8 | 16)) { + return false; + } + case 152: + case 156: + case 155: + case 157: + case 146: + case 234: + case 160: + case 161: + case 163: + case 159: + case 164: + case 165: + case 166: + case 167: + case 168: + return isDeclarationVisible(node.parent); + case 239: + case 240: + case 242: + return false; + case 145: + case 265: + case 236: + return true; + case 243: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node) { + var exportSymbol; + if (node.parent && node.parent.kind === 243) { + exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node); + } + else if (node.parent.kind === 246) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); + } + var result = []; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + getNodeLinks(declaration).isVisible = true; + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (!ts.contains(result, resultNode)) { + result.push(resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + var length_4 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_4; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + if (propertyName === 0) { + return getSymbolLinks(target).type; + } + if (propertyName === 2) { + return getSymbolLinks(target).declaredType; + } + if (propertyName === 1) { + return target.resolvedBaseConstructorType; + } + if (propertyName === 3) { + return target.resolvedReturnType; + } + ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + } + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 226: + case 227: + case 242: + case 241: + case 240: + case 239: + return false; + default: + return true; + } + }); + return node && node.parent; + } + function getTypeOfPrototypeProperty(prototype) { + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1) !== 0; + } + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); + } + function isComputedNonLiteralName(name) { + return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144); }); + if (source.flags & 8192) { + return emptyObjectType; + } + if (source.flags & 65536) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createSymbolTable(); + var names = ts.createUnderscoreEscapedMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name), true); + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = names.has(prop.escapedName); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + members.set(prop.escapedName, prop); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0); + var numberIndexInfo = getIndexInfoOfType(source, 1); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + if (parentType === unknownType) { + return unknownType; + } + if (!parentType || isTypeAny(parentType)) { + if (declaration.initializer) { + return checkDeclarationInitializer(declaration); + } + return parentType; + } + var type; + if (pattern.kind === 174) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + var name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + var text = ts.getTextOfPropertyName(name); + var declaredType = getTypeOfPropertyOfType(parentType, text); + type = declaredType && getFlowTypeOfReference(declaration, declaredType) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || + getIndexTypeOfType(parentType, 0); + if (!type) { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); + return unknownType; + } + } + } + else { + var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); + if (declaration.dotDotDotToken) { + type = createArrayType(elementType); + } + else { + var propName = "" + ts.indexOf(pattern.elements, declaration); + type = isTupleLikeType(parentType) + ? getTypeOfPropertyOfType(parentType, propName) + : elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + } + return unknownType; + } + } + } + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + type = getTypeWithFacts(type, 131072); + } + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 177 && expr.elements.length === 0; + } + function addOptionality(type, optional) { + return strictNullChecks && optional ? getNullableType(type, 2048) : type; + } + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + if (declaration.parent.parent.kind === 215) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 | 262144) ? indexType : stringType; + } + if (declaration.parent.parent.kind === 216) { + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + var declaredType = getTypeFromTypeNode(typeNode); + return addOptionality(declaredType, declaration.questionToken && includeOptionality); + } + if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 146) { + var func = declaration.parent; + if (func.kind === 154 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + var type = void 0; + if (declaration.symbol.escapedName === "this") { + type = getContextualThisParameterType(func); + } + else { + type = getContextuallyTypedParameterType(declaration); + } + if (type) { + return addOptionality(type, declaration.questionToken && includeOptionality); + } + } + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, declaration.questionToken && includeOptionality); + } + if (ts.isJsxAttribute(declaration)) { + return trueType; + } + if (declaration.kind === 262) { + return checkIdentifier(declaration.name); + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, false, true); + } + return undefined; + } + function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + 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 : + declaration.kind === 179 ? ts.getAncestor(declaration, 194) : + undefined; + if (!expression) { + return unknownType; + } + if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { + if (ts.getThisContainer(expression, false).kind === 152) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + 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)); + } + } + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } + } + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + } + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return checkDeclarationInitializer(element); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAnyError(element, anyType); + } + return anyType; + } + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var hasComputedProperties = false; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + hasComputedProperties = true; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 | (e.initializer ? 16777216 : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + if (includePatternInType) { + result.pattern = pattern; + } + if (hasComputedProperties) { + result.objectFlags |= 512; + } + return result; + } + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + return pattern.kind === 174 + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + var type = getTypeForVariableLikeDeclaration(declaration, true); + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + if (declaration.kind === 261) { + return type; + } + return getWidenedType(type); + } + type = declaration.dotDotDotToken ? anyArrayType : anyType; + if (reportErrors && noImplicitAny) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAnyError(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 146 ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 4194304) { + return links.type = getTypeOfPrototypeProperty(symbol); + } + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return links.type = anyType; + } + if (declaration.kind === 243) { + return links.type = checkExpression(declaration.expression); + } + if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = void 0; + if (declaration.kind === 194 || + declaration.kind === 179 && declaration.parent.kind === 194) { + type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } + else { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function getAnnotatedAccessorType(accessor) { + if (accessor) { + if (accessor.kind === 153) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + } + } + return undefined; + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var getter = ts.getDeclarationOfKind(symbol, 153); + var setter = ts.getDeclarationOfKind(symbol, 154); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return links.type = jsDocType; + } + } + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = void 0; + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + else { + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 153); + error(getter_1, 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, symbolToString(symbol)); + } + } + links.type = type; + } + return links.type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { + links.type = anyType; + } + else { + var type = createObjectType(16, symbol); + if (symbol.flags & 32) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + links.type = strictNullChecks && symbol.flags & 16777216 ? getNullableType(type, 2048) : type; + } + } + } + return links.type; + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getDeclaredTypeOfEnumMember(symbol); + } + return links.type; + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + links.type = targetSymbol.flags & 107455 + ? getTypeOfSymbol(targetSymbol) + : unknownType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbolInstantiationDepth === 100) { + error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); + links.type = unknownType; + } + else { + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + symbolInstantiationDepth++; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + symbolInstantiationDepth--; + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + } + return links.type; + } + function reportCircularityError(symbol) { + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (symbol.flags & (3 | 4)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152) { + return getTypeOfAlias(symbol); + } + return unknownType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (getObjectFlags(type) & 4) !== 0 + && type.target === target; + } + function getTargetType(type) { + return getObjectFlags(type) & 4 ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (getObjectFlags(type) & (3 | 4)) { + var target = getTargetType(type); + return target === checkBase || ts.forEach(getBaseTypes(target), check); + } + else if (type.flags & 131072) { + return ts.forEach(type.types, check); + } + } + } + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + if (!typeParameters) { + typeParameters = [tp]; + } + else if (!ts.contains(typeParameters, tp)) { + typeParameters.push(tp); + } + } + return typeParameters; + } + function appendOuterTypeParameters(typeParameters, node) { + while (true) { + node = node.parent; + if (!node) { + return typeParameters; + } + if (node.kind === 229 || node.kind === 199 || + node.kind === 228 || node.kind === 186 || + node.kind === 151 || node.kind === 187) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); + } + } + } + } + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); + return appendOuterTypeParameters(undefined, declaration); + } + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 230 || node.kind === 229 || + node.kind === 199 || node.kind === 231) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } + return result; + } + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { + return true; + } + if (type.flags & 540672) { + var constraint = getBaseConstraintOfType(type); + return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return false; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavaScript = ts.isInJavaScriptFile(location); + return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + } + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & (32768 | 131072)) { + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = unknownType; + } + if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + return type.resolvedBaseConstructorType = unknownType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 | 64)) { + if (type.symbol.flags & 32) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { + 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, typeArgs); + } + else if (baseConstructorType.flags & 1) { + baseType = baseConstructorType; + } + else { + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } + if (baseType === unknownType) { + return; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + return; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + return; + } + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + function areAllOuterTypeParametersApplied(type) { + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } + function isValidBaseType(type) { + return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || + type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== unknownType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + } + } + else { + error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + } + } + } + } + } + } + function isIndependentInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230) { + if (declaration.flags & 64) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064, true); + if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 ? 1 : 2; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + type.objectFlags |= 4; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + if (!pushTypeResolution(symbol, 2)) { + return unknownType; + } + var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 || d.kind === 231; }); + var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + switch (expr.kind) { + case 9: + case 8: + return true; + case 192: + return expr.operator === 38 && + expr.operand.kind === 8; + case 71: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + default: + return false; + } + } + 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 (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 : 1; + } + 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) { + 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); + } + } + } + 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; + } + } + 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)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(16384); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 | 64)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152) { + return getDeclaredTypeOfAlias(symbol); + } + return unknownType; + } + function isIndependentTypeReference(node) { + if (node.typeArguments) { + for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { + var typeNode = _a[_i]; + if (!isIndependentType(typeNode)) { + return false; + } + } + } + return true; + } + function isIndependentType(node) { + switch (node.kind) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 134: + case 105: + case 139: + case 95: + case 130: + case 173: + return true; + case 164: + return isIndependentType(node.elementType); + case 159: + return isIndependentTypeReference(node); + } + return false; + } + function isIndependentVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isIndependentType(typeNode) : !node.initializer; + } + function isIndependentFunctionLikeDeclaration(node) { + if (node.kind !== 152) { + var typeNode = ts.getEffectiveReturnTypeNode(node); + if (!typeNode || !isIndependentType(typeNode)) { + return false; + } + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (!isIndependentVariableLikeDeclaration(parameter)) { + return false; + } + } + return true; + } + function isIndependentMember(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 149: + case 148: + return isIndependentVariableLikeDeclaration(declaration); + case 151: + case 150: + case 152: + return isIndependentFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); + type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + } + return type; + } + function getTypeWithThisArgument(type, thisArgument) { + if (getObjectFlags(type) & 4) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + } + } + else if (type.flags & 131072) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + } + return type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === source.symbol.members) { + members = ts.createSymbolTable(source.declaredProperties); + } + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, false) : + getIndexInfoOfType(instantiatedBaseType, 0); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { + return undefined; + } + } + return [signature]; + } + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); + if (!match) { + return undefined; + } + if (!ts.contains(result, match)) { + (result || (result = [])).push(match); + } + } + return result; + } + function getUnionSignatures(types, kind) { + var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + if (!result || !findMatchingSignature(result, signature, false, true, true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + if (unionSignatures.length > 1) { + s = cloneSignature(signature); + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s.resolvedReturnType = undefined; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + 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; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + var callSignatures = getUnionSignatures(type.types, 0); + var constructSignatures = getUnionSignatures(type.types, 1); + var stringIndexInfo = getUnionIndexInfo(type.types, 0); + var numberIndexInfo = getUnionIndexInfo(type.types, 1); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_3 = function (i) { + var t = type.types[i]; + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); + }; + for (var i = 0; i < types.length; i++) { + _loop_3(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048) { + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members.get("__call")); + var constructSignatures = getSignaturesOfSymbol(members.get("__new")); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + var members = emptySymbols; + var constructSignatures = ts.emptyArray; + var stringIndexInfo = undefined; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (32768 | 131072 | 540672)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, false); + } + } + var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } + } + } + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 170) { + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var propertySymbol = _a[_i]; + addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); + } + if (getIndexInfoOfType(modifiersType, 0)) { + addMemberForKeyType(stringType); + } + } + else { + var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t, propertySymbol) { + var iterationMapper = createTypeMapper([typeParameter], [t]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + if (t.flags & 32) { + var propName = ts.escapeLeadingUnderscores(t.value); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216); + var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + prop.type = propType; + if (propertySymbol) { + prop.syntheticOrigin = propertySymbol; + prop.declarations = propertySymbol.declarations; + } + members.set(propName, prop); + } + else if (t.flags & 2) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 170) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function isPartialMappedType(type) { + return getObjectFlags(type) & 32 && !!type.declaration.questionToken; + } + function isGenericMappedType(type) { + return getObjectFlags(type) & 32 && + maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 | 262144); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 32768) { + if (type.objectFlags & 4) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 65536) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 131072) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + function getPropertiesOfObjectType(type) { + if (type.flags & 32768) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + function getPropertyOfObjectType(type, name) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + if (type.flags & 65536) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 196608 ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createSymbolTable(); + 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 escapedName = _c[_b].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } + function getConstraintOfType(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? getConstraintOfIndexedAccess(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var baseObjectType = getBaseConstraintOfType(type.objectType); + var baseIndexType = getBaseConstraintOfType(type.indexType); + return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (540672 | 196608)) { + var constraint = getResolvedBaseConstraint(type); + if (constraint !== noConstraintType && constraint !== circularConstraintType) { + return constraint; + } + } + else if (type.flags & 262144) { + return stringType; + } + return undefined; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + function getResolvedBaseConstraint(type) { + var typeStack; + var circular; + if (!type.resolvedBaseConstraint) { + typeStack = []; + var constraint = getBaseConstraint(type); + type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + } + return type.resolvedBaseConstraint; + function getBaseConstraint(t) { + if (ts.contains(typeStack, t)) { + circular = true; + return undefined; + } + typeStack.push(t); + var result = computeBaseConstraint(t); + typeStack.pop(); + return result; + } + function computeBaseConstraint(t) { + if (t.flags & 16384) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType ? constraint : + constraint ? getBaseConstraint(constraint) : undefined; + } + if (t.flags & 196608) { + var types = t.types; + var baseTypes = []; + 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); + } + } + return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 262144) { + return stringType; + } + if (t.flags & 524288) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + } + function getDefaultFromTypeParameter(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + } + } + return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + } + function getApparentType(type) { + var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : + t.flags & 262178 ? globalStringType : + t.flags & 84 ? globalNumberType : + t.flags & 136 ? globalBooleanType : + t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 16777216 ? emptyObjectType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var types = containingType.types; + var isUnion = containingType.flags & 65536; + var excludeModifiers = isUnion ? 24 : 0; + var commonFlags = isUnion ? 0 : 16777216; + var syntheticFlag = 4; + var checkFlags = 0; + 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + if (!props) { + props = [prop]; + } + else if (!ts.contains(props, prop)) { + props.push(prop); + } + checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | + (!(modifiers & 24) ? 64 : 0) | + (modifiers & 16 ? 128 : 0) | + (modifiers & 8 ? 256 : 0) | + (modifiers & 32 ? 512 : 0); + if (!isMethodLike(prop)) { + syntheticFlag = 2; + } + } + else if (isUnion) { + checkFlags |= 16; + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16)) { + return props[0]; + } + var propTypes = []; + var declarations = []; + var commonType = undefined; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; + if (prop.declarations) { + ts.addRange(declarations, prop.declarations); + } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + checkFlags |= 32; + } + propTypes.push(type); + } + var result = createSymbol(4 | commonFlags, name); + result.checkFlags = syntheticFlag | checkFlags; + result.containingType = containingType; + result.declarations = declarations; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; + } + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 196608) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 229376) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 229376) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, true); + } + } + return undefined; + } + function getTypeParametersFromDeclaration(declaration) { + var result; + ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + var tp = getDeclaredTypeOfTypeParameter(node.symbol); + if (!ts.contains(result, tp)) { + if (!result) { + result = []; + } + result.push(tp); + } + }); + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + if (ts.isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 272) { + return true; + } + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 272; + } + } + } + } + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signatureDeclaration = node.parent; + var signature = getSignatureFromDeclaration(signatureDeclaration); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= signature.minArgumentCount; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } + return false; + } + function createTypePredicateFromTypePredicateNode(node) { + var parameterName = node.parameterName; + if (parameterName.kind === 71) { + return { + kind: 1, + parameterName: parameterName ? parameterName.escapedText : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0, + type: getTypeFromTypeNode(node.type) + }; + } + } + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!getDefaultFromTypeParameter(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + var numTypeParameters = ts.length(typeParameters); + if (numTypeParameters) { + var numTypeArguments = ts.length(typeArguments); + var isJavaScript = ts.isInJavaScriptFile(location); + if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (!typeArguments) { + typeArguments = []; + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, typeArguments); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + } + } + } + return typeArguments; + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = undefined; + var hasThisParameter = void 0; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this") { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (param.type && param.type.kind === 173) { + hasLiteralTypes = true; + } + var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !param.type || + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + if ((declaration.kind === 153 || declaration.kind === 154) && + !ts.hasDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 153 ? 154 : 153; + var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 152 ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 158 ? + createTypePredicateFromTypePredicateNode(declaration.type) : + undefined; + var hasRestLikeParameter = ts.hasRestParameter(declaration); + if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { + hasRestLikeParameter = true; + var syntheticArgsSymbol = createSymbol(3, "args"); + syntheticArgsSymbol.type = anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + parameters.push(syntheticArgsSymbol); + } + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { + if (isJSConstructSignature) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { + return classType; + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 154); + return getAnnotatedAccessorType(setter); + } + if (ts.nodeIsMissing(declaration.body)) { + return anyType; + } + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 71: + return node.escapedText === "arguments" && ts.isPartOfExpression(node); + case 149: + case 151: + case 153: + case 154: + return node.name.kind === 144 + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var node = symbol.declarations[i]; + switch (node.kind) { + case 160: + case 161: + case 228: + case 151: + case 150: + case 152: + case 155: + case 156: + case 157: + case 153: + case 154: + case 186: + case 187: + case 273: + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + break; + } + } + result.push(getSignatureFromDeclaration(node)); + } + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3)) { + return unknownType; + } + var type = void 0; + if (signature.target) { + type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); + } + else if (signature.unionSignatures) { + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + } + else { + type = getReturnTypeFromBody(signature.declaration); + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var declaration = signature.declaration; + 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); + } + } + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + if (getObjectFlags(type) & 4 && type.target === globalArrayType) { + return type.typeArguments[0]; + } + } + return anyType; + } + function getSignatureInstantiation(signature, typeArguments) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + } + function getErasedSignature(signature) { + if (!signature.typeParameters) + return signature; + if (!signature.erasedSignatureCache) { + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + return signature.erasedSignatureCache; + } + function getOrCreateTypeFromSignature(signature) { + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; + var type = createObjectType(16); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index"); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 ? 133 : 136; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = decl; + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 145).constraint; + } + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_5 = types.length; + var i = 0; + while (i < length_5) { + var startId = types[i].id; + var count = 1; + while (i + count < length_5 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 14680064; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : 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(typeArgs, typeParameters, minTypeArgumentCount, node)); + return createTypeReference(type, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + } + return instantiation; + } + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return unknownType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + function getTypeFromNonGenericTypeReference(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 159: + return node.typeName; + case 201: + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); + if (symbol === unknownSymbol) { + return unknownType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + if (symbol.flags & 107455 && isJSDocTypeReference(node)) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; + } + } + resolveTypeReferenceName(getTypeReferenceName(node), 793064); + return valueType; + } + return getTypeFromNonGenericTypeReference(node, symbol); + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 | 64)) { + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function isJSDocTypeReference(node) { + return node.flags & 1048576 && node.kind === 159; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + if (node.typeName.escapedText === "Object") { + if (node.typeArguments && node.typeArguments.length === 2) { + var indexed = getTypeFromTypeNode(node.typeArguments[0]); + var target = getTypeFromTypeNode(node.typeArguments[1]); + var index = createIndexInfo(target, false); + if (indexed === stringType || indexed === numberType) { + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + } + } + return anyType; + } + switch (node.typeName.escapedText) { + case "String": + return stringType; + case "Number": + return numberType; + case "Boolean": + return booleanType; + case "Void": + return voidType; + case "Undefined": + return undefinedType; + case "Null": + return nullType; + case "Function": + case "function": + return globalFunctionType; + case "Array": + case "array": + return !node.typeArguments || !node.typeArguments.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getUnionType([type, nullType]) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 793064; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 107455; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + 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) { + links.resolvedType = getWidenedType(checkExpression(node.exprName)); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + switch (declaration.kind) { + case 229: + case 230: + case 232: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 32768)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName(undefined, name, meaning, diagnostic, name); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 793064, undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getExportedTypeFromNamespace(namespace, name) { + var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); + return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); + } + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384); + typeParameters.push(typeParameter); + var property = createSymbol(4, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(8 | 4); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + return type; + } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + } + return links.resolvedType; + } + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 65536) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144) { + if (flags & 2048) + typeSet.containsUndefined = true; + if (flags & 4096) + typeSet.containsNull = true; + if (!(flags & 2097152)) + typeSet.containsNonWideningType = true; + } + else if (!(flags & 8192)) { + if (flags & 2) + typeSet.containsString = true; + if (flags & 4) + typeSet.containsNumber = true; + if (flags & 96) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } + } + } + function addTypesToUnion(typeSet, types) { + 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_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function isSubtypeOfAny(candidate, types) { + 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; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 && types.containsString || + t.flags & 64 && types.containsNumber || + t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + addTypesToUnion(typeSet, types); + if (typeSet.containsAny) { + return anyType; + } + if (subtypeReduction) { + removeSubtypes(typeSet); + } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } + if (typeSet.length === 0) { + return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : + typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : + neverType; + } + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); + type = createType(65536 | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, type) { + if (type.flags & 131072) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (type.flags & 8192) { + typeSet.containsNever = true; + } + else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { + typeSet.containsEmptyObject = true; + } + else if ((strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + if (type.flags & 32768) { + typeSet.containsObjectType = true; + } + if (type.flags & 65536 && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } + if (!(type.flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } + } + } + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; + addTypeToIntersection(typeSet, type); + } + } + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return emptyObjectType; + } + var typeSet = []; + addTypesToIntersection(typeSet, types); + if (typeSet.containsNever) { + return neverType; + } + if (typeSet.containsAny) { + return anyType; + } + if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { + typeSet.push(emptyObjectType); + } + if (typeSet.length === 1) { + return typeSet[0]; + } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); + type = createType(131072 | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + neverType : + getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; + var propName = indexType.flags & 96 ? + ts.escapeLeadingUnderscores("" + indexType.value) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? + ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || + getIndexInfoOfType(objectType, 0) || + undefined; + if (indexInfo) { + if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + 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.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)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + return unknownType; + } + return anyType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1) { + return objectType; + } + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (node.symbol.members.size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function getSpreadType(left, right) { + if (left.flags & 1 || right.flags & 1) { + return anyType; + } + if (left.flags & 8192) { + return right; + } + if (right.flags & 8192) { + return left; + } + if (left.flags & 65536) { + return mapType(left, function (t) { return getSpreadType(t, right); }); + } + if (right.flags & 65536) { + return mapType(right, function (t) { return getSpreadType(left, t); }); + } + if (right.flags & 16777216) { + return emptyObjectType; + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + stringIndexInfo = getIndexInfoOfType(right, 0); + numberIndexInfo = getIndexInfoOfType(right, 1); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 && !(leftProp.flags & 32768) + || skippedPrivateMembers.has(leftProp.escapedName) + || isClassMethod(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 | (leftProp.flags & 16777216); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + } + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getNonReadonlySymbol(prop) { + if (!isReadonlySymbol(prop)) { + return prop; + } + var flags = 4 | (prop.flags & 16777216); + var result = createSymbol(flags, prop.escapedName); + result.type = getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.syntheticOrigin = prop; + return result; + } + function isClassMethod(prop) { + return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + 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.value, type.symbol); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; + } + 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) { + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { + if (!(ts.getModifierFlags(container) & 32) && + (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return unknownType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 119: + case 268: + case 269: + return anyType; + case 136: + return stringType; + case 133: + return numberType; + case 122: + return booleanType; + case 137: + return esSymbolType; + case 105: + return voidType; + case 139: + return undefinedType; + case 95: + return nullType; + case 130: + return neverType; + case 134: + return node.flags & 65536 ? anyType : nonPrimitiveType; + case 169: + case 99: + return getTypeFromThisTypeNode(node); + case 173: + return getTypeFromLiteralTypeNode(node); + case 159: + return getTypeFromTypeReference(node); + case 158: + return booleanType; + case 201: + return getTypeFromTypeReference(node); + case 162: + return getTypeFromTypeQueryNode(node); + case 164: + return getTypeFromArrayTypeNode(node); + case 165: + return getTypeFromTupleTypeNode(node); + case 166: + return getTypeFromUnionTypeNode(node); + case 167: + return getTypeFromIntersectionTypeNode(node); + case 270: + return getTypeFromJSDocNullableTypeNode(node); + case 168: + case 271: + case 272: + case 267: + return getTypeFromTypeNode(node.type); + case 160: + case 161: + case 163: + case 285: + case 273: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 170: + return getTypeFromTypeOperatorNode(node); + case 171: + return getTypeFromIndexedAccessTypeNode(node); + case 172: + return getTypeFromMappedTypeNode(node); + case 71: + case 143: + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + case 274: + return getTypeFromJSDocVariadicType(node); + default: + return unknownType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + var result = []; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; + result.push(instantiator(v, mapper)); + } + return result; + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + mapper.mappedTypes = sources; + return mapper; + } + function createTypeEraser(sources) { + return createTypeMapper(sources, undefined); + } + function createBackreferenceMapper(typeParameters, index) { + var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + mapper.mappedTypes = typeParameters; + return mapper; + } + function isInferenceContext(mapper) { + return !!mapper.signature; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.signature, mapper.flags | 2, mapper.inferences) : + mapper; + } + function identityMapper(type) { + return type; + } + function combineTypeMappers(mapper1, mapper2) { + var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; + mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); + return mapper; + } + function createReplacementMapper(source, target, baseMapper) { + var mapper = function (t) { return t === source ? target : baseMapper(t); }; + mapper.mappedTypes = baseMapper.mappedTypes; + return mapper; + } + function cloneTypeParameter(typeParameter) { + var result = createType(16384); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + var freshTypePredicate; + if (signature.typeParameters && !eraseTypeParameters) { + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + if (signature.typePredicate) { + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); + } + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + if (ts.getCheckFlags(symbol) & 1) { + var links = getSymbolLinks(symbol); + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + var result = createSymbol(symbol.flags, symbol.escapedName); + result.checkFlags = 1; + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + return result; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(16 | 64, type.symbol); + result.target = type.objectFlags & 64 ? type.target : type; + result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144) { + var typeVariable_1 = constraintType.type; + if (typeVariable_1.flags & 16384) { + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + } + return t; + }); + } + } + } + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 | 32768 | 131072 | 524288); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 | 64, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } + var mappedTypes = mapper.mappedTypes; + return !!ts.findAncestor(symbol.declarations[0], function (node) { + if (node.kind === 233 || node.kind === 265) { + return "quit"; + } + switch (node.kind) { + case 160: + case 161: + case 228: + case 151: + case 150: + case 152: + case 155: + case 156: + case 157: + case 153: + case 154: + case 186: + case 187: + case 229: + case 199: + case 230: + case 231: + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var d = typeParameters_1[_i]; + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { + return true; + } + } + } + if (ts.isClassLike(node) || node.kind === 230) { + var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + if (thisType && ts.contains(mappedTypes, thisType)) { + return true; + } + } + break; + case 172: + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { + return true; + } + break; + case 273: + var func = node; + for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { + var p = _b[_a]; + if (ts.contains(mappedTypes, getTypeOfNode(p))) { + return true; + } + } + break; + } + }); + } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 265 || parentKind === 234; + } + return false; + } + function instantiateType(type, mapper) { + if (type && mapper !== identityMapper) { + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; + } + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { + return type.symbol && + type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && + (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; + } + if (type.objectFlags & 32) { + return instantiateCached(type, mapper, instantiateMappedType); + } + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + } + } + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + return type; + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 186: + case 187: + return isContextSensitiveFunctionLikeDeclaration(node); + case 178: + return ts.forEach(node.properties, isContextSensitive); + case 177: + return ts.forEach(node.elements, isContextSensitive); + case 195: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 194: + return node.operatorToken.kind === 54 && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 261: + return isContextSensitive(node.initializer); + case 151: + case 150: + return isContextSensitiveFunctionLikeDeclaration(node); + case 185: + return isContextSensitive(node.expression); + case 254: + return ts.forEach(node.properties, isContextSensitive); + case 253: + return node.initializer && isContextSensitive(node.initializer); + case 256: + return node.expression && isContextSensitive(node.expression); + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + if (node.typeParameters) { + return false; + } + if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind === 187) { + return false; + } + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length) { + var result = createObjectType(16, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 131072) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeInstanceOf(source, target) { + return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + } + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + } + function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + if (source === target) { + return -1; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0; + } + if (source.typeParameters) { + source = instantiateSignatureInContextOf(source, target); + } + var result = -1; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType, false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0; + } + result &= related; + } + } + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); + var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); + var related = callbacks ? + compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : + !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + } + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0; + } + } + else { + result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + if (source.kind === 1) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 16777216 ? true : + type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + false; + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined) { + return relation; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { + enumRelation.set(id, false); + return false; + } + 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.escapedName); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + } + enumRelation.set(id, false); + return false; + } + } + } + enumRelation.set(id, true); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 8192) + return false; + if (t & 1 || s & 8192) + return true; + if (s & 262178 && t & 2) + return true; + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) + return true; + if (s & 84 && t & 4) + return true; + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) + return true; + if (s & 136 && t & 8) + return true; + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + 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 (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (s & 1) + return true; + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 && source.flags & 1048576) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 1048576) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 32768 && target.flags & 32768) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + return related === 1; + } + } + if (source.flags & 1032192 || target.flags & 1032192) { + return checkTypeRelatedTo(source, target, relation, undefined); + } + return false; + } + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + var errorInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0; + var overflow = false; + var isIntersectionConstituent = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return result !== 0; + function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, undefined, 256); + targetType = typeToString(target, undefined, 256); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + function isRelatedTo(source, target, reportErrors, headMessage) { + if (source.flags & 96 && source.flags & 1048576) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 1048576) { + target = target.regularType; + } + if (source === target) + return -1; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1; + if (getObjectFlags(source) & 128 && source.flags & 1048576) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0; + } + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && + !(source.flags & 196608) && + !(target.flags & 65536) && + !isIntersectionConstituent && + source !== globalObjectType && + getPropertiesOfType(source).length > 0 && + isWeakType(target) && + !hasCommonProperties(source, target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + return 0; + } + var result = 0; + var saveErrorInfo = errorInfo; + var saveIsIntersectionConstituent = isIntersectionConstituent; + isIntersectionConstituent = false; + if (source.flags & 65536) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + } + else { + if (target.flags & 65536) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190)); + } + else if (target.flags & 131072) { + isIntersectionConstituent = true; + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 131072) { + result = someTypeRelatedToType(source, target, false); + } + if (!result && (source.flags & 1032192 || target.flags & 1032192)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + } + } + } + isIntersectionConstituent = saveIsIntersectionConstituent; + if (!result && reportErrors) { + if (source.flags & 32768 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 32768 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + if (source.flags & 32768 && target.flags & 32768) { + return recursiveTypeRelatedTo(source, target, false); + } + if (source.flags & 65536 && target.flags & 65536 || + source.flags & 131072 && target.flags & 131072) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0; + } + function hasExcessProperties(source, target, reportErrors) { + if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { + var isComparingJsxAttributes = !!(source.flags & 33554432); + if ((relation === assignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + var _loop_4 = function (prop) { + if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + ts.Debug.assert(!!errorNode); + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + errorNode = prop.valueDeclaration; + } + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, false); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 65536 && containsType(targetTypes, source)) { + return -1; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, false); + if (related) { + return related; + } + } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); + } + return 0; + } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 65536 && containsType(sourceTypes, target)) { + return -1; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(source, target, reportErrors) { + var sources = source.typeArguments || ts.emptyArray; + var targets = target.typeArguments || ts.emptyArray; + if (sources.length !== targets.length && relation === identityRelation) { + return 0; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1; + for (var i = 0; i < length; i++) { + var related = isRelatedTo(sources[i], targets[i], reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function recursiveTypeRelatedTo(source, target, reportErrors) { + if (overflow) { + return 0; + } + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2) { + relation.set(id, 3); + } + else { + return related === 1 ? -1 : 0; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + if (id === maybeKeys[i]) { + return 1; + } + } + if (depth === 100) { + overflow = true; + return 0; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2; + var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 || depth === 0) { + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1); + } + maybeCount = maybeStart; + } + } + else { + relation.set(id, reportErrors ? 3 : 2); + maybeCount = maybeStart; + } + return result; + } + function structuredTypeRelatedTo(source, target, reportErrors) { + var result; + var saveErrorInfo = errorInfo; + if (target.flags & 16384) { + if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144) { + if (source.flags & 262144) { + if (result = isRelatedTo(target.type, source.type, false)) { + return result; + } + } + var constraint = getConstraintOfType(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + else if (target.flags & 524288) { + var constraint = getConstraintOfType(target); + if (constraint) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + if (source.flags & 16384) { + if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + var constraint = getConstraintOfTypeParameter(source); + if (constraint || !(target.flags & 16777216)) { + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + constraint = getTypeWithThisArgument(constraint, source); + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else if (source.flags & 524288) { + var constraint = getConstraintOfType(source); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (target.flags & 524288 && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + } + else { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + return result; + } + } + var sourceIsPrimitive = !!(source.flags & 8190); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (source.flags & (32768 | 131072) && target.flags & 32768) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + result = -1; + } + else if (isGenericMappedType(target)) { + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; + } + else { + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + return 0; + } + function mappedTypeRelatedTo(source, target, reportErrors) { + var sourceReadonly = !!source.declaration.readonlyToken; + var sourceOptional = !!source.declaration.questionToken; + var targetReadonly = !!target.declaration.readonlyToken; + var targetOptional = !!target.declaration.questionToken; + var modifiersRelated = relation === identityRelation ? + sourceReadonly === targetReadonly && sourceOptional === targetOptional : + relation === comparableRelation || !sourceOptional || targetOptional; + if (modifiersRelated) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var result = -1; + var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp !== targetProp) { + if (!sourceProp) { + if (!(targetProp.flags & 16777216) || requireOptionalProperties) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); + } + return 0; + } + } + else if (!(targetProp.flags & 4194304)) { + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 || targetPropFlags & 8) { + 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)); + } + return 0; + } + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (reportErrors) { + if (sourcePropFlags & 8 && targetPropFlags & 8) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); + } + } + return 0; + } + } + else if (targetPropFlags & 16) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0; + } + } + else if (sourcePropFlags & 16) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0; + } + result &= related; + if (relation !== comparableRelation && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + } + } + } + return result; + } + function isWeakType(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 131072) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(source.flags & 33554432); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 32768 && target.flags & 32768)) { + return 0; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0; + } + var result = -1; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1; + } + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0; + } + } + var result = -1; + var saveErrorInfo = errorInfo; + 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], true, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + 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, true, 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 result; + } + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0; + } + var result = -1; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 1 && !sourceIsPrimitive) { + return -1; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 && getIndexInfoOfType(source, 0); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1; + if (kind === 0) { + var sourceNumberInfo = getIndexInfoOfType(source, 1); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; + if (targetAccessibility === 8) { + return true; + } + if (targetAccessibility === 16 && sourceAccessibility !== 8) { + return true; + } + if (targetAccessibility !== 16 && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function forEachProperty(prop, callback) { + 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.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + 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 ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + function isAbstractConstructorType(type) { + if (getObjectFlags(type) & 16) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && ts.getModifierFlags(declaration) & 128) { + return true; + } + } + } + return false; + } + function isDeeplyNestedType(type, stack, depth) { + if (depth >= 5 && type.flags & 32768) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 32768 && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + if (sourceProp === targetProp) { + return -1; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0; + } + } + else { + if ((sourceProp.flags & 16777216) !== (targetProp.flags & 16777216)) { + return 0; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + if (source === target) { + return -1; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0; + } + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0; + } + result &= related; + } + } + } + var targetLen = target.parameters.length; + for (var i = 0; i < targetLen; i++) { + var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); + var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var related = compareTypes(s, t); + if (!related) { + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function isRestParameterIndex(signature, parameterIndex) { + return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getUnionType(types, true); + } + function isArrayType(type) { + return getObjectFlags(type) & 4 && type.target === globalArrayType; + } + function isArrayLikeType(type) { + return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isTupleLikeType(type) { + return !!getPropertyOfType(type, "0"); + } + function isUnitType(type) { + return (type.flags & (224 | 2048 | 4096)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 ? true : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + 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 & 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) { + return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + result |= getFalsyFlags(t); + } + return result; + } + function getFalsyFlags(type) { + return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : + 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 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; + } + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && + getSignaturesOfType(type, 0).length === 0 && + getSignaturesOfType(type, 1).length === 0; + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + function getRegularTypeOfObjectLiteral(type) { + if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576; + regularNew.objectFlags |= 128; + type.regularType = regularNew; + return regularNew; + } + function getWidenedProperty(prop) { + var original = getTypeOfSymbol(prop); + var widened = getWidenedType(original); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getWidenedTypeOfObjectLiteral(type) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop) : prop); + } + var stringIndexInfo = getIndexInfoOfType(type, 0); + var numberIndexInfo = getIndexInfoOfType(type, 1); + return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + } + function getWidenedConstituentType(type) { + return type.flags & 6144 ? type : getWidenedType(type); + } + function getWidenedType(type) { + if (type.flags & 6291456) { + if (type.flags & 6144) { + return anyType; + } + if (getObjectFlags(type) & 128) { + return getWidenedTypeOfObjectLiteral(type); + } + if (type.flags & 65536) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 65536) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (getObjectFlags(type) & 128) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 2097152) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + return errorReported; + } + function reportImplicitAnyError(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + var diagnostic; + switch (declaration.kind) { + case 149: + case 148: + diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + break; + case 146: + diagnostic = declaration.dotDotDotToken ? + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + break; + case 176: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 228: + case 151: + case 150: + case 153: + case 154: + case 186: + case 187: + if (!declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + break; + default: + diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + } + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { + if (!reportWideningErrorsInType(type)) { + reportImplicitAnyError(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var count; + if (source.hasRestParameter && target.hasRestParameter) { + count = Math.max(sourceMax, targetMax); + } + else if (source.hasRestParameter) { + count = targetMax; + } + else if (target.hasRestParameter) { + count = sourceMax; + } + else { + count = Math.min(sourceMax, targetMax); + } + for (var i = 0; i < count; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + } + function createInferenceContext(signature, flags, baseInferences) { + var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + var context = mapper; + context.mappedTypes = signature.typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 || + objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || + objectFlags & 32 || + type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var inference = createInferenceInfo(typeParameter); + var inferences = [inference]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 16777216; + var members = ts.createSymbolTable(); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + members.set(prop.escapedName, inferredProp); + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + inference.candidates = undefined; + inferTypes(inferences, sourceType, templateType); + return inference.candidates && getUnionType(inference.candidates, true); + } + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + 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++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (64 | 32)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 540672) { + if (source.flags & 8388608 || source === silentNeverType) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (!inference.candidates || priority < inference.priority) { + inference.candidates = [source]; + inference.priority = priority; + } + else if (priority === inference.priority) { + inference.candidates.push(source); + } + if (!(priority & 4) && target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + } + else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + for (var i = 0; i < count; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 196608) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 196608) { + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + source = getApparentType(source); + if (source.flags & 32768) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (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); + } + } + } + } + function getInferenceInfoForType(type) { + if (type.flags & 540672) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144) { + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + var savePriority = priority; + priority |= 2; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return; + } + if (constraintType.flags & 16384) { + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } + function inferFromProperties(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + for (var i = 0; i < len; i++) { + inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + } + } + function inferFromSignature(source, target) { + forEachMatchingParameterType(source, target, inferFromTypes); + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 0); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1) || + getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 1); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190 | 262144); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + if (inference.candidates) { + var signature = context.signature; + var widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; + var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? + getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2) { + inferredType = silentNeverType; + } + else { + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + } + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); + } + function getFlowCacheKey(node) { + if (node.kind === 71) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 99) { + return "0"; + } + if (node.kind === 179) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + } + if (node.kind === 176) { + var container = node.parent.parent; + var key = container.kind === 176 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getLeftmostIdentifierOrThis(node) { + switch (node.kind) { + case 71: + case 99: + return node; + case 179: + return getLeftmostIdentifierOrThis(node.expression); + } + return undefined; + } + function getBindingElementNameText(element) { + if (element.parent.kind === 174) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 71: + return ts.unescapeLeadingUnderscores(name.escapedText); + case 144: + return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + case 9: + case 8: + return name.text; + default: + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + element.parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 71: + return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 226 || target.kind === 176) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 99: + return target.kind === 99; + case 97: + return target.kind === 97; + case 179: + return target.kind === 179 && + source.name.escapedText === target.name.escapedText && + isMatchingReference(source.expression, target.expression); + case 176: + if (target.kind !== 179) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 176 && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 226) { + var maybeId = source.parent.parent.initializer; + return maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function containsMatchingReference(source, target) { + while (source.kind === 179) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 179 && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 71) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 179) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 65536) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 179 && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 65536)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 8192) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 2) { + return strictNullChecks ? 4079361 : 4194049; + } + if (flags & 32) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { + return strictNullChecks ? 4079234 : 4193922; + } + if (flags & 64) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 3030658 : 1982082 : + isZero ? 3145346 : 4193922; + } + if (flags & 8) { + return strictNullChecks ? 4078980 : 4193668; + } + if (flags & 136) { + return strictNullChecks ? + type === falseType ? 3030404 : 1981828 : + type === falseType ? 3145092 : 4193668; + } + if (flags & 32768) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 : 8376288 : + strictNullChecks ? 6166480 : 8378320; + } + if (flags & (1024 | 2048)) { + return 2457472; + } + if (flags & 4096) { + return 2340752; + } + if (flags & 512) { + return strictNullChecks ? 1981320 : 4193160; + } + if (flags & 16777216) { + return strictNullChecks ? 6166480 : 8378320; + } + if (flags & 540672) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 196608) { + return getTypeFactsOfTypes(type.types); + } + return 8388607; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 131072), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getTypeOfPropertyOfType(type, text) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || + getIndexTypeOfType(type, 0) || + unknownType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + checkIteratedTypeOrElementType(type, undefined, false, false) || + unknownType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 194 && parent.parent.left === parent || + parent.parent.kind === 216 && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 215: + return stringType; + case 216: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; + case 194: + return getAssignedTypeOfBinaryExpression(parent); + case 188: + return undefinedType; + case 177: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 198: + return getAssignedTypeOfSpreadExpression(parent); + case 261: + return getAssignedTypeOfPropertyAssignment(parent); + case 262: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return unknownType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 174 ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 215) { + return stringType; + } + if (node.parent.parent.kind === 216) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; + } + return unknownType; + } + function getInitialType(node) { + return node.kind === 226 ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node) { + return node.kind === 226 || node.kind === 176 ? + getInitialType(node) : + getAssignedType(node); + } + function isEmptyArrayAssignment(node) { + return node.kind === 226 && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 176 && node.parent.kind === 194 && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 185: + return getReferenceCandidate(node.expression); + case 194: + switch (node.operatorToken.kind) { + case 58: + return getReferenceCandidate(node.left); + case 26: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 185 || + parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || + parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 257) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + var type = getTypeOfSwitchClause(clause); + if (type === undefined) { + return links.switchTypes = ts.emptyArray; + } + links.switchTypes.push(type); + } + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 65536) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 65536) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper) { + if (!(type.flags & 65536)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function createEvolvingArrayType(elementType) { + var result = createObjectType(256); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 ? + autoArrayType : + createArrayType(elementType.flags & 65536 ? + getUnionType(elementType.types, true) : + elementType); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; + if (!(t.flags & 8192)) { + if (!(getObjectFlags(t) & 256)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.escapedText === "length" || + parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 180 && + parent.expression === root && + parent.parent.kind === 194 && + parent.parent.operatorToken.kind === 58 && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 97) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { + return declaredType; + } + var visitedFlowStart = visitedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + visitedFlowCount = visitedFlowStart; + var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + while (true) { + if (flow.flags & 1024) { + for (var i = visitedFlowStart; i < visitedFlowCount; i++) { + if (visitedFlowNodes[i] === flow) { + return visitedFlowTypes[i]; + } + } + } + var type = void 0; + if (flow.flags & 4096) { + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048) { + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 96) { + type = getTypeAtFlowCondition(flow); + } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } + else if (flow.flags & 12) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flow.flags & 4 ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flow.flags & 256) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 2) { + var container = flow.container; + if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { + flow = container.flowNode; + continue; + } + type = initialType; + } + else { + type = convertAutoToAny(declaredType); + } + if (flow.flags & 1024) { + visitedFlowNodes[visitedFlowCount] = flow; + visitedFlowTypes[visitedFlowCount] = type; + visitedFlowCount++; + } + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; + } + if (containsMatchingReference(reference, node)) { + return declaredType; + } + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 181 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 181) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 8192) { + return flowType; + } + var assumeTrue = (flow.flags & 32) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 && antecedent.lock.locked) { + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + if (type === declaredType && declaredType === initialType) { + return type; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); + } + } + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (type === declaredType) { + break; + } + } + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + return expr.kind === 179 && + computedType.flags & 65536 && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(computedType, expr.name.escapedText); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.escapedText; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 58: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 32: + case 33: + case 34: + case 35: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 189 && right_1.kind === 9) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 189 && left_1.kind === 9) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 93: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 26: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1) { + return type; + } + if (operator === 33 || operator === 35) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 6144) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 32 || operator === 33; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + value.kind === 95 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); + } + if (type.flags & 16810497) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { + return declaredType; + } + return type; + } + if (operator === 33 || operator === 35) { + assumeTrue = !assumeTrue; + } + if (assumeTrue && !(type.flags & 65536)) { + var targetType = typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 540672) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 : + typeofNEFacts.get(literal.text) || 8192; + return getTypeWithFacts(type, facts); + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + if (containsMatchingReference(reference, left)) { + return declaredType; + } + return type; + } + var rightType = getTypeOfExpression(expr.right); + if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = void 0; + if (getObjectFlags(rightType) & 2) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; + } + else if (getObjectFlags(rightType) & 16) { + constructSignatures = getSignaturesOfType(rightType, 1); + } + if (constructSignatures && constructSignatures.length) { + targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + } + } + if (targetType) { + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + } + return type; + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + if (type.flags & 65536) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 8192)) { + return assignableType; + } + } + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 71: + case 99: + case 97: + case 179: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 181: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 185: + return narrowType(type, expr.expression, assumeTrue); + case 194: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 192: + if (expr.operator === 51) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + if (location.kind === 71) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 234 || + node.kind === 265 || + node.kind === 149; + }); + } + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304)) { + links.flags |= 4194304; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); + } + function markParameterAssignments(node) { + if (node.kind === 71) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 146 && + declaration.initializer && + getFalsyFlags(declaredType) & 2048 && + !(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) { + return unknownType; + } + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2) { + if (container.kind === 187) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192; + return getTypeOfSymbol(symbol); + } + if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32) { + if (declaration.kind === 229 + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 199) { + var container = ts.getThisContainer(node, false); + while (container !== undefined) { + if (container.parent === declaration) { + if (container.kind === 149 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + } + break; + } + container = ts.getThisContainer(container, false); + } + } + } + checkCollisionWithCapturedSuperVariable(node, node); + checkCollisionWithCapturedThisVariable(node, node); + checkCollisionWithCapturedNewTargetVariable(node, node); + checkNestedBlockScopedBinding(node, symbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152; + if (localOrExportSymbol.flags & 3) { + if (assignmentKind === 1) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + var isParameter = ts.getRootDeclaration(declaration).kind === 146; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || + flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + var assumeInitialized = isParameter || isAlias || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || + node.parent.kind === 203 || + ts.isInAmbientContext(declaration); + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getNullableType(type, 2048); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + 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); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 || + (symbol.flags & (2 | 32)) === 0 || + symbol.valueDeclaration.parent.kind === 260) { + return; + } + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + getNodeLinks(current).flags |= 65536; + } + if (container.kind === 214 && + ts.getAncestor(symbol.valueDeclaration, 227).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + } + getNodeLinks(symbol.valueDeclaration).flags |= 262144; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + while (current.parent.kind === 185) { + current = current.parent; + } + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 192 || current.parent.kind === 193)) { + var expr = current.parent; + isAssigned = expr.operator === 43 || expr.operator === 44; + } + if (!isAssigned) { + return false; + } + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2; + if (container.kind === 149 || container.kind === 152) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4; + } + else { + getNodeLinks(container).flags |= 4; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + var container = ts.getThisContainer(node, true); + var needToCaptureLexicalThis = false; + if (container.kind === 152) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + if (container.kind === 187) { + container = ts.getThisContainer(container, false); + needToCaptureLexicalThis = (languageVersion < 2); + } + switch (container.kind) { + case 233: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + break; + case 232: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + break; + case 152: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + } + break; + case 149: + case 148: + if (ts.getModifierFlags(container) & 32) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + } + break; + case 144: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node, container); + } + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + if (container.kind === 186 && + container.parent.kind === 194 && + ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { + var className = container.parent + .left + .expression + .expression; + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + return getInferredClassType(classSymbol); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return thisType; + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + } + if (noImplicitThis) { + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return anyType; + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 273) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this") { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; + var container = ts.getSuperContainer(node, true); + var needToCaptureLexicalThis = false; + if (!isCallExpression) { + while (container && container.kind === 187) { + container = ts.getSuperContainer(container, true); + needToCaptureLexicalThis = languageVersion < 2; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); + if (current && current.kind === 144) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return unknownType; + } + if (!isCallExpression && container.kind === 152) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if ((ts.getModifierFlags(container) & 32) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (container.kind === 151 && ts.getModifierFlags(container) & 256) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096; + } + else { + getNodeLinks(container).flags |= 2048; + } + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 178) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return unknownType; + } + return nodeCheckFlag === 512 + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + return container.kind === 152; + } + else { + if (ts.isClassLike(container.parent) || container.parent.kind === 178) { + if (ts.getModifierFlags(container) & 32) { + return container.kind === 151 || + container.kind === 150 || + container.kind === 153 || + container.kind === 154; + } + else { + return container.kind === 151 || + container.kind === 150 || + container.kind === 153 || + container.kind === 154 || + container.kind === 149 || + container.kind === 148 || + container.kind === 152; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 151 || + func.kind === 153 || + func.kind === 154) && func.parent.kind === 178 ? func.parent : + func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 187) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 261) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { + var target = func.parent.left; + if (target.kind === 179 || target.kind === 180) { + return checkExpressionCached(target.expression); + } + } + } + return undefined; + } + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); + } + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + } + } + } + return undefined; + } + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 146) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, true, false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 176) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + return functionFlags & 2 + ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) + : contextualReturnType; + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (node.parent.kind === 146 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + if (functionDecl.kind === 152 || + ts.getEffectiveReturnTypeNode(functionDecl) || + isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + } + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); + if (argIndex >= 0) { + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + return getTypeAtPosition(signature, argIndex); + } + return undefined; + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 183) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var operator = binaryExpression.operatorToken.kind; + if (ts.isAssignmentOperator(operator)) { + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + return undefined; + } + if (node === binaryExpression.right) { + return getTypeOfExpression(binaryExpression.left); + } + } + else if (operator === 54) { + var type = getContextualType(binaryExpression); + if (!type && node === binaryExpression.right) { + type = getTypeOfExpression(binaryExpression.left); + } + return type; + } + else if (operator === 53 || operator === 26) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } + return undefined; + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; + return prop ? getTypeOfSymbol(prop) : undefined; + }); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + } + function contextualTypeIsTupleLikeType(type) { + return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + } + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (isInsideWithStatementBody(node)) { + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!ts.hasDynamicName(element)) { + var symbolName = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || + getIndexTypeOfContextualType(type, 0); + } + return undefined; + } + function getContextualTypeForElementExpression(node) { + var arrayLiteral = node.parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + if (type) { + var index = ts.indexOf(arrayLiteral.elements, node); + return getTypeOfPropertyOfContextualType(type, "" + index) + || getIndexTypeOfContextualType(type, 1) + || getIteratedTypeOrElementType(type, undefined, false, false, false); + } + return undefined; + } + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? + node.parent.parent : + node.parent.openingElement.attributes; + var attributesType = getContextualType(jsxAttributes); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + if (ts.isJsxAttribute(node.parent)) { + return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + } + else if (node.parent.kind === 249) { + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + } + else { + return attributesType; + } + } + function getContextualTypeForJsxAttribute(attribute) { + var attributesType = getContextualType(attribute.parent); + if (ts.isJsxAttribute(attribute)) { + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + } + else { + return attributesType; + } + } + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); + return type && getApparentType(type); + } + function getContextualType(node) { + if (isInsideWithStatementBody(node)) { + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 176: + return getContextualTypeForInitializerExpression(node); + case 187: + case 219: + return getContextualTypeForReturnExpression(node); + case 197: + return getContextualTypeForYieldOperand(parent); + case 181: + case 182: + return getContextualTypeForArgument(parent, node); + case 184: + case 202: + return getTypeFromTypeNode(parent.type); + case 194: + return getContextualTypeForBinaryOperand(node); + case 261: + case 262: + return getContextualTypeForObjectLiteralElement(parent); + case 263: + return getApparentTypeOfContextualType(parent.parent); + case 177: + return getContextualTypeForElementExpression(node); + case 195: + return getContextualTypeForConditionalOperand(node); + case 205: + ts.Debug.assert(parent.parent.kind === 196); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 185: + return getContextualType(parent); + case 256: + return getContextualTypeForJsxExpression(parent); + case 253: + case 255: + return getContextualTypeForJsxAttribute(parent); + case 251: + case 250: + return getAttributesTypeFromJsxOpeningLikeElement(parent); + } + return undefined; + } + function getContextualMapper(node) { + node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return node ? node.contextualMapper : identityMapper; + } + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfStructuredType(type, 0); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 186 || node.kind === 187; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 65536)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { + return undefined; + } + else { + signatureList.push(signature); + } + } + } + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.resolvedReturnType = undefined; + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); + } + function hasDefaultValue(node) { + return (node.kind === 176 && !!node.initializer) || + (node.kind === 194 && node.operatorToken.kind === 58); + } + function checkArrayLiteral(node, checkMode) { + var elements = node.elements; + var hasSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; + if (inDestructuringPattern && e.kind === 198) { + var restArrayType = checkExpression(e.expression, checkMode); + var restElementType = getIndexTypeOfType(restArrayType, 1) || + getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var type = checkExpressionForMutableLocation(e, checkMode); + elementTypes.push(type); + } + hasSpreadElement = hasSpreadElement || e.kind === 198; + } + if (!hasSpreadElement) { + if (inDestructuringPattern && elementTypes.length) { + var type = cloneTypeReference(createTupleType(elementTypes)); + type.pattern = node; + return type; + } + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { + var patternElements = pattern.elements; + for (var i = elementTypes.length; i < patternElements.length; i++) { + var patternElement = patternElements[i]; + if (hasDefaultValue(patternElement)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else { + if (patternElement.kind !== 200) { + error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(unknownType); + } + } + } + if (elementTypes.length) { + return createTupleType(elementTypes); + } + } + } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, true) : + strictNullChecks ? neverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 144: + return isNumericComputedName(name); + case 71: + return isNumericLiteralName(name.escapedText); + case 8: + case 9: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || isTypeOfKind(type, kind); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + 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 { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + return createIndexInfo(unionType, false); + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable = ts.createSymbolTable(); + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); + var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + var isInJSFile = ts.isInJavaScriptFile(node); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 261 || + memberDecl.kind === 262 || + ts.isObjectLiteralMethod(memberDecl)) { + var jsdocType = void 0; + if (isInJSFile) { + jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); + } + var type = void 0; + if (memberDecl.kind === 261) { + type = checkPropertyAssignment(memberDecl, checkMode); + } + else if (memberDecl.kind === 151) { + type = checkObjectLiteralMethod(memberDecl, checkMode); + } + else { + ts.Debug.assert(memberDecl.kind === 262); + type = checkExpressionForMutableLocation(memberDecl.name, checkMode); + } + if (jsdocType) { + checkTypeAssignableTo(type, jsdocType, memberDecl); + type = jsdocType; + } + typeFlags |= type.flags; + var prop = createSymbol(4 | member.flags, member.escapedName); + if (inDestructuringPattern) { + var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216; + } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } + } + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 263) { + if (languageVersion < 2) { + checkExternalEmitHelpers(memberDecl, 2); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type); + offset = i + 1; + continue; + } + else { + ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); + checkNodeDeferred(memberDecl); + } + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName)) { + if (!(prop.flags & 16777216)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + } + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; + spread.symbol = node.symbol; + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.objectFlags |= 128; + if (patternWithComputedProperties) { + result.objectFlags |= 512; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144)) { + propagatedFlags |= (result.flags & 14680064); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 | 4096 | 2048 | 16777216) || + type.flags & 32768 && !isGenericMappedType(type) || + type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + } + function checkJsxSelfClosingElement(node) { + checkJsxOpeningLikeElement(node); + return getJsxGlobalElementType() || anyType; + } + function checkJsxElement(node) { + checkJsxOpeningLikeElement(node.openingElement); + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + return getJsxGlobalElementType() || anyType; + } + function isUnhyphenatedJsxName(name) { + return name.indexOf("-") < 0; + } + function isJsxIntrinsicIdentifier(tagName) { + switch (tagName.kind) { + case 179: + case 99: + return false; + case 71: + return ts.isIntrinsicJsxName(tagName.escapedText); + default: + ts.Debug.fail(); + } + } + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + 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; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = attributeDecl.initializer ? + checkExpression(attributeDecl.initializer, checkMode) : + trueType; + var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + attributesArray.push(attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 255); + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpression(attributeDecl.expression); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createSymbolTable(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; + if (!filter || filter(attr)) { + attributesTable.set(attr.escapedName, attr); + } + } + } + var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = []; + 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); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + createArrayType(getUnionType(childrenTypes, false)); + attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + } + } + 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, ts.emptyArray, ts.emptyArray, undefined, undefined); + result.flags |= 33554432 | 4194304; + result.objectFlags |= 128; + return result; + } + } + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); + } + function getJsxType(name) { + var jsxType = jsxTypes.get(name); + if (jsxType === undefined) { + jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); + } + return jsxType; + } + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + if (!ts.isIdentifier(node.tagName)) + throw ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1; + return links.resolvedSymbol = intrinsicProp; + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + links.jsxFlags |= 2; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxElementInstanceType(node, valueType) { + ts.Debug.assert(!(valueType.flags & 65536)); + if (isTypeAny(valueType)) { + return anyType; + } + var signatures = getSignaturesOfType(valueType, 1); + if (signatures.length === 0) { + signatures = getSignaturesOfType(valueType, 0); + if (signatures.length === 0) { + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return unknownType; + } + } + 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); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxElementPropertiesName() { + if (!_hasComputedJsxElementPropertiesName) { + _hasComputedJsxElementPropertiesName = true; + _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); + } + return _jsxElementPropertiesName; + } + function getJsxElementChildrenPropertyname() { + if (!_hasComputedJsxElementChildrenPropertyName) { + _hasComputedJsxElementChildrenPropertyName = true; + _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); + } + 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)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); + 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) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + } + } + } + return undefined; + } + function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { + ts.Debug.assert(!(elementType.flags & 65536)); + if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + var candidatesOutArray = []; + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + var result = void 0; + var allMatchingAttributesType = void 0; + for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { + 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++) { + var attribute = _b[_a]; + if (ts.isJsxAttribute(attribute) && + isUnhyphenatedJsxName(attribute.name.escapedText) && + !getPropertyOfType(paramType, attribute.name.escapedText)) { + shouldBeCandidate = false; + break; + } + } + if (shouldBeCandidate) { + result = intersectTypes(result, paramType); + } + allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); + } + } + if (!result) { + result = allMatchingAttributesType; + } + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + result = intersectTypes(intrinsicAttributes, result); + } + return result; + } + } + return undefined; + } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { + if (!elementType) { + elementType = checkExpression(openingLikeElement.tagName); + } + if (elementType.flags & 65536) { + var types = elementType.types; + return getUnionType(types.map(function (type) { + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); + }), true); + } + if (elementType.flags & 2) { + return anyType; + } + else if (elementType.flags & 32) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + return indexSignatureType; + } + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + } + return anyType; + } + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? + tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : + defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); + if (statelessAttributesType) { + return statelessAttributesType; + } + if (elementClassType) { + checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + if (isTypeAny(elemInstanceType)) { + return elemInstanceType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + return anyType; + } + else if (propsName === "") { + return elemInstanceType; + } + else { + var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + if (!attributesType) { + return emptyObjectType; + } + else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + return attributesType; + } + else { + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; + } + else { + return links.resolvedJsxElementAttributesType = unknownType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var elemClassType = getJsxGlobalElementClassType(); + return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + } + return links.resolvedJsxElementAttributesType; + } + function getAllAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, true); + } + } + function getAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, false); + } + } + function getJsxAttributePropertySymbol(attrib) { + var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); + var prop = getPropertyOfType(attributesType, attrib.name.escapedText); + return prop || unknownSymbol; + } + function getJsxGlobalElementClassType() { + if (!deferredJsxElementClassType) { + deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); + } + return deferredJsxElementClassType; + } + function getJsxGlobalElementType() { + if (!deferredJsxElementType) { + deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); + } + return deferredJsxElementType; + } + function getJsxGlobalStatelessElementType() { + if (!deferredJsxStatelessElementType) { + var jsxElementType = getJsxGlobalElementType(); + if (jsxElementType) { + deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); + } + } + return deferredJsxStatelessElementType; + } + function getJsxIntrinsicTagNames() { + var intrinsics = getJsxType(JsxNames.IntrinsicElements); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + if ((compilerOptions.jsx || 0) === 0) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxGlobalElementType() === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElement(node) { + checkGrammarJsxElement(node); + checkJsxPreconditions(node); + var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(); + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + if (reactSym) { + reactSym.isReferenced = true; + if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + checkJsxAttributesAssignableToTagNameAttributes(node); + } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(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) : + getCustomJsxElementAttributesType(openingLikeElement, false); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { + return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); + }); + if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + } + else { + 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.escapedText, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + break; + } + } + } + } + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + } + return type; + } + else { + return unknownType; + } + } + function getDeclarationKindFromSymbol(s) { + return s.valueDeclaration ? s.valueDeclaration.kind : 149; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + function isMethodLike(symbol) { + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); + } + function checkPropertyAccessibility(node, left, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 179 || node.kind === 226 ? + node.name : + node.right; + 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; + } + if (left.kind === 97) { + if (languageVersion < 2) { + var hasNonMethodDeclaration = forEachProperty(prop, function (p) { + var propKind = getDeclarationKindFromSymbol(p); + return propKind !== 151 && propKind !== 150; + }); + if (hasNonMethodDeclaration) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + if (!(flags & 24)) { + return true; + } + if (flags & 8) { + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + if (left.kind === 97) { + return true; + } + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + if (!enclosingClass) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + if (flags & 32) { + return true; + } + if (type.flags & 16384 && type.isThisType) { + type = getConstraintOfTypeParameter(type); + } + if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); + } + function checkNonNullType(type, errorNode) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; + if (kind) { + error(errorNode, kind & 2048 ? kind & 4096 ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + var t = getNonNullableType(type); + return t.flags & (6144 | 8192) ? unknownType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.escapedText); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0); + if (stringIndexType) { + return stringIndexType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + if (prop.valueDeclaration.kind === 229 && + node.parent && node.parent.kind !== 159 && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); + return unknownType; + } + } + if (node.kind !== 179 || assignmentKind === 1 || + !(prop.flags & (3 | 4 | 98304)) && + !(prop.flags & 8192 && propType.flags & 65536)) { + return propType; + } + 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.escapedText)) { + 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(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455); + return suggestion && suggestion.escapedName; + } + 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(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.escapedName; + } + } + 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; + var justCheckExactMatches = false; + 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]; + var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); + if (candidate.flags & meaning && + candidateName && + Math.abs(candidateName.length - name.length) < maximumLengthDifference) { + candidateName = candidateName.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + 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) { + justCheckExactMatches = true; + bestCandidate = 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 + : node.left; + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { + if (type !== unknownType && !isTypeAny(type)) { + var prop = getPropertyOfType(type, propertyName); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); + } + if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; + } + return true; + } + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 227) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 71) { + return getResolvedSymbol(initializer); + } + return undefined; + } + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); + } + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 71) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 215 && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 182 && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return unknownType; + } + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === unknownType) { + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + if ((expressionType.flags & 512) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); + if (!globalESSymbol) { + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + 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); + } + else if (node.kind !== 147) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + 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) { + if (lastParent && parent === lastParent) { + index++; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function getSpreadArgumentIndex(args) { + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (arg && arg.kind === 198) { + return i; + } + } + return -1; + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var typeArguments; + var callIsIncomplete; + var isDecorator; + var spreadArgIndex = -1; + if (ts.isJsxOpeningLikeElement(node)) { + return true; + } + if (node.kind === 183) { + var tagExpression = node; + argCount = args.length; + typeArguments = undefined; + if (tagExpression.template.kind === 196) { + var templateExpression = tagExpression.template; + var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); + ts.Debug.assert(lastSpan !== undefined); + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + var templateLiteral = tagExpression.template; + ts.Debug.assert(templateLiteral.kind === 13); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 147) { + isDecorator = true; + typeArguments = undefined; + argCount = getEffectiveArgumentCount(node, undefined, signature); + } + else { + var callExpression = node; + if (!callExpression.arguments) { + ts.Debug.assert(callExpression.kind === 182); + return signature.minArgumentCount === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + callIsIncomplete = callExpression.arguments.end === callExpression.end; + typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); + } + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + var hasRightNumberOfTypeArgs = !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + if (!hasRightNumberOfTypeArgs) { + return false; + } + if (spreadArgIndex >= 0) { + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + } + if (!signature.hasRestParameter && argCount > signature.parameters.length) { + return false; + } + var hasEnoughArguments = argCount >= signature.minArgumentCount; + return callIsIncomplete || hasEnoughArguments; + } + function getSingleCallSignature(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { + var context = createInferenceContext(signature, 1); + forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); + } + return getSignatureInstantiation(signature, getInferredTypes(context)); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isExpression(node)) { + var contextualType = getContextualType(node); + if (contextualType) { + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 200) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i); + if (argType === undefined) { + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + argType = checkExpressionWithContextualType(arg, paramType, mapper); + } + inferTypes(context.inferences, argType, paramType); + } + } + if (excludeArgument) { + for (var i = 0; i < argCount; i++) { + if (excludeArgument[i] === false) { + var arg = args[i]; + var paramType = getTypeAtPosition(signature, i); + inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); + } + } + } + return getInferredTypes(context); + } + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + var typeParameters = signature.typeParameters; + var typeArgumentsAreAssignable = true; + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + if (typeArgumentsAreAssignable) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); + } + } + } + return typeArgumentsAreAssignable; + } + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { + var callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var paramType = getTypeAtPosition(signature, 0); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); + var argProperties = getPropertiesOfType(attributesType); + for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { + var arg = argProperties_1[_i]; + if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { + return false; + } + } + return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 182) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 200) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } + } + } + return true; + } + function getThisArgumentOfCall(node) { + if (node.kind === 181) { + var callee = node.expression; + if (callee.kind === 179) { + return callee.expression; + } + else if (callee.kind === 180) { + return callee.expression; + } + } + } + function getEffectiveCallArguments(node) { + if (node.kind === 183) { + var template = node.template; + var args_4 = [undefined]; + if (template.kind === 196) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + else if (node.kind === 147) { + return undefined; + } + else if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + } + else { + return node.arguments || ts.emptyArray; + } + } + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 147) { + switch (node.parent.kind) { + case 229: + case 199: + return 1; + case 149: + return 2; + case 151: + case 153: + case 154: + if (languageVersion === 0) { + return 2; + } + return signature.parameters.length >= 3 ? 3 : 2; + case 146: + return 3; + } + } + else { + return args.length; + } + } + function getEffectiveDecoratorFirstArgumentType(node) { + if (node.kind === 229) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + if (node.kind === 146) { + node = node.parent; + if (node.kind === 152) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + } + if (node.kind === 149 || + node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + return getParentTypeOfClassElement(node); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorSecondArgumentType(node) { + if (node.kind === 229) { + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + } + if (node.kind === 146) { + node = node.parent; + if (node.kind === 152) { + return anyType; + } + } + if (node.kind === 149 || + node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + var element = node; + switch (element.name.kind) { + case 71: + return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + case 8: + case 9: + return getLiteralType(element.name.text); + case 144: + var nameType = checkComputedPropertyName(element.name); + if (isTypeOfKind(nameType, 512)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorThirdArgumentType(node) { + if (node.kind === 229) { + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 146) { + return numberType; + } + if (node.kind === 149) { + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + function getEffectiveArgumentType(node, argIndex) { + if (node.kind === 147) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 183) { + return getGlobalTemplateStringsArrayType(); + } + return undefined; + } + function getEffectiveArgument(node, args, argIndex) { + if (node.kind === 147 || + (argIndex === 0 && node.kind === 183)) { + return undefined; + } + return args[argIndex]; + } + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 147) { + return node.expression; + } + else if (argIndex === 0 && node.kind === 183) { + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + var isTaggedTemplate = node.kind === 183; + var isDecorator = node.kind === 147; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var typeArguments; + if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { + typeArguments = node.typeArguments; + if (node.expression.kind !== 97) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + reorderCandidates(signatures, candidates); + if (!candidates.length) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + var excludeArgument; + var excludeCount = 0; + if (!isDecorator) { + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + excludeCount++; + } + } + } + var candidateForArgumentError; + var candidateForTypeArgumentError; + var result; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + if (candidateForArgumentError) { + if (isJsxOpeningOrSelfClosingElement) { + return candidateForArgumentError; + } + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); + } + else if (candidateForTypeArgumentError) { + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + } + 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) { + ts.Debug.assert(candidates.length > 0); + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { + var typeArguments_2 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_2.length > typeParameters.length) { + typeArguments_2.pop(); + } + while (typeArguments_2.length < typeParameters.length) { + typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + candidates[bestIndex] = instantiated; + return instantiated; + } + return candidate; + } + return resolveErrorCall(node); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var originalCandidate = candidates[candidateIndex]; + if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + continue; + } + var candidate = void 0; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + undefined; + while (true) { + candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } + } + else { + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; + break; + } + if (excludeCount === 0) { + candidates[candidateIndex] = candidate; + return candidate; + } + excludeCount--; + if (excludeCount > 0) { + excludeArgument[ts.indexOf(excludeArgument, true)] = false; + } + else { + excludeArgument = undefined; + } + } + } + return undefined; + } + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + return i; + } + if (candidate.parameters.length > maxParams) { + maxParams = candidate.parameters.length; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray) { + if (node.expression.kind === 97) { + var superType = checkSuperExpression(node.expression); + if (superType !== unknownType) { + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType !== unknownType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + if (constructSignatures.length) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + } + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + if (funcType.flags & 65536) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } + function resolveNewExpression(node, candidatesOutArray) { + if (node.arguments && languageVersion < 1) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + return resolveErrorCall(node); + } + 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(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + var constructSignatures = getSignaturesOfType(expressionType, 1); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray); + } + var callSignatures = getSignaturesOfType(expressionType, 0); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray); + if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + return signature; + } + error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + return resolveErrorCall(node); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getModifierFlags(declaration); + if (!(modifiers & 24)) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + while (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + baseTypes = getBaseTypes(baseType); + } + } + if (modifiers & 8) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function resolveTaggedTemplateExpression(node, candidatesOutArray) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 229: + case 199: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 146: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 149: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 151: + case 153: + case 154: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = void 0; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + ts.Debug.assert(!(elementType.flags & 65536)); + var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); + return callSignature; + } + function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { + if (elementType.flags & 65536) { + var types = elementType.types; + var result = void 0; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; + result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); + } + return result; + } + var callSignatures = elementType && getSignaturesOfType(elementType, 0); + if (callSignatures && callSignatures.length > 0) { + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + } + return undefined; + } + function resolveSignature(node, candidatesOutArray) { + switch (node.kind) { + case 181: + return resolveCallExpression(node, candidatesOutArray); + case 182: + return resolveNewExpression(node, candidatesOutArray); + case 183: + return resolveTaggedTemplateExpression(node, candidatesOutArray); + case 147: + return resolveDecorator(node, candidatesOutArray); + case 251: + case 250: + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + } + ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + } + function getResolvedSignature(node, candidatesOutArray) { + var links = getNodeLinks(node); + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray); + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + function isJavaScriptConstructor(node) { + if (ts.isInJavaScriptFile(node)) { + if (ts.getJSDocClassTag(node)) + return true; + var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : + ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + undefined; + return symbol && symbol.members !== undefined; + } + return false; + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && getObjectFlags(type) & 16 + && getSymbolLinks(type.symbol).inferredClassType === type; + } + function checkCallExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 97) { + return voidType; + } + if (node.kind === 182) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 152 && + declaration.kind !== 156 && + declaration.kind !== 161 && + !ts.isJSDocConstructSignature(declaration)) { + var funcSymbol = node.expression.kind === 71 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { + funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); + } + if (funcSymbol && funcSymbol.flags & 16 && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { + return getInferredClassType(funcSymbol); + } + else if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + return getReturnTypeOfSignature(signature); + } + function checkImportCallExpression(node) { + checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 2048 || specifierType.flags & 4096 || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, true)) { + return false; + } + if (!ts.isIdentifier(node.expression)) + throw ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined); + if (!resolvedRequire) { + return true; + } + if (resolvedRequire.flags & 2097152) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 + ? 228 + : resolvedRequire.flags & 3 + ? 226 + : 0; + if (targetDeclarationKind !== 0) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return ts.isInAmbientContext(decl); + } + return false; + } + function checkTaggedTemplateExpression(node) { + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== unknownType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return unknownType; + } + else if (container.kind === 152) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && declaration.initializer) { + return getNullableType(type, 2048); + } + } + return type; + } + function getTypeAtPosition(signature, pos) { + return signature.hasRestParameter ? + pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : + pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + } + function getTypeOfFirstParameterOfSignature(signature) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + var parameter = ts.lastOrUndefined(signature.parameters); + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + function assignBindingElementTypes(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + assignBindingElementTypes(element); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); + if (links.type === emptyObjectType && + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); + } + assignBindingElementTypes(parameter.valueDeclaration); + } + } + function createPromiseType(promisedType) { + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return unknownType; + } + else if (!getGlobalPromiseConstructorSymbol(true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!func.body) { + return unknownType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 207) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = void 0; + if (functionFlags & 1) { + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 + ? createAsyncIterableIteratorType(anyType) + : createIterableIteratorType(anyType); + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (!types) { + return functionFlags & 2 + ? createPromiseReturnType(func, neverType) + : neverType; + } + if (types.length === 0) { + return functionFlags & 2 + ? createPromiseReturnType(func, voidType) + : voidType; + } + } + type = getUnionType(types, true); + if (functionFlags & 1) { + type = functionFlags & 2 + ? createAsyncIterableIteratorType(type) + : createIterableIteratorType(type); + } + } + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } + var widenedType = getWidenedType(type); + return (functionFlags & 3) === 2 + ? createPromiseReturnType(func, widenedType) + : widenedType; + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var functionFlags = ts.getFunctionFlags(func); + ts.forEachYieldExpression(func.body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (yieldExpression.asteriskToken) { + type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); + } + if (functionFlags & 2) { + type = checkAwaitedType(type, expr, yieldExpression.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 8192) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 186 || func.kind === 187)) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (!ts.contains(aggregatedTypes, undefinedType)) { + aggregatedTypes.push(undefinedType); + } + } + return aggregatedTypes; + } + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + return; + } + if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256; + if (returnType && returnType.flags & 8192) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186) { + checkGrammarForGenerator(node); + } + if (checkMode === 1 && isContextSensitive(node)) { + checkNodeDeferred(node); + return anyFunctionType; + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(node.symbol); + if (!(links.flags & 1024)) { + var contextualSignature = getContextualSignature(node); + if (!(links.flags & 1024)) { + links.flags |= 1024; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + checkNodeDeferred(node); + } + } + if (produceDiagnostics && node.kind !== 151) { + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + } + return type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnOrPromisedType = returnTypeNode && + ((functionFlags & 3) === 2 ? + checkAsyncFunctionReturnType(node) : + getTypeFromTypeNode(returnTypeNode)); + if ((functionFlags & 1) === 0) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!returnTypeNode) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 207) { + checkSourceElement(node.body); + } + else { + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3) === 2) { + 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); + } + else { + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + } + } + } + registerForUnusedIdentifiersCheck(node); + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlySymbol(symbol) { + 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); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + if (symbol.flags & 4 && + (expr.kind === 179 || expr.kind === 180) && + expr.expression.kind === 99) { + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 152)) { + return true; + } + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 179 || expr.kind === 180) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 71) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 240; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + var node = ts.skipOuterExpressions(expr, 2 | 1); + if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 179 && expr.kind !== 180) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 16384)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 38 && node.operand.kind === 8) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + switch (node.operator) { + case 37: + case 38: + case 52: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 512)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + return numberType; + case 51: + var facts = getTypeFacts(operandType) & (1048576 | 2097152); + return facts === 1048576 ? falseType : + facts === 2097152 ? trueType : + booleanType; + case 43: + case 44: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + return unknownType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + function maybeTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 196608) { + var types = type.types; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 65536) { + var types = type.types; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; + if (!isTypeOfKind(t, kind)) { + return false; + } + } + return true; + } + if (type.flags & 131072) { + var types = type.types; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isConstEnumObjectType(type) { + return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (isTypeOfKind(leftType, 8190)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + if (!(isTypeAny(rightType) || + getSignaturesOfType(rightType, 0).length || + getSignaturesOfType(rightType, 1).length || + isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + 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)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType) { + var properties = node.properties; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + } + return sourceType; + } + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 261 || property.kind === 262) { + var name = property.name; + if (name.kind === 144) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var text = ts.getTextOfPropertyName(name); + var type = isTypeAny(objectLiteralType) + ? objectLiteralType + : getTypeOfPropertyOfType(objectLiteralType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || + getIndexTypeOfType(objectLiteralType, 0); + if (type) { + if (property.kind === 262) { + return checkDestructuringAssignment(property, type); + } + else { + return checkDestructuringAssignment(property.initializer, type); + } + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 263) { + if (languageVersion < 5) { + checkExternalEmitHelpers(property, 4); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || unknownType; + var elements = node.elements; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 200) { + if (element.kind !== 198) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) + ? getTypeOfPropertyOfType(sourceType, propName) + : elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + else { + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + var target; + if (exprOrAssignment.kind === 262) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + sourceType = getTypeWithFacts(sourceType, 131072); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 194 && target.operatorToken.kind === 58) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 178) { + return checkObjectLiteralAssignment(target, sourceType); + } + if (target.kind === 177) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 263 ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableTo(sourceType, targetType, target, undefined); + } + return sourceType; + } + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 71: + case 9: + case 12: + case 183: + case 196: + case 13: + case 8: + case 101: + case 86: + case 95: + case 139: + case 186: + case 199: + case 187: + case 177: + case 178: + case 189: + case 203: + case 250: + case 249: + return true; + case 195: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 194: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 192: + case 193: + switch (node.operator) { + case 51: + case 37: + case 38: + case 52: + return true; + } + return false; + case 190: + case 184: + case 202: + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], true); + } + function checkBinaryExpression(node, checkMode) { + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 58 && (left.kind === 178 || left.kind === 177)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + } + var leftType = checkExpression(left, checkMode); + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 39: + case 40: + case 61: + case 62: + case 41: + case 63: + case 42: + case 64: + case 38: + case 60: + case 45: + case 65: + case 46: + case 66: + case 47: + case 67: + case 49: + case 69: + case 50: + case 70: + case 48: + case 68: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + if ((leftType.flags & 136) && + (rightType.flags & 136) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + } + else { + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + if (leftOk && rightOk) { + checkAssignmentOperator(numberType); + } + } + return numberType; + case 37: + case 59: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { + resultType = numberType; + } + else { + if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 59) { + checkAssignmentOperator(resultType); + } + return resultType; + case 27: + case 29: + case 30: + case 31: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + reportOperatorError(); + } + } + return booleanType; + case 32: + case 33: + case 34: + case 35: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 93: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 92: + return checkInExpression(left, right, leftType, rightType); + case 53: + return getTypeFacts(leftType) & 1048576 ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 54: + return getTypeFacts(leftType) & 2097152 ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; + case 58: + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + case 26: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + } + function isEvalNode(node) { + return node.kind === 71 && node.escapedText === "eval"; + } + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : + maybeTypeOfKind(rightType, 512) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 49: + case 69: + return 54; + case 50: + case 70: + return 35; + case 48: + case 68: + return 53; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { + checkTypeAssignableTo(valueType, leftType, left, undefined); + } + } + } + function reportOperatorError() { + error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + if (node.expression) { + var func = ts.getContainingFunction(node); + var functionFlags = func && ts.getFunctionFlags(func); + if (node.asteriskToken) { + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); + } + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256); + } + } + if (functionFlags & 1) { + var expressionType = checkExpressionCached(node.expression); + var expressionElementType = void 0; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); + } + var returnType = ts.getEffectiveReturnTypeNode(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2) !== 0) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(functionFlags & 2 + ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionElementType, signatureElementType, node.expression, undefined); + } + else { + checkTypeAssignableTo(functionFlags & 2 + ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionType, signatureElementType, node.expression, undefined); + } + } + } + } + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getBestChoiceType(type1, type2); + } + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8: + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 101: + return trueType; + case 86: + return falseType; + } + } + function checkTemplateExpression(node) { + ts.forEach(node.templateSpans, function (templateSpan) { + checkExpression(templateSpan.expression); + }); + return stringType; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var saveContextualType = node.contextualType; + var saveContextualMapper = node.contextualMapper; + node.contextualType = contextualType; + node.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 : + contextualMapper ? 2 : 0; + var result = checkExpression(node, checkMode); + node.contextualType = saveContextualType; + node.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 184 || node.kind === 202; + } + function checkDeclarationInitializer(declaration) { + var type = getTypeOfExpression(declaration.initializer, true); + return ts.getCombinedNodeFlags(declaration) & 2 || + ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 540672) { + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + if (constraint.flags & (2 | 4 | 8 | 16)) { + return true; + } + contextualType = constraint; + } + return maybeTypeOfKind(contextualType, (224 | 262144)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode) { + var type = checkExpression(node, checkMode); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } + function checkPropertyAssignment(node, checkMode) { + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + checkGrammarMethod(node); + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + function getTypeOfExpression(node, cache) { + if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + return cache ? checkExpressionCached(node) : checkExpression(node); + } + function getContextFreeTypeOfExpression(node) { + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = getTypeOfExpression(node); + node.contextualType = saveContextualType; + return type; + } + function checkExpression(node, checkMode) { + var type; + if (node.kind === 143) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + var ok = (node.parent.kind === 179 && node.parent.expression === node) || + (node.parent.kind === 180 && node.parent.expression === node) || + ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281; }); }); + if (typecasts && typecasts.length) { + var cast_1 = typecasts[0]; + return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); + } + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode) { + switch (node.kind) { + case 71: + return checkIdentifier(node); + case 99: + return checkThisExpression(node); + case 97: + return checkSuperExpression(node); + case 95: + return nullWideningType; + case 9: + case 8: + case 101: + case 86: + return checkLiteralExpression(node); + case 196: + return checkTemplateExpression(node); + case 13: + return stringType; + case 12: + return globalRegExpType; + case 177: + return checkArrayLiteral(node, checkMode); + case 178: + return checkObjectLiteral(node, checkMode); + case 179: + return checkPropertyAccessExpression(node); + case 180: + return checkIndexedAccess(node); + case 181: + if (node.expression.kind === 91) { + return checkImportCallExpression(node); + } + case 182: + return checkCallExpression(node); + case 183: + return checkTaggedTemplateExpression(node); + case 185: + return checkParenthesizedExpression(node, checkMode); + case 199: + return checkClassExpression(node); + case 186: + case 187: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 189: + return checkTypeOfExpression(node); + case 184: + case 202: + return checkAssertion(node); + case 203: + return checkNonNullAssertion(node); + case 204: + return checkMetaProperty(node); + case 188: + return checkDeleteExpression(node); + case 190: + return checkVoidExpression(node); + case 191: + return checkAwaitExpression(node); + case 192: + return checkPrefixUnaryExpression(node); + case 193: + return checkPostfixUnaryExpression(node); + case 194: + return checkBinaryExpression(node, checkMode); + case 195: + return checkConditionalExpression(node, checkMode); + case 198: + return checkSpreadExpression(node, checkMode); + case 200: + return undefinedWideningType; + case 197: + return checkYieldExpression(node); + case 256: + return checkJsxExpression(node, checkMode); + case 249: + return checkJsxElement(node); + case 250: + return checkJsxSelfClosingElement(node); + case 254: + return checkJsxAttributes(node, checkMode); + case 251: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return unknownType; + } + function checkTypeParameter(node) { + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.getModifierFlags(node) & 92) { + func = ts.getContainingFunction(node); + if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (ts.indexOf(func.parameters, node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 152 || func.kind === 156 || func.kind === 161) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + } + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 && param.name.escapedText === parameter.escapedText) { + return i; + } + } + } + return -1; + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 187: + case 155: + case 228: + case 186: + case 160: + case 151: + case 150: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 71 && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 175 || name.kind === 174) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + if (node.kind === 157) { + checkGrammarIndexSignature(node); + } + else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || + node.kind === 155 || node.kind === 152 || + node.kind === 156) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); + } + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); + } + if ((functionFlags & 3) !== 0 && languageVersion < 2) { + checkExternalEmitHelpers(node, 128); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 156: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 155: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 | 1)) === 1) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 + ? createAsyncIterableIteratorType(generatorElementType) + : createIterableIteratorType(generatorElementType); + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3) === 2) { + checkAsyncFunctionReturnType(node); + } + } + if (noUnusedIdentifiers && !node.body) { + checkUnusedTypeParameters(node); + } + } + } + function checkClassForDuplicateDeclarations(node) { + var instanceNames = ts.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 152) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3); + } + } + } + else { + var isStatic = ts.getModifierFlags(member) & 32; + var names = isStatic ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 153: + addName(names, member.name, memberName, 1); + break; + case 154: + addName(names, member.name, memberName, 2); + break; + case 149: + addName(names, member.name, memberName, 3); + break; + case 151: + addName(names, member.name, memberName, 4); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4) { + if (meaning !== 4) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.getModifierFlags(member) & 32; + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbol(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + var memberName = void 0; + switch (member.name.kind) { + case 9: + case 8: + memberName = member.name.text; + break; + case 71: + memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 230) { + var nodeSymbol = getSymbolOfNode(node); + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 136: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 133: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + checkFunctionOrMethodDeclaration(node); + if (ts.getModifierFlags(node) & 128 && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + checkSignatureDeclaration(node); + checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function containsSuperCallAsComputedPropertyName(n) { + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); + } + function containsSuperCall(n) { + if (ts.isSuperCall(n)) { + return true; + } + else if (ts.isFunctionLike(n)) { + return false; + } + else if (ts.isClassLike(n)) { + return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); + } + return ts.forEachChild(n, containsSuperCall); + } + function markThisReferencesAsErrors(n) { + if (n.kind === 99) { + error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + } + else if (n.kind !== 186 && n.kind !== 228) { + ts.forEachChild(n, markThisReferencesAsErrors); + } + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 149 && + !(ts.getModifierFlags(n) & 32) && + !!n.initializer; + } + var containingClassDecl = node.parent; + if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 153) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (!(node.flags & 256)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + var otherKind = node.kind === 153 ? 154 : 153; + var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (otherAccessor) { + if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 153) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + mapper = createTypeMapper(typeParameters, typeArguments); + } + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== unknownType) { + if (node.typeArguments) { + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var symbol = getNodeLinks(node).resolvedSymbol; + var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); + } + } + 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)); + } + } + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { + grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + } + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 524288)) { + return type; + } + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + return type; + } + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { + var constraint = getBaseConstraintOfType(objectType); + if (constraint && getIndexInfoOfType(constraint, 1)) { + return type; + } + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); + } + function isPrivateWithinAmbient(node) { + return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + if (n.parent.kind !== 230 && + n.parent.kind !== 229 && + n.parent.kind !== 199 && + ts.isInAmbientContext(n)) { + if (!(flags & 2)) { + flags |= 1; + } + flags |= 2; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 | 16)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 | 2 | 8 | 16 | 128; + var someNodeFlags = 0; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 151 || node.kind === 150) && + (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); + if (reportError) { + var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + if (ts.getModifierFlags(node) & 128) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var current = declarations_5[_i]; + var node = current; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = undefined; + } + if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + 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; + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + var symbol = node.localSymbol; + if (!symbol) { + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + return; + } + } + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0; + var nonExportedDeclarationSpaces = 0; + var defaultExportedDeclarationSpaces = 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); + if (effectiveDeclarationFlags & 1) { + if (effectiveDeclarationFlags & 512) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + function getDeclarationSpaces(d) { + switch (d.kind) { + case 230: + case 231: + return 2; + case 233: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 + ? 4 | 1 + : 4; + case 229: + case 232: + return 2 | 1; + case 237: + var result_3 = 0; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 226: + case 176: + case 228: + case 242: + return 1; + default: + ts.Debug.fail(ts.SyntaxKind[d.kind]); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + function getPromisedTypeOfPromise(promise, errorNode) { + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + } + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 65536) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { + if (errorNode) { + ts.Debug.assert(!!diagnosticMessage); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + function checkAsyncFunctionReturnType(node) { + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } + } + else { + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + } + return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 229: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 146: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 149: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 151: + case 153: + case 154: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + } + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 ? 793064 : 1920) | 2097152, undefined, undefined); + if (rootSymbol + && rootSymbol.flags & 2097152 + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + 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.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + function checkDecorators(node) { + if (!node.decorators) { + return; + } + if (!ts.nodeCanBeDecorated(node)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8); + if (node.kind === 146) { + checkExternalEmitHelpers(firstDecorator, 32); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16); + switch (node.kind) { + case 229: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 151: + case 153: + case 154: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 149: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 146: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDoc(node) { + if (!ts.isInJavaScriptFile(node)) { + return; + } + ts.forEach(node.jsDoc, checkSourceElement); + } + function checkJSDocComment(node) { + if (node.tags) { + for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + checkSourceElement(tag); + } + } + } + function checkFunctionOrMethodDeclaration(node) { + checkJSDoc(node); + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + if (node.name && node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + checkFunctionOrConstructorSymbol(symbol); + } + } + } + checkSourceElement(node.body); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if ((functionFlags & 1) === 0) { + var returnOrPromisedType = returnTypeNode && (functionFlags & 2 + ? checkAsyncFunctionReturnType(node) + : getTypeFromTypeNode(returnTypeNode)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !returnTypeNode) { + if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (functionFlags & 1 && ts.nodeIsPresent(node.body)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + registerForUnusedIdentifiersCheck(node); + } + function registerForUnusedIdentifiersCheck(node) { + if (deferredUnusedIdentifierNodes) { + deferredUnusedIdentifierNodes.push(node); + } + } + function checkUnusedIdentifiers() { + if (deferredUnusedIdentifierNodes) { + for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { + var node = deferredUnusedIdentifierNodes_1[_i]; + switch (node.kind) { + case 265: + case 233: + checkUnusedModuleMembers(node); + break; + case 229: + case 199: + checkUnusedClassMembers(node); + checkUnusedTypeParameters(node); + break; + case 230: + checkUnusedTypeParameters(node); + break; + case 207: + case 235: + case 214: + case 215: + case 216: + checkUnusedLocalsAndParameters(node); + break; + case 152: + case 186: + case 228: + case 187: + case 151: + case 153: + case 154: + if (node.body) { + checkUnusedLocalsAndParameters(node); + } + checkUnusedTypeParameters(node); + break; + case 150: + case 155: + case 156: + case 157: + case 160: + case 161: + checkUnusedTypeParameters(node); + break; + case 231: + checkUnusedTypeParameters(node); + break; + } + } + } + } + function checkUnusedLocalsAndParameters(node) { + if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + 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(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + } + } + }); + } + } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 226 && ts.isForInOrOfStatement(declaration.parent.parent)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 71 && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95; + } + function checkUnusedClassMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.members) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 151 || member.kind === 149) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { + error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + } + } + else if (member.kind === 152) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + } + } + } + } + } + } + } + function checkUnusedTypeParameters(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.typeParameters) { + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var typeParameter = _a[_i]; + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + } + } + } + } + } + function checkUnusedModuleMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + } + }); + } + } + function checkBlock(node) { + if (node.kind === 207) { + checkGrammarStatementInAmbientContext(node); + } + ts.forEach(node.statements, checkSourceElement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 149 || + node.kind === 148 || + node.kind === 151 || + node.kind === 150 || + node.kind === 153 || + node.kind === 154) { + return false; + } + if (ts.isInAmbientContext(node)) { + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { + return false; + } + return true; + } + function checkCollisionWithCapturedThisVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_this")) { + potentialThisCollisions.push(node); + } + } + function checkCollisionWithCapturedNewTargetVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + potentialNewTargetCollisions.push(node); + } + } + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4) { + var isDeclaration_1 = node.kind !== 71; + if (isDeclaration_1) { + 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); + } + return true; + } + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8) { + var isDeclaration_2 = node.kind !== 71; + if (isDeclaration_2) { + 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); + } + return true; + } + }); + } + function checkCollisionWithCapturedSuperVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_super")) { + return; + } + var enclosingClass = ts.getContainingClass(node); + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + return; + } + if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { + var isDeclaration_3 = node.kind !== 71; + if (isDeclaration_3) { + error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); + } + } + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + if (node.kind === 226 && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1) { + if (!ts.isIdentifier(node.name)) + throw ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); + var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + var namesShareScope = container && + (container.kind === 207 && ts.isFunctionLike(container.parent) || + container.kind === 234 || + container.kind === 233 || + container.kind === 265); + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 146) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + return; + } + if (n.kind === 179) { + return visit(n.expression); + } + else if (n.kind === 71) { + var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 146 || + symbol.valueDeclaration.kind === 176) { + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + (current.parent.kind === 149 && + !(ts.hasModifier(current.parent, 32)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + checkSourceElement(node.type); + if (!node.name) { + return; + } + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 176) { + if (node.parent.kind === 174 && languageVersion < 5) { + checkExternalEmitHelpers(node, 4); + } + if (node.propertyName && node.propertyName.kind === 144) { + checkComputedPropertyName(node.propertyName); + } + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + markPropertyAsReferenced(property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); + } + } + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + ts.forEach(node.name.elements, checkSourceElement); + } + if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + if (ts.isBindingPattern(node.name)) { + if (node.initializer && node.parent.parent.kind !== 215) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + if (node === symbol.valueDeclaration) { + if (node.initializer && node.parent.parent.kind !== 215) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); + checkParameterInitializer(node); + } + } + else { + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { + error(node.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(node.name), typeToString(type), typeToString(declarationType)); + } + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + 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)); + } + } + if (node.kind !== 149 && node.kind !== 148) { + checkExportsOnMergedDeclarations(node); + if (node.kind === 226 || node.kind === 176) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 146 && right.kind === 226) || + (left.kind === 226 && right.kind === 146)) { + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 | + 16 | + 256 | + 128 | + 64 | + 32; + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { + if (node.modifiers && node.parent.kind === 178) { + if (ts.getFunctionFlags(node) & 2) { + if (node.modifiers.length > 1) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function checkExpressionStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 209) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkExpression(node.expression); + } + function checkWhileStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.statement); + } + function checkForStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 227) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 227) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.kind === 216) { + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2) { + checkExternalEmitHelpers(node, 256); + } + } + if (node.initializer.kind === 227) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + if (varExpr.kind === 177 || varExpr.kind === 178) { + checkDestructuringAssignment(varExpr, iteratedType || unknownType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + if (iteratedType) { + checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + checkGrammarForInOrForOfStatement(node); + var rightType = checkNonNullExpression(node.expression); + if (node.initializer.kind === 227) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 177 || varExpr.kind === 178) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, true) || anyType; + } + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + var uplevelIteration = languageVersion >= 2; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + if (allowStringInput) { + if (arrayType.flags & 65536) { + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, true); + } + } + else if (arrayType.flags & 262178) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + if (arrayType.flags & 8192) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1); + if (hasStringConstituent && arrayElementType) { + if (arrayElementType.flags & 262178) { + return stringType; + } + return getUnionType([arrayElementType, stringType], true); + } + return arrayElementType; + } + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return typeAsIterable.iteratedTypeOfIterable; + } + if (isReferenceToType(type, getGlobalIterableType(false)) || + isReferenceToType(type, getGlobalIterableIteratorType(false))) { + return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType && getSignaturesOfType(methodType, 0); + if (!ts.some(signatures)) { + if (errorNode) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + return asyncMethodType + ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); + if (isTypeAny(nextResult)) { + return undefined; + } + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, !isAsyncGenerator, false) + || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + } + function isGetAccessorWithAnnotatedSetAccessor(node) { + return node.kind === 153 + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154)) !== undefined; + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 + ? getPromisedTypeOfPromise(returnType) + : returnType; + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + } + function checkReturnStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + var functionBlock = ts.getContainingFunction(node); + if (!functionBlock) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + } + } + var func = ts.getContainingFunction(node); + if (func) { + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + if (strictNullChecks || node.expression || returnType.flags & 8192) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return; + } + if (func.kind === 154) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 152) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableTo(exprType, returnType, node); + } + } + } + else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + } + function checkWithStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + if (clause.kind === 258 && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 257) { + var caseClause = clause; + var caseType = checkExpression(caseClause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 222 && current.label.escapedText === node.label.escapedText) { + var sourceFile = ts.getSourceFileOfNode(node); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); + return true; + } + }); + } + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); + var stringIndexType = getIndexTypeOfType(type, 0); + var numberIndexType = getIndexTypeOfType(type, 1); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); + }); + if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { + var classDeclaration = type.symbol.valueDeclaration; + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + if (!errorNode && (getObjectFlags(type) & 2)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + var propDeclaration = prop.valueDeclaration; + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + return; + } + var errorNode; + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (getObjectFlags(containingType) & 2) { + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + switch (name.escapedText) { + case "any": + case "number": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, typeParameters) { + var maxTypeArgumentCount = ts.length(typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var numTypeParameters = ts.length(declaration.typeParameters); + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = declaration.typeParameters[i]; + var target = typeParameters[i]; + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); + var targetConstraint = getConstraintFromTypeParameter(target); + if ((sourceConstraint || targetConstraint) && + (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { + return false; + } + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !(ts.getModifierFlags(node) & 512)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkTypeParameters(node.typeParameters); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + if (!ts.isInAmbientContext(node)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + if (languageVersion < 2) { + checkExternalEmitHelpers(baseTypeNode.parent, 1); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== unknownType) { + if (isValidBaseType(t)) { + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + } + else { + error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.getModifierFlags(declaration) & 8) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(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; }); + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 229 || d.kind === 230; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + 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) { + var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { + if (derivedClassDecl.kind === 199) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { + continue; + } + if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { + continue; + } + var errorMessage = void 0; + if (isMethodLike(base)) { + if (derived.flags & 98304) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 4) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkInterfaceDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384)) { + nodeLinks.flags |= 16384; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + 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); + } + } + 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; + } + } + 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; + case 47: return left >>> right; + case 45: return left << right; + case 50: return left ^ right; + case 39: return left * right; + case 41: return left / right; + case 37: return left + right; + case 38: return left - right; + case 42: return left % right; + } + } + 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.escapedText); + case 180: + case 179: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = void 0; + if (ex.kind === 179) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + 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; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isConst(node); + if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + if (declaration.kind !== 232) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 229 || + (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && + !ts.isInAmbientContext(declaration)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!inAmbientContext && node.name.kind === 9) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + if (symbol.flags & 512 + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + var mergedClass = ts.getDeclarationOfKind(symbol, 229); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 208: + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 243: + case 244: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 237: + case 238: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 176: + case 226: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + case 229: + case 232: + case 228: + case 230: + case 233: + case 231: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + var reportError = !(symbol.flags & 33554432); + if (!reportError) { + reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 71: + return node; + case 143: + do { + node = node.left; + } while (node.kind !== 71); + return node; + case 179: + do { + node = node.expression; + } while (node.kind !== 71); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 265 && !inAmbientExternalModule) { + error(moduleName, node.kind === 244 ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (!isTopLevelInExternalModuleAugmentation(node)) { + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | + (symbol.flags & 793064 ? 793064 : 0) | + (symbol.flags & 1920 ? 1920 : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 246 ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + if (compilerOptions.isolatedModules + && node.kind === 246 + && !(target.flags & 107455) + && !ts.isInAmbientContext(node)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 240) { + checkImportBinding(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.getModifierFlags(node) & 1) { + markExportAsReferenced(node); + } + if (ts.isInternalModuleImportEqualsDeclaration(node)) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 107455) { + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 793064) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + grammarErrorOnNode(node, ts.Diagnostics.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); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && + !node.moduleSpecifier && ts.isInAmbientContext(node); + if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + checkExternalEmitHelpers(node, 32768); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + return; + } + var container = node.parent.kind === 265 ? node.parent : node.parent.parent; + if (container.kind === 233 && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 71) { + markExportAsReferenced(node); + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (modulekind === ts.ModuleKind.System) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + var exports = getExportsOfModule(moduleSymbol); + exports && exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + if (flags & (1920 | 64 | 384)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + links.exportsChecked = true; + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 && declaration.kind !== 151) || + !!declaration.body; + } + } + function checkSourceElement(node) { + if (!node) { + return; + } + var kind = node.kind; + if (cancellationToken) { + switch (kind) { + case 233: + case 229: + case 230: + case 228: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 145: + return checkTypeParameter(node); + case 146: + return checkParameter(node); + case 149: + case 148: + return checkPropertyDeclaration(node); + case 160: + case 161: + case 155: + case 156: + return checkSignatureDeclaration(node); + case 157: + return checkSignatureDeclaration(node); + case 151: + case 150: + return checkMethodDeclaration(node); + case 152: + return checkConstructorDeclaration(node); + case 153: + case 154: + return checkAccessorDeclaration(node); + case 159: + return checkTypeReferenceNode(node); + case 158: + return checkTypePredicate(node); + case 162: + return checkTypeQuery(node); + case 163: + return checkTypeLiteral(node); + case 164: + return checkArrayType(node); + case 165: + return checkTupleType(node); + case 166: + case 167: + return checkUnionOrIntersectionType(node); + case 168: + case 170: + return checkSourceElement(node.type); + case 275: + return checkJSDocComment(node); + case 279: + return checkSourceElement(node.typeExpression); + case 273: + checkSignatureDeclaration(node); + case 274: + case 271: + case 270: + case 268: + case 269: + if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + return; + case 267: + return checkSourceElement(node.type); + case 171: + return checkIndexedAccessType(node); + case 172: + return checkMappedType(node); + case 228: + return checkFunctionDeclaration(node); + case 207: + case 234: + return checkBlock(node); + case 208: + return checkVariableStatement(node); + case 210: + return checkExpressionStatement(node); + case 211: + return checkIfStatement(node); + case 212: + return checkDoStatement(node); + case 213: + return checkWhileStatement(node); + case 214: + return checkForStatement(node); + case 215: + return checkForInStatement(node); + case 216: + return checkForOfStatement(node); + case 217: + case 218: + return checkBreakOrContinueStatement(node); + case 219: + return checkReturnStatement(node); + case 220: + return checkWithStatement(node); + case 221: + return checkSwitchStatement(node); + case 222: + return checkLabeledStatement(node); + case 223: + return checkThrowStatement(node); + case 224: + return checkTryStatement(node); + case 226: + return checkVariableDeclaration(node); + case 176: + return checkBindingElement(node); + case 229: + return checkClassDeclaration(node); + case 230: + return checkInterfaceDeclaration(node); + case 231: + return checkTypeAliasDeclaration(node); + case 232: + return checkEnumDeclaration(node); + case 233: + return checkModuleDeclaration(node); + case 238: + return checkImportDeclaration(node); + case 237: + return checkImportEqualsDeclaration(node); + case 244: + return checkExportDeclaration(node); + case 243: + return checkExportAssignment(node); + case 209: + checkGrammarStatementInAmbientContext(node); + return; + case 225: + checkGrammarStatementInAmbientContext(node); + return; + case 247: + return checkMissingDeclaration(node); + } + } + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 186: + case 187: + case 151: + case 150: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 153: + case 154: + checkAccessorDeclaration(node); + break; + case 199: + checkClassExpressionDeferred(node); + break; + } + } + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1)) { + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; + } + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + deferredNodes = []; + deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + ts.forEach(node.statements, checkSourceElement); + checkDeferredNodes(); + if (ts.isExternalModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile) { + checkUnusedIdentifiers(); + } + deferredNodes = undefined; + deferredUnusedIdentifierNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1; + } + } + function getDiagnostics(sourceFile, ct) { + try { + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + function isInsideWithStatementBody(node) { + if (node) { + while (node.parent) { + if (node.parent.kind === 220 && node.parent.statement === node) { + return true; + } + node = node.parent; + } + } + return false; + } + function getSymbolsInScope(location, meaning) { + if (isInsideWithStatementBody(location)) { + return []; + } + var symbols = ts.createSymbolTable(); + var memberFlags = 0; + populateSymbols(); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 233: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); + break; + case 232: + copySymbols(getSymbolOfNode(location).exports, meaning & 8); + break; + case 199: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + case 229: + case 230: + if (!(memberFlags & 32)) { + copySymbols(getSymbolOfNode(location).members, meaning & 793064); + } + break; + case 186: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + memberFlags = ts.getModifierFlags(location); + location = location.parent; + } + copySymbols(globals, meaning); + } + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 71 && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 145: + case 229: + case 230: + case 231: + case 232: + return true; + } + } + function isTypeReferenceIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 143) { + node = node.parent; + } + return node.parent && node.parent.kind === 159; + } + function isHeritageClauseElementIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 179) { + node = node.parent; + } + return node.parent && node.parent.kind === 201; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 143) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 237) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 243) { + return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1: + case 3: + return getSymbolOfNode(entityName.parent); + case 4: + case 2: + case 5: + return getSymbolOfNode(entityName.parent.parent); + } + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJavaScriptFile(entityName) && + entityName.parent.kind === 179 && + entityName.parent === entityName.parent.parent.left) { + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); + } + if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 237); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); + } + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0; + if (entityName.parent.kind === 201) { + meaning = 793064; + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 107455; + } + } + else { + meaning = 1920; + } + meaning |= 2097152; + var entityNameSymbol = resolveEntityName(entityName, meaning); + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 279) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 145 && entityName.parent.parent.kind === 282) { + ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isPartOfExpression(entityName)) { + if (ts.nodeIsMissing(entityName)) { + return undefined; + } + if (entityName.kind === 71) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + return getIntrinsicTagSymbol(entityName.parent); + } + return resolveEntityName(entityName, 107455, false, true); + } + else if (entityName.kind === 179 || entityName.kind === 143) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 179) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 159 ? 793064 : 1920; + return resolveEntityName(entityName, meaning, false, true); + } + else if (entityName.parent.kind === 253) { + return getJsxAttributePropertySymbol(entityName.parent); + } + if (entityName.parent.kind === 158) { + return resolveEntityName(entityName, 1); + } + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 265) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + if (isInsideWithStatementBody(node)) { + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + return getSymbolOfNode(node.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(node.parent.parent); + } + if (node.kind === 71) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (node.parent.kind === 176 && + node.parent.parent.kind === 174 && + node === node.parent.propertyName) { + var typeOfPattern = getTypeOfNode(node.parent.parent); + var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 71: + case 179: + case 143: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 99: + var container = ts.getThisContainer(node, false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + case 97: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); + return type.symbol; + case 169: + return getTypeFromTypeNode(node).symbol; + case 123: + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 152) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 9: + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { + return resolveExternalModuleName(node, node); + } + case 8: + if (node.parent.kind === 180 && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); + if (objectType === unknownType) + return undefined; + var apparentType = getApparentType(objectType); + if (apparentType === unknownType) + return undefined; + return getPropertyOfType(apparentType, node.text); + } + break; + } + return undefined; + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 262) { + return resolveEntityName(location.name, 107455 | 2097152); + } + return undefined; + } + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 2097152); + } + function getTypeOfNode(node) { + if (isInsideWithStatementBody(node)) { + return unknownType; + } + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + var containingClass = ts.getContainingClass(node); + var classType = getTypeOfNode(containingClass); + typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + } + return typeFromTypeNode; + } + if (ts.isPartOfExpression(node)) { + return getRegularTypeOfExpression(node); + } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + var classNode = ts.getContainingClass(node); + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var baseType = getBaseTypes(classType)[0]; + return baseType && getTypeWithThisArgument(baseType, classType.thisType); + } + if (isTypeDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + } + if (ts.isDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getTypeOfSymbol(symbol); + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, true); + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + } + return unknownType; + } + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 178 || expr.kind === 177); + if (expr.parent.kind === 216) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + if (expr.parent.kind === 194) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + if (expr.parent.kind === 261) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + } + ts.Debug.assert(expr.parent.kind === 177); + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + } + function getPropertySymbolOfDestructuringAssignment(location) { + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.getModifierFlags(node) & 32 + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function getRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; + var name_2 = symbol.escapedName; + ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { + var symbol = getPropertyOfType(t, name_2); + if (symbol) { + symbols_4.push(symbol); + } + }); + return symbols_4; + } + else if (symbol.flags & 33554432) { + var transient = symbol; + if (transient.leftSpread) { + return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); + } + if (transient.syntheticOrigin) { + return getRootSymbols(transient.syntheticOrigin); + } + var target = void 0; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + if (target) { + return [target]; + } + } + return [symbol]; + } + function isArgumentsLocalBinding(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + function getReferencedImportDeclaration(node) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (isNonLocalAlias(symbol, 107455)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined)) { + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072) { + var isDeclaredInLoop = nodeLinks_1.flags & 262144; + var inLoopInitializer = ts.isIterationStatement(container, false); + var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + function getReferencedDeclarationWithCollidingName(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + function isDeclarationWithCollidingName(node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 237: + case 239: + case 240: + case 242: + case 246: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 244: + var exportClause = node.exportClause; + return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + case 243: + return node.expression + && node.expression.kind === 71 + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(node) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + return target.flags & 107455 && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + } + if (checkChildren) { + return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + return signaturesOfSymbol.length > 1 || + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92); + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 264: + case 179: + case 180: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 264) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8)) { + if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { + return getEnumMemberValue(symbol.valueDeclaration); + } + } + return undefined; + } + function isFunctionType(type) { + return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; + } + function getTypeReferenceSerializationKind(typeName, location) { + var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); + var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === unknownType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 1) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeOfKind(type, 136)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeOfKind(type, 84)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeOfKind(type, 262178)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeOfKind(type, 512)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 | 131072)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : unknownType; + if (flags & 8192) { + type = getNullableType(type, 2048); + } + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + var signature = getSignatureFromDeclaration(signatureDeclaration); + getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + } + function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + var type = getWidenedType(getRegularTypeOfExpression(expr)); + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined); + } + function getReferencedValueDeclaration(reference) { + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 && type.flags & 1048576); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); + } + function createResolver() { + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : undefined; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + writeTypeOfDeclaration: writeTypeOfDeclaration, + writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, + writeTypeOfExpression: writeTypeOfExpression, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + }; + function getTypeReferenceDirectivesForEntityName(node) { + if (!fileToDirective) { + return undefined; + } + var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) + ? 107455 | 1048576 + : 793064 | 1920; + var symbol = resolveEntityName(node, meaning, true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + if (!symbol.declarations) { + return false; + } + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { + return false; + } + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 265); + } + function initializeTypeChecker() { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + if (augmentations) { + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + mergeModuleAugmentation(augmentation); + } + } + } + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); + getSymbolLinks(unknownSymbol).type = unknownType; + globalArrayType = getGlobalType("Array", 1, true); + globalObjectType = getGlobalType("Object", 0, true); + globalFunctionType = getGlobalType("Function", 0, true); + globalStringType = getGlobalType("String", 0, true); + globalNumberType = getGlobalType("Number", 0, true); + globalBooleanType = getGlobalType("Boolean", 0, true); + globalRegExpType = getGlobalType("RegExp", 0, true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", 1); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1; helper <= 32768; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1: return "__extends"; + case 2: return "__assign"; + case 4: return "__rest"; + case 8: return "__decorate"; + case 16: return "__metadata"; + case 32: return "__param"; + case 64: return "__awaiter"; + case 128: return "__generator"; + case 256: return "__values"; + case 512: return "__read"; + case 1024: return "__spread"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; + case 32768: return "__exportStar"; + default: ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node)) { + if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 153 || node.kind === 154) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var flags = 0; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 131) { + if (node.kind === 148 || node.kind === 150) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 157) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 76: + if (node.kind !== 232 && node.parent.kind === 229) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); + } + break; + case 114: + case 113: + case 112: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 113) { + lastProtected = modifier; + } + else if (modifier.kind === 112) { + lastPrivate = modifier; + } + if (flags & 28) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 234 || node.parent.kind === 265) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128) { + if (modifier.kind === 112) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 115: + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 234 || node.parent.kind === 265) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32; + lastStatic = modifier; + break; + case 131: + if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64; + lastReadonly = modifier; + break; + case 84: + if (flags & 1) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 229) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1; + break; + case 79: + var container = node.parent.kind === 265 ? node.parent : node.parent.parent; + if (container.kind === 233 && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512; + break; + case 124: + if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 229) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2; + lastDeclare = modifier; + break; + case 117: + if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 229) { + if (node.kind !== 151 && + node.kind !== 149 && + node.kind !== 153 && + node.kind !== 154) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128; + break; + case 120: + if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256; + lastAsync = modifier; + break; + } + } + if (node.kind === 152) { + if (flags & 32) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return; + } + else if ((node.kind === 238 || node.kind === 237) && flags & 2) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256) { + return checkGrammarAsyncModifier(node, lastAsync); + } + } + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 153: + case 154: + case 152: + case 149: + case 148: + case 151: + case 150: + case 157: + case 233: + case 238: + case 237: + case 244: + case 243: + case 186: + case 187: + case 146: + return false; + default: + if (node.parent.kind === 234 || node.parent.kind === 265) { + return false; + } + switch (node.kind) { + case 228: + return nodeHasAnyModifiersExcept(node, 120); + case 229: + return nodeHasAnyModifiersExcept(node, 117); + case 230: + case 208: + case 231: + return true; + case 232: + return nodeHasAnyModifiersExcept(node, 76); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 151: + case 228: + case 186: + case 187: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list) { + if (list && list.hasTrailingComma) { + var start = list.end - ",".length; + var end = list.end; + var sourceFile = ts.getSourceFileOfNode(list[0]); + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (checkGrammarForDisallowedTrailingComma(typeParameters)) { + return true; + } + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function checkGrammarFunctionLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (node.kind === 187) { + var arrowFunction = node; + var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + if (startLine !== endLine) { + return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + } + return false; + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.getModifierFlags(parameter) !== 0) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + } + function checkGrammarIndexSignature(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(node, args) { + if (args) { + var sourceFile = ts.getSourceFileOfNode(node); + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 200) { + return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + } + function checkGrammarArguments(node, args) { + return checkGrammarForOmittedArgument(node, args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + var sourceFile = ts.getSourceFileOfNode(node); + return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + if (node.kind !== 144) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 228 || + node.kind === 186 || + node.kind === 151); + if (ts.isInAmbientContext(node)) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + if (questionToken) { + return grammarErrorOnNode(questionToken, message); + } + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var seen = ts.createUnderscoreEscapedMap(); + var Property = 1; + var GetAccessor = 2; + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263) { + continue; + } + var name = prop.name; + if (name.kind === 144) { + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 120 || prop.kind !== 151) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + var currentKind = void 0; + if (prop.kind === 261 || prop.kind === 262) { + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8) { + checkGrammarNumericLiteral(name); + } + currentKind = Property; + } + else if (prop.kind === 151) { + currentKind = Property; + } + else if (prop.kind === 153) { + currentKind = GetAccessor; + } + else if (prop.kind === 154) { + currentKind = SetAccessor; + } + else { + ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === Property && existingKind === Property) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { + if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 255) { + continue; + } + var jsxAttr = attr; + var name = jsxAttr.name; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + var initializer = jsxAttr.initializer; + if (initializer && initializer.kind === 256 && !initializer.expression) { + return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384) === 0) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 227) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (ts.isInAmbientContext(accessor)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { + return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 153 ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 154) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + } + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarForNonSymbolComputedProperty(node, message) { + if (ts.isDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || + checkGrammarFunctionLikeDeclaration(node) || + checkGrammarForGenerator(node)) { + return true; + } + if (node.parent.kind === 178) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (ts.isClassLike(node.parent)) { + if (ts.isInAmbientContext(node)) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + } + else if (!node.body) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + } + } + else if (node.parent.kind === 230) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + } + else if (node.parent.kind === 163) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 222: + if (node.label && current.label.escapedText === node.label.escapedText) { + var isMisplacedContinueLabel = node.kind === 217 + && !ts.isIterationStatement(current.statement, true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 221: + if (node.kind === 218 && !node.label) { + return false; + } + break; + default: + if (ts.isIterationStatement(current, false) && !node.label) { + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 218 + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 218 + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.lastOrUndefined(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + if (node.name.kind === 175 || node.name.kind === 174) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (node.initializer) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 || expr.kind === 8 || + expr.kind === 192 && expr.operator === 38 && + expr.operand.kind === 8; + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { + if (ts.isInAmbientContext(node)) { + if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 71) { + if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 71) { + if (name.originalKeywordKind === 110) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 211: + case 212: + case 213: + case 220: + case 214: + case 215: + case 216: + return false; + case 222: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + if (node.keywordToken === 94) { + if (node.name.escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + } + function checkGrammarConstructorTypeParameters(node) { + if (node.typeParameters) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + if (node.type) { + return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + else if (node.parent.kind === 230) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 163) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (ts.isInAmbientContext(node) && node.initializer) { + return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + if (node.kind === 230 || + node.kind === 231 || + node.kind === 238 || + node.kind === 237 || + node.kind === 244 || + node.kind === 243 || + node.kind === 236 || + ts.getModifierFlags(node) & (2 | 1 | 512)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 208) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + } + function checkGrammarSourceFile(node) { + return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (ts.isInAmbientContext(node)) { + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { + var links_1 = getNodeLinks(node.parent); + if (!links_1.hasReportedStatementInAmbientContext) { + return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + } + } + } + function checkGrammarNumericLiteral(node) { + if (node.numericLiteralFlags & 4) { + var diagnosticMessage = void 0; + if (languageVersion >= 1) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 173)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 264)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); + return true; + } + } + function getAmbientModules() { + var result = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { + result.push(global); + } + }); + return result; + } + function checkGrammarImportCallExpression(node) { + if (modulekind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + } + } + ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + return true; + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 239: + case 237: + case 240: + case 242: + return true; + case 71: + return decl.parent.kind === 242; + default: + return false; + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -9917,13 +37589,13 @@ var ts; return node; } function createLiteralFromNode(sourceNode) { - var node = createStringLiteral(sourceNode.text); + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; return node; } function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); - node.text = ts.escapeIdentifier(text); + node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; @@ -9935,7 +37607,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(node.text, typeArguments), node) + ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -10109,13 +37781,14 @@ var ts; return node; } ts.createProperty = createProperty; - function updateProperty(node, decorators, modifiers, name, type, initializer) { + function updateProperty(node, decorators, modifiers, name, questionToken, type, initializer) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name + || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer), node) + ? updateNode(createProperty(decorators, modifiers, name, questionToken, type, initializer), node) : node; } ts.updateProperty = updateProperty; @@ -10155,6 +37828,7 @@ var ts; || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name + || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type @@ -10350,7 +38024,7 @@ var ts; ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { var node = createSynthesizedNode(164); - node.elementType = ts.parenthesizeElementTypeMember(elementType); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } ts.createArrayTypeNode = createArrayTypeNode; @@ -10551,7 +38225,7 @@ var ts; function updatePropertyAccess(node, expression, name) { return node.expression !== expression || node.name !== name - ? updateNode(setEmitFlags(createPropertyAccess(expression, name), getEmitFlags(node)), node) + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) : node; } ts.updatePropertyAccess = updatePropertyAccess; @@ -11821,28 +39495,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295); + var node = createSynthesizedNode(287); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299); + var node = createSynthesizedNode(291); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(290); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296); + var node = createSynthesizedNode(288); node.expression = expression; node.original = original; setTextRange(node, original); @@ -11858,7 +39532,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297) { + if (node.kind === 289) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -11868,7 +39542,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(289); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -11892,6 +39566,10 @@ var ts; return node; } ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; function createComma(left, right) { return createBinary(left, 26, right); } @@ -11994,11 +39672,6 @@ var ts; return range; } ts.setTextRange = setTextRange; - function getEmitFlags(node) { - var emitNode = node.emitNode; - return emitNode && emitNode.flags; - } - ts.getEmitFlags = getEmitFlags; function setEmitFlags(node, emitFlags) { getOrCreateEmitNode(node).flags = emitFlags; return node; @@ -12014,6 +39687,11 @@ var ts; return node; } ts.setSourceMapRange = setSourceMapRange; + var SourceMapSource; + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; function getTokenSourceMapRange(node, token) { var emitNode = node.emitNode; var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; @@ -12265,12 +39943,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(jsxFactory.right.text); - right.text = jsxFactory.right.text; + var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(jsxFactory.text, parent); + return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -12493,27 +40171,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_1 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_1.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_1.push(setter); + properties_8.push(setter); } - properties_1.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_1.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_1, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -12595,8 +40273,20 @@ var ts; return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); } ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + ts.Debug.assert(!!node.body); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (node.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; } function addPrologue(target, source, ensureUseStrict, visitor) { var offset = addStandardPrologue(target, source, ensureUseStrict); @@ -12651,8 +40341,8 @@ var ts; ts.startsWithUseStrict = startsWithUseStrict; function ensureUseStrict(statements) { var foundUseStrict = false; - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; if (ts.isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { foundUseStrict = true; @@ -12672,7 +40362,7 @@ var ts; } ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var skipped = skipPartiallyEmittedExpressions(operand); + var skipped = ts.skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { return operand; } @@ -12684,7 +40374,7 @@ var ts; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var binaryOperatorPrecedence = ts.getOperatorPrecedence(194, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(194, binaryOperator); - var emittedOperand = skipPartiallyEmittedExpressions(operand); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: @@ -12725,7 +40415,7 @@ var ts; || binaryOperator === 50; } function getLiteralKindOfBinaryPlusOperand(node) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } @@ -12745,7 +40435,7 @@ var ts; } function parenthesizeForConditionalHead(condition) { var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { return ts.createParen(condition); @@ -12760,7 +40450,7 @@ var ts; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; function parenthesizeForNew(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { case 181: return ts.createParen(expression); @@ -12773,7 +40463,7 @@ var ts; } ts.parenthesizeForNew = parenthesizeForNew; function parenthesizeForAccess(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 182 || emittedExpression.arguments)) { return expression; @@ -12811,7 +40501,7 @@ var ts; } ts.parenthesizeListElements = parenthesizeListElements; function parenthesizeExpressionForList(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); var commaPrecedence = ts.getOperatorPrecedence(194, 26); return expressionPrecedence > commaPrecedence @@ -12820,14 +40510,14 @@ var ts; } ts.parenthesizeExpressionForList = parenthesizeExpressionForList; function parenthesizeExpressionForExpressionStatement(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; - var kind = skipPartiallyEmittedExpressions(callee).kind; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; if (kind === 186 || kind === 187) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); - return recreatePartiallyEmittedExpressions(expression, mutableCall); + return recreateOuterExpressions(expression, mutableCall, 4); } } else { @@ -12850,31 +40540,32 @@ var ts; return member; } ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 162: + case 170: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; function parenthesizeElementTypeMembers(members) { return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); } ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; function parenthesizeTypeParameters(typeParameters) { if (ts.some(typeParameters)) { - var nodeArray = ts.createNodeArray(); + var params = []; for (var i = 0; i < typeParameters.length; ++i) { var entry = typeParameters[i]; - nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? ts.createParenthesizedType(entry) : entry); } - return nodeArray; + return ts.createNodeArray(params); } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { - if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { - var clone_1 = ts.getMutableClone(originalOuterExpression); - clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); - return clone_1; - } - return newInnerExpression; - } function getLeftmostExpression(node) { while (true) { switch (node.kind) { @@ -12892,7 +40583,7 @@ var ts; case 179: node = node.expression; continue; - case 296: + case 288: node = node.expression; continue; } @@ -12906,13 +40597,21 @@ 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 isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7; } + switch (node.kind) { + case 185: + return (kinds & 1) !== 0; + case 184: + case 202: + case 203: + return (kinds & 2) !== 0; + case 288: + return (kinds & 4) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7; } var previousNode; @@ -12925,7 +40624,7 @@ var ts; node = skipAssertions(node); } if (kinds & 4) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); } } while (previousNode !== node); return node; @@ -12939,19 +40638,29 @@ var ts; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node)) { + while (ts.isAssertionExpression(node) || node.kind === 203) { node = node.expression; } return node; } ts.skipAssertions = skipAssertions; - function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296) { - node = node.expression; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 185: return ts.updateParen(outerExpression, expression); + case 184: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 202: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 203: return ts.updateNonNullExpression(outerExpression, expression); + case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } - return node; } - ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7; } + if (outerExpression && isOuterExpression(outerExpression, kinds)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { node.startsOnNewLine = true; return node; @@ -12963,23 +40672,33 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { - if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } - var helpers = ts.getEmitHelpers(node); - if (helpers) { - for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { - var helper = helpers_2[_i]; - if (!helper.scoped) { - var parseNode = ts.getOriginalNode(node, ts.isSourceFile); - var emitNode = ts.getOrCreateEmitNode(parseNode); - return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = hasExportStarsToExportValues + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } } } } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } } } ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; @@ -13043,7 +40762,7 @@ var ts; if (ts.isAssignmentExpression(bindingElement, true)) { return bindingElement.right; } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); } } @@ -13066,7 +40785,7 @@ var ts; if (ts.isAssignmentExpression(bindingElement, true)) { return getTargetOfBindingOrAssignmentElement(bindingElement.left); } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return bindingElement; @@ -13192,28010 +40911,6 @@ var ts; return node; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; - function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { - var externalImports = []; - var exportSpecifiers = ts.createMultiMap(); - var exportedBindings = []; - var uniqueExports = ts.createMap(); - var exportedNames; - var hasExportDefault = false; - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); - var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - if (externalHelpersImportDeclaration) { - externalImports.push(externalHelpersImportDeclaration); - } - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 238: - externalImports.push(node); - break; - case 237: - if (node.moduleReference.kind === 248) { - externalImports.push(node); - } - break; - case 244: - if (node.moduleSpecifier) { - if (!node.exportClause) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - else { - externalImports.push(node); - } - } - else { - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - if (!uniqueExports.get(specifier.name.text)) { - var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(name.text, specifier); - var decl = resolver.getReferencedImportDeclaration(name) - || resolver.getReferencedValueDeclaration(name); - if (decl) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); - } - uniqueExports.set(specifier.name.text, true); - exportedNames = ts.append(exportedNames, specifier.name); - } - } - } - break; - case 243: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; - case 208: - if (ts.hasModifier(node, 1)) { - for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { - var decl = _e[_d]; - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); - } - } - break; - case 228: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - case 229: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - } - } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; - } - ts.collectExternalModuleInfo = collectExternalModuleInfo; - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { - if (ts.isBindingPattern(decl.name)) { - for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); - } - } - } - else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(decl.name.text)) { - uniqueExports.set(decl.name.text, true); - exportedNames = ts.append(exportedNames, decl.name); - } - } - return exportedNames; - } - function multiMapSparseArrayAdd(map, key, value) { - var values = map[key]; - if (values) { - values.push(value); - } - else { - map[key] = values = [value]; - } - return values; - } -})(ts || (ts = {})); -var ts; -(function (ts) { - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - function createNode(kind, pos, end) { - if (kind === 265) { - return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); - } - else if (kind === 71) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 143) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } - else { - return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); - } - } - ts.createNode = createNode; - function visitNode(cbNode, node) { - if (node) { - return cbNode(node); - } - } - function visitNodeArray(cbNodes, nodes) { - if (nodes) { - return cbNodes(nodes); - } - } - function visitEachNode(cbNode, nodes) { - if (nodes) { - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; - var result = cbNode(node); - if (result) { - return result; - } - } - } - } - function forEachChild(node, cbNode, cbNodeArray) { - if (!node) { - return; - } - var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; - var cbNodes = cbNodeArray || cbNode; - switch (node.kind) { - case 143: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); - case 145: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.constraint) || - visitNode(cbNode, node.default) || - visitNode(cbNode, node.expression); - case 262: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.equalsToken) || - visitNode(cbNode, node.objectAssignmentInitializer); - case 263: - return visitNode(cbNode, node.expression); - case 146: - case 149: - case 148: - case 261: - case 226: - case 176: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 160: - case 161: - case 155: - case 156: - case 157: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 151: - case 150: - case 152: - case 153: - case 154: - case 186: - case 228: - case 187: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.equalsGreaterThanToken) || - visitNode(cbNode, node.body); - case 159: - return visitNode(cbNode, node.typeName) || - visitNodes(cbNodes, node.typeArguments); - case 158: - return visitNode(cbNode, node.parameterName) || - visitNode(cbNode, node.type); - case 162: - return visitNode(cbNode, node.exprName); - case 163: - return visitNodes(cbNodes, node.members); - case 164: - return visitNode(cbNode, node.elementType); - case 165: - return visitNodes(cbNodes, node.elementTypes); - case 166: - case 167: - return visitNodes(cbNodes, node.types); - case 168: - case 170: - return visitNode(cbNode, node.type); - case 171: - return visitNode(cbNode, node.objectType) || - visitNode(cbNode, node.indexType); - case 172: - return visitNode(cbNode, node.readonlyToken) || - visitNode(cbNode, node.typeParameter) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); - case 173: - return visitNode(cbNode, node.literal); - case 174: - case 175: - return visitNodes(cbNodes, node.elements); - case 177: - return visitNodes(cbNodes, node.elements); - case 178: - return visitNodes(cbNodes, node.properties); - case 179: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.name); - case 180: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.argumentExpression); - case 181: - case 182: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments) || - visitNodes(cbNodes, node.arguments); - case 183: - return visitNode(cbNode, node.tag) || - visitNode(cbNode, node.template); - case 184: - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.expression); - case 188: - return visitNode(cbNode, node.expression); - case 189: - return visitNode(cbNode, node.expression); - case 190: - return visitNode(cbNode, node.expression); - case 192: - return visitNode(cbNode, node.operand); - case 197: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 191: - return visitNode(cbNode, node.expression); - case 193: - return visitNode(cbNode, node.operand); - case 194: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.operatorToken) || - visitNode(cbNode, node.right); - case 202: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.type); - case 203: - return visitNode(cbNode, node.expression); - case 204: - return visitNode(cbNode, node.name); - case 195: - return visitNode(cbNode, node.condition) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.whenTrue) || - visitNode(cbNode, node.colonToken) || - visitNode(cbNode, node.whenFalse); - case 198: - return visitNode(cbNode, node.expression); - case 207: - case 234: - return visitNodes(cbNodes, node.statements); - case 265: - return visitNodes(cbNodes, node.statements) || - visitNode(cbNode, node.endOfFileToken); - case 208: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.declarationList); - case 227: - return visitNodes(cbNodes, node.declarations); - case 210: - return visitNode(cbNode, node.expression); - case 211: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.thenStatement) || - visitNode(cbNode, node.elseStatement); - case 212: - return visitNode(cbNode, node.statement) || - visitNode(cbNode, node.expression); - case 213: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 214: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.condition) || - visitNode(cbNode, node.incrementor) || - visitNode(cbNode, node.statement); - case 215: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 216: - return visitNode(cbNode, node.awaitModifier) || - visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 217: - case 218: - return visitNode(cbNode, node.label); - case 219: - return visitNode(cbNode, node.expression); - case 220: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 221: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 235: - return visitNodes(cbNodes, node.clauses); - case 257: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 258: - return visitNodes(cbNodes, node.statements); - case 222: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); - case 223: - return visitNode(cbNode, node.expression); - case 224: - return visitNode(cbNode, node.tryBlock) || - visitNode(cbNode, node.catchClause) || - visitNode(cbNode, node.finallyBlock); - case 260: - return visitNode(cbNode, node.variableDeclaration) || - visitNode(cbNode, node.block); - case 147: - return visitNode(cbNode, node.expression); - case 229: - case 199: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 230: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 231: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); - case 232: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 264: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 233: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); - case 237: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); - case 238: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.importClause) || - visitNode(cbNode, node.moduleSpecifier); - case 239: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.namedBindings); - case 236: - return visitNode(cbNode, node.name); - case 240: - return visitNode(cbNode, node.name); - case 241: - case 245: - return visitNodes(cbNodes, node.elements); - case 244: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.exportClause) || - visitNode(cbNode, node.moduleSpecifier); - case 242: - case 246: - return visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name); - case 243: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.expression); - case 196: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 205: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144: - return visitNode(cbNode, node.expression); - case 259: - return visitNodes(cbNodes, node.types); - case 201: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments); - case 248: - 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) || - visitNode(cbNode, node.closingElement); - case 250: - case 251: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.attributes); - case 254: - return visitNodes(cbNodes, node.properties); - case 253: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 255: - return visitNode(cbNode, node.expression); - case 256: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.expression); - case 252: - return visitNode(cbNode, node.tagName); - case 267: - return visitNode(cbNode, node.type); - case 271: - return visitNodes(cbNodes, node.types); - case 272: - return visitNodes(cbNodes, node.types); - case 270: - return visitNode(cbNode, node.elementType); - case 274: - return visitNode(cbNode, node.type); - case 273: - return visitNode(cbNode, node.type); - case 275: - return visitNode(cbNode, node.literal); - case 277: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 278: - return visitNode(cbNode, node.type); - case 279: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 280: - return visitNode(cbNode, node.type); - case 281: - return visitNode(cbNode, node.type); - case 282: - return visitNode(cbNode, node.type); - case 276: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.type); - case 283: - return visitNodes(cbNodes, node.tags); - case 286: - return visitNode(cbNode, node.preParameterName) || - visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.postParameterName); - case 287: - return visitNode(cbNode, node.typeExpression); - case 288: - return visitNode(cbNode, node.typeExpression); - case 285: - return visitNode(cbNode, node.typeExpression); - case 289: - return visitNodes(cbNodes, node.typeParameters); - case 290: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.jsDocTypeLiteral); - case 292: - return visitNodes(cbNodes, node.jsDocPropertyTags); - case 291: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - case 296: - return visitNode(cbNode, node.expression); - case 293: - return visitNode(cbNode, node.literal); - } - } - ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { - if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); - return result; - } - ts.createSourceFile = createSourceFile; - function parseIsolatedEntityName(text, languageVersion) { - return Parser.parseIsolatedEntityName(text, languageVersion); - } - ts.parseIsolatedEntityName = parseIsolatedEntityName; - function isExternalModule(file) { - return file.externalModuleIndicator !== undefined; - } - ts.isExternalModule = isExternalModule; - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - } - ts.updateSourceFile = updateSourceFile; - function parseIsolatedJSDocComment(content, start, length) { - var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDoc) { - Parser.fixupParentReferences(result.jsDoc); - } - return result; - } - ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocTypeExpressionForTests(content, start, length) { - return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); - } - ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - var Parser; - (function (Parser) { - var scanner = ts.createScanner(5, true); - var disallowInAndDecoratorContext = 2048 | 8192; - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - var sourceFile; - var parseDiagnostics; - var syntaxCursor; - var currentToken; - var sourceText; - var nodeCount; - var identifiers; - var identifierCount; - var parsingContext; - var contextFlags; - var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { - scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); - clearState(); - return result; - } - Parser.parseSourceFile = parseSourceFile; - function parseIsolatedEntityName(content, languageVersion) { - initializeState(content, languageVersion, undefined, 1); - nextToken(); - var entityName = parseEntityName(true); - var isInvalid = token() === 1 && !parseDiagnostics.length; - clearState(); - return isInvalid ? entityName : undefined; - } - Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function getLanguageVariant(scriptKind) { - return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; - } - function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { - NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); - SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); - sourceText = _sourceText; - syntaxCursor = _syntaxCursor; - parseDiagnostics = []; - parsingContext = 0; - identifiers = ts.createMap(); - identifierCount = 0; - nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 65536 : 0; - parseErrorBeforeNextFinishedNode = false; - scanner.setText(sourceText); - scanner.setOnError(scanError); - scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(getLanguageVariant(scriptKind)); - } - function clearState() { - scanner.setText(""); - scanner.setOnError(undefined); - parseDiagnostics = undefined; - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); - sourceFile.flags = contextFlags; - nextToken(); - processReferenceComments(sourceFile); - sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token() === 1); - sourceFile.endOfFileToken = parseTokenNode(); - setExternalModuleIndicator(sourceFile); - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.identifiers = identifiers; - sourceFile.parseDiagnostics = parseDiagnostics; - if (setParentNodes) { - fixupParentReferences(sourceFile); - } - return sourceFile; - } - function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; - } - node.jsDoc.push(jsDoc); - } - } - return node; - } - function fixupParentReferences(rootNode) { - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDoc) { - for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - jsDoc.parent = n; - parent = jsDoc; - forEachChild(jsDoc, visitNode); - } - } - parent = saveParent; - } - } - } - Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); - nodeCount++; - sourceFile.text = sourceText; - sourceFile.bindDiagnostics = []; - sourceFile.languageVersion = languageVersion; - sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); - sourceFile.scriptKind = scriptKind; - return sourceFile; - } - function setContextFlag(val, flag) { - if (val) { - contextFlags |= flag; - } - else { - contextFlags &= ~flag; - } - } - function setDisallowInContext(val) { - setContextFlag(val, 2048); - } - function setYieldContext(val) { - setContextFlag(val, 4096); - } - function setDecoratorContext(val) { - setContextFlag(val, 8192); - } - function setAwaitContext(val) { - setContextFlag(val, 16384); - } - function doOutsideOfContext(context, func) { - var contextFlagsToClear = context & contextFlags; - if (contextFlagsToClear) { - setContextFlag(false, contextFlagsToClear); - var result = func(); - setContextFlag(true, contextFlagsToClear); - return result; - } - return func(); - } - function doInsideOfContext(context, func) { - var contextFlagsToSet = context & ~contextFlags; - if (contextFlagsToSet) { - setContextFlag(true, contextFlagsToSet); - var result = func(); - setContextFlag(false, contextFlagsToSet); - return result; - } - return func(); - } - function allowInAnd(func) { - return doOutsideOfContext(2048, func); - } - function disallowInAnd(func) { - return doInsideOfContext(2048, func); - } - function doInYieldContext(func) { - return doInsideOfContext(4096, func); - } - function doInDecoratorContext(func) { - return doInsideOfContext(8192, func); - } - function doInAwaitContext(func) { - return doInsideOfContext(16384, func); - } - function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(16384, func); - } - function doInYieldAndAwaitContext(func) { - return doInsideOfContext(4096 | 16384, func); - } - function inContext(flags) { - return (contextFlags & flags) !== 0; - } - function inYieldContext() { - return inContext(4096); - } - function inDisallowInContext() { - return inContext(2048); - } - function inDecoratorContext() { - return inContext(8192); - } - function inAwaitContext() { - return inContext(16384); - } - function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); - } - function parseErrorAtPosition(start, length, message, arg0) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (!lastError || start !== lastError.start) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); - } - parseErrorBeforeNextFinishedNode = true; - } - function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); - } - function getNodePos() { - return scanner.getStartPos(); - } - function getNodeEnd() { - return scanner.getStartPos(); - } - function token() { - return currentToken; - } - function nextToken() { - return currentToken = scanner.scan(); - } - function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); - } - function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); - } - function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); - } - function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); - } - function scanJsxText() { - return currentToken = scanner.scanJsxToken(); - } - function scanJsxAttributeValue() { - return currentToken = scanner.scanJsxAttributeValue(); - } - function speculationHelper(callback, isLookAhead) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var saveContextFlags = contextFlags; - var result = isLookAhead - ? scanner.lookAhead(callback) - : scanner.tryScan(callback); - ts.Debug.assert(saveContextFlags === contextFlags); - if (!result || isLookAhead) { - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - } - return result; - } - function lookAhead(callback) { - return speculationHelper(callback, true); - } - function tryParse(callback) { - return speculationHelper(callback, false); - } - function isIdentifier() { - if (token() === 71) { - return true; - } - if (token() === 116 && inYieldContext()) { - return false; - } - if (token() === 121 && inAwaitContext()) { - return false; - } - return token() > 107; - } - function parseExpected(kind, diagnosticMessage, shouldAdvance) { - if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { - if (shouldAdvance) { - nextToken(); - } - return true; - } - if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage); - } - else { - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); - } - return false; - } - function parseOptional(t) { - if (token() === t) { - nextToken(); - return true; - } - return false; - } - function parseOptionalToken(t) { - if (token() === t) { - return parseTokenNode(); - } - return undefined; - } - function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { - return parseOptionalToken(t) || - createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); - } - function parseTokenNode() { - var node = createNode(token()); - nextToken(); - return finishNode(node); - } - function canParseSemicolon() { - if (token() === 25) { - return true; - } - return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); - } - function parseSemicolon() { - if (canParseSemicolon()) { - if (token() === 25) { - nextToken(); - } - return true; - } - else { - return parseExpected(25); - } - } - function createNode(kind, pos) { - nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); - } - return kind >= 143 ? new NodeConstructor(kind, pos, pos) : - kind === 71 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); - } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } - array.pos = pos; - array.end = pos; - return array; - } - function finishNode(node, end) { - node.end = end === undefined ? scanner.getStartPos() : end; - if (contextFlags) { - node.flags |= contextFlags; - } - if (parseErrorBeforeNextFinishedNode) { - parseErrorBeforeNextFinishedNode = false; - node.flags |= 32768; - } - return node; - } - function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { - if (reportAtCurrentPosition) { - parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); - } - else { - parseErrorAtCurrentToken(diagnosticMessage, arg0); - } - var result = createNode(kind, scanner.getStartPos()); - result.text = ""; - return finishNode(result); - } - function internIdentifier(text) { - text = ts.escapeIdentifier(text); - var identifier = identifiers.get(text); - if (identifier === undefined) { - identifiers.set(text, identifier = text); - } - return identifier; - } - function createIdentifier(isIdentifier, diagnosticMessage) { - identifierCount++; - if (isIdentifier) { - var node = createNode(71); - if (token() !== 71) { - node.originalKeywordKind = token(); - } - node.text = internIdentifier(scanner.getTokenValue()); - nextToken(); - return finishNode(node); - } - return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); - } - function parseIdentifier(diagnosticMessage) { - return createIdentifier(isIdentifier(), diagnosticMessage); - } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8; - } - function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { - return parseLiteralNode(true); - } - if (allowComputedPropertyNames && token() === 21) { - return parseComputedPropertyName(); - } - return parseIdentifierName(); - } - function parsePropertyName() { - return parsePropertyNameWorker(true); - } - function parseSimplePropertyName() { - return parsePropertyNameWorker(false); - } - function isSimplePropertyName() { - return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); - } - function parseComputedPropertyName() { - var node = createNode(144); - parseExpected(21); - node.expression = allowInAnd(parseExpression); - parseExpected(22); - return finishNode(node); - } - function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); - } - function nextTokenIsOnSameLineAndCanFollowModifier() { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); - } - function nextTokenCanFollowModifier() { - if (token() === 76) { - return nextToken() === 83; - } - if (token() === 84) { - nextToken(); - if (token() === 79) { - return lookAhead(nextTokenIsClassOrFunctionOrAsync); - } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); - } - if (token() === 79) { - return nextTokenIsClassOrFunctionOrAsync(); - } - if (token() === 115) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); - } - function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); - } - function canFollowModifier() { - return token() === 21 - || token() === 17 - || token() === 39 - || token() === 24 - || isLiteralPropertyName(); - } - function nextTokenIsClassOrFunctionOrAsync() { - nextToken(); - return token() === 75 || token() === 89 || - (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); - } - function isListElement(parsingContext, inErrorRecovery) { - var node = currentNode(parsingContext); - if (node) { - return true; - } - switch (parsingContext) { - case 0: - case 1: - case 3: - return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); - case 2: - return token() === 73 || token() === 79; - case 4: - return lookAhead(isTypeMemberStart); - case 5: - return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); - case 6: - return token() === 21 || isLiteralPropertyName(); - case 12: - return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); - case 17: - return isLiteralPropertyName(); - case 9: - return token() === 21 || token() === 24 || isLiteralPropertyName(); - case 7: - if (token() === 17) { - return lookAhead(isValidHeritageClauseObjectLiteral); - } - if (!inErrorRecovery) { - return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - else { - return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - case 8: - return isIdentifierOrPattern(); - case 10: - return token() === 26 || token() === 24 || isIdentifierOrPattern(); - case 18: - return isIdentifier(); - case 11: - case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); - case 16: - return isStartOfParameter(); - case 19: - case 20: - return token() === 26 || isStartOfType(); - case 21: - return isHeritageClause(); - case 22: - return ts.tokenIsIdentifierOrKeyword(token()); - case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; - case 14: - return true; - case 23: - case 24: - case 26: - return JSDocParser.isJSDocType(); - case 25: - return isSimplePropertyName(); - } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); - } - function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17); - if (nextToken() === 18) { - var next = nextToken(); - return next === 26 || next === 17 || next === 85 || next === 108; - } - return true; - } - function nextTokenIsIdentifier() { - nextToken(); - return isIdentifier(); - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); - } - function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 || - token() === 85) { - return lookAhead(nextTokenIsStartOfExpression); - } - return false; - } - function nextTokenIsStartOfExpression() { - nextToken(); - return isStartOfExpression(); - } - function isListTerminator(kind) { - if (token() === 1) { - return true; - } - switch (kind) { - case 1: - case 2: - case 4: - case 5: - case 6: - case 12: - case 9: - case 22: - return token() === 18; - case 3: - return token() === 18 || token() === 73 || token() === 79; - case 7: - return token() === 17 || token() === 85 || token() === 108; - case 8: - return isVariableDeclaratorListTerminator(); - case 18: - return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; - case 11: - return token() === 20 || token() === 25; - case 15: - case 20: - case 10: - return token() === 22; - case 16: - case 17: - return token() === 20 || token() === 22; - case 19: - return token() !== 26; - case 21: - return token() === 17 || token() === 18; - case 13: - return token() === 29 || token() === 41; - case 14: - return token() === 27 && lookAhead(nextTokenIsSlash); - case 23: - return token() === 20 || token() === 56 || token() === 18; - case 24: - return token() === 29 || token() === 18; - case 26: - return token() === 22 || token() === 18; - case 25: - return token() === 18; - } - } - function isVariableDeclaratorListTerminator() { - if (canParseSemicolon()) { - return true; - } - if (isInOrOfKeyword(token())) { - return true; - } - if (token() === 36) { - return true; - } - return false; - } - function isInSomeParsingContext() { - for (var kind = 0; kind < 27; kind++) { - if (parsingContext & (1 << kind)) { - if (isListElement(kind, true) || isListTerminator(kind)) { - return true; - } - } - } - return false; - } - function parseList(kind, parseElement) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - while (!isListTerminator(kind)) { - if (isListElement(kind, false)) { - var element = parseListElement(kind, parseElement); - result.push(element); - continue; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function parseListElement(parsingContext, parseElement) { - var node = currentNode(parsingContext); - if (node) { - return consumeNode(node); - } - return parseElement(); - } - function currentNode(parsingContext) { - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - return undefined; - } - var node = syntaxCursor.currentNode(scanner.getStartPos()); - if (ts.nodeIsMissing(node)) { - return undefined; - } - if (node.intersectsChange) { - return undefined; - } - if (ts.containsParseError(node)) { - return undefined; - } - var nodeContextFlags = node.flags & 96256; - if (nodeContextFlags !== contextFlags) { - return undefined; - } - if (!canReuseNode(node, parsingContext)) { - return undefined; - } - return node; - } - function consumeNode(node) { - scanner.setTextPos(node.end); - nextToken(); - return node; - } - function canReuseNode(node, parsingContext) { - switch (parsingContext) { - case 5: - return isReusableClassMember(node); - case 2: - return isReusableSwitchClause(node); - case 0: - case 1: - case 3: - return isReusableStatement(node); - case 6: - return isReusableEnumMember(node); - case 4: - return isReusableTypeMember(node); - case 8: - return isReusableVariableDeclaration(node); - case 16: - return isReusableParameter(node); - case 17: - return false; - case 21: - case 18: - case 20: - case 19: - case 11: - case 12: - case 7: - case 13: - case 14: - } - return false; - } - function isReusableClassMember(node) { - if (node) { - switch (node.kind) { - case 152: - case 157: - case 153: - case 154: - case 149: - case 206: - return true; - case 151: - var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 && - methodDeclaration.name.originalKeywordKind === 123; - return !nameIsConstructor; - } - } - return false; - } - function isReusableSwitchClause(node) { - if (node) { - switch (node.kind) { - case 257: - case 258: - return true; - } - } - return false; - } - function isReusableStatement(node) { - if (node) { - switch (node.kind) { - case 228: - case 208: - case 207: - case 211: - case 210: - case 223: - case 219: - case 221: - case 218: - case 217: - case 215: - case 216: - case 214: - case 213: - case 220: - case 209: - case 224: - case 222: - case 212: - case 225: - case 238: - case 237: - case 244: - case 243: - case 233: - case 229: - case 230: - case 232: - case 231: - return true; - } - } - return false; - } - function isReusableEnumMember(node) { - return node.kind === 264; - } - function isReusableTypeMember(node) { - if (node) { - switch (node.kind) { - case 156: - case 150: - case 157: - case 148: - case 155: - return true; - } - } - return false; - } - function isReusableVariableDeclaration(node) { - if (node.kind !== 226) { - return false; - } - var variableDeclarator = node; - return variableDeclarator.initializer === undefined; - } - function isReusableParameter(node) { - if (node.kind !== 146) { - return false; - } - var parameter = node; - return parameter.initializer === undefined; - } - function abortParsingListOrMoveToNextToken(kind) { - parseErrorAtCurrentToken(parsingContextErrors(kind)); - if (isInSomeParsingContext()) { - return true; - } - nextToken(); - return false; - } - function parsingContextErrors(context) { - switch (context) { - case 0: return ts.Diagnostics.Declaration_or_statement_expected; - case 1: return ts.Diagnostics.Declaration_or_statement_expected; - case 2: return ts.Diagnostics.case_or_default_expected; - case 3: return ts.Diagnostics.Statement_expected; - case 17: - case 4: return ts.Diagnostics.Property_or_signature_expected; - case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; - case 6: return ts.Diagnostics.Enum_member_expected; - case 7: return ts.Diagnostics.Expression_expected; - case 8: return ts.Diagnostics.Variable_declaration_expected; - case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; - case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; - case 11: return ts.Diagnostics.Argument_expression_expected; - case 12: return ts.Diagnostics.Property_assignment_expected; - case 15: return ts.Diagnostics.Expression_or_comma_expected; - case 16: return ts.Diagnostics.Parameter_declaration_expected; - case 18: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19: return ts.Diagnostics.Type_argument_expected; - case 20: return ts.Diagnostics.Type_expected; - case 21: return ts.Diagnostics.Unexpected_token_expected; - case 22: return ts.Diagnostics.Identifier_expected; - case 13: return ts.Diagnostics.Identifier_expected; - case 14: return ts.Diagnostics.Identifier_expected; - case 23: return ts.Diagnostics.Parameter_declaration_expected; - case 24: return ts.Diagnostics.Type_argument_expected; - case 26: return ts.Diagnostics.Type_expected; - case 25: return ts.Diagnostics.Property_assignment_expected; - } - } - function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - var commaStart = -1; - while (true) { - if (isListElement(kind, false)) { - result.push(parseListElement(kind, parseElement)); - commaStart = scanner.getTokenPos(); - if (parseOptional(26)) { - continue; - } - commaStart = -1; - if (isListTerminator(kind)) { - break; - } - parseExpected(26); - if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - } - continue; - } - if (isListTerminator(kind)) { - break; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - if (commaStart >= 0) { - result.hasTrailingComma = true; - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function createMissingList() { - return createNodeArray(); - } - function parseBracketedList(kind, parseElement, open, close) { - if (parseExpected(open)) { - var result = parseDelimitedList(kind, parseElement); - parseExpected(close); - return result; - } - return createMissingList(); - } - function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(23)) { - var node = createNode(143, entity.pos); - node.left = entity; - node.right = parseRightSideOfDot(allowReservedWords); - entity = finishNode(node); - } - return entity; - } - function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { - var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - if (matchesPattern) { - return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); - } - } - return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); - } - function parseTemplateExpression() { - var template = createNode(196); - template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); - do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; - return finishNode(template); - } - function parseTemplateSpan() { - var span = createNode(205); - span.expression = allowInAnd(parseExpression); - var literal; - if (token() === 18) { - reScanTemplateToken(); - literal = parseTemplateMiddleOrTemplateTail(); - } - else { - literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); - } - span.literal = literal; - return finishNode(span); - } - function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); - } - function parseTemplateHead() { - var fragment = parseLiteralLikeNode(token(), false); - ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); - return fragment; - } - function parseTemplateMiddleOrTemplateTail() { - var fragment = parseLiteralLikeNode(token(), false); - ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); - return fragment; - } - function parseLiteralLikeNode(kind, internName) { - var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = internName ? internIdentifier(text) : text; - if (scanner.hasExtendedUnicodeEscape()) { - node.hasExtendedUnicodeEscape = true; - } - if (scanner.isUnterminated()) { - node.isUnterminated = true; - } - if (node.kind === 8) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); - } - nextToken(); - finishNode(node); - return node; - } - function parseTypeReference() { - var node = createNode(159); - node.typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } - return finishNode(node); - } - function parseThisTypePredicate(lhs) { - nextToken(); - var node = createNode(158, lhs.pos); - node.parameterName = lhs; - node.type = parseType(); - return finishNode(node); - } - function parseThisTypeNode() { - var node = createNode(169); - nextToken(); - return finishNode(node); - } - function parseTypeQuery() { - var node = createNode(162); - parseExpected(103); - node.exprName = parseEntityName(true); - return finishNode(node); - } - function parseTypeParameter() { - var node = createNode(145); - node.name = parseIdentifier(); - if (parseOptional(85)) { - if (isStartOfType() || !isStartOfExpression()) { - node.constraint = parseType(); - } - else { - node.expression = parseUnaryExpressionOrHigher(); - } - } - if (parseOptional(58)) { - node.default = parseType(); - } - return finishNode(node); - } - function parseTypeParameters() { - if (token() === 27) { - return parseBracketedList(18, parseTypeParameter, 27, 29); - } - } - function parseParameterType() { - if (parseOptional(56)) { - return parseType(); - } - return undefined; - } - function isStartOfParameter() { - return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 || token() === 99; - } - function parseParameter() { - var node = createNode(146); - if (token() === 99) { - node.name = createIdentifier(true); - node.type = parseParameterType(); - return finishNode(node); - } - node.decorators = parseDecorators(); - node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24); - node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { - nextToken(); - } - node.questionToken = parseOptionalToken(55); - node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(true); - return addJSDocComment(finishNode(node)); - } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(true); - } - function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 36; - signature.typeParameters = parseTypeParameters(); - signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); - if (returnTokenRequired) { - parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); - } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); - } - } - function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - if (parseExpected(19)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(yieldContext); - setAwaitContext(awaitContext); - var result = parseDelimitedList(16, parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20) && requireCompleteParameterList) { - return undefined; - } - return result; - } - return requireCompleteParameterList ? undefined : createMissingList(); - } - function parseTypeMemberSemicolon() { - if (parseOptional(26)) { - return; - } - parseSemicolon(); - } - function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156) { - parseExpected(94); - } - fillSignature(56, false, false, false, node); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); - } - function isIndexSignature() { - if (token() !== 21) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); - } - function isUnambiguouslyIndexSignature() { - nextToken(); - if (token() === 24 || token() === 22) { - return true; - } - if (ts.isModifierKind(token())) { - nextToken(); - if (isIdentifier()) { - return true; - } - } - else if (!isIdentifier()) { - return false; - } - else { - nextToken(); - } - if (token() === 56 || token() === 26) { - return true; - } - if (token() !== 55) { - return false; - } - nextToken(); - return token() === 56 || token() === 26 || token() === 22; - } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.parameters = parseBracketedList(16, parseParameter, 21, 22); - node.type = parseTypeAnnotation(); - parseTypeMemberSemicolon(); - return finishNode(node); - } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (token() === 19 || token() === 27) { - var method = createNode(150, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - fillSignature(56, false, false, false, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); - } - else { - var property = createNode(148, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - if (token() === 58) { - property.initializer = parseNonParameterInitializer(); - } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); - } - } - function isTypeMemberStart() { - if (token() === 19 || token() === 27) { - return true; - } - var idToken; - while (ts.isModifierKind(token())) { - idToken = true; - nextToken(); - } - if (token() === 21) { - return true; - } - if (isLiteralPropertyName()) { - idToken = true; - nextToken(); - } - if (idToken) { - return token() === 19 || - token() === 27 || - token() === 55 || - token() === 56 || - token() === 26 || - canParseSemicolon(); - } - return false; - } - function parseTypeMember() { - if (token() === 19 || token() === 27) { - return parseSignatureMember(155); - } - if (token() === 94 && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(156); - } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); - } - return parsePropertyOrMethodSignature(fullStart, modifiers); - } - function isStartOfConstructSignature() { - nextToken(); - return token() === 19 || token() === 27; - } - function parseTypeLiteral() { - var node = createNode(163); - node.members = parseObjectTypeMembers(); - return finishNode(node); - } - function parseObjectTypeMembers() { - var members; - if (parseExpected(17)) { - members = parseList(4, parseTypeMember); - parseExpected(18); - } - else { - members = createMissingList(); - } - return members; - } - function isStartOfMappedType() { - nextToken(); - if (token() === 131) { - nextToken(); - } - return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; - } - function parseMappedTypeParameter() { - var node = createNode(145); - node.name = parseIdentifier(); - parseExpected(92); - node.constraint = parseType(); - return finishNode(node); - } - function parseMappedType() { - var node = createNode(172); - parseExpected(17); - node.readonlyToken = parseOptionalToken(131); - parseExpected(21); - node.typeParameter = parseMappedTypeParameter(); - parseExpected(22); - node.questionToken = parseOptionalToken(55); - node.type = parseTypeAnnotation(); - parseSemicolon(); - parseExpected(18); - return finishNode(node); - } - function parseTupleType() { - var node = createNode(165); - node.elementTypes = parseBracketedList(20, parseType, 21, 22); - return finishNode(node); - } - function parseParenthesizedType() { - var node = createNode(168); - parseExpected(19); - node.type = parseType(); - parseExpected(20); - return finishNode(node); - } - function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161) { - parseExpected(94); - } - fillSignature(36, false, false, false, node); - return finishNode(node); - } - function parseKeywordAndNoDot() { - var node = parseTokenNode(); - return token() === 23 ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(173); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8; - } - function parseNonArrayType() { - switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 139: - case 130: - case 134: - var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); - case 9: - case 8: - case 101: - case 86: - return parseLiteralTypeNode(); - case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 105: - case 95: - return parseTokenNode(); - case 99: { - var thisKeyword = parseThisTypeNode(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { - return parseThisTypePredicate(thisKeyword); - } - else { - return thisKeyword; - } - } - case 103: - return parseTypeQuery(); - case 17: - return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21: - return parseTupleType(); - case 19: - return parseParenthesizedType(); - default: - return parseTypeReference(); - } - } - function isStartOfType() { - switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 105: - case 139: - case 95: - case 99: - case 103: - case 130: - case 17: - case 21: - case 27: - case 49: - case 48: - case 94: - case 9: - case 8: - case 101: - case 86: - case 134: - return true; - case 38: - return lookAhead(nextTokenIsNumericLiteral); - case 19: - return lookAhead(isStartOfParenthesizedOrFunctionType); - default: - return isIdentifier(); - } - } - function isStartOfParenthesizedOrFunctionType() { - nextToken(); - return token() === 20 || isStartOfParameter() || isStartOfType(); - } - function parseArrayTypeOrHigher() { - var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { - if (isStartOfType()) { - var node = createNode(171, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22); - type = finishNode(node); - } - else { - var node = createNode(164, type.pos); - node.elementType = type; - parseExpected(22); - type = finishNode(node); - } - } - return type; - } - function parseTypeOperator(operator) { - var node = createNode(170); - parseExpected(operator); - node.operator = operator; - node.type = parseTypeOperatorOrHigher(); - return finishNode(node); - } - function parseTypeOperatorOrHigher() { - switch (token()) { - case 127: - return parseTypeOperator(127); - } - return parseArrayTypeOrHigher(); - } - function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { - parseOptional(operator); - var type = parseConstituentType(); - if (token() === operator) { - var types = createNodeArray([type], type.pos); - while (parseOptional(operator)) { - types.push(parseConstituentType()); - } - types.end = getNodeEnd(); - var node = createNode(kind, type.pos); - node.types = types; - type = finishNode(node); - } - return type; - } - function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); - } - function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); - } - function isStartOfFunctionType() { - if (token() === 27) { - return true; - } - return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); - } - function skipParameterStart() { - if (ts.isModifierKind(token())) { - parseModifiers(); - } - if (isIdentifier() || token() === 99) { - nextToken(); - return true; - } - if (token() === 21 || token() === 17) { - var previousErrorCount = parseDiagnostics.length; - parseIdentifierOrPattern(); - return previousErrorCount === parseDiagnostics.length; - } - return false; - } - function isUnambiguouslyStartOfFunctionType() { - nextToken(); - if (token() === 20 || token() === 24) { - return true; - } - if (skipParameterStart()) { - if (token() === 56 || token() === 26 || - token() === 55 || token() === 58) { - return true; - } - if (token() === 20) { - nextToken(); - if (token() === 36) { - return true; - } - } - } - return false; - } - function parseTypeOrTypePredicate() { - var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); - var type = parseType(); - if (typePredicateVariable) { - var node = createNode(158, typePredicateVariable.pos); - node.parameterName = typePredicateVariable; - node.type = type; - return finishNode(node); - } - else { - return type; - } - } - function parseTypePredicatePrefix() { - var id = parseIdentifier(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - return id; - } - } - function parseType() { - return doOutsideOfContext(20480, parseTypeWorker); - } - function parseTypeWorker() { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160); - } - if (token() === 94) { - return parseFunctionOrConstructorType(161); - } - return parseUnionTypeOrHigher(); - } - function parseTypeAnnotation() { - return parseOptional(56) ? parseType() : undefined; - } - function isStartOfLeftHandSideExpression() { - switch (token()) { - case 99: - case 97: - case 95: - case 101: - case 86: - case 8: - case 9: - case 13: - case 14: - case 19: - case 21: - case 17: - case 89: - case 75: - case 94: - case 41: - case 63: - case 71: - return true; - default: - return isIdentifier(); - } - } - function isStartOfExpression() { - if (isStartOfLeftHandSideExpression()) { - return true; - } - switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 43: - case 44: - case 27: - case 121: - case 116: - return true; - default: - if (isBinaryOperator()) { - return true; - } - return isIdentifier(); - } - } - function isStartOfExpressionStatement() { - return token() !== 17 && - token() !== 89 && - token() !== 75 && - token() !== 57 && - isStartOfExpression(); - } - function parseExpression() { - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var expr = parseAssignmentExpressionOrHigher(); - var operatorToken; - while ((operatorToken = parseOptionalToken(26))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); - } - if (saveDecoratorContext) { - setDecoratorContext(true); - } - return expr; - } - function parseInitializer(inParameter) { - if (token() !== 58) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { - return undefined; - } - } - parseExpected(58); - return parseAssignmentExpressionOrHigher(); - } - function parseAssignmentExpressionOrHigher() { - if (isYieldExpression()) { - return parseYieldExpression(); - } - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); - if (arrowExpression) { - return arrowExpression; - } - var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 71 && token() === 36) { - return parseSimpleArrowFunctionExpression(expr); - } - if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); - } - return parseConditionalExpressionRest(expr); - } - function isYieldExpression() { - if (token() === 116) { - if (inYieldContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); - } - return false; - } - function nextTokenIsIdentifierOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && isIdentifier(); - } - function parseYieldExpression() { - var node = createNode(197); - nextToken(); - if (!scanner.hasPrecedingLineBreak() && - (token() === 39 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - else { - return finishNode(node); - } - } - function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node; - if (asyncModifier) { - node = createNode(187, asyncModifier.pos); - node.modifiers = asyncModifier; - } - else { - node = createNode(187, identifier.pos); - } - var parameter = createNode(146, identifier.pos); - parameter.name = identifier; - finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - node.body = parseArrowFunctionExpressionBody(!!asyncModifier); - return addJSDocComment(finishNode(node)); - } - function tryParseParenthesizedArrowFunctionExpression() { - var triState = isParenthesizedArrowFunctionExpression(); - if (triState === 0) { - return undefined; - } - var arrowFunction = triState === 1 - ? parseParenthesizedArrowFunctionExpressionHead(true) - : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); - if (!arrowFunction) { - return undefined; - } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); - var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 36 || lastToken === 17) - ? parseArrowFunctionExpressionBody(isAsync) - : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); - } - function isParenthesizedArrowFunctionExpression() { - if (token() === 19 || token() === 27 || token() === 120) { - return lookAhead(isParenthesizedArrowFunctionExpressionWorker); - } - if (token() === 36) { - return 1; - } - return 0; - } - function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120) { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return 0; - } - if (token() !== 19 && token() !== 27) { - return 0; - } - } - var first = token(); - var second = nextToken(); - if (first === 19) { - if (second === 20) { - var third = nextToken(); - switch (third) { - case 36: - case 56: - case 17: - return 1; - default: - return 0; - } - } - if (second === 21 || second === 17) { - return 2; - } - if (second === 24) { - return 1; - } - if (!isIdentifier()) { - return 0; - } - if (nextToken() === 56) { - return 1; - } - return 2; - } - else { - ts.Debug.assert(first === 27); - if (!isIdentifier()) { - return 0; - } - if (sourceFile.languageVariant === 1) { - var isArrowFunctionInJsx = lookAhead(function () { - var third = nextToken(); - if (third === 85) { - var fourth = nextToken(); - switch (fourth) { - case 58: - case 29: - return false; - default: - return true; - } - } - else if (third === 26) { - return true; - } - return false; - }); - if (isArrowFunctionInJsx) { - return 1; - } - return 0; - } - return 2; - } - } - function parsePossibleParenthesizedArrowFunctionExpressionHead() { - return parseParenthesizedArrowFunctionExpressionHead(false); - } - function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 120) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1) { - var asyncModifier = parseModifiersForArrowFunction(); - var expr = parseBinaryExpressionOrHigher(0); - return parseSimpleArrowFunctionExpression(expr, asyncModifier); - } - } - return undefined; - } - function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 120) { - nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 36) { - return 0; - } - var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { - return 1; - } - } - return 0; - } - function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187); - node.modifiers = parseModifiersForArrowFunction(); - var isAsync = !!(ts.getModifierFlags(node) & 256); - fillSignature(56, false, isAsync, !allowAmbiguity, node); - if (!node.parameters) { - return undefined; - } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { - return undefined; - } - return node; - } - function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17) { - return parseFunctionBlock(false, isAsync, false); - } - if (token() !== 25 && - token() !== 89 && - token() !== 75 && - isStartOfStatement() && - !isStartOfExpressionStatement()) { - return parseFunctionBlock(false, isAsync, true); - } - return isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); - } - function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(55); - if (!questionToken) { - return leftOperand; - } - var node = createNode(195, leftOperand.pos); - node.condition = leftOperand; - node.questionToken = questionToken; - node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseBinaryExpressionOrHigher(precedence) { - var leftOperand = parseUnaryExpressionOrHigher(); - return parseBinaryExpressionRest(precedence, leftOperand); - } - function isInOrOfKeyword(t) { - return t === 92 || t === 142; - } - function parseBinaryExpressionRest(precedence, leftOperand) { - while (true) { - reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 40 ? - newPrecedence >= precedence : - newPrecedence > precedence; - if (!consumeCurrentOperator) { - break; - } - if (token() === 92 && inDisallowInContext()) { - break; - } - if (token() === 118) { - if (scanner.hasPrecedingLineBreak()) { - break; - } - else { - nextToken(); - leftOperand = makeAsExpression(leftOperand, parseType()); - } - } - else { - leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); - } - } - return leftOperand; - } - function isBinaryOperator() { - if (inDisallowInContext() && token() === 92) { - return false; - } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54: - return 1; - case 53: - return 2; - case 49: - return 3; - case 50: - return 4; - case 48: - return 5; - case 32: - case 33: - case 34: - case 35: - return 6; - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - return 7; - case 45: - case 46: - case 47: - return 8; - case 37: - case 38: - return 9; - case 39: - case 41: - case 42: - return 10; - case 40: - return 11; - } - return -1; - } - function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194, left.pos); - node.left = left; - node.operatorToken = operatorToken; - node.right = right; - return finishNode(node); - } - function makeAsExpression(left, right) { - var node = createNode(202, left.pos); - node.expression = left; - node.type = right; - return finishNode(node); - } - function parsePrefixUnaryExpression() { - var node = createNode(192); - node.operator = token(); - nextToken(); - node.operand = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseDeleteExpression() { - var node = createNode(188); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseTypeOfExpression() { - var node = createNode(189); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseVoidExpression() { - var node = createNode(190); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function isAwaitExpression() { - if (token() === 121) { - if (inAwaitContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOnSameLine); - } - return false; - } - function parseAwaitExpression() { - var node = createNode(191); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseUnaryExpressionOrHigher() { - if (isUpdateExpression()) { - var incrementExpression = parseIncrementExpression(); - return token() === 40 ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : - incrementExpression; - } - var unaryOperator = token(); - var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184) { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); - } - else { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); - } - } - return simpleUnaryExpression; - } - function parseSimpleUnaryExpression() { - switch (token()) { - case 37: - case 38: - case 52: - case 51: - return parsePrefixUnaryExpression(); - case 80: - return parseDeleteExpression(); - case 103: - return parseTypeOfExpression(); - case 105: - return parseVoidExpression(); - case 27: - return parseTypeAssertion(); - case 121: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - default: - return parseIncrementExpression(); - } - } - function isUpdateExpression() { - switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 121: - return false; - case 27: - if (sourceFile.languageVariant !== 1) { - return false; - } - default: - return true; - } - } - function parseIncrementExpression() { - if (token() === 43 || token() === 44) { - var node = createNode(192); - node.operator = token(); - nextToken(); - node.operand = parseLeftHandSideExpressionOrHigher(); - return finishNode(node); - } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { - return parseJsxElementOrSelfClosingElement(true); - } - var expression = parseLeftHandSideExpressionOrHigher(); - ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193, expression.pos); - node.operand = expression; - node.operator = token(); - nextToken(); - return finishNode(node); - } - return expression; - } - function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 97 - ? parseSuperExpression() - : parseMemberExpressionOrHigher(); - return parseCallExpressionRest(expression); - } - function parseMemberExpressionOrHigher() { - var expression = parsePrimaryExpression(); - return parseMemberExpressionRest(expression); - } - function parseSuperExpression() { - var expression = parseTokenNode(); - if (token() === 19 || token() === 23 || token() === 21) { - return expression; - } - var node = createNode(179, expression.pos); - node.expression = expression; - parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - node.name = parseRightSideOfDot(true); - return finishNode(node); - } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 71) { - return lhs.text === rhs.text; - } - if (lhs.kind === 99) { - return true; - } - return lhs.name.text === rhs.name.text && - tagNamesAreEquivalent(lhs.expression, rhs.expression); - } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); - var result; - if (opening.kind === 251) { - var node = createNode(249, opening.pos); - node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); - node.closingElement = parseJsxClosingElement(inExpressionContext); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); - } - result = finishNode(node); - } - else { - ts.Debug.assert(opening.kind === 250); - result = opening; - } - if (inExpressionContext && token() === 27) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); - if (invalidElement) { - parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194, result.pos); - badNode.end = invalidElement.end; - badNode.left = result; - badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26, false, undefined); - badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; - return badNode; - } - } - return result; - } - function parseJsxText() { - var node = createNode(10, scanner.getStartPos()); - node.containsOnlyWhiteSpaces = currentToken === 11; - currentToken = scanner.scanJsxToken(); - return finishNode(node); - } - function parseJsxChild() { - switch (token()) { - case 10: - case 11: - return parseJsxText(); - case 17: - return parseJsxExpression(false); - case 27: - return parseJsxElementOrSelfClosingElement(false); - } - ts.Debug.fail("Unknown JSX child kind " + token()); - } - function parseJsxChildren(openingTagName) { - var result = createNodeArray(); - var saveParsingContext = parsingContext; - parsingContext |= 1 << 14; - while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28) { - break; - } - else if (token() === 1) { - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); - break; - } - else if (token() === 7) { - break; - } - var child = parseJsxChild(); - if (child) { - result.push(child); - } - } - result.end = scanner.getTokenPos(); - parsingContext = saveParsingContext; - return result; - } - function parseJsxAttributes() { - var jsxAttributes = createNode(254); - jsxAttributes.properties = parseList(13, parseJsxAttribute); - return finishNode(jsxAttributes); - } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { - var fullStart = scanner.getStartPos(); - parseExpected(27); - var tagName = parseJsxElementName(); - var attributes = parseJsxAttributes(); - var node; - if (token() === 29) { - node = createNode(251, fullStart); - scanJsxText(); - } - else { - parseExpected(41); - if (inExpressionContext) { - parseExpected(29); - } - else { - parseExpected(29, undefined, false); - scanJsxText(); - } - node = createNode(250, fullStart); - } - node.tagName = tagName; - node.attributes = attributes; - return finishNode(node); - } - function parseJsxElementName() { - scanJsxIdentifier(); - var expression = token() === 99 ? - parseTokenNode() : parseIdentifierName(); - while (parseOptional(23)) { - var propertyAccess = createNode(179, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); - expression = finishNode(propertyAccess); - } - return expression; - } - function parseJsxExpression(inExpressionContext) { - var node = createNode(256); - parseExpected(17); - if (token() !== 18) { - node.dotDotDotToken = parseOptionalToken(24); - node.expression = parseAssignmentExpressionOrHigher(); - } - if (inExpressionContext) { - parseExpected(18); - } - else { - parseExpected(18, undefined, false); - scanJsxText(); - } - return finishNode(node); - } - function parseJsxAttribute() { - if (token() === 17) { - return parseJsxSpreadAttribute(); - } - scanJsxIdentifier(); - var node = createNode(253); - node.name = parseIdentifierName(); - if (token() === 58) { - switch (scanJsxAttributeValue()) { - case 9: - node.initializer = parseLiteralNode(); - break; - default: - node.initializer = parseJsxExpression(true); - break; - } - } - return finishNode(node); - } - function parseJsxSpreadAttribute() { - var node = createNode(255); - parseExpected(17); - parseExpected(24); - node.expression = parseExpression(); - parseExpected(18); - return finishNode(node); - } - function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252); - parseExpected(28); - node.tagName = parseJsxElementName(); - if (inExpressionContext) { - parseExpected(29); - } - else { - parseExpected(29, undefined, false); - scanJsxText(); - } - return finishNode(node); - } - function parseTypeAssertion() { - var node = createNode(184); - parseExpected(27); - node.type = parseType(); - parseExpected(29); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseMemberExpressionRest(expression) { - while (true) { - var dotToken = parseOptionalToken(23); - if (dotToken) { - var propertyAccess = createNode(179, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); - expression = finishNode(propertyAccess); - continue; - } - if (token() === 51 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var nonNullExpression = createNode(203, expression.pos); - nonNullExpression.expression = expression; - expression = finishNode(nonNullExpression); - continue; - } - if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(180, expression.pos); - indexedAccess.expression = expression; - if (token() !== 22) { - indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { - var literal = indexedAccess.argumentExpression; - literal.text = internIdentifier(literal.text); - } - } - parseExpected(22); - expression = finishNode(indexedAccess); - continue; - } - if (token() === 13 || token() === 14) { - var tagExpression = createNode(183, expression.pos); - tagExpression.tag = expression; - tagExpression.template = token() === 13 - ? parseLiteralNode() - : parseTemplateExpression(); - expression = finishNode(tagExpression); - continue; - } - return expression; - } - } - function parseCallExpressionRest(expression) { - while (true) { - expression = parseMemberExpressionRest(expression); - if (token() === 27) { - var typeArguments = tryParse(parseTypeArgumentsInExpression); - if (!typeArguments) { - return expression; - } - var callExpr = createNode(181, expression.pos); - callExpr.expression = expression; - callExpr.typeArguments = typeArguments; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - else if (token() === 19) { - var callExpr = createNode(181, expression.pos); - callExpr.expression = expression; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - return expression; - } - } - function parseArgumentList() { - parseExpected(19); - var result = parseDelimitedList(11, parseArgumentExpression); - parseExpected(20); - return result; - } - function parseTypeArgumentsInExpression() { - if (!parseOptional(27)) { - return undefined; - } - var typeArguments = parseDelimitedList(19, parseType); - if (!parseExpected(29)) { - return undefined; - } - return typeArguments && canFollowTypeArgumentsInExpression() - ? typeArguments - : undefined; - } - function canFollowTypeArgumentsInExpression() { - switch (token()) { - case 19: - case 23: - case 20: - case 22: - case 56: - case 25: - case 55: - case 32: - case 34: - case 33: - case 35: - case 53: - case 54: - case 50: - case 48: - case 49: - case 18: - case 1: - return true; - case 26: - case 17: - default: - return false; - } - } - function parsePrimaryExpression() { - switch (token()) { - case 8: - case 9: - case 13: - return parseLiteralNode(); - case 99: - case 97: - case 95: - case 101: - case 86: - return parseTokenNode(); - case 19: - return parseParenthesizedExpression(); - case 21: - return parseArrayLiteralExpression(); - case 17: - return parseObjectLiteralExpression(); - case 120: - if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { - break; - } - return parseFunctionExpression(); - case 75: - return parseClassExpression(); - case 89: - return parseFunctionExpression(); - case 94: - return parseNewExpression(); - case 41: - case 63: - if (reScanSlashToken() === 12) { - return parseLiteralNode(); - } - break; - case 14: - return parseTemplateExpression(); - } - return parseIdentifier(ts.Diagnostics.Expression_expected); - } - function parseParenthesizedExpression() { - var node = createNode(185); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - return finishNode(node); - } - function parseSpreadElement() { - var node = createNode(198); - parseExpected(24); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseArgumentOrArrayLiteralElement() { - return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(200) : - parseAssignmentExpressionOrHigher(); - } - function parseArgumentExpression() { - return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); - } - function parseArrayLiteralExpression() { - var node = createNode(177); - parseExpected(21); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(22); - return finishNode(node); - } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(153, fullStart, decorators, modifiers); - } - else if (parseContextualModifier(135)) { - return parseAccessorDeclaration(154, fullStart, decorators, modifiers); - } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24); - if (dotDotDotToken) { - var spreadElement = createNode(263, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - var asteriskToken = parseOptionalToken(39); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); - } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); - if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(58); - if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); - } - return addJSDocComment(finishNode(shorthandDeclaration)); - } - else { - var propertyAssignment = createNode(261, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; - parseExpected(56); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); - } - } - function parseObjectLiteralExpression() { - var node = createNode(178); - parseExpected(17); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(18); - return finishNode(node); - } - function parseFunctionExpression() { - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var node = createNode(186); - node.modifiers = parseModifiers(); - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - var isGenerator = !!node.asteriskToken; - var isAsync = !!(ts.getModifierFlags(node) & 256); - node.name = - isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : - isGenerator ? doInYieldContext(parseOptionalIdentifier) : - isAsync ? doInAwaitContext(parseOptionalIdentifier) : - parseOptionalIdentifier(); - fillSignature(56, isGenerator, isAsync, false, node); - node.body = parseFunctionBlock(isGenerator, isAsync, false); - if (saveDecoratorContext) { - setDecoratorContext(true); - } - return addJSDocComment(finishNode(node)); - } - function parseOptionalIdentifier() { - return isIdentifier() ? parseIdentifier() : undefined; - } - function parseNewExpression() { - var fullStart = scanner.getStartPos(); - parseExpected(94); - if (parseOptional(23)) { - var node_1 = createNode(204, fullStart); - node_1.keywordToken = 94; - node_1.name = parseIdentifierName(); - return finishNode(node_1); - } - var node = createNode(182, fullStart); - node.expression = parseMemberExpressionOrHigher(); - node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 19) { - node.arguments = parseArgumentList(); - } - return finishNode(node); - } - function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207); - if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.statements = parseList(1, parseStatement); - parseExpected(18); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseFunctionBlock(allowYield, allowAwait, ignoreMissingOpenBrace, diagnosticMessage) { - var savedYieldContext = inYieldContext(); - setYieldContext(allowYield); - var savedAwaitContext = inAwaitContext(); - setAwaitContext(allowAwait); - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); - if (saveDecoratorContext) { - setDecoratorContext(true); - } - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - return block; - } - function parseEmptyStatement() { - var node = createNode(209); - parseExpected(25); - return finishNode(node); - } - function parseIfStatement() { - var node = createNode(211); - parseExpected(90); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82) ? parseStatement() : undefined; - return finishNode(node); - } - function parseDoStatement() { - var node = createNode(212); - parseExpected(81); - node.statement = parseStatement(); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - parseOptional(25); - return finishNode(node); - } - function parseWhileStatement() { - var node = createNode(213); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.statement = parseStatement(); - return finishNode(node); - } - function parseForOrForInOrForOfStatement() { - var pos = getNodePos(); - parseExpected(88); - var awaitToken = parseOptionalToken(121); - parseExpected(19); - var initializer = undefined; - if (token() !== 25) { - if (token() === 104 || token() === 110 || token() === 76) { - initializer = parseVariableDeclarationList(true); - } - else { - initializer = disallowInAnd(parseExpression); - } - } - var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142) : parseOptional(142)) { - var forOfStatement = createNode(216, pos); - forOfStatement.awaitModifier = awaitToken; - forOfStatement.initializer = initializer; - forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20); - forOrForInOrForOfStatement = forOfStatement; - } - else if (parseOptional(92)) { - var forInStatement = createNode(215, pos); - forInStatement.initializer = initializer; - forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20); - forOrForInOrForOfStatement = forInStatement; - } - else { - var forStatement = createNode(214, pos); - forStatement.initializer = initializer; - parseExpected(25); - if (token() !== 25 && token() !== 20) { - forStatement.condition = allowInAnd(parseExpression); - } - parseExpected(25); - if (token() !== 20) { - forStatement.incrementor = allowInAnd(parseExpression); - } - parseExpected(20); - forOrForInOrForOfStatement = forStatement; - } - forOrForInOrForOfStatement.statement = parseStatement(); - return finishNode(forOrForInOrForOfStatement); - } - function parseBreakOrContinueStatement(kind) { - var node = createNode(kind); - parseExpected(kind === 218 ? 72 : 77); - if (!canParseSemicolon()) { - node.label = parseIdentifier(); - } - parseSemicolon(); - return finishNode(node); - } - function parseReturnStatement() { - var node = createNode(219); - parseExpected(96); - if (!canParseSemicolon()) { - node.expression = allowInAnd(parseExpression); - } - parseSemicolon(); - return finishNode(node); - } - function parseWithStatement() { - var node = createNode(220); - parseExpected(107); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.statement = parseStatement(); - return finishNode(node); - } - function parseCaseClause() { - var node = createNode(257); - parseExpected(73); - node.expression = allowInAnd(parseExpression); - parseExpected(56); - node.statements = parseList(3, parseStatement); - return finishNode(node); - } - function parseDefaultClause() { - var node = createNode(258); - parseExpected(79); - parseExpected(56); - node.statements = parseList(3, parseStatement); - return finishNode(node); - } - function parseCaseOrDefaultClause() { - return token() === 73 ? parseCaseClause() : parseDefaultClause(); - } - function parseSwitchStatement() { - var node = createNode(221); - parseExpected(98); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - var caseBlock = createNode(235, scanner.getStartPos()); - parseExpected(17); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); - parseExpected(18); - node.caseBlock = finishNode(caseBlock); - return finishNode(node); - } - function parseThrowStatement() { - var node = createNode(223); - parseExpected(100); - node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); - parseSemicolon(); - return finishNode(node); - } - function parseTryStatement() { - var node = createNode(224); - parseExpected(102); - node.tryBlock = parseBlock(false); - node.catchClause = token() === 74 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 87) { - parseExpected(87); - node.finallyBlock = parseBlock(false); - } - return finishNode(node); - } - function parseCatchClause() { - var result = createNode(260); - parseExpected(74); - if (parseExpected(19)) { - result.variableDeclaration = parseVariableDeclaration(); - } - parseExpected(20); - result.block = parseBlock(false); - return finishNode(result); - } - function parseDebuggerStatement() { - var node = createNode(225); - parseExpected(78); - parseSemicolon(); - return finishNode(node); - } - function parseExpressionOrLabeledStatement() { - var fullStart = scanner.getStartPos(); - var expression = allowInAnd(parseExpression); - if (expression.kind === 71 && parseOptional(56)) { - var labeledStatement = createNode(222, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); - } - else { - var expressionStatement = createNode(210, fullStart); - expressionStatement.expression = expression; - parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); - } - } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsClassKeywordOnSameLine() { - nextToken(); - return token() === 75 && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsFunctionKeywordOnSameLine() { - nextToken(); - return token() === 89 && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { - nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); - } - function isDeclaration() { - while (true) { - switch (token()) { - case 104: - case 110: - case 76: - case 89: - case 75: - case 83: - return true; - case 109: - case 138: - return nextTokenIsIdentifierOnSameLine(); - case 128: - case 129: - return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117: - case 120: - case 124: - case 112: - case 113: - case 114: - case 131: - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - continue; - case 141: - nextToken(); - return token() === 17 || token() === 71 || token() === 84; - case 91: - nextToken(); - return token() === 9 || token() === 39 || - token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); - case 84: - nextToken(); - if (token() === 58 || token() === 39 || - token() === 17 || token() === 79 || - token() === 118) { - return true; - } - continue; - case 115: - nextToken(); - continue; - default: - return false; - } - } - } - function isStartOfDeclaration() { - return lookAhead(isDeclaration); - } - function isStartOfStatement() { - switch (token()) { - case 57: - case 25: - case 17: - case 104: - case 110: - case 89: - case 75: - case 83: - case 90: - case 81: - case 106: - case 88: - case 77: - case 72: - case 96: - case 107: - case 98: - case 100: - case 102: - case 78: - case 74: - case 87: - return true; - case 76: - case 84: - case 91: - return isStartOfDeclaration(); - case 120: - case 124: - case 109: - case 128: - case 129: - case 138: - case 141: - return true; - case 114: - case 112: - case 113: - case 115: - case 131: - return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - default: - return isStartOfExpression(); - } - } - function nextTokenIsIdentifierOrStartOfDestructuring() { - nextToken(); - return isIdentifier() || token() === 17 || token() === 21; - } - function isLetDeclaration() { - return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); - } - function parseStatement() { - switch (token()) { - case 25: - return parseEmptyStatement(); - case 17: - return parseBlock(false); - case 104: - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - case 110: - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - } - break; - case 89: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); - case 75: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 90: - return parseIfStatement(); - case 81: - return parseDoStatement(); - case 106: - return parseWhileStatement(); - case 88: - return parseForOrForInOrForOfStatement(); - case 77: - return parseBreakOrContinueStatement(217); - case 72: - return parseBreakOrContinueStatement(218); - case 96: - return parseReturnStatement(); - case 107: - return parseWithStatement(); - case 98: - return parseSwitchStatement(); - case 100: - return parseThrowStatement(); - case 102: - case 74: - case 87: - return parseTryStatement(); - case 78: - return parseDebuggerStatement(); - case 57: - return parseDeclaration(); - case 120: - case 109: - case 138: - case 128: - case 129: - case 124: - case 76: - case 83: - case 84: - case 91: - case 112: - case 113: - case 114: - case 117: - case 115: - case 131: - case 141: - if (isStartOfDeclaration()) { - return parseDeclaration(); - } - break; - } - return parseExpressionOrLabeledStatement(); - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - switch (token()) { - case 104: - case 110: - case 76: - return parseVariableStatement(fullStart, decorators, modifiers); - case 89: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 75: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 109: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 138: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 83: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141: - case 128: - case 129: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 91: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 84: - nextToken(); - switch (token()) { - case 79: - case 58: - return parseExportAssignment(fullStart, decorators, modifiers); - case 118: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); - default: - return parseExportDeclaration(fullStart, decorators, modifiers); - } - default: - if (decorators || modifiers) { - var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); - } - } - } - function nextTokenIsIdentifierOrStringLiteralOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); - } - function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 17 && canParseSemicolon()) { - parseSemicolon(); - return; - } - return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); - } - function parseArrayBindingElement() { - if (token() === 26) { - return createNode(200); - } - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); - node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(false); - return finishNode(node); - } - function parseObjectBindingElement() { - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56) { - node.name = propertyName; - } - else { - parseExpected(56); - node.propertyName = propertyName; - node.name = parseIdentifierOrPattern(); - } - node.initializer = parseBindingElementInitializer(false); - return finishNode(node); - } - function parseObjectBindingPattern() { - var node = createNode(174); - parseExpected(17); - node.elements = parseDelimitedList(9, parseObjectBindingElement); - parseExpected(18); - return finishNode(node); - } - function parseArrayBindingPattern() { - var node = createNode(175); - parseExpected(21); - node.elements = parseDelimitedList(10, parseArrayBindingElement); - parseExpected(22); - return finishNode(node); - } - function isIdentifierOrPattern() { - return token() === 17 || token() === 21 || isIdentifier(); - } - function parseIdentifierOrPattern() { - if (token() === 21) { - return parseArrayBindingPattern(); - } - if (token() === 17) { - return parseObjectBindingPattern(); - } - return parseIdentifier(); - } - function parseVariableDeclaration() { - var node = createNode(226); - node.name = parseIdentifierOrPattern(); - node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(false); - } - return finishNode(node); - } - function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227); - switch (token()) { - case 104: - break; - case 110: - node.flags |= 1; - break; - case 76: - node.flags |= 2; - break; - default: - ts.Debug.fail(); - } - nextToken(); - if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { - node.declarations = createMissingList(); - } - else { - var savedDisallowIn = inDisallowInContext(); - setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8, parseVariableDeclaration); - setDisallowInContext(savedDisallowIn); - } - return finishNode(node); - } - function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20; - } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.declarationList = parseVariableDeclarationList(false); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); - var isGenerator = !!node.asteriskToken; - var isAsync = ts.hasModifier(node, 256); - fillSignature(56, isGenerator, isAsync, false, node); - node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152, pos); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(123); - fillSignature(56, false, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; - var isGenerator = !!asteriskToken; - var isAsync = ts.hasModifier(method, 256); - fillSignature(56, isGenerator, isAsync, false, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - property.initializer = ts.hasModifier(property, 32) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); - parseSemicolon(); - return addJSDocComment(finishNode(property)); - } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(39); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); - } - } - function parseNonParameterInitializer() { - return parseInitializer(false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.name = parsePropertyName(); - fillSignature(56, false, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false, false); - return addJSDocComment(finishNode(node)); - } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114: - case 112: - case 113: - case 115: - case 131: - return true; - default: - return false; - } - } - function isClassMemberStart() { - var idToken; - if (token() === 57) { - return true; - } - while (ts.isModifierKind(token())) { - idToken = token(); - if (isClassMemberModifier(idToken)) { - return true; - } - nextToken(); - } - if (token() === 39) { - return true; - } - if (isLiteralPropertyName()) { - idToken = token(); - nextToken(); - } - if (token() === 21) { - return true; - } - if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { - return true; - } - switch (token()) { - case 19: - case 27: - case 56: - case 58: - case 55: - return true; - default: - return canParseSemicolon(); - } - } - return false; - } - function parseDecorators() { - var decorators; - while (true) { - var decoratorStart = getNodePos(); - if (!parseOptional(57)) { - break; - } - var decorator = createNode(147, decoratorStart); - decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); - } - return decorators; - } - function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; - while (true) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 76 && permitInvalidConstAsModifier) { - if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { - break; - } - } - else { - if (!parseAnyContextualModifier()) { - break; - } - } - var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseModifiersForArrowFunction() { - var modifiers; - if (token() === 120) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - nextToken(); - var modifier = finishNode(createNode(modifierKind, modifierStart)); - modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseClassElement() { - if (token() === 25) { - var result = createNode(206); - nextToken(); - return finishNode(result); - } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - if (token() === 123) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); - } - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); - } - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8 || - token() === 39 || - token() === 21) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); - } - if (decorators || modifiers) { - var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); - } - ts.Debug.fail("Should not have attempted to parse class member declaration."); - } - function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); - } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); - } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(75); - node.name = parseNameOfClassDeclarationOrExpression(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17)) { - node.members = parseClassMembers(); - parseExpected(18); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseNameOfClassDeclarationOrExpression() { - return isIdentifier() && !isImplementsClause() - ? parseIdentifier() - : undefined; - } - function isImplementsClause() { - return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); - } - function parseHeritageClauses() { - if (isHeritageClause()) { - return parseList(21, parseHeritageClause); - } - return undefined; - } - function parseHeritageClause() { - var tok = token(); - if (tok === 85 || tok === 108) { - var node = createNode(259); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; - } - function parseExpressionWithTypeArguments() { - var node = createNode(201); - node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } - return finishNode(node); - } - function isHeritageClause() { - return token() === 85 || token() === 108; - } - function parseClassMembers() { - return parseList(5, parseClassElement); - } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(109); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); - } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(138); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - parseExpected(58); - node.type = parseType(); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseEnumMember() { - var node = createNode(264, scanner.getStartPos()); - node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); - } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(83); - node.name = parseIdentifier(); - if (parseExpected(17)) { - node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(18); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseModuleBlock() { - var node = createNode(234, scanner.getStartPos()); - if (parseExpected(17)) { - node.statements = parseList(1, parseStatement); - parseExpected(18); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233, fullStart); - var namespaceFlag = flags & 16; - node.decorators = decorators; - node.modifiers = modifiers; - node.flags |= flags; - node.name = parseIdentifier(); - node.body = parseOptional(23) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) - : parseModuleBlock(); - return addJSDocComment(finishNode(node)); - } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141) { - node.name = parseIdentifier(); - node.flags |= 512; - } - else { - node.name = parseLiteralNode(true); - } - if (token() === 17) { - node.body = parseModuleBlock(); - } - else { - parseSemicolon(); - } - return finishNode(node); - } - function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = 0; - if (token() === 141) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - else if (parseOptional(129)) { - flags |= 16; - } - else { - parseExpected(128); - if (token() === 9) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); - } - function isExternalModuleReference() { - return token() === 132 && - lookAhead(nextTokenIsOpenParen); - } - function nextTokenIsOpenParen() { - return nextToken() === 19; - } - function nextTokenIsSlash() { - return nextToken() === 41; - } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; - parseExpected(118); - parseExpected(129); - exportDeclaration.name = parseIdentifier(); - parseSemicolon(); - return finishNode(exportDeclaration); - } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(91); - var afterImportPos = scanner.getStartPos(); - var identifier; - if (isIdentifier()) { - identifier = parseIdentifier(); - if (token() !== 26 && token() !== 140) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); - } - } - var importDeclaration = createNode(238, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; - if (identifier || - token() === 39 || - token() === 17) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140); - } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); - parseSemicolon(); - return finishNode(importDeclaration); - } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; - parseExpected(58); - importEqualsDeclaration.moduleReference = parseModuleReference(); - parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); - } - function parseImportClause(identifier, fullStart) { - var importClause = createNode(239, fullStart); - if (identifier) { - importClause.name = identifier; - } - if (!importClause.name || - parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); - } - return finishNode(importClause); - } - function parseModuleReference() { - return isExternalModuleReference() - ? parseExternalModuleReference() - : parseEntityName(false); - } - function parseExternalModuleReference() { - var node = createNode(248); - parseExpected(132); - parseExpected(19); - node.expression = parseModuleSpecifier(); - parseExpected(20); - return finishNode(node); - } - function parseModuleSpecifier() { - if (token() === 9) { - var result = parseLiteralNode(); - internIdentifier(result.text); - return result; - } - else { - return parseExpression(); - } - } - function parseNamespaceImport() { - var namespaceImport = createNode(240); - parseExpected(39); - parseExpected(118); - namespaceImport.name = parseIdentifier(); - return finishNode(namespaceImport); - } - function parseNamedImportsOrExports(kind) { - var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); - return finishNode(node); - } - function parseExportSpecifier() { - return parseImportOrExportSpecifier(246); - } - function parseImportSpecifier() { - return parseImportOrExportSpecifier(242); - } - function parseImportOrExportSpecifier(kind) { - var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - var checkIdentifierStart = scanner.getTokenPos(); - var checkIdentifierEnd = scanner.getTextPos(); - var identifierName = parseIdentifierName(); - if (token() === 118) { - node.propertyName = identifierName; - parseExpected(118); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - checkIdentifierStart = scanner.getTokenPos(); - checkIdentifierEnd = scanner.getTextPos(); - node.name = parseIdentifierName(); - } - else { - node.name = identifierName; - } - if (kind === 242 && checkIdentifierIsKeyword) { - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); - } - return finishNode(node); - } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(39)) { - parseExpected(140); - node.moduleSpecifier = parseModuleSpecifier(); - } - else { - node.exportClause = parseNamedImportsOrExports(245); - if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(140); - node.moduleSpecifier = parseModuleSpecifier(); - } - } - parseSemicolon(); - return finishNode(node); - } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(58)) { - node.isExportEquals = true; - } - else { - parseExpected(79); - } - node.expression = parseAssignmentExpressionOrHigher(); - parseSemicolon(); - return finishNode(node); - } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*".length; - return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function parseQualifiedName(left) { - var result = createNode(143, left.pos); - result.left = left; - result.right = parseIdentifierName(); - return finishNode(result); - } - function parseJSDocRecordType() { - var result = createNode(275); - result.literal = parseTypeLiteral(); - return finishNode(result); - } - function parseJSDocNonNullableType() { - var result = createNode(274); - nextToken(); - result.type = parseJSDocType(); - return finishNode(result); - } - function parseJSDocTupleType() { - var result = createNode(272); - nextToken(); - result.types = parseDelimitedList(26, parseJSDocType); - checkForTrailingComma(result.types); - parseExpected(22); - return finishNode(result); - } - function checkForTrailingComma(list) { - if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - var start = list.end - ",".length; - parseErrorAtPosition(start, ",".length, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function parseJSDocUnionType() { - var result = createNode(271); - nextToken(); - result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(20); - return finishNode(result); - } - function parseJSDocTypeList(firstType) { - ts.Debug.assert(!!firstType); - var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(49)) { - types.push(parseJSDocType()); - } - types.end = scanner.getStartPos(); - return types; - } - function parseJSDocAllType() { - var result = createNode(268); - nextToken(); - return finishNode(result); - } - function parseJSDocLiteralType() { - var result = createNode(293); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } - function parseJSDocUnknownOrNullableType() { - var pos = scanner.getStartPos(); - nextToken(); - if (token() === 26 || - token() === 18 || - token() === 20 || - token() === 29 || - token() === 58 || - token() === 49) { - var result = createNode(269, pos); - return finishNode(result); - } - else { - var result = createNode(273, pos); - result.type = parseJSDocType(); - return finishNode(result); - } - } - function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = { languageVariant: 0, text: content }; - var jsDoc = parseJSDocCommentWorker(start, length); - var diagnostics = parseDiagnostics; - clearState(); - return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; - } - JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var comment = parseJSDocCommentWorker(start, length); - if (comment) { - comment.parent = parent; - } - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - 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; - var end = length === undefined ? content.length : start + length; - length = end - start; - ts.Debug.assert(start >= 0); - ts.Debug.assert(start <= end); - ts.Debug.assert(end <= content.length); - var tags; - var comments = []; - var result; - if (!isJsDocStart(content, start)) { - return result; - } - scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; - var state = 1; - var margin = undefined; - var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); - } - if (token() === 4) { - state = 0; - indent = 0; - nextJSDocToken(); - } - while (token() !== 1) { - switch (token()) { - case 57: - if (state === 0 || state === 1) { - removeTrailingNewlines(comments); - parseTag(indent); - state = 0; - advanceToken = false; - margin = undefined; - indent++; - } - else { - pushComment(scanner.getTokenText()); - } - break; - case 4: - comments.push(scanner.getTokenText()); - state = 0; - indent = 0; - break; - case 39: - var asterisk = scanner.getTokenText(); - if (state === 1 || state === 2) { - state = 2; - pushComment(asterisk); - } - else { - state = 1; - indent += asterisk.length; - } - break; - case 71: - pushComment(scanner.getTokenText()); - state = 2; - break; - case 5: - var whitespace = scanner.getTokenText(); - if (state === 2) { - comments.push(whitespace); - } - else if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - break; - case 1: - break; - default: - state = 2; - pushComment(scanner.getTokenText()); - break; - } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - result = createJSDocComment(); - }); - return result; - function removeLeadingNewlines(comments) { - while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { - comments.shift(); - } - } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { - comments.pop(); - } - } - function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 && - content.charCodeAt(start + 1) === 42 && - content.charCodeAt(start + 2) === 42 && - content.charCodeAt(start + 3) !== 42; - } - function createJSDocComment() { - var result = createNode(283, start); - result.tags = tags; - result.comment = comments.length ? comments.join("") : undefined; - return finishNode(result, end); - } - function skipWhitespace() { - while (token() === 5 || token() === 4) { - nextJSDocToken(); - } - } - function parseTag(indent) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return; - } - var tag; - if (tagName) { - switch (tagName.text) { - case "augments": - tag = parseAugmentsTag(atToken, tagName); - break; - case "arg": - case "argument": - case "param": - tag = parseParamTag(atToken, tagName); - break; - case "return": - case "returns": - tag = parseReturnTag(atToken, tagName); - break; - case "template": - tag = parseTemplateTag(atToken, tagName); - break; - case "type": - tag = parseTypeTag(atToken, tagName); - break; - case "typedef": - tag = parseTypedefTag(atToken, tagName); - break; - default: - tag = parseUnknownTag(atToken, tagName); - break; - } - } - else { - tag = parseUnknownTag(atToken, tagName); - } - if (!tag) { - return; - } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); - } - function parseTagComments(indent) { - var comments = []; - var state = 0; - var margin; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - while (token() !== 57 && token() !== 1) { - switch (token()) { - case 4: - if (state >= 1) { - state = 0; - comments.push(scanner.getTokenText()); - } - indent = 0; - break; - case 57: - break; - case 5: - if (state === 2) { - pushComment(scanner.getTokenText()); - } - else { - var whitespace = scanner.getTokenText(); - if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - } - break; - case 39: - if (state === 0) { - state = 1; - indent += scanner.getTokenText().length; - break; - } - default: - state = 2; - pushComment(scanner.getTokenText()); - break; - } - if (token() === 57) { - break; - } - nextJSDocToken(); - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - return comments; - } - function parseUnknownTag(atToken, tagName) { - var result = createNode(284, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - return finishNode(result); - } - function addTag(tag, comments) { - tag.comment = comments.join(""); - if (!tags) { - tags = createNodeArray([tag], tag.pos); - } - else { - tags.push(tag); - } - tags.end = tag.end; - } - function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17) { - return undefined; - } - return parseJSDocTypeExpression(); - }); - } - function parseParamTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name; - var isBracketed; - if (parseOptionalToken(21)) { - name = parseJSDocIdentifierName(); - skipWhitespace(); - isBracketed = true; - if (parseOptionalToken(58)) { - parseExpression(); - } - parseExpected(22); - } - else if (ts.tokenIsIdentifierOrKeyword(token())) { - name = parseJSDocIdentifierName(); - } - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var preName, postName; - if (typeExpression) { - postName = name; - } - else { - preName = name; - } - if (!typeExpression) { - typeExpression = tryParseTypeExpression(); - } - var result = createNode(286, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.preParameterName = preName; - result.typeExpression = typeExpression; - result.postParameterName = postName; - result.parameterName = postName || preName; - result.isBracketed = isBracketed; - return finishNode(result); - } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(287, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 288; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(288, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parsePropertyTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var result = createNode(291, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.name = name; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - var result = createNode(285, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseTypedefTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(290, atToken.pos); - typedefTag.atToken = atToken; - typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 || !rightNode.body) { - typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } - typedefTag.typeExpression = typeExpression; - skipWhitespace(); - if (typeExpression) { - if (typeExpression.type.kind === 277) { - var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 71) { - var name = jsDocTypeReference.name; - if (name.text === "Object") { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - } - } - if (!typedefTag.jsDocTypeLiteral) { - typedefTag.jsDocTypeLiteral = typeExpression.type; - } - } - else { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - return finishNode(typedefTag); - function scanChildTags() { - var jsDocTypeLiteral = createNode(292, scanner.getStartPos()); - var resumePos = scanner.getStartPos(); - var canParseTag = true; - var seenAsterisk = false; - var parentTagTerminated = false; - while (token() !== 1 && !parentTagTerminated) { - nextJSDocToken(); - switch (token()) { - case 57: - if (canParseTag) { - parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } - } - seenAsterisk = false; - break; - case 4: - resumePos = scanner.getStartPos() - 1; - canParseTag = true; - seenAsterisk = false; - break; - case 39: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 71: - canParseTag = false; - break; - case 1: - break; - } - } - scanner.setTextPos(resumePos); - return finishNode(jsDocTypeLiteral); - } - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(233, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); - return jsDocNamespaceNode; - } - if (typeNameOrNamespaceName && flags & 4) { - typeNameOrNamespaceName.isInJSDocNamespace = true; - } - return typeNameOrNamespaceName; - } - } - function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getStartPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return false; - } - switch (tagName.text) { - case "type": - if (parentTag.jsDocTypeTag) { - return false; - } - parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); - return true; - case "prop": - case "property": - var propertyTag = parsePropertyTag(atToken, tagName); - if (propertyTag) { - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } - parentTag.jsDocPropertyTags.push(propertyTag); - return true; - } - return false; - } - return false; - } - function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var typeParameters = createNodeArray(); - while (true) { - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var typeParameter = createNode(145, name.pos); - typeParameter.name = name; - finishNode(typeParameter); - typeParameters.push(typeParameter); - if (token() === 26) { - nextJSDocToken(); - skipWhitespace(); - } - else { - break; - } - } - var result = createNode(289, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeParameters = typeParameters; - finishNode(result); - typeParameters.end = result.end; - return result; - } - function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); - } - function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function createJSDocIdentifier(isIdentifier) { - if (!isIdentifier) { - parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - return undefined; - } - var pos = scanner.getTokenPos(); - var end = scanner.getTextPos(); - var result = createNode(71, pos); - result.text = content.substring(pos, end); - finishNode(result, end); - nextJSDocToken(); - return result; - } - } - JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; - })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); - })(Parser || (Parser = {})); - var IncrementalParser; - (function (IncrementalParser) { - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); - checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); - if (ts.textChangeRangeIsUnchanged(textChangeRange)) { - return sourceFile; - } - if (sourceFile.statements.length === 0) { - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); - } - var incrementalSourceFile = sourceFile; - ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); - incrementalSourceFile.hasBeenIncrementallyParsed = true; - var oldText = sourceFile.text; - var syntaxCursor = createSyntaxCursor(sourceFile); - var changeRange = extendToAffectedRange(sourceFile, textChangeRange); - checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); - ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); - ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); - ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); - var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; - updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); - return result; - } - IncrementalParser.updateSourceFile = updateSourceFile; - function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { - if (isArray) { - visitArray(element); - } - else { - visitNode(element); - } - return; - function visitNode(node) { - var text = ""; - if (aggressiveChecks && shouldCheckNode(node)) { - text = oldText.substring(node.pos, node.end); - } - if (node._children) { - node._children = undefined; - } - node.pos += delta; - node.end += delta; - if (aggressiveChecks && shouldCheckNode(node)) { - ts.Debug.assert(text === newText.substring(node.pos, node.end)); - } - forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - forEachChild(jsDocComment, visitNode, visitArray); - } - } - checkNodePositions(node, aggressiveChecks); - } - function visitArray(array) { - array._children = undefined; - array.pos += delta; - array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; - visitNode(node); - } - } - } - function shouldCheckNode(node) { - switch (node.kind) { - case 9: - case 8: - case 71: - return true; - } - return false; - } - function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { - ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); - ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); - ts.Debug.assert(element.pos <= element.end); - element.pos = Math.min(element.pos, changeRangeNewEnd); - if (element.end >= changeRangeOldEnd) { - element.end += delta; - } - else { - element.end = Math.min(element.end, changeRangeNewEnd); - } - ts.Debug.assert(element.pos <= element.end); - if (element.parent) { - ts.Debug.assert(element.pos >= element.parent.pos); - ts.Debug.assert(element.end <= element.parent.end); - } - } - function checkNodePositions(node, aggressiveChecks) { - if (aggressiveChecks) { - var pos_2 = node.pos; - forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; - }); - ts.Debug.assert(pos_2 <= node.end); - } - } - function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { - visitNode(sourceFile); - return; - function visitNode(child) { - ts.Debug.assert(child.pos <= child.end); - if (child.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); - return; - } - var fullEnd = child.end; - if (fullEnd >= changeStart) { - child.intersectsChange = true; - child._children = undefined; - adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - forEachChild(child, visitNode, visitArray); - checkNodePositions(child, aggressiveChecks); - return; - } - ts.Debug.assert(fullEnd < changeStart); - } - function visitArray(array) { - ts.Debug.assert(array.pos <= array.end); - if (array.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); - return; - } - var fullEnd = array.end; - if (fullEnd >= changeStart) { - array.intersectsChange = true; - array._children = undefined; - adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; - visitNode(node); - } - return; - } - ts.Debug.assert(fullEnd < changeStart); - } - } - function extendToAffectedRange(sourceFile, changeRange) { - var maxLookahead = 1; - var start = changeRange.span.start; - for (var i = 0; start > 0 && i <= maxLookahead; i++) { - var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); - ts.Debug.assert(nearestNode.pos <= start); - var position = nearestNode.pos; - start = Math.max(0, position - 1); - } - var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); - var finalLength = changeRange.newLength + (changeRange.span.start - start); - return ts.createTextChangeRange(finalSpan, finalLength); - } - function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { - var bestResult = sourceFile; - var lastNodeEntirelyBeforePosition; - forEachChild(sourceFile, visit); - if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); - if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { - bestResult = lastChildOfLastEntireNodeBeforePosition; - } - } - return bestResult; - function getLastChild(node) { - while (true) { - var lastChild = getLastChildWorker(node); - if (lastChild) { - node = lastChild; - } - else { - return node; - } - } - } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } - function visit(child) { - if (ts.nodeIsMissing(child)) { - return; - } - if (child.pos <= position) { - if (child.pos >= bestResult.pos) { - bestResult = child; - } - if (position < child.end) { - forEachChild(child, visit); - return true; - } - else { - ts.Debug.assert(child.end <= position); - lastNodeEntirelyBeforePosition = child; - } - } - else { - ts.Debug.assert(child.pos > position); - return true; - } - } - } - function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { - var oldText = sourceFile.text; - if (textChangeRange) { - ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); - if (aggressiveChecks || ts.Debug.shouldAssert(3)) { - var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - var newTextPrefix = newText.substr(0, textChangeRange.span.start); - ts.Debug.assert(oldTextPrefix === newTextPrefix); - var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); - var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); - ts.Debug.assert(oldTextSuffix === newTextSuffix); - } - } - } - function createSyntaxCursor(sourceFile) { - var currentArray = sourceFile.statements; - var currentArrayIndex = 0; - ts.Debug.assert(currentArrayIndex < currentArray.length); - var current = currentArray[currentArrayIndex]; - var lastQueriedPosition = -1; - return { - currentNode: function (position) { - if (position !== lastQueriedPosition) { - if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { - currentArrayIndex++; - current = currentArray[currentArrayIndex]; - } - if (!current || current.pos !== position) { - findHighestListElementThatStartsAtPosition(position); - } - } - lastQueriedPosition = position; - ts.Debug.assert(!current || current.pos === position); - return current; - } - }; - function findHighestListElementThatStartsAtPosition(position) { - currentArray = undefined; - currentArrayIndex = -1; - current = undefined; - forEachChild(sourceFile, visitNode, visitArray); - return; - function visitNode(node) { - if (position >= node.pos && position < node.end) { - forEachChild(node, visitNode, visitArray); - return true; - } - return false; - } - function visitArray(array) { - if (position >= array.pos && position < array.end) { - for (var i = 0; i < array.length; i++) { - var child = array[i]; - if (child) { - if (child.pos === position) { - currentArray = array; - currentArrayIndex = i; - current = child; - return true; - } - else { - if (child.pos < position && position < child.end) { - forEachChild(child, visitNode, visitArray); - return true; - } - } - } - } - } - return false; - } - } - } - 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; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2; - } - else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { - return 0; - } - else if (node.kind === 234) { - var state_1 = 0; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0: - return false; - case 2: - state_1 = 2; - return false; - case 1: - state_1 = 1; - return true; - } - }); - return state_1; - } - else if (node.kind === 233) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1; - } - else if (node.kind === 71 && node.isInJSDocNamespace) { - return 0; - } - else { - return 1; - } - } - 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"); - binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var languageVersion; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - var currentFlow; - var currentBreakTarget; - var currentContinueTarget; - var currentReturnTarget; - var currentTrueTarget; - var currentFalseTarget; - var preSwitchCaseFlow; - var activeLabels; - var hasExplicitReturn; - var emitFlags; - var inStrictMode; - var symbolCount = 0; - var Symbol; - var classifiableNames; - var unreachableFlow = { flags: 1 }; - var reportedUnreachableFlow = { flags: 1 }; - var subtreeTransformFlags = 0; - var skipTransformFlagAggregation; - function bindSourceFile(f, opts) { - file = f; - options = opts; - languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = ts.createMap(); - symbolCount = 0; - skipTransformFlagAggregation = file.isDeclarationFile; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = 0; - subtreeTransformFlags = 0; - } - return bindSourceFile; - function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = ts.createMap(); - } - if (symbolFlags & 6240 && !symbol.members) { - symbol.members = ts.createMap(); - } - if (symbolFlags & 107455) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { - symbol.valueDeclaration = node; - } - } - } - function getDeclarationName(node) { - var name = ts.getNameOfDeclaration(node); - if (name) { - if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; - } - 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 name.text; - } - switch (node.kind) { - case 152: - return "__constructor"; - case 160: - case 155: - return "__call"; - case 161: - case 156: - return "__new"; - case 157: - return "__index"; - case 244: - return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; - case 194: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2: - return "export="; - case 1: - case 4: - case 5: - return node.left.name.text; - case 3: - return node.left.expression.name.text; - } - ts.Debug.fail("Unknown binary declaration kind"); - break; - case 228: - case 229: - return ts.hasModifier(node, 512) ? "default" : undefined; - case 279: - return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 146: - ts.Debug.assert(node.parent.kind === 279); - var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); - return "arg" + index; - case 290: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71) { - nameFromParentNode = nameIdentifier.text; - } - } - } - return nameFromParentNode; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512); - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name === undefined) { - symbol = createSymbol(0, "__missing"); - } - else { - symbol = symbolTable.get(name); - if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0, name)); - } - if (name && (includes & 788448)) { - classifiableNames.set(name, name); - } - if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - symbolTable.set(name, symbol = createSymbol(0, name)); - } - else { - if (node.name) { - node.name.parent = node; - } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - if (symbol.declarations && symbol.declarations.length) { - if (isDefaultExport) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); - } - } - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; - if (symbolFlags & 8388608) { - if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - else { - var isJSDocTypedefInJSDocNamespace = node.kind === 290 && - node.name && - node.name.kind === 71 && - node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793064 ? 2097152 : 0) | - (symbolFlags & 1920 ? 4194304 : 0); - var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - } - function bindContainer(node, containerFlags) { - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - if (containerFlags & 1) { - container = blockScopeContainer = node; - if (containerFlags & 32) { - container.locals = ts.createMap(); - } - addToContainerChain(container); - } - else if (containerFlags & 2) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & 4) { - var saveCurrentFlow = currentFlow; - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - var saveReturnTarget = currentReturnTarget; - var saveActiveLabels = activeLabels; - var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { - currentFlow = { flags: 2 }; - if (containerFlags & (16 | 128)) { - currentFlow.container = node; - } - currentReturnTarget = undefined; - } - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - node.flags &= ~1408; - if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { - node.flags |= 128; - if (hasExplicitReturn) - node.flags |= 256; - } - if (node.kind === 265) { - node.flags |= emitFlags; - } - if (isIIFE) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - } - else { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & 64) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - function bindChildren(node) { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & 536870912) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - function bindEach(nodes) { - if (nodes === undefined) { - return; - } - if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var nodeArrayFlags = 0; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; - bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912; - } - nodes.transformFlags = nodeArrayFlags | 536870912; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - } - function bindEachChild(node) { - ts.forEachChild(node, bind, bindEach); - } - function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } - if (checkUnreachable(node)) { - bindEachChild(node); - return; - } - switch (node.kind) { - case 213: - bindWhileStatement(node); - break; - case 212: - bindDoStatement(node); - break; - case 214: - bindForStatement(node); - break; - case 215: - case 216: - bindForInOrForOfStatement(node); - break; - case 211: - bindIfStatement(node); - break; - case 219: - case 223: - bindReturnOrThrow(node); - break; - case 218: - case 217: - bindBreakOrContinueStatement(node); - break; - case 224: - bindTryStatement(node); - break; - case 221: - bindSwitchStatement(node); - break; - case 235: - bindCaseBlock(node); - break; - case 257: - bindCaseClause(node); - break; - case 222: - bindLabeledStatement(node); - break; - case 192: - bindPrefixUnaryExpressionFlow(node); - break; - case 193: - bindPostfixUnaryExpressionFlow(node); - break; - case 194: - bindBinaryExpressionFlow(node); - break; - case 188: - bindDeleteExpressionFlow(node); - break; - case 195: - bindConditionalExpressionFlow(node); - break; - case 226: - bindVariableDeclarationFlow(node); - break; - case 181: - bindCallExpressionFlow(node); - break; - case 283: - bindJSDocComment(node); - break; - case 290: - bindJSDocTypedefTag(node); - break; - default: - bindEachChild(node); - break; - } - } - function isNarrowingExpression(expr) { - switch (expr.kind) { - case 71: - case 99: - case 179: - return isNarrowableReference(expr); - case 181: - return hasNarrowableArgument(expr); - case 185: - return isNarrowingExpression(expr.expression); - case 194: - return isNarrowingBinaryExpression(expr); - case 192: - return expr.operator === 51 && isNarrowingExpression(expr.operand); - } - return false; - } - function isNarrowableReference(expr) { - return expr.kind === 71 || - expr.kind === 99 || - expr.kind === 97 || - expr.kind === 179 && isNarrowableReference(expr.expression); - } - function hasNarrowableArgument(expr) { - if (expr.arguments) { - for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === 179 && - isNarrowableReference(expr.expression.expression)) { - return true; - } - return false; - } - function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; - } - function isNarrowingBinaryExpression(expr) { - switch (expr.operatorToken.kind) { - case 58: - return isNarrowableReference(expr.left); - case 32: - case 33: - case 34: - case 35: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93: - return isNarrowableOperand(expr.left); - case 26: - return isNarrowingExpression(expr.right); - } - return false; - } - function isNarrowableOperand(expr) { - switch (expr.kind) { - case 185: - return isNarrowableOperand(expr.expression); - case 194: - switch (expr.operatorToken.kind) { - case 58: - return isNarrowableOperand(expr.left); - case 26: - return isNarrowableOperand(expr.right); - } - } - return isNarrowableReference(expr); - } - function createBranchLabel() { - return { - flags: 4, - antecedents: undefined - }; - } - function createLoopLabel() { - return { - flags: 8, - antecedents: undefined - }; - } - function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 512 ? 1024 : 512; - } - function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1) { - return antecedent; - } - if (!expression) { - return flags & 32 ? antecedent : unreachableFlow; - } - if (expression.kind === 101 && flags & 64 || - expression.kind === 86 && flags & 32) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; - } - function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: 128, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; - } - function createFlowAssignment(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 16, - antecedent: antecedent, - node: node - }; - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 256, - antecedent: antecedent, - node: node - }; - } - function finishFlowLabel(flow) { - var antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - function isStatementCondition(node) { - var parent = node.parent; - switch (parent.kind) { - case 211: - case 213: - case 212: - return parent.expression === node; - case 214: - case 195: - return parent.condition === node; - } - return false; - } - function isLogicalExpression(node) { - while (true) { - if (node.kind === 185) { - node = node.expression; - } - else if (node.kind === 192 && node.operator === 51) { - node = node.operand; - } - else { - return node.kind === 194 && (node.operatorToken.kind === 53 || - node.operatorToken.kind === 54); - } - } - } - function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 || - node.parent.kind === 192 && - node.parent.operator === 51) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - function bindCondition(node, trueTarget, falseTarget) { - var saveTrueTarget = currentTrueTarget; - var saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); - } - } - function bindIterativeStatement(node, breakTarget, continueTarget) { - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - function bindWhileStatement(node) { - var preWhileLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - function bindDoStatement(node) { - var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 - ? ts.lastOrUndefined(activeLabels) - : undefined; - var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); - var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - function bindForStatement(node) { - var preLoopLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindForInOrForOfStatement(node) { - var preLoopLabel = createLoopLabel(); - var postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - if (node.kind === 216) { - bind(node.awaitModifier); - } - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== 227) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindIfStatement(node) { - var thenLabel = createBranchLabel(); - var elseLabel = createBranchLabel(); - var postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - function bindReturnOrThrow(node) { - bind(node.expression); - if (node.kind === 219) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - function findActiveLabel(name) { - if (activeLabels) { - for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { - var label = activeLabels_1[_i]; - if (label.name === name) { - return label; - } - } - } - return undefined; - } - function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - function bindBreakOrContinueStatement(node) { - bind(node.label); - if (node.label) { - var activeLabel = findActiveLabel(node.label.text); - if (activeLabel) { - activeLabel.referenced = true; - bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; - } - if (node.finallyBlock) { - var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); - bind(node.finallyBlock); - if (!(currentFlow.flags & 1)) { - if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } - } - if (!(currentFlow.flags & 1)) { - var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; - } - } - else { - currentFlow = finishFlowLabel(preFinallyLabel); - } - } - function bindSwitchStatement(node) { - var postSwitchLabel = createBranchLabel(); - bind(node.expression); - var saveBreakTarget = currentBreakTarget; - var savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - function bindCaseBlock(node) { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var clauses = node.clauses; - var fallthroughFlow = unreachableFlow; - for (var i = 0; i < clauses.length; i++) { - var clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - var clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - clauses.transformFlags = subtreeTransformFlags | 536870912; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - function bindCaseClause(node) { - var saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - bindEach(node.statements); - } - function pushActiveLabel(name, breakTarget, continueTarget) { - var activeLabel = { - name: name, - breakTarget: breakTarget, - continueTarget: continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - function popActiveLabel() { - activeLabels.pop(); - } - function bindLabeledStatement(node) { - var preStatementLabel = createLoopLabel(); - var postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - var activeLabel = pushActiveLabel(node.label.text, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); - } - if (!node.statement || node.statement.kind !== 212) { - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - } - function bindDestructuringTargetFlow(node) { - if (node.kind === 194 && node.operatorToken.kind === 58) { - bindAssignmentTargetFlow(node.left); - } - else { - bindAssignmentTargetFlow(node); - } - } - function bindAssignmentTargetFlow(node) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === 177) { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var e = _a[_i]; - if (e.kind === 198) { - bindAssignmentTargetFlow(e.expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === 178) { - for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { - var p = _c[_b]; - if (p.kind === 261) { - bindDestructuringTargetFlow(p.initializer); - } - else if (p.kind === 262) { - bindAssignmentTargetFlow(p.name); - } - else if (p.kind === 263) { - bindAssignmentTargetFlow(p.expression); - } - } - } - } - function bindLogicalExpression(node, trueTarget, falseTarget) { - var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51) { - var saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - bindEachChild(node); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { - bindAssignmentTargetFlow(node.operand); - } - } - } - function bindPostfixUnaryExpressionFlow(node) { - bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { - bindAssignmentTargetFlow(node.operand); - } - } - function bindBinaryExpressionFlow(node) { - var operator = node.operatorToken.kind; - if (operator === 53 || operator === 54) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - bindEachChild(node); - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 58 && node.left.kind === 180) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - function bindDeleteExpressionFlow(node) { - bindEachChild(node); - if (node.expression.kind === 179) { - bindAssignmentTargetFlow(node.expression); - } - } - function bindConditionalExpressionFlow(node) { - var trueLabel = createBranchLabel(); - var falseLabel = createBranchLabel(); - var postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.questionToken); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.colonToken); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - function bindInitializedVariableFlow(node) { - var name = !ts.isOmittedExpression(node) ? node.name : undefined; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var child = _a[_i]; - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - function bindVariableDeclarationFlow(node) { - bindEachChild(node); - if (node.initializer || node.parent.parent.kind === 215 || node.parent.parent.kind === 216) { - bindInitializedVariableFlow(node); - } - } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 290) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - if (node.fullName && n === node.name && node.fullName.kind !== 71) { - return; - } - bind(n); - }); - } - function bindCallExpressionFlow(node) { - var expr = node.expression; - while (expr.kind === 185) { - expr = expr.expression; - } - if (expr.kind === 186 || expr.kind === 187) { - bindEach(node.typeArguments); - bindEach(node.arguments); - bind(node.expression); - } - else { - bindEachChild(node); - } - if (node.expression.kind === 179) { - var propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 199: - case 229: - case 232: - case 178: - case 163: - case 292: - case 275: - case 254: - return 1; - case 230: - return 1 | 64; - case 279: - case 233: - case 231: - case 172: - return 1 | 32; - case 265: - return 1 | 4 | 32; - case 151: - if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 | 4 | 32 | 8 | 128; - } - case 152: - case 228: - case 150: - case 153: - case 154: - case 155: - case 156: - case 157: - case 160: - case 161: - return 1 | 4 | 32 | 8; - case 186: - case 187: - return 1 | 4 | 32 | 8 | 16; - case 234: - return 4; - case 149: - return node.initializer ? 4 : 0; - case 260: - case 214: - case 215: - case 216: - case 235: - return 2; - case 207: - return ts.isFunctionLike(node.parent) ? 0 : 2; - } - return 0; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { - switch (container.kind) { - case 233: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199: - case 229: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 232: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163: - case 178: - case 230: - case 275: - case 292: - case 254: - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160: - case 161: - case 155: - case 156: - case 157: - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 186: - case 187: - case 279: - case 231: - case 172: - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 265 ? node : node.body; - if (body && (body.kind === 265 || body.kind === 234)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 244 || stat.kind === 243) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 32; - } - else { - node.flags &= ~32; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1)) { - errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (ts.isExternalModuleAugmentation(node)) { - declareModuleSymbol(node); - } - else { - var pattern = void 0; - if (node.name.kind === 9) { - var text = node.name.text; - if (ts.hasZeroOrOneAsteriskCharacter(text)) { - pattern = ts.tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } - } - } - else { - var state = declareModuleSymbol(node); - if (state !== 0) { - if (node.symbol.flags & (16 | 32 | 256)) { - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2; - if (node.symbol.constEnumOnlyModule === undefined) { - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function declareModuleSymbol(node) { - var state = getModuleInstanceState(node); - var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); - return state; - } - function bindFunctionOrConstructorType(node) { - var symbol = createSymbol(131072, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072); - var typeLiteralSymbol = createSymbol(2048, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = ts.createMap(); - 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++) { - var prop = _a[_i]; - if (prop.kind === 263 || prop.name.kind !== 71) { - continue; - } - var identifier = prop.name; - var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 - ? 1 - : 2; - var existingKind = seen.get(identifier.text); - if (!existingKind) { - seen.set(identifier.text, currentKind); - continue; - } - if (currentKind === 1 && existingKind === 1) { - var span_1 = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - return bindAnonymousDeclaration(node, 4096, "__object"); - } - function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); - } - function bindJsxAttribute(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 233: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 265: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 107455); - } - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 108 && - node.originalKeywordKind <= 116 && - !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 71) { - var span_2 = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 71 && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71) { - var identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); - } - } - } - function getStrictModeEvalOrArgumentsMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - } - function getStrictModeBlockScopeFunctionDeclarationMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2) { - if (blockScopeContainer.kind !== 265 && - blockScopeContainer.kind !== 233 && - !ts.isFunctionLike(blockScopeContainer)) { - var errorSpan = ts.getErrorSpanForNode(file, node); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - function checkStrictModePostfixUnaryExpression(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - function checkStrictModePrefixUnaryExpression(node) { - if (inStrictMode) { - if (node.operator === 43 || node.operator === 44) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } - bindWorker(node); - if (node.kind > 142) { - var saveParent = parent; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags === 0) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; - } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 290) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; - } - } - } - } - function updateStrictModeStatementList(statements) { - if (!inStrictMode) { - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - case 71: - if (node.isInJSDocNamespace) { - var parentNode = node.parent; - while (parentNode && parentNode.kind !== 290) { - parentNode = parentNode.parent; - } - bindBlockScopedDeclaration(parentNode, 524288, 793064); - break; - } - case 99: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case 179: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - break; - case 194: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case 1: - bindExportsPropertyAssignment(node); - break; - case 2: - bindModuleExportsAssignment(node); - break; - case 3: - bindPrototypePropertyAssignment(node); - break; - case 4: - bindThisPropertyAssignment(node); - break; - case 5: - bindStaticPropertyAssignment(node); - break; - case 0: - break; - default: - ts.Debug.fail("Unknown special property assignment kind"); - } - return checkStrictModeBinaryExpression(node); - case 260: - return checkStrictModeCatchClause(node); - case 188: - return checkStrictModeDeleteExpression(node); - case 8: - return checkStrictModeNumericLiteral(node); - case 193: - return checkStrictModePostfixUnaryExpression(node); - case 192: - return checkStrictModePrefixUnaryExpression(node); - case 220: - return checkStrictModeWithStatement(node); - case 169: - seenThisKeyword = true; - return; - case 158: - return checkTypePredicate(node); - case 145: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); - case 146: - return bindParameter(node); - case 226: - case 176: - return bindVariableDeclarationOrBindingElement(node); - case 149: - case 148: - case 276: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); - case 291: - return bindJSDocProperty(node); - case 261: - case 262: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 264: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 263: - case 255: - var root = container; - var hasRest = false; - while (root.parent) { - if (root.kind === 178 && - root.parent.kind === 194 && - root.parent.operatorToken.kind === 58 && - root.parent.left === root) { - hasRest = true; - break; - } - root = root.parent; - } - return; - case 155: - case 156: - case 157: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); - case 151: - case 150: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 67108864 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 228: - return bindFunctionDeclaration(node); - case 152: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); - case 153: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); - case 154: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 160: - case 161: - case 279: - return bindFunctionOrConstructorType(node); - case 163: - case 172: - case 292: - case 275: - return bindAnonymousDeclaration(node, 2048, "__type"); - case 178: - return bindObjectLiteralExpression(node); - case 186: - case 187: - return bindFunctionExpression(node); - case 181: - if (ts.isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - case 199: - case 229: - inStrictMode = true; - return bindClassLikeDeclaration(node); - case 230: - return bindBlockScopedDeclaration(node, 64, 792968); - case 290: - if (!node.fullName || node.fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); - } - break; - case 231: - return bindBlockScopedDeclaration(node, 524288, 793064); - case 232: - return bindEnumDeclaration(node); - case 233: - return bindModuleDeclaration(node); - case 254: - return bindJsxAttributes(node); - case 253: - return bindJsxAttribute(node, 4, 0); - case 237: - case 240: - case 242: - case 246: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - case 236: - return bindNamespaceExportDeclaration(node); - case 239: - return bindImportClause(node); - case 244: - return bindExportDeclaration(node); - case 243: - return bindExportAssignment(node); - case 265: - updateStrictModeStatementList(node.statements); - return bindSourceFileIfExternalModule(); - case 207: - if (!ts.isFunctionLike(node.parent)) { - return; - } - case 234: - return updateStrictModeStatementList(node.statements); - } - } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 169) { - seenThisKeyword = true; - } - bind(type); - } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } - function bindExportAssignment(node) { - if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); - } - else { - var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) - ? 8388608 - : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); - } - } - function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); - } - if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); - } - function bindExportDeclaration(node) { - if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 33554432, getDeclarationName(node)); - } - else if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 33554432, 0); - } - } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - } - } - function setCommonJsModuleIndicator(node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } - } - } - function bindExportsPropertyAssignment(node) { - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 7340032, 0); - } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (node.kind === 71) { - var symbol = lookupSymbolForName(node.text); - if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === 226) { - var declaration = symbol.valueDeclaration; - if (declaration.initializer) { - return isExportsOrModuleExportsOrAliasOrAssignemnt(declaration.initializer); - } - } - } - return false; - } - function isExportsOrModuleExportsOrAliasOrAssignemnt(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignemnt(node.left) || isExportsOrModuleExportsOrAliasOrAssignemnt(node.right))); - } - function bindModuleExportsAssignment(node) { - var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { - setCommonJsModuleIndicator(node); - return; - } - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); - } - function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, false); - switch (container.kind) { - case 228: - case 186: - container.symbol.members = container.symbol.members || ts.createMap(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); - break; - case 152: - case 149: - case 151: - case 153: - case 154: - var containingClass = container.parent; - var symbol = declareSymbol(ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members, containingClass.symbol, node, 4, 0); - if (symbol) { - symbol.isReplaceableByMethod = true; - } - break; - } - } - function bindPrototypePropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var classPrototype = leftSideOfAssignment.expression; - var constructorFunction = classPrototype.expression; - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.text, leftSideOfAssignment, true); - } - function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.text, leftSideOfAssignment, false); - } - } - function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; - } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { - return; - } - var symbolTable = isPrototypeProperty ? - (targetSymbol.members || (targetSymbol.members = ts.createMap())) : - (targetSymbol.exports || (targetSymbol.exports = ts.createMap())); - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); - } - function bindCallExpression(node) { - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { - setCommonJsModuleIndicator(node); - } - } - function bindClassLikeDeclaration(node) { - if (node.kind === 229) { - bindBlockScopedDeclaration(node, 32, 899519); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32, bindingName); - if (node.name) { - classifiableNames.set(node.name.text, node.name.text); - } - } - var symbol = node.symbol; - var prototypeSymbol = createSymbol(4 | 16777216, "prototype"); - var symbolExport = symbol.exports.get(prototypeSymbol.name); - if (symbolExport) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports.set(prototypeSymbol.name, prototypeSymbol); - prototypeSymbol.parent = symbol; - } - function bindEnumDeclaration(node) { - return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128, 899967) - : bindBlockScopedDeclaration(node, 256, 899327); - } - function bindVariableDeclarationOrBindingElement(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (!ts.isBindingPattern(node.name)) { - if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 107455); - } - else { - declareSymbolAndAddToSymbolTable(node, 1, 107454); - } - } - } - function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1, 107455); - } - if (ts.isParameterPropertyDeclaration(node)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 67108864 : 0), 0); - } - } - function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 106927); - } - else { - declareSymbolAndAddToSymbolTable(node, 16, 106927); - } - } - function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16, bindingName); - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4, 0); - } - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); - } - function checkUnreachable(node) { - if (!(currentFlow.flags & 1)) { - return false; - } - if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || - node.kind === 229 || - (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentFlow = reportedUnreachableFlow; - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - } - return true; - } - } - function computeTransformFlagsForNode(node, subtreeFlags) { - var kind = node.kind; - switch (kind) { - case 181: - return computeCallExpression(node, subtreeFlags); - case 182: - return computeNewExpression(node, subtreeFlags); - case 233: - return computeModuleDeclaration(node, subtreeFlags); - case 185: - return computeParenthesizedExpression(node, subtreeFlags); - case 194: - return computeBinaryExpression(node, subtreeFlags); - case 210: - return computeExpressionStatement(node, subtreeFlags); - case 146: - return computeParameter(node, subtreeFlags); - case 187: - return computeArrowFunction(node, subtreeFlags); - case 186: - return computeFunctionExpression(node, subtreeFlags); - case 228: - return computeFunctionDeclaration(node, subtreeFlags); - case 226: - return computeVariableDeclaration(node, subtreeFlags); - case 227: - return computeVariableDeclarationList(node, subtreeFlags); - case 208: - return computeVariableStatement(node, subtreeFlags); - case 222: - return computeLabeledStatement(node, subtreeFlags); - case 229: - return computeClassDeclaration(node, subtreeFlags); - case 199: - return computeClassExpression(node, subtreeFlags); - case 259: - return computeHeritageClause(node, subtreeFlags); - case 260: - return computeCatchClause(node, subtreeFlags); - case 201: - return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152: - return computeConstructor(node, subtreeFlags); - case 149: - return computePropertyDeclaration(node, subtreeFlags); - case 151: - return computeMethod(node, subtreeFlags); - case 153: - case 154: - return computeAccessor(node, subtreeFlags); - case 237: - return computeImportEquals(node, subtreeFlags); - case 179: - return computePropertyAccess(node, subtreeFlags); - default: - return computeOther(node, kind, subtreeFlags); - } - } - ts.computeTransformFlagsForNode = computeTransformFlagsForNode; - function computeCallExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (node.typeArguments) { - transformFlags |= 3; - } - if (subtreeFlags & 524288 - || isSuperOrSuperProperty(expression, expressionKind)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97: - return true; - case 179: - case 180: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97; - } - return false; - } - function computeNewExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= 3; - } - if (subtreeFlags & 524288) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function computeBinaryExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var operatorTokenKind = node.operatorToken.kind; - var leftKind = node.left.kind; - if (operatorTokenKind === 58 && leftKind === 178) { - transformFlags |= 8 | 192 | 3072; - } - else if (operatorTokenKind === 58 && leftKind === 177) { - transformFlags |= 192 | 3072; - } - else if (operatorTokenKind === 40 - || operatorTokenKind === 62) { - transformFlags |= 32; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeParameter(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var name = node.name; - var initializer = node.initializer; - var dotDotDotToken = node.dotDotDotToken; - if (node.questionToken - || node.type - || subtreeFlags & 4096 - || ts.isThisIdentifier(name)) { - transformFlags |= 3; - } - if (modifierFlags & 92) { - transformFlags |= 3 | 262144; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { - transformFlags |= 192 | 131072; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeParenthesizedExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 202 - || expressionKind === 184) { - transformFlags |= 3; - } - if (expressionTransformFlags & 1024) { - transformFlags |= 1024; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeClassDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 274432) - || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; - } - function computeClassExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 274432 - || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; - } - function computeHeritageClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - switch (node.token) { - case 85: - transformFlags |= 192; - break; - case 108: - transformFlags |= 3; - break; - default: - ts.Debug.fail("Unexpected token for heritage clause"); - break; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeCatchClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; - } - function computeExpressionWithTypeArguments(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (node.typeArguments) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeConstructor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computeMethod(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (node.decorators - || ts.hasModifier(node, 2270) - || node.typeParameters - || node.type - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computeAccessor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.decorators - || ts.hasModifier(node, 2270) - || node.type - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computePropertyDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags | 3; - if (node.initializer) { - transformFlags |= 8192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeFunctionDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body || (modifierFlags & 2)) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags | 33554432; - if (modifierFlags & 2270 - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (modifierFlags & 256) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 163840) { - transformFlags |= 192; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; - } - function computeFunctionExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 163840) { - transformFlags |= 192; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; - } - function computeArrowFunction(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (ts.hasModifier(node, 2270) - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 16384) { - transformFlags |= 32768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; - } - function computePropertyAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeVariableDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags; - transformFlags |= 192 | 8388608; - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (node.type) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeVariableStatement(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var declarationListTransformFlags = node.declarationList.transformFlags; - if (modifierFlags & 2) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608) { - transformFlags |= 192; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeLabeledStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (subtreeFlags & 4194304 - && ts.isIterationStatement(node, true)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeImportEquals(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeExpressionStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 1024) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3; - var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2) === 0) { - transformFlags |= subtreeFlags; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; - } - function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432; - if (subtreeFlags & 8388608) { - transformFlags |= 192; - } - if (node.flags & 3) { - transformFlags |= 192 | 4194304; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; - } - function computeOther(node, kind, subtreeFlags) { - var transformFlags = subtreeFlags; - var excludeFlags = 536872257; - switch (kind) { - case 120: - case 191: - transformFlags |= 8 | 16; - break; - case 114: - case 112: - case 113: - case 117: - case 124: - case 76: - case 232: - case 264: - case 184: - case 202: - case 203: - case 131: - transformFlags |= 3; - break; - case 249: - case 250: - case 251: - case 10: - case 252: - case 253: - case 254: - case 255: - case 256: - transformFlags |= 4; - break; - case 13: - case 14: - case 15: - case 16: - case 196: - case 183: - case 262: - case 115: - case 204: - transformFlags |= 192; - break; - case 9: - if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192; - } - break; - case 8: - if (node.numericLiteralFlags & 48) { - transformFlags |= 192; - } - break; - case 216: - if (node.awaitModifier) { - transformFlags |= 8; - } - transformFlags |= 192; - break; - case 197: - transformFlags |= 8 | 192 | 16777216; - break; - case 119: - case 133: - case 130: - case 134: - case 136: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 158: - case 159: - case 160: - case 161: - case 162: - case 163: - case 164: - case 165: - case 166: - case 167: - case 168: - case 230: - case 231: - case 169: - case 170: - case 171: - case 172: - case 173: - transformFlags = 3; - excludeFlags = -3; - break; - case 144: - transformFlags |= 2097152; - if (subtreeFlags & 16384) { - transformFlags |= 65536; - } - break; - case 198: - transformFlags |= 192 | 524288; - break; - case 263: - transformFlags |= 8 | 1048576; - break; - case 97: - transformFlags |= 192; - break; - case 99: - transformFlags |= 16384; - break; - case 174: - transformFlags |= 192 | 8388608; - if (subtreeFlags & 524288) { - transformFlags |= 8 | 1048576; - } - excludeFlags = 537396545; - break; - case 175: - transformFlags |= 192 | 8388608; - excludeFlags = 537396545; - break; - case 176: - transformFlags |= 192; - if (node.dotDotDotToken) { - transformFlags |= 524288; - } - break; - case 147: - transformFlags |= 3 | 4096; - break; - case 178: - excludeFlags = 540087617; - if (subtreeFlags & 2097152) { - transformFlags |= 192; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - break; - case 177: - case 182: - excludeFlags = 537396545; - if (subtreeFlags & 524288) { - transformFlags |= 192; - } - break; - case 212: - case 213: - case 214: - case 215: - if (subtreeFlags & 4194304) { - transformFlags |= 192; - } - break; - case 265: - if (subtreeFlags & 32768) { - transformFlags |= 192; - } - break; - case 219: - case 217: - case 218: - transformFlags |= 33554432; - break; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~excludeFlags; - } - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 && kind <= 173) { - return -3; - } - switch (kind) { - case 181: - case 182: - case 177: - return 537396545; - case 233: - return 574674241; - case 146: - return 536872257; - case 187: - return 601249089; - case 186: - case 228: - return 601281857; - case 227: - return 546309441; - case 229: - case 199: - return 539358529; - case 152: - return 601015617; - case 151: - case 153: - case 154: - return 601015617; - case 119: - case 133: - case 130: - case 136: - case 134: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 230: - case 231: - return -3; - case 178: - return 540087617; - case 260: - return 537920833; - case 174: - case 175: - return 537396545; - default: - return 536872257; - } - } - ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; -})(ts || (ts = {})); -var ts; -(function (ts) { - function trace(host) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - var Extensions; - (function (Extensions) { - Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; - Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; - })(Extensions || (Extensions = {})); - function resolvedTypeScriptOnly(resolved) { - if (!resolved) { - return undefined; - } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; - } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, - failedLookupLocations: failedLookupLocations - }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); - } - return path; - } - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - if (currentDirectory !== undefined) { - return getDefaultTypeRoots(currentDirectory, host); - } - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { - var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - return undefined; - }); - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - var resolved = primaryLookup(); - var primary = true; - if (!resolved) { - resolved = secondaryLookup(); - primary = false; - } - var resolvedTypeReferenceDirective; - if (resolved) { - resolved = realpath(resolved, host, traceEnabled); - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); - } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; - } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; - function primaryLookup() { - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - return ts.forEach(typeRoots, function (typeRoot) { - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); - if (!directoryExists && traceEnabled) { - trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); - } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); - }); - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - } - function secondaryLookup() { - var resolvedFile; - var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - return resolvedFile; - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - } - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createFileMap(); - var moduleNameToDirectoryMap = ts.createMap(); - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { - var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; - } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (!moduleHasNonRelativeName(nonRelativeModuleName)) { - return undefined; - } - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); - } - return perModuleNameCache; - } - function createPerModuleNameCache() { - var directoryPathMap = ts.createFileMap(); - return { get: get, set: set }; - function get(directory) { - return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); - } - function set(directory, result) { - var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); - if (directoryPathMap.contains(path)) { - return; - } - directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; - var commonPrefix = getCommonPrefix(path, resolvedFileName); - var current = path; - while (true) { - var parent = ts.getDirectoryPath(current); - if (parent === current || directoryPathMap.contains(parent)) { - break; - } - directoryPathMap.set(parent, result); - current = parent; - if (current === commonPrefix) { - break; - } - } - } - function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } - var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); - var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { - i++; - } - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { - return undefined; - } - return directory.substr(0, sep); - } - } - } - ts.createModuleResolutionCache = createModuleResolutionCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); - var result = perFolderCache && perFolderCache.get(moduleName); - if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); - } - } - else { - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); - break; - 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); - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); - } - } - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); - } - else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); - } - } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var tsExtension = ts.tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, false, state); - return path_1 && { path: path_1, extension: tsExtension }; - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, undefined, true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; - 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 }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); - if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); - } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); - if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); - } - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); - } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); - } - } - } - function realpath(path, host, traceEnabled) { - if (!host.realpath) { - return path; - } - var real = ts.normalizePath(host.realpath(path)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); - } - return real; - } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); - } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { - if (!onlyRecordFailures) { - var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); - } - onlyRecordFailures = true; - } - } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); - if (resolvedFromFile) { - return resolvedFromFile; - } - } - if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); - if (!candidateExists) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); - } - onlyRecordFailures = true; - } - } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - switch (extensions) { - case Extensions.DtsOnly: - return tryExtension(".d.ts", ts.Extension.Dts); - case Extensions.TypeScript: - return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); - case Extensions.JavaScript: - return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); - } - function tryExtension(ext, extension) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; - } - } - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - if (state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - } - } - failedLookupLocations.push(fileName); - return undefined; - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { - if (considerPackageJson === void 0) { considerPackageJson = true; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); - } - } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); - if (!file) { - return undefined; - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); - } - } - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); - } - function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; - } - function extensionIsOk(extensions, extension) { - switch (extensions) { - case Extensions.JavaScript: - return extension === ts.Extension.Js || extension === ts.Extension.Jsx; - case Extensions.TypeScript: - return extension === ts.Extension.Ts || extension === ts.Extension.Tsx || extension === ts.Extension.Dts; - case Extensions.DtsOnly: - return extension === ts.Extension.Dts; - } - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - } - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, false, cache); - } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, true, undefined); - } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { - if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); - if (resolutionFromCache) { - return resolutionFromCache; - } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); - } - }); - } - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - if (!nodeModulesFolderExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); - } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); - if (packageResult) { - return packageResult; - } - if (extensions !== Extensions.JavaScript) { - var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); - var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); - } - nodeModulesAtTypesExists = false; - } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); - } - } - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, "__"); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; - } - } - return moduleName; - } - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { - var result = cache && cache.get(containingDirectory); - if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); - } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; - } - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var failedLookupLocations = []; - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, false, failedLookupLocations); - function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); - if (resolvedUsingSettings) { - return { value: resolvedUsingSettings }; - } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - if (moduleHasNonRelativeName(moduleName)) { - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); - if (resolutionFromCache) { - return resolutionFromCache; - } - var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); - }); - if (resolved_3) { - return resolved_3; - } - if (extensions === Extensions.TypeScript) { - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, false, state)); - } - } - } - ts.classicNameResolver = classicNameResolver; - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); - } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, true, failedLookupLocations); - } - ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; - function toSearchResult(value) { - return value !== undefined ? { value: value } : undefined; - } - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } -})(ts || (ts = {})); -var ts; -(function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; - var nextSymbolId = 1; - var nextNodeId = 1; - var nextMergeId = 1; - var nextFlowId = 1; - function getNodeId(node) { - if (!node.id) { - node.id = nextNodeId; - nextNodeId++; - } - return node.id; - } - ts.getNodeId = getNodeId; - function getSymbolId(symbol) { - if (!symbol.id) { - symbol.id = nextSymbolId; - nextSymbolId++; - } - return symbol.id; - } - ts.getSymbolId = getSymbolId; - function createTypeChecker(host, produceDiagnostics) { - var cancellationToken; - var requestedExternalEmitHelpers; - var externalHelpersModule; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var Type = ts.objectAllocator.getTypeConstructor(); - var Signature = ts.objectAllocator.getSignatureConstructor(); - var typeCount = 0; - var symbolCount = 0; - var enumCount = 0; - var symbolInstantiationDepth = 0; - var emptyArray = []; - var emptySymbols = ts.createMap(); - var compilerOptions = host.getCompilerOptions(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); - var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; - var emitResolver = createResolver(); - var nodeBuilder = createNodeBuilder(); - var undefinedSymbol = createSymbol(4, "undefined"); - undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4, "arguments"); - var checker = { - getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCount: function () { return typeCount; }, - isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, - isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, - isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, - getMergedSymbol: getMergedSymbol, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeOfSymbolAtLocation: function (symbol, location) { - location = ts.getParseTreeNode(location); - return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; - }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); - return getSymbolsOfParameterPropertyDeclaration(parameter, parameterName); - }, - getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, - getPropertiesOfType: getPropertiesOfType, - getPropertyOfType: getPropertyOfType, - getIndexInfoOfType: getIndexInfoOfType, - getSignaturesOfType: getSignaturesOfType, - getIndexTypeOfType: getIndexTypeOfType, - getBaseTypes: getBaseTypes, - getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, - getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); - return node ? getTypeFromTypeNode(node) : unknownType; - }, - getParameterType: getTypeAtPosition, - getReturnTypeOfSignature: getReturnTypeOfSignature, - getNonNullableType: getNonNullableType, - typeToTypeNode: nodeBuilder.typeToTypeNode, - indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, - signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, - getSymbolsInScope: function (location, meaning) { - location = ts.getParseTreeNode(location); - return location ? getSymbolsInScope(location, meaning) : []; - }, - getSymbolAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getSymbolAtLocation(node) : undefined; - }, - getShorthandAssignmentValueSymbol: function (node) { - node = ts.getParseTreeNode(node); - return node ? getShorthandAssignmentValueSymbol(node) : undefined; - }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); - return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; - }, - getTypeAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getTypeOfNode(node) : unknownType; - }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); - return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; - }, - signatureToString: function (signature, enclosingDeclaration, flags, kind) { - return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); - }, - typeToString: function (type, enclosingDeclaration, flags) { - return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); - }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); - }, - getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, - getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); - return node ? getContextualType(node) : undefined; - }, - getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); - return node ? getResolvedSignature(node, candidatesOutArray) : undefined; - }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, propertyName) : false; - }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); - return declaration ? getSignatureFromDeclaration(declaration) : undefined; - }, - isImplementationOfOverload: function (node) { - node = ts.getParseTreeNode(node, ts.isFunctionLike); - return node ? isImplementationOfOverload(node) : undefined; - }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - links.immediateTarget = getTargetOfAliasDeclaration(node, true); - } - return links.immediateTarget; - }, - getAliasedSymbol: resolveAlias, - getEmitResolver: getEmitResolver, - getExportsOfModule: getExportsOfModuleAsArray, - getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); - return node ? isOptionalParameter(node) : false; - }, - tryGetMemberInModuleExports: tryGetMemberInModuleExports, - tryFindAmbientModuleWithoutAugmentations: function (moduleName) { - return tryFindAmbientModule(moduleName, false); - }, - getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, - getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, - getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, - getBaseConstraintOfType: getBaseConstraintOfType, - }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var literalTypes = ts.createMap(); - var indexedAccessTypes = ts.createMap(); - var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4, "unknown"); - var resolvingSymbol = createSymbol(0, "__resolving__"); - var anyType = createIntrinsicType(1, "any"); - var autoType = createIntrinsicType(1, "any"); - var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); - var stringType = createIntrinsicType(2, "string"); - var numberType = createIntrinsicType(4, "number"); - var trueType = createIntrinsicType(128, "true"); - var falseType = createIntrinsicType(128, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); - var silentNeverType = createIntrinsicType(8192, "never"); - var nonPrimitiveType = createIntrinsicType(16777216, "object"); - var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); - emptyTypeLiteralSymbol.members = ts.createMap(); - var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); - var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; - var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, undefined, 0, false, false); - var enumNumberIndexInfo = createIndexInfo(stringType, true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); - var globals = ts.createMap(); - var patternAmbientModules; - var globalObjectType; - var globalFunctionType; - var globalArrayType; - var globalReadonlyArrayType; - var globalStringType; - var globalNumberType; - var globalBooleanType; - var globalRegExpType; - var globalThisType; - var anyArrayType; - var autoArrayType; - var anyReadonlyArrayType; - var deferredGlobalESSymbolConstructorSymbol; - var deferredGlobalESSymbolType; - var deferredGlobalTypedPropertyDescriptorType; - var deferredGlobalPromiseType; - var deferredGlobalPromiseConstructorSymbol; - var deferredGlobalPromiseConstructorLikeType; - var deferredGlobalIterableType; - var deferredGlobalIteratorType; - var deferredGlobalIterableIteratorType; - var deferredGlobalAsyncIterableType; - var deferredGlobalAsyncIteratorType; - var deferredGlobalAsyncIterableIteratorType; - var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; - var deferredNodes; - var deferredUnusedIdentifierNodes; - var flowLoopStart = 0; - var flowLoopCount = 0; - var visitedFlowCount = 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 = []; - var flowLoopCaches = []; - var flowLoopNodes = []; - var flowLoopKeys = []; - var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; - var potentialThisCollisions = []; - 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, - "boolean": 4, - "symbol": 8, - "undefined": 16384, - "object": 16, - "function": 32 - }); - var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128, - "number": 256, - "boolean": 512, - "symbol": 1024, - "undefined": 131072, - "object": 2048, - "function": 4096 - }); - var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType - }); - var typeofType = createTypeofType(); - var _jsxNamespace; - var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - var jsxTypes = ts.createMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - 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(); - return checker; - function getJsxNamespace() { - if (!_jsxNamespace) { - _jsxNamespace = "React"; - if (compilerOptions.jsxFactory) { - _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); - if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; - } - } - else if (compilerOptions.reactNamespace) { - _jsxNamespace = compilerOptions.reactNamespace; - } - } - return _jsxNamespace; - } - function getEmitResolver(sourceFile, cancellationToken) { - getDiagnostics(sourceFile, cancellationToken); - return emitResolver; - } - function error(location, message, arg0, arg1, arg2) { - var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); - diagnostics.add(diagnostic); - } - function createSymbol(flags, name) { - symbolCount++; - var symbol = (new Symbol(flags | 134217728, name)); - symbol.checkFlags = 0; - return symbol; - } - function isTransientSymbol(symbol) { - return (symbol.flags & 134217728) !== 0; - } - function getExcludedSymbolFlags(flags) { - var result = 0; - if (flags & 2) - result |= 107455; - if (flags & 1) - result |= 107454; - if (flags & 4) - result |= 0; - if (flags & 8) - result |= 900095; - if (flags & 16) - result |= 106927; - if (flags & 32) - result |= 899519; - if (flags & 64) - result |= 792968; - if (flags & 256) - result |= 899327; - if (flags & 128) - result |= 899967; - if (flags & 512) - result |= 106639; - if (flags & 8192) - result |= 99263; - if (flags & 32768) - result |= 41919; - if (flags & 65536) - result |= 74687; - if (flags & 262144) - result |= 530920; - if (flags & 524288) - result |= 793064; - if (flags & 8388608) - result |= 8388608; - return result; - } - function recordMergedSymbol(target, source) { - if (!source.mergeId) { - source.mergeId = nextMergeId; - nextMergeId++; - } - mergedSymbols[source.mergeId] = target; - } - function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags, symbol.name); - result.declarations = symbol.declarations.slice(0); - result.parent = symbol.parent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = ts.cloneMap(symbol.members); - if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); - recordMergedSymbol(result, symbol); - return result; - } - function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { - if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { - target.constEnumOnlyModule = false; - } - target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { - target.valueDeclaration = source.valueDeclaration; - } - ts.addRange(target.declarations, source.declarations); - if (source.members) { - if (!target.members) - target.members = ts.createMap(); - mergeSymbolTable(target.members, source.members); - } - if (source.exports) { - if (!target.exports) - target.exports = ts.createMap(); - mergeSymbolTable(target.exports, source.exports); - } - recordMergedSymbol(target, source); - } - else if (target.flags & 1024) { - 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - } - } - function mergeSymbolTable(target, source) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - } - else { - if (!(targetSymbol.flags & 134217728)) { - targetSymbol = cloneSymbol(targetSymbol); - target.set(id, targetSymbol); - } - mergeSymbol(targetSymbol, sourceSymbol); - } - }); - } - function mergeModuleAugmentation(moduleName) { - var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { - ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); - return; - } - if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports); - } - else { - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) - ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found - : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); - if (!mainModule) { - return; - } - mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920) { - mainModule = mainModule.flags & 134217728 ? mainModule : cloneSymbol(mainModule); - mergeSymbol(mainModule, moduleAugmentation.symbol); - } - else { - error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); - } - } - } - function addToSymbolTable(target, source, message) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (targetSymbol) { - ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(id, message)); - } - else { - target.set(id, sourceSymbol); - } - }); - function addDeclarationDiagnostic(id, message) { - return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; - } - } - function getSymbolLinks(symbol) { - if (symbol.flags & 134217728) - return symbol; - var id = getSymbolId(symbol); - return symbolLinks[id] || (symbolLinks[id] = {}); - } - function getNodeLinks(node) { - var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); - } - function getObjectFlags(type) { - return type.flags & 32768 ? type.objectFlags : 0; - } - function isGlobalSourceFile(node) { - return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); - } - function getSymbol(symbols, name, meaning) { - if (meaning) { - var symbol = symbols.get(name); - if (symbol) { - ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } - } - } - } - function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { - var constructorDeclaration = parameter.parent; - var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); - if (parameterSymbol && propertySymbol) { - return [parameterSymbol, propertySymbol]; - } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); - } - function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { - var declarationFile = ts.getSourceFileOfNode(declaration); - var useFile = ts.getSourceFileOfNode(usage); - if (declarationFile !== useFile) { - if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out) || - ts.isInAmbientContext(declaration)) { - return true; - } - if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - return true; - } - var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); - } - if (declaration.pos <= usage.pos) { - if (declaration.kind === 176) { - var errorBindingElement = ts.getAncestor(usage, 176); - if (errorBindingElement) { - return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || - declaration.pos < errorBindingElement.pos; - } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); - } - else if (declaration.kind === 226) { - return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); - } - return true; - } - if (usage.parent.kind === 246) { - return true; - } - var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); - function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); - switch (declaration.parent.parent.kind) { - case 208: - case 214: - case 216: - if (isSameScopeDescendentOf(usage, declaration, container)) { - return true; - } - break; - } - switch (declaration.parent.parent.kind) { - case 215: - case 216: - if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { - return true; - } - } - return false; - } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { - return !!ts.findAncestor(usage, function (current) { - if (current === container) { - return "quit"; - } - if (ts.isFunctionLike(current)) { - return true; - } - var initializerOfProperty = current.parent && - current.parent.kind === 149 && - current.parent.initializer === current; - if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32) { - if (declaration.kind === 151) { - return true; - } - } - else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); - if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { - return true; - } - } - } - }); - } - } - 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; - var errorLocation = location; - var grandparent; - var isInExternalModule = false; - loop: while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - 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) { - useResult = result.flags & 262144 - ? lastLocation === location.type || - lastLocation.kind === 146 || - lastLocation.kind === 145 - : false; - } - if (meaning & 107455 && result.flags & 1) { - useResult = - lastLocation.kind === 146 || - (lastLocation === location.type && - result.valueDeclaration.kind === 146); - } - } - if (useResult) { - break loop; - } - else { - result = undefined; - } - } - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) - break; - isInExternalModule = true; - case 233: - var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 || ts.isAmbientModule(location)) { - if (result = moduleExports.get("default")) { - var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { - break loop; - } - result = undefined; - } - var moduleExport = moduleExports.get(name); - if (moduleExport && - moduleExport.flags === 8388608 && - ts.getDeclarationOfKind(moduleExport, 246)) { - break; - } - } - if (result = lookup(moduleExports, name, meaning & 8914931)) { - break loop; - } - break; - case 232: - if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { - break loop; - } - break; - case 149: - case 148: - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { - var ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455)) { - propertyWithInvalidInitializer = location; - } - } - } - break; - case 229: - case 199: - case 230: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { - if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { - result = undefined; - break; - } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); - return undefined; - } - break loop; - } - if (location.kind === 199 && meaning & 32) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; - case 144: - grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - 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; - } - } - break; - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 187: - if (meaning & 3 && name === "arguments") { - result = argumentsSymbol; - break loop; - } - break; - case 186: - if (meaning & 3 && name === "arguments") { - result = argumentsSymbol; - break loop; - } - if (meaning & 16) { - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; - } - } - break; - case 147: - if (location.parent && location.parent.kind === 146) { - location = location.parent; - } - if (location.parent && ts.isClassElement(location.parent)) { - location = location.parent; - } - break; - } - lastLocation = location; - location = location.parent; - } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { - result.isReferenced = true; - } - if (!result) { - result = lookup(globals, name, meaning); - } - if (!result) { - if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation) && - !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && - !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - 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; - } - if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer) { - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return undefined; - } - if (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455)) { - var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); - if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { - checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); - } - } - if (result && isInExternalModule && (meaning & 107455) === 107455) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); - } - } - } - return result; - } - function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 145 && decl.parent === container) { - return true; - } - } - return false; - } - function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 71 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { - return false; - } - var container = ts.getThisContainer(errorLocation, true); - var location = container; - while (location) { - if (ts.isClassLike(location.parent)) { - var classSymbol = getSymbolOfNode(location.parent); - if (!classSymbol) { - break; - } - var constructorType = getTypeOfSymbol(classSymbol); - if (getPropertyOfType(constructorType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); - return true; - } - if (location === container && !(ts.getModifierFlags(location) & 32)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; - if (getPropertyOfType(instanceType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return true; - } - } - } - location = location.parent; - } - return false; - } - function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { - error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - } - return isError; - } - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 71: - case 179: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } - } - function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); - return true; - } - } - return false; - } - 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); - return true; - } - } - return false; - } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (107455 & ~1024 & ~793064)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, name); - return true; - } - } - else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, name); - return true; - } - } - return false; - } - function checkResolvedBlockScopedVariable(result, errorLocation) { - ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); - 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(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 256) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - } - } - function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); - } - function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237) { - return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); - } - } - function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); - } - function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248) { - return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); - } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); - } - function getTargetOfImportClause(node, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); - if (moduleSymbol) { - var exportDefaultSymbol = void 0; - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - exportDefaultSymbol = moduleSymbol; - } - else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); - } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { - return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - return exportDefaultSymbol; - } - } - function getTargetOfNamespaceImport(node, dontResolveAlias) { - var moduleSpecifier = node.parent.parent.moduleSpecifier; - return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); - } - function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 | 1920)) { - return valueSymbol; - } - var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); - result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); - result.parent = valueSymbol.parent || typeSymbol.parent; - if (valueSymbol.valueDeclaration) - result.valueDeclaration = valueSymbol.valueDeclaration; - if (typeSymbol.members) - result.members = typeSymbol.members; - if (valueSymbol.exports) - result.exports = valueSymbol.exports; - return result; - } - function getExportOfModule(symbol, name, dontResolveAlias) { - if (symbol.flags & 1536) { - return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); - } - } - function getPropertyOfVariable(symbol, name) { - if (symbol.flags & 3) { - var typeAnnotation = symbol.valueDeclaration.type; - if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); - } - } - } - function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); - if (targetSymbol) { - var name = specifier.propertyName || specifier.name; - if (name.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return moduleSymbol; - } - var symbolFromVariable = void 0; - if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text); - } - else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); - } - symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name.text, dontResolveAlias); - if (!symbolFromModule && allowSyntheticDefaultImports && name.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - var symbol = symbolFromModule && symbolFromVariable ? - combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : - symbolFromModule || symbolFromVariable; - if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); - } - return symbol; - } - } - } - function getTargetOfImportSpecifier(node, dontResolveAlias) { - return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); - } - function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { - return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); - } - function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); - } - function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); - } - function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { - switch (node.kind) { - case 237: - return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239: - return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240: - return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242: - return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246: - return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); - case 243: - return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236: - return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - } - } - function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)); - return shouldResolve ? resolveAlias(symbol) : symbol; - } - function resolveAlias(symbol) { - ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.target) { - links.target = resolvingSymbol; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - var target = getTargetOfAliasDeclaration(node); - if (links.target === resolvingSymbol) { - links.target = target || unknownSymbol; - } - else { - error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); - } - } - else if (links.target === resolvingSymbol) { - links.target = unknownSymbol; - } - return links.target; - } - function markExportAsReferenced(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target) { - var markAlias = target === unknownSymbol || - ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); - if (markAlias) { - markAliasSymbolAsReferenced(symbol); - } - } - } - function markAliasSymbolAsReferenced(symbol) { - var links = getSymbolLinks(symbol); - if (!links.referenced) { - links.referenced = true; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - if (node.kind === 243) { - checkExpressionCached(node.expression); - } - else if (node.kind === 246) { - checkExpressionCached(node.propertyName || node.name); - } - else if (ts.isInternalModuleImportEqualsDeclaration(node)) { - checkExpressionCached(node.moduleReference); - } - } - } - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (entityName.kind === 71 || entityName.parent.kind === 143) { - return resolveEntityName(entityName, 1920, false, dontResolveAlias); - } - else { - ts.Debug.assert(entityName.parent.kind === 237); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); - } - } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); - } - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { - if (ts.nodeIsMissing(name)) { - return undefined; - } - var symbol; - if (name.kind === 71) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); - if (!symbol) { - return undefined; - } - } - else if (name.kind === 143 || name.kind === 179) { - var left = void 0; - if (name.kind === 143) { - left = name.left; - } - else if (name.kind === 179 && - (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { - left = name.expression; - } - else { - return undefined; - } - var right = name.kind === 143 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); - if (!namespace || ts.nodeIsMissing(right)) { - return undefined; - } - else if (namespace === unknownSymbol) { - return namespace; - } - symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); - if (!symbol) { - if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); - } - return undefined; - } - } - else if (name.kind === 185) { - return ts.isEntityNameExpression(name.expression) ? - resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : - undefined; - } - else { - ts.Debug.fail("Unknown entity name kind."); - } - 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) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); - } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - if (moduleReferenceExpression.kind !== 9 && moduleReferenceExpression.kind !== 13) { - return; - } - var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); - } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - var moduleName = ts.escapeIdentifier(moduleReference); - 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; - } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); - var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); - if (sourceFile) { - if (sourceFile.symbol) { - return getMergedSymbol(sourceFile.symbol); - } - if (moduleNotFoundError) { - error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - } - return undefined; - } - if (patternAmbientModules) { - var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleName); - if (pattern) { - return getMergedSymbol(pattern.symbol); - } - } - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { - if (isForAugmentation) { - var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); - } - else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return undefined; - } - if (moduleNotFoundError) { - if (resolutionDiagnostic) { - error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); - } - else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(errorNode, moduleNotFoundError, moduleName); - } - } - } - return undefined; - } - function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; - } - function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { - 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)); - } - return symbol; - } - function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; - } - function getExportsOfModuleAsArray(moduleSymbol) { - return symbolsToArray(getExportsOfModule(moduleSymbol)); - } - function getExportsAndPropertiesOfModule(moduleSymbol) { - var exports = getExportsOfModuleAsArray(moduleSymbol); - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); - } - return exports; - } - function tryGetMemberInModuleExports(memberName, moduleSymbol) { - var symbolTable = getExportsOfModule(moduleSymbol); - if (symbolTable) { - return symbolTable.get(memberName); - } - } - function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; - } - function getExportsOfModule(moduleSymbol) { - var links = getSymbolLinks(moduleSymbol); - return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); - } - function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { - if (id === "default") - return; - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - if (lookupTable && exportNode) { - lookupTable.set(id, { - specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) - }); - } - } - else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { - var collisionTracker = lookupTable.get(id); - if (!collisionTracker.exportsWithDuplicate) { - collisionTracker.exportsWithDuplicate = [exportNode]; - } - else { - collisionTracker.exportsWithDuplicate.push(exportNode); - } - } - }); - } - function getExportsForModule(moduleSymbol) { - var visitedSymbols = []; - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - return visit(moduleSymbol) || moduleSymbol.exports; - function visit(symbol) { - if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { - return; - } - visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); - var exportStars = symbol.exports.get("__export"); - if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable_1 = ts.createMap(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); - } - lookupTable_1.forEach(function (_a, id) { - var exportsWithDuplicate = _a.exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { - return; - } - for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { - var node = exportsWithDuplicate_1[_i]; - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, id)); - } - }); - extendExportSymbols(symbols, nestedSymbols); - } - return symbols; - } - } - function getMergedSymbol(symbol) { - var merged; - return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; - } - function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); - } - function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); - } - function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; - } - function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 || symbol.flags & 8388608 && resolveAlias(symbol).flags & 107455); - } - function findConstructorDeclaration(node) { - var members = node.members; - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var member = members_1[_i]; - if (member.kind === 152 && ts.nodeIsPresent(member.body)) { - return member; - } - } - } - function createType(flags) { - var result = new Type(checker, flags); - typeCount++; - result.id = typeCount; - return result; - } - function createIntrinsicType(kind, intrinsicName) { - var type = createType(kind); - type.intrinsicName = intrinsicName; - return type; - } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8; - type.intrinsicName = "boolean"; - return type; - } - function createObjectType(objectFlags, symbol) { - var type = createType(32768); - type.objectFlags = objectFlags; - type.symbol = symbol; - return type; - } - function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); - } - function isReservedMemberName(name) { - return name.charCodeAt(0) === 95 && - name.charCodeAt(1) === 95 && - name.charCodeAt(2) !== 95 && - name.charCodeAt(2) !== 64; - } - function getNamedMembers(members) { - var result; - members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } - } - }); - return result || emptyArray; - } - function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; - return type; - } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function forEachSymbolTableInScope(enclosingDeclaration, callback) { - var result; - for (var location = enclosingDeclaration; location; location = location.parent) { - if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { - return result; - } - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - case 233: - if (result = callback(getSymbolOfNode(location).exports)) { - return result; - } - break; - } - } - return callback(globals); - } - function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; - } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); - } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { - return undefined; - } - visitedSymbolTables.push(symbols); - var result = trySymbolTable(symbols); - visitedSymbolTables.pop(); - return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } - } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.name))) { - return [symbol]; - } - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } - } - }); - } - } - if (symbol) { - if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - } - } - } - function needsQualification(symbol, enclosingDeclaration, meaning) { - var qualify = false; - forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable.get(symbol.name); - if (!symbolFromSymbolTable) { - return false; - } - if (symbolFromSymbolTable === symbol) { - return true; - } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { - qualify = true; - return true; - } - return false; - }); - return qualify; - } - function isPropertyOrMethodDeclarationSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - switch (declaration.kind) { - case 149: - case 151: - case 153: - case 154: - continue; - default: - return false; - } - } - return true; - } - return false; - } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, - }; - } - return hasAccessibleDeclarations; - } - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); - } - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); - if (symbolExternalModule) { - var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); - if (symbolExternalModule !== enclosingExternalModule) { - return { - accessibility: 2, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) - }; - } - } - return { - accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - }; - } - return { accessibility: 0 }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } - } - function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); - } - function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { - var aliasesToMakeVisible; - if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { - return undefined; - } - return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; - function getIsDeclarationVisible(declaration) { - if (!isDeclarationVisible(declaration)) { - var anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1) && - isDeclarationVisible(anyImportSyntax.parent)) { - if (shouldComputeAliasToMakeVisible) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } - } - return true; - } - return false; - } - return true; - } - } - function isEntityNameVisible(entityName, enclosingDeclaration) { - var meaning; - if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning = 107455 | 1048576; - } - else if (entityName.kind === 143 || entityName.kind === 179 || - entityName.parent.kind === 237) { - meaning = 1920; - } - else { - meaning = 793064; - } - var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol, true)) || { - accessibility: 1, - errorSymbolName: ts.getTextOfNode(firstIdentifier), - errorNode: firstIdentifier - }; - } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function typeToString(type, enclosingDeclaration, flags) { - 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) { - 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() { - return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - 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) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - } - }; - function createNodeBuilderContext(enclosingDeclaration, flags) { - return { - enclosingDeclaration: enclosingDeclaration, - flags: flags, - encounteredError: false, - symbolStack: undefined - }; - } - function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; - if (!type) { - context.encounteredError = true; - return undefined; - } - if (type.flags & 1) { - return ts.createKeywordTypeNode(119); - } - if (type.flags & 2) { - return ts.createKeywordTypeNode(136); - } - if (type.flags & 4) { - return ts.createKeywordTypeNode(133); - } - if (type.flags & 8) { - return ts.createKeywordTypeNode(122); - } - 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.setEmitFlags(ts.createLiteral(type.value), 16777216)); - } - if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.value))); - } - if (type.flags & 128) { - return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); - } - if (type.flags & 1024) { - return ts.createKeywordTypeNode(105); - } - if (type.flags & 2048) { - return ts.createKeywordTypeNode(139); - } - if (type.flags & 4096) { - return ts.createKeywordTypeNode(95); - } - if (type.flags & 8192) { - return ts.createKeywordTypeNode(130); - } - if (type.flags & 512) { - return ts.createKeywordTypeNode(137); - } - if (type.flags & 16777216) { - return ts.createKeywordTypeNode(134); - } - if (type.flags & 16384 && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { - context.encounteredError = true; - } - } - return ts.createThis(); - } - var objectFlags = getObjectFlags(type); - if (objectFlags & 4) { - ts.Debug.assert(!!(type.flags & 32768)); - return typeReferenceToTypeNode(type); - } - if (type.flags & 16384 || objectFlags & 3) { - var name = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name, undefined); - } - 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); - } - 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)) { - context.encounteredError = true; - } - return undefined; - } - } - 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, context); - return ts.createTypeOperatorNode(indexTypeNode); - } - if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); - var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); - return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); - } - ts.Debug.fail("Should be unreachable."); - function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768)); - var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; - var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - 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; - if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 | 512) || - shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455); - } - else if (ts.contains(context.symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - var entityName = symbolToName(typeAlias, context, 793064, false); - return ts.createTypeReferenceNode(entityName, undefined); - } - else { - return ts.createKeywordTypeNode(119); - } - } - else { - if (!context.symbolStack) { - context.symbolStack = []; - } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; - } - } - else { - return createTypeNodeFromObjectType(type); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); - } - } - } - function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - return createMappedTypeNodeFromType(type); - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); - return signatureNode; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); - return signatureNode; - } - } - var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; - var members = createTypeNodesFromResolvedType(resolved); - context.flags = savedFlags; - var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); - } - 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) { - 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - return ts.createTupleTypeNode(tupleConstituentNodes); - } - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { - context.encounteredError = true; - } - return undefined; - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - var qualifiedName = void 0; - if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - 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 { - qualifiedName = ts.createQualifiedName(namePart, undefined); - } - } - } - } - var entityName = undefined; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } - 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, context)); - } - for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); - } - if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); - } - if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); - } - var properties = resolvedType.properties; - if (!properties) { - return typeElements; - } - for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { - var propertySymbol = properties_2[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); - 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, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - typeElements.push(methodDeclaration); - } - } - else { - 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 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 ? 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.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, context); - } - 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, context) { - var name = symbolToName(type.symbol, context, 793064, true); - var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); - var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); - } - 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); - 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, context, meaning, expectsIdentifier) { - var chain; - var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { - chain = getSymbolChain(symbol, meaning, true); - ts.Debug.assert(chain && chain.length > 0); - } - else { - chain = [symbol]; - } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(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 typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - 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) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); - var parentSymbol; - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); - } - } - } - if (accessibleSymbolChain) { - return accessibleSymbolChain; - } - if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - return [symbol]; - } - } - } - 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; - } - } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144)) { - if (t.flags & (128 | 256)) { - 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); - } - } - if (flags & 4096) - result.push(nullType); - if (flags & 2048) - result.push(undefinedType); - return result || types; - } - function visibilityToString(flags) { - if (flags === 8) { - return "private"; - } - if (flags === 16) { - return "protected"; - } - return "public"; - } - function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); - if (node.kind === 231) { - return getSymbolOfNode(node); - } - } - return undefined; - } - function isTopLevelInExternalModuleAugmentation(node) { - return node && node.parent && - node.parent.kind === 234 && - ts.isExternalModuleAugmentation(node.parent.parent); - } - function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; - } - function getNameOfSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } - } - return symbol.name; - } - function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); - } - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - writePunctuation(writer, 21); - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 23); - writer.writeSymbol(symbolName, symbol); - } - } - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 128 & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & 16; - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~512; - if (type.flags & 16793231) { - writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 16384 && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (getObjectFlags(type) & 4) { - writeTypeReference(type, nextFlags); - } - 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 & (272 | 16384)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 512) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 196608) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (getObjectFlags(type) & (16 | 32)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 96) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 262144) { - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 64); - } - else if (type.flags & 524288) { - writeType(type.objectType, 64); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 17); - writeSpace(writer); - writePunctuation(writer, 24); - writeSpace(writer); - writePunctuation(writer, 18); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 ? 0 : 64); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); - } - if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 256); - pos++; - while (pos < end) { - writePunctuation(writer, 26); - writeSpace(writer); - writeType(typeArguments[pos], 0); - pos++; - } - writePunctuation(writer, 29); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 64); - writePunctuation(writer, 21); - writePunctuation(writer, 22); - } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23); - } - } - } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 64) { - writePunctuation(writer, 19); - } - if (type.flags & 65536) { - writeTypeList(formatUnionTypes(type.types), 49); - } - else { - writeTypeList(type.types, 48); - } - if (flags & 64) { - writePunctuation(writer, 20); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); - } - else if (ts.contains(symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); - } - else { - writeKeyword(writer, 119); - } - } - else { - if (!symbolStack) { - symbolStack = []; - } - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - else { - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 2) || - (ts.contains(symbolStack, symbol)); - } - } - } - function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 103); - writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); - writeSpace(writer); - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 67108864) { - writePunctuation(writer, 55); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 64) { - return true; - } - else if (flags & 256) { - var typeParameters = callSignature.target && (flags & 32) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - writeMappedType(type); - return; - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 64) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 94); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); - if (flags & 64) { - writePunctuation(writer, 20); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56); - writeSpace(writer); - writeType(t, 0); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); - if (type.declaration.questionToken) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 174) { - writePunctuation(writer, 17); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); - } - else if (bindingPattern.kind === 175) { - writePunctuation(writer, 21); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); - } - writePunctuation(writer, 22); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 176); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 256; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - flags = 0; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99); - } - writeSpace(writer); - writeKeyword(writer, 126); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 2048 && isTypeAny(returnType)) { - return; - } - if (flags & 8) { - writeSpace(writer); - writePunctuation(writer, 36); - } - else { - writePunctuation(writer, 56); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); - writeSpace(writer); - } - if (signature.target && (flags & 32)) { - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); - writeSpace(writer); - switch (kind) { - case 1: - writeKeyword(writer, 133); - break; - case 0: - writeKeyword(writer, 136); - break; - } - writePunctuation(writer, 22); - writePunctuation(writer, 56); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } - function isDeclarationVisible(node) { - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } - return false; - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 176: - return isDeclarationVisible(node.parent.parent); - case 226: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - return false; - } - case 233: - case 229: - case 230: - case 231: - case 228: - case 232: - case 237: - if (ts.isExternalModuleAugmentation(node)) { - return true; - } - var parent = getDeclarationContainer(node); - if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { - return isGlobalSourceFile(parent); - } - return isDeclarationVisible(parent); - case 149: - case 148: - case 153: - case 154: - case 151: - case 150: - if (ts.getModifierFlags(node) & (8 | 16)) { - return false; - } - case 152: - case 156: - case 155: - case 157: - case 146: - case 234: - case 160: - case 161: - case 163: - case 159: - case 164: - case 165: - case 166: - case 167: - case 168: - return isDeclarationVisible(node.parent); - case 239: - case 240: - case 242: - return false; - case 145: - case 265: - case 236: - return true; - case 243: - return false; - default: - return false; - } - } - } - function collectLinkedAliases(node) { - var exportSymbol; - if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); - } - else if (node.parent.kind === 246) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); - } - var result = []; - if (exportSymbol) { - buildVisibleNodeList(exportSymbol.declarations); - } - return result; - function buildVisibleNodeList(declarations) { - ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; - var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } - if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { - var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); - if (importSymbol) { - buildVisibleNodeList(importSymbol.declarations); - } - } - }); - } - } - function pushTypeResolution(target, propertyName) { - var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); - if (resolutionCycleStartIndex >= 0) { - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { - resolutionResults[i] = false; - } - return false; - } - resolutionTargets.push(target); - resolutionResults.push(true); - resolutionPropertyNames.push(propertyName); - return true; - } - function findResolutionCycleStartIndex(target, propertyName) { - for (var i = resolutionTargets.length - 1; i >= 0; i--) { - if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { - return -1; - } - if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { - return i; - } - } - return -1; - } - function hasType(target, propertyName) { - if (propertyName === 0) { - return getSymbolLinks(target).type; - } - if (propertyName === 2) { - return getSymbolLinks(target).declaredType; - } - if (propertyName === 1) { - return target.resolvedBaseConstructorType; - } - if (propertyName === 3) { - return target.resolvedReturnType; - } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); - } - function popTypeResolution() { - resolutionTargets.pop(); - resolutionPropertyNames.pop(); - return resolutionResults.pop(); - } - function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { - switch (node.kind) { - case 226: - case 227: - case 242: - case 241: - case 240: - case 239: - return false; - default: - return true; - } - }); - return node && node.parent; - } - function getTypeOfPrototypeProperty(prototype) { - var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); - return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; - } - function getTypeOfPropertyOfType(type, name) { - var prop = getPropertyOfType(type, name); - return prop ? getTypeOfSymbol(prop) : undefined; - } - function isTypeAny(type) { - return type && (type.flags & 1) !== 0; - } - function getTypeForBindingElementParent(node) { - var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); - } - function isComputedNonLiteralName(name) { - return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); - } - function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144); }); - if (source.flags & 8192) { - return emptyObjectType; - } - if (source.flags & 65536) { - return mapType(source, function (t) { return getRestType(t, properties, symbol); }); - } - var members = ts.createMap(); - var names = ts.createMap(); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var name = properties_3[_i]; - names.set(ts.getTextOfPropertyName(name), true); - } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - var inNamesToRemove = names.has(prop.name); - 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); - } - } - var stringIndexInfo = getIndexInfoOfType(source, 0); - var numberIndexInfo = getIndexInfoOfType(source, 1); - return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getTypeForBindingElement(declaration) { - var pattern = declaration.parent; - var parentType = getTypeForBindingElementParent(pattern.parent); - if (parentType === unknownType) { - return unknownType; - } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } - return parentType; - } - var type; - if (pattern.kind === 174) { - if (declaration.dotDotDotToken) { - if (!isValidSpreadType(parentType)) { - error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); - return unknownType; - } - var literalMembers = []; - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!element.dotDotDotToken) { - literalMembers.push(element.propertyName || element.name); - } - } - type = getRestType(parentType, literalMembers, declaration.symbol); - } - else { - var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - return anyType; - } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - var text = ts.getTextOfPropertyName(name); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return unknownType; - } - } - } - else { - var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); - if (declaration.dotDotDotToken) { - type = createArrayType(elementType); - } - else { - var propName = "" + ts.indexOf(pattern.elements, declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); - } - return unknownType; - } - } - } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { - type = getTypeWithFacts(type, 131072); - } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : - type; - } - function getTypeForDeclarationFromJSDocComment(declaration) { - var jsdocType = ts.getJSDocType(declaration); - if (jsdocType) { - return getTypeFromTypeNode(jsdocType); - } - return undefined; - } - function isNullOrUndefined(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; - } - function isEmptyArrayLiteral(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 177 && expr.elements.length === 0; - } - function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048) : type; - } - function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - if (declaration.parent.parent.kind === 215) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 | 262144) ? indexType : stringType; - } - if (declaration.parent.parent.kind === 216) { - var forOfStatement = declaration.parent.parent; - return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; - } - if (ts.isBindingPattern(declaration.parent)) { - return getTypeForBindingElement(declaration); - } - if (declaration.type) { - var declaredType = getTypeFromTypeNode(declaration.type); - return addOptionality(declaredType, declaration.questionToken && includeOptionality); - } - if ((noImplicitAny || declaration.flags & 65536) && - declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { - if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { - return autoType; - } - if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { - return autoArrayType; - } - } - if (declaration.kind === 146) { - var func = declaration.parent; - if (func.kind === 154 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); - if (getter) { - var getterSignature = getSignatureFromDeclaration(getter); - var thisParameter = getAccessorThisParameter(func); - if (thisParameter && declaration === thisParameter) { - ts.Debug.assert(!thisParameter.type); - return getTypeOfSymbol(getterSignature.thisParameter); - } - return getReturnTypeOfSignature(getterSignature); - } - } - var type = void 0; - if (declaration.symbol.name === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } - if (type) { - return addOptionality(type, declaration.questionToken && includeOptionality); - } - } - if (declaration.initializer) { - var type = checkDeclarationInitializer(declaration); - return addOptionality(type, declaration.questionToken && includeOptionality); - } - if (ts.isJsxAttribute(declaration)) { - return trueType; - } - if (declaration.kind === 262) { - return checkIdentifier(declaration.name); - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false, true); - } - return undefined; - } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { - 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 : - declaration.kind === 179 ? ts.getAncestor(declaration, 194) : - undefined; - if (!expression) { - return unknownType; - } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 152) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - 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)); - } - } - else if (!jsDocType) { - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); - } - } - var type = jsDocType || getUnionType(types, true); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - } - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { - if (element.initializer) { - return checkDeclarationInitializer(element); - } - if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); - } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); - } - return anyType; - } - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); - var stringIndexInfo; - var hasComputedProperties = false; - ts.forEach(pattern.elements, function (e) { - var name = e.propertyName || e.name; - if (isComputedNonLiteralName(name)) { - hasComputedProperties = true; - return; - } - if (e.dotDotDotToken) { - stringIndexInfo = createIndexInfo(anyType, false); - return; - } - var text = ts.getTextOfPropertyName(name); - var flags = 4 | (e.initializer ? 67108864 : 0); - var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); - symbol.bindingElement = e; - members.set(symbol.name, symbol); - }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); - if (includePatternInType) { - result.pattern = pattern; - } - if (hasComputedProperties) { - result.objectFlags |= 512; - } - return result; - } - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { - var elements = pattern.elements; - var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; - } - var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); - if (includePatternInType) { - result = cloneTypeReference(result); - result.pattern = pattern; - } - return result; - } - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); - } - function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, true); - if (type) { - if (reportErrors) { - reportErrorsFromWidening(declaration, type); - } - if (declaration.kind === 261) { - return type; - } - return getWidenedType(type); - } - type = declaration.dotDotDotToken ? anyArrayType : anyType; - if (reportErrors && noImplicitAny) { - if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); - } - } - return type; - } - function declarationBelongsToPrivateAmbientMember(declaration) { - var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 ? root.parent : root; - return isPrivateWithinAmbient(memberDeclaration); - } - function getTypeOfVariableOrParameterOrProperty(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 16777216) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - if (declaration.kind === 243) { - return links.type = checkExpression(declaration.expression); - } - if (declaration.flags & 65536 && declaration.kind === 291 && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - var type = void 0; - if (declaration.kind === 194 || - declaration.kind === 179 && declaration.parent.kind === 194) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; - } - function getAnnotatedAccessorType(accessor) { - if (accessor) { - if (accessor.kind === 153) { - return accessor.type && getTypeFromTypeNode(accessor.type); - } - else { - var setterTypeAnnotation = ts.getSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); - } - } - return undefined; - } - function getAnnotatedAccessorThisParameter(accessor) { - var parameter = getAccessorThisParameter(accessor); - return parameter && parameter.symbol; - } - function getThisTypeOfDeclaration(declaration) { - return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); - } - function getTypeOfAccessors(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153); - var setter = ts.getDeclarationOfKind(symbol, 154); - if (getter && getter.flags & 65536) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - var type = void 0; - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; - } - else { - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; - } - else { - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - type = anyType; - } - } - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153); - error(getter_1, 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, symbolToString(symbol)); - } - } - links.type = type; - } - return links.type; - } - function getBaseTypeVariableOfClass(symbol) { - var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; - } - function getTypeOfFuncClassEnumModule(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else { - var type = createObjectType(16, symbol); - if (symbol.flags & 32) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; - } - else { - links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; - } - } - } - return links.type; - } - function getTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; - } - function getTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 107455 - ? getTypeOfSymbol(targetSymbol) - : unknownType; - } - return links.type; - } - function getTypeOfInstantiatedSymbol(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = unknownType; - } - else { - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - } - return links.type; - } - function reportCircularityError(symbol) { - if (symbol.valueDeclaration.type) { - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - return unknownType; - } - if (noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - return anyType; - } - function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 1) { - return getTypeOfInstantiatedSymbol(symbol); - } - if (symbol.flags & (3 | 4)) { - return getTypeOfVariableOrParameterOrProperty(symbol); - } - if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { - return getTypeOfFuncClassEnumModule(symbol); - } - if (symbol.flags & 8) { - return getTypeOfEnumMember(symbol); - } - if (symbol.flags & 98304) { - return getTypeOfAccessors(symbol); - } - if (symbol.flags & 8388608) { - return getTypeOfAlias(symbol); - } - return unknownType; - } - function isReferenceToType(type, target) { - return type !== undefined - && target !== undefined - && (getObjectFlags(type) & 4) !== 0 - && type.target === target; - } - function getTargetType(type) { - return getObjectFlags(type) & 4 ? type.target : type; - } - function hasBaseType(type, checkBase) { - return check(type); - function check(type) { - if (getObjectFlags(type) & (3 | 4)) { - var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); - } - else if (type.flags & 131072) { - return ts.forEach(type.types, check); - } - } - } - function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } - } - return typeParameters; - } - function appendOuterTypeParameters(typeParameters, node) { - while (true) { - node = node.parent; - if (!node) { - return typeParameters; - } - if (node.kind === 229 || node.kind === 199 || - node.kind === 228 || node.kind === 186 || - node.kind === 151 || node.kind === 187) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } - } - } - } - function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); - return appendOuterTypeParameters(undefined, declaration); - } - function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { - var result; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - if (node.kind === 230 || node.kind === 229 || - node.kind === 199 || node.kind === 231) { - var declaration = node; - if (declaration.typeParameters) { - result = appendTypeParameters(result, declaration.typeParameters); - } - } - } - return result; - } - function getTypeParametersOfClassOrInterface(symbol) { - return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); - } - function isMixinConstructorType(type) { - var signatures = getSignaturesOfType(type, 1); - if (signatures.length === 1) { - var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; - } - return false; - } - function isConstructorType(type) { - if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { - return true; - } - if (type.flags & 540672) { - var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); - } - return false; - } - function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); - } - function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); - } - function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; - } - function getBaseConstructorTypeOfClass(type) { - if (!type.resolvedBaseConstructorType) { - var baseTypeNode = getBaseTypeNodeOfClass(type); - if (!baseTypeNode) { - return type.resolvedBaseConstructorType = undefinedType; - } - if (!pushTypeResolution(type, 1)) { - return unknownType; - } - var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 | 131072)) { - resolveStructuredTypeMembers(baseConstructorType); - } - if (!popTypeResolution()) { - error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = unknownType; - } - if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); - return type.resolvedBaseConstructorType = unknownType; - } - type.resolvedBaseConstructorType = baseConstructorType; - } - return type.resolvedBaseConstructorType; - } - function getBaseTypes(type) { - if (!type.resolvedBaseTypes) { - if (type.objectFlags & 8) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 | 64)) { - if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(type); - } - } - else { - ts.Debug.fail("type must be class or interface"); - } - } - return type.resolvedBaseTypes; - } - function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { - 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, typeArgs); - } - else if (baseConstructorType.flags & 1) { - baseType = baseConstructorType; - } - else { - var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); - if (!constructors.length) { - error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; - } - baseType = getReturnTypeOfSignature(constructors[0]); - } - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } - if (baseType === unknownType) { - return; - } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; - } - if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - return; - } - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - function areAllOuterTypeParametersApplied(type) { - var outerTypeParameters = type.outerTypeParameters; - if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; - var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; - } - return true; - } - function isValidBaseType(type) { - return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || - type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); - } - function resolveBaseTypesOfInterface(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - } - } - else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); - } - } - } - } - } - } - function isIndependentInterface(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230) { - if (declaration.flags & 64) { - return false; - } - var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); - if (baseTypeNodes) { - for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { - var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064, true); - if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { - return false; - } - } - } - } - } - } - return true; - } - function getDeclaredTypeOfClassOrInterface(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var kind = symbol.flags & 32 ? 1 : 2; - var type = links.declaredType = createObjectType(kind, symbol); - var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); - var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { - type.objectFlags |= 4; - type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); - type.outerTypeParameters = outerTypeParameters; - type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384); - type.thisType.isThisType = true; - type.thisType.symbol = symbol; - type.thisType.constraint = type; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - if (!pushTypeResolution(symbol, 2)) { - return unknownType; - } - var declaration = ts.getDeclarationOfKind(symbol, 290); - var type = void 0; - if (declaration) { - if (declaration.jsDocTypeLiteral) { - type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); - } - else { - type = getTypeFromTypeNode(declaration.typeExpression.type); - } - } - else { - declaration = ts.getDeclarationOfKind(symbol, 231); - type = getTypeFromTypeNode(declaration.type); - } - if (popTypeResolution()) { - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (typeParameters) { - links.typeParameters = typeParameters; - links.instantiations = ts.createMap(); - links.instantiations.set(getTypeListId(typeParameters), type); - } - } - else { - type = unknownType; - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); - } - links.declaredType = type; - } - return links.declaredType; - } - function isLiteralEnumMember(member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && - expr.operand.kind === 8 || - expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); - } - 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 (member.initializer && member.initializer.kind === 9) { - return links.enumKind = 1; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; - } - } - } - } - return links.enumKind = hasNonLiteralMember ? 0 : 1; - } - 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) { - 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); - } - } - } - 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; - } - } - 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)); - if (!links.declaredType) { - links.declaredType = enumType; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeParameter(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(16384); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; - } - function getDeclaredTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; - } - function getDeclaredTypeOfSymbol(symbol) { - if (symbol.flags & (32 | 64)) { - return getDeclaredTypeOfClassOrInterface(symbol); - } - if (symbol.flags & 524288) { - return getDeclaredTypeOfTypeAlias(symbol); - } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); - } - if (symbol.flags & 384) { - return getDeclaredTypeOfEnum(symbol); - } - if (symbol.flags & 8) { - return getDeclaredTypeOfEnumMember(symbol); - } - if (symbol.flags & 8388608) { - return getDeclaredTypeOfAlias(symbol); - } - return unknownType; - } - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; - } - function isIndependentType(node) { - switch (node.kind) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 134: - case 105: - case 139: - case 95: - case 130: - case 173: - return true; - case 164: - return isIndependentType(node.elementType); - case 159: - return isIndependentTypeReference(node); - } - return false; - } - function isIndependentVariableLikeDeclaration(node) { - return node.type && isIndependentType(node.type) || !node.type && !node.initializer; - } - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152 && (!node.type || !isIndependentType(node.type))) { - return false; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; - } - function isIndependentMember(symbol) { - if (symbol.declarations && symbol.declarations.length === 1) { - var declaration = symbol.declarations[0]; - if (declaration) { - switch (declaration.kind) { - case 149: - case 148: - return isIndependentVariableLikeDeclaration(declaration); - case 151: - case 150: - case 152: - return isIndependentFunctionLikeDeclaration(declaration); - } - } - } - return false; - } - function createSymbolTable(symbols) { - var result = ts.createMap(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - result.set(symbol.name, symbol); - } - return result; - } - function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; - result.set(symbol.name, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); - } - return result; - } - function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { - var s = baseSymbols_1[_i]; - if (!symbols.has(s.name)) { - symbols.set(s.name, s); - } - } - } - function resolveDeclaredMembers(type) { - if (!type.declaredProperties) { - var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); - type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - } - return type; - } - function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4) { - var target = type.target; - var typeArguments = type.typeArguments; - if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); - } - } - else if (type.flags & 131072) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); - } - return type; - } - function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { - mapper = createTypeMapper(typeParameters, typeArguments); - members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); - callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); - constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); - stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); - numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); - } - var baseTypes = getBaseTypes(source); - if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { - members = createSymbolTable(source.declaredProperties); - } - var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { - var baseType = baseTypes_1[_i]; - var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; - addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); - constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); - if (!stringIndexInfo) { - stringIndexInfo = instantiatedBaseType === anyType ? - createIndexInfo(anyType, false) : - getIndexInfoOfType(instantiatedBaseType, 0); - } - numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); - } - } - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveClassOrInterfaceMembers(type) { - resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); - } - function resolveTypeReferenceMembers(type) { - var source = resolveDeclaredMembers(type.target); - var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); - var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? - type.typeArguments : ts.concatenate(type.typeArguments, [type]); - resolveObjectTypeMembers(type, source, typeParameters, typeArguments); - } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); - sig.declaration = declaration; - sig.typeParameters = typeParameters; - sig.parameters = parameters; - sig.thisParameter = thisParameter; - sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; - sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; - return sig; - } - function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); - } - function getDefaultConstructSignatures(classType) { - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - var baseSignatures = getSignaturesOfType(baseConstructorType, 1); - if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; - } - var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); - var typeArgCount = ts.length(typeArguments); - var result = []; - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var baseSig = baseSignatures_1[_i]; - var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); - var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); - sig.typeParameters = classType.localTypeParameters; - sig.resolvedReturnType = classType; - result.push(sig); - } - } - return result; - } - function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { - for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { - var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { - return s; - } - } - } - function findMatchingSignatures(signatureLists, signature, listIndex) { - if (signature.typeParameters) { - if (listIndex > 0) { - return undefined; - } - for (var i = 1; i < signatureLists.length; i++) { - if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { - return undefined; - } - } - return [signature]; - } - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); - if (!match) { - return undefined; - } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } - } - return result; - } - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { - var signature = _a[_i]; - if (!result || !findMatchingSignature(result, signature, false, true, true)) { - var unionSignatures = findMatchingSignatures(signatureLists, signature, i); - if (unionSignatures) { - var s = signature; - if (unionSignatures.length > 1) { - s = cloneSignature(signature); - if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); - } - s.resolvedReturnType = undefined; - s.unionSignatures = unionSignatures; - } - (result || (result = [])).push(s); - } - } - } - } - return result || emptyArray; - } - function getUnionIndexInfo(types, kind) { - var indexTypes = []; - var isAnyReadonly = false; - 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; - } - indexTypes.push(indexInfo.type); - isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; - } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); - } - function resolveUnionTypeMembers(type) { - var callSignatures = getUnionSignatures(type.types, 0); - var constructSignatures = getUnionSignatures(type.types, 1); - var stringIndexInfo = getUnionIndexInfo(type.types, 0); - var numberIndexInfo = getUnionIndexInfo(type.types, 1); - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function intersectTypes(type1, type2) { - return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); - } - function intersectIndexInfos(info1, info2) { - return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); - } - function unionSpreadIndexInfos(info1, info2) { - return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); - } - function includeMixinType(type, types, index) { - var mixedTypes = []; - for (var i = 0; i < types.length; i++) { - if (i === index) { - mixedTypes.push(type); - } - else if (isMixinConstructorType(types[i])) { - mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); - } - } - return getIntersectionType(mixedTypes); - } - function resolveIntersectionTypeMembers(type) { - var callSignatures = emptyArray; - var constructSignatures = emptyArray; - var stringIndexInfo; - var numberIndexInfo; - var types = type.types; - var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_3 = function (i) { - var t = type.types[i]; - if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { - var signatures = getSignaturesOfType(t, 1); - if (signatures.length && mixinCount > 0) { - signatures = ts.map(signatures, function (s) { - var clone = cloneSignature(s); - clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); - return clone; - }); - } - constructSignatures = ts.concatenate(constructSignatures, signatures); - } - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); - stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); - numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); - }; - for (var i = 0; i < types.length; i++) { - _loop_3(i); - } - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveAnonymousTypeMembers(type) { - var symbol = type.symbol; - if (type.target) { - var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); - var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); - var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); - var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else if (symbol.flags & 2048) { - var members = symbol.members; - var callSignatures = getSignaturesOfSymbol(members.get("__call")); - var constructSignatures = getSignaturesOfSymbol(members.get("__new")); - var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else { - var members = emptySymbols; - var constructSignatures = emptyArray; - var stringIndexInfo = undefined; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - } - if (symbol.flags & 32) { - var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 | 131072 | 540672)) { - members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); - } - else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, false); - } - } - var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); - if (symbol.flags & (16 | 8192)) { - type.callSignatures = getSignaturesOfSymbol(symbol); - } - } - } - function resolveMappedTypeMembers(type) { - var members = ts.createMap(); - var stringIndexInfo; - setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var typeParameter = getTypeParameterFromMappedType(type); - var constraintType = getConstraintTypeFromMappedType(type); - var templateType = getTemplateTypeFromMappedType(type); - var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); - var templateReadonly = !!type.declaration.readonlyToken; - var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170) { - for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { - var propertySymbol = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); - } - if (getIndexInfoOfType(modifiersType, 0)) { - addMemberForKeyType(stringType); - } - } - else { - var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; - forEachType(iterationType, addMemberForKeyType); - } - setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { - var iterationMapper = createTypeMapper([typeParameter], [t]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; - var propType = instantiateType(templateType, templateMapper); - if (t.flags & 32) { - var propName = t.value; - var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); - var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; - prop.type = propType; - if (propertySymbol) { - prop.syntheticOrigin = propertySymbol; - } - members.set(propName, prop); - } - else if (t.flags & 2) { - stringIndexInfo = createIndexInfo(propType, templateReadonly); - } - } - } - function getTypeParameterFromMappedType(type) { - return type.typeParameter || - (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); - } - function getConstraintTypeFromMappedType(type) { - return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); - } - function getTemplateTypeFromMappedType(type) { - return type.templateType || - (type.templateType = type.declaration.type ? - instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : - unknownType); - } - function getModifiersTypeFromMappedType(type) { - if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170) { - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); - } - else { - var declaredType = getTypeFromMappedTypeNode(type.declaration); - var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; - } - } - return type.modifiersType; - } - function isGenericMappedType(type) { - if (getObjectFlags(type) & 32) { - var constraintType = getConstraintTypeFromMappedType(type); - return maybeTypeOfKind(constraintType, 540672 | 262144); - } - return false; - } - function resolveStructuredTypeMembers(type) { - if (!type.members) { - if (type.flags & 32768) { - if (type.objectFlags & 4) { - resolveTypeReferenceMembers(type); - } - else if (type.objectFlags & 3) { - resolveClassOrInterfaceMembers(type); - } - else if (type.objectFlags & 16) { - resolveAnonymousTypeMembers(type); - } - else if (type.objectFlags & 32) { - resolveMappedTypeMembers(type); - } - } - else if (type.flags & 65536) { - resolveUnionTypeMembers(type); - } - else if (type.flags & 131072) { - resolveIntersectionTypeMembers(type); - } - } - return type; - } - function getPropertiesOfObjectType(type) { - if (type.flags & 32768) { - return resolveStructuredTypeMembers(type).properties; - } - return emptyArray; - } - function getPropertyOfObjectType(type, name) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - } - } - function getPropertiesOfUnionOrIntersectionType(type) { - if (!type.resolvedProperties) { - var members = ts.createMap(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var current = _a[_i]; - for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { - var prop = _c[_b]; - if (!members.has(prop.name)) { - var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.name); - if (combinedProp) { - members.set(prop.name, combinedProp); - } - } - } - if (type.flags & 65536) { - break; - } - } - type.resolvedProperties = getNamedMembers(members); - } - return type.resolvedProperties; - } - function getPropertiesOfType(type) { - type = getApparentType(type); - return type.flags & 196608 ? - 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) : - getBaseConstraintOfType(type); - } - function getConstraintOfTypeParameter(typeParameter) { - return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; - } - function getConstraintOfIndexedAccess(type) { - var baseObjectType = getBaseConstraintOfType(type.objectType); - var baseIndexType = getBaseConstraintOfType(type.indexType); - return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; - } - function getBaseConstraintOfType(type) { - if (type.flags & (540672 | 196608)) { - var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } - } - else if (type.flags & 262144) { - return stringType; - } - return undefined; - } - function hasNonCircularBaseConstraint(type) { - return getResolvedBaseConstraint(type) !== circularConstraintType; - } - function getResolvedBaseConstraint(type) { - var typeStack; - var circular; - if (!type.resolvedBaseConstraint) { - typeStack = []; - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); - } - return type.resolvedBaseConstraint; - function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { - circular = true; - return undefined; - } - typeStack.push(t); - var result = computeBaseConstraint(t); - typeStack.pop(); - return result; - } - function computeBaseConstraint(t) { - if (t.flags & 16384) { - var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; - } - if (t.flags & 196608) { - var types = t.types; - var baseTypes = []; - 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); - } - } - return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : - undefined; - } - if (t.flags & 262144) { - return stringType; - } - if (t.flags & 524288) { - var baseObjectType = getBaseConstraint(t.objectType); - var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; - return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; - } - return t; - } - } - function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); - } - function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameter(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; - } - function getApparentType(type) { - var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 ? globalStringType : - t.flags & 84 ? globalNumberType : - t.flags & 136 ? globalBooleanType : - t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : - t; - } - function createUnionOrIntersectionProperty(containingType, name) { - var props; - var types = containingType.types; - var isUnion = containingType.flags & 65536; - var excludeModifiers = isUnion ? 24 : 0; - var commonFlags = isUnion ? 0 : 67108864; - var syntheticFlag = 4; - var checkFlags = 0; - 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { - commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } - checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | - (!(modifiers & 24) ? 64 : 0) | - (modifiers & 16 ? 128 : 0) | - (modifiers & 8 ? 256 : 0) | - (modifiers & 32 ? 512 : 0); - if (!isMethodLike(prop)) { - syntheticFlag = 2; - } - } - else if (isUnion) { - checkFlags |= 16; - } - } - } - if (!props) { - return undefined; - } - if (props.length === 1 && !(checkFlags & 16)) { - return props[0]; - } - var propTypes = []; - var declarations = []; - var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; - if (prop.declarations) { - ts.addRange(declarations, prop.declarations); - } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - checkFlags |= 32; - } - propTypes.push(type); - } - var result = createSymbol(4 | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; - result.containingType = containingType; - result.declarations = declarations; - result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); - return result; - } - function getUnionOrIntersectionProperty(type, name) { - var properties = type.propertyCache || (type.propertyCache = ts.createMap()); - var property = properties.get(name); - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties.set(name, property); - } - } - return property; - } - function getPropertyOfUnionOrIntersectionType(type, name) { - var property = getUnionOrIntersectionProperty(type, name); - return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; - } - function getPropertyOfType(type, name) { - type = getApparentType(type); - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; - } - } - return getPropertyOfObjectType(globalObjectType, name); - } - if (type.flags & 196608) { - return getPropertyOfUnionOrIntersectionType(type, name); - } - return undefined; - } - function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; - } - return emptyArray; - } - function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); - } - function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; - } - } - function getIndexTypeOfStructuredType(type, kind) { - var info = getIndexInfoOfStructuredType(type, kind); - return info && info.type; - } - function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); - } - function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); - } - function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { - var propTypes = []; - for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.name)) { - propTypes.push(getTypeOfSymbol(prop)); - } - } - if (propTypes.length) { - return getUnionType(propTypes, true); - } - } - return undefined; - } - function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 65536) { - var templateTag = ts.getJSDocTemplateTag(declaration); - if (templateTag) { - return getTypeParametersFromDeclaration(templateTag.typeParameters); - } - } - return undefined; - } - function getTypeParametersFromDeclaration(typeParameterDeclarations) { - var result = []; - ts.forEach(typeParameterDeclarations, function (node) { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - result.push(tp); - } - }); - return result; - } - function symbolsToArray(symbols) { - var result = []; - symbols.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - result.push(symbol); - } - }); - return result; - } - function isJSDocOptionalParameter(node) { - if (node.flags & 65536) { - if (node.type && node.type.kind === 278) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 278; - } - } - } - } - } - function tryFindAmbientModule(moduleName, withAugmentations) { - if (ts.isExternalModuleNameRelative(moduleName)) { - return undefined; - } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); - return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; - } - function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { - return true; - } - if (node.initializer) { - var signatureDeclaration = node.parent; - var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); - ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; - } - var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); - if (iife) { - return !node.type && - !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; - } - return false; - } - function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 71) { - var parameterName = node.parameterName; - return { - kind: 1, - parameterName: parameterName ? parameterName.text : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; - } - else { - return { - kind: 0, - type: getTypeFromTypeNode(node.type) - }; - } - } - function getMinTypeArgumentCount(typeParameters) { - var minTypeArgumentCount = 0; - if (typeParameters) { - for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { - minTypeArgumentCount = i + 1; - } - } - } - return minTypeArgumentCount; - } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { - var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { - if (!typeArguments) { - typeArguments = []; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = isJavaScript ? anyType : emptyObjectType; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : isJavaScript ? anyType : emptyObjectType; - } - } - } - return typeArguments; - } - function getSignatureFromDeclaration(declaration) { - var links = getNodeLinks(declaration); - if (!links.resolvedSignature) { - var parameters = []; - var hasLiteralTypes = false; - var minArgumentCount = 0; - var thisParameter = undefined; - var hasThisParameter = void 0; - var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); - var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); - for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { - var param = declaration.parameters[i]; - var paramSymbol = param.symbol; - if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.name, 107455, undefined, undefined); - paramSymbol = resolvedSymbol; - } - if (i === 0 && paramSymbol.name === "this") { - hasThisParameter = true; - thisParameter = param.symbol; - } - else { - parameters.push(paramSymbol); - } - if (param.type && param.type.kind === 173) { - hasLiteralTypes = true; - } - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; - if (!isOptionalParameter_1) { - minArgumentCount = parameters.length; - } - } - if ((declaration.kind === 153 || declaration.kind === 154) && - !ts.hasDynamicName(declaration) && - (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 ? 154 : 153; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); - if (other) { - thisParameter = getAnnotatedAccessorThisParameter(other); - } - } - var classType = declaration.kind === 152 ? - getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) - : undefined; - var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : - getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); - } - return links.resolvedSignature; - } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); - } - else if (classType) { - return classType; - } - else if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.flags & 65536) { - var type = getReturnTypeFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } - } - function containsArgumentsReference(declaration) { - var links = getNodeLinks(declaration); - if (links.containsArgumentsReference === undefined) { - if (links.flags & 8192) { - links.containsArgumentsReference = true; - } - else { - links.containsArgumentsReference = traverse(declaration.body); - } - } - return links.containsArgumentsReference; - function traverse(node) { - if (!node) - return false; - switch (node.kind) { - case 71: - return node.text === "arguments" && ts.isPartOfExpression(node); - case 149: - case 151: - case 153: - case 154: - return node.name.kind === 144 - && traverse(node.name); - default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); - } - } - } - function getSignaturesOfSymbol(symbol) { - if (!symbol) - return emptyArray; - var result = []; - for (var i = 0; i < symbol.declarations.length; i++) { - var node = symbol.declarations[i]; - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 279: - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); - } - } - return result; - } - function resolveExternalModuleTypeByLiteral(name) { - var moduleSym = resolveExternalModuleName(name, name); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - return getTypeOfSymbol(resolvedModuleSymbol); - } - } - return anyType; - } - function getThisTypeOfSignature(signature) { - if (signature.thisParameter) { - return getTypeOfSymbol(signature.thisParameter); - } - } - function getReturnTypeOfSignature(signature) { - if (!signature.resolvedReturnType) { - if (!pushTypeResolution(signature, 3)) { - return unknownType; - } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - 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); - } - } - } - signature.resolvedReturnType = type; - } - return signature.resolvedReturnType; - } - function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; - } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); - var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); - var id = getTypeListId(typeArguments); - var instantiation = instantiations.get(id); - if (!instantiation) { - instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); - } - return instantiation; - } - function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); - } - function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); - } - return signature.erasedSignatureCache; - } - function getOrCreateTypeFromSignature(signature) { - if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; - var type = createObjectType(16); - type.members = emptySymbols; - type.properties = emptyArray; - type.callSignatures = !isConstructor ? [signature] : emptyArray; - type.constructSignatures = isConstructor ? [signature] : emptyArray; - signature.isolatedSignatureType = type; - } - return signature.isolatedSignatureType; - } - function getIndexSymbol(symbol) { - return symbol.members.get("__index"); - } - function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 133 : 136; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var node = decl; - if (node.parameters.length === 1) { - var parameter = node.parameters[0]; - if (parameter && parameter.type && parameter.type.kind === syntaxKind) { - return node; - } - } - } - } - return undefined; - } - function createIndexInfo(type, isReadonly, declaration) { - return { type: type, isReadonly: isReadonly, declaration: declaration }; - } - function getIndexInfoOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); - } - return undefined; - } - function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145).constraint; - } - function getConstraintFromTypeParameter(typeParameter) { - if (!typeParameter.constraint) { - if (typeParameter.target) { - var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); - typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; - } - else { - var constraintDeclaration = getConstraintDeclaration(typeParameter); - typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; - } - } - return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; - } - function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); - } - function getTypeListId(types) { - var result = ""; - if (types) { - var length_4 = types.length; - var i = 0; - while (i < length_4) { - var startId = types[i].id; - var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; - } - } - return result; - } - function getPropagatingFlagsOfTypes(types, excludeKinds) { - var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; - if (!(type.flags & excludeKinds)) { - result |= type.flags; - } - } - return result & 14680064; - } - function createTypeReference(target, typeArguments) { - var id = getTypeListId(typeArguments); - var type = target.instantiations.get(id); - if (!type) { - type = createObjectType(4, target.symbol); - target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - type.target = target; - type.typeArguments = typeArguments; - } - return type; - } - function cloneTypeReference(source) { - var type = createType(source.flags); - type.symbol = source.symbol; - type.objectFlags = source.objectFlags; - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return ts.length(type.target.typeParameters); - } - function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { - var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); - var typeParameters = type.localTypeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : 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(typeArgs, typeParameters, minTypeArgumentCount, node)); - return createTypeReference(type, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - return unknownType; - } - return type; - } - function getTypeAliasInstantiation(symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var links = getSymbolLinks(symbol); - var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); - var instantiation = links.instantiations.get(id); - if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); - } - return instantiation; - } - function getTypeFromTypeAliasReference(node, symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeParameters = getSymbolLinks(symbol).typeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); - return unknownType; - } - return getTypeAliasInstantiation(symbol, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return type; - } - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } - function getTypeReferenceName(node) { - switch (node.kind) { - case 159: - return node.typeName; - case 277: - return node.name; - case 201: - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; - } - } - return undefined; - } - function resolveTypeReferenceName(typeReferenceName) { - if (!typeReferenceName) { - return unknownSymbol; - } - 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, typeArguments); - } - if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol, typeArguments); - } - if (symbol.flags & 107455 && node.kind === 277) { - return getTypeOfSymbol(symbol); - } - return getTypeFromNonGenericTypeReference(node, symbol); - } - function getPrimitiveTypeFromJSDocTypeReference(node) { - if (ts.isIdentifier(node.name)) { - switch (node.name.text) { - case "String": - return stringType; - case "Number": - return numberType; - case "Boolean": - return booleanType; - case "Void": - return voidType; - case "Undefined": - return undefinedType; - case "Null": - return nullType; - case "Object": - return anyType; - case "Function": - return anyFunctionType; - case "Array": - case "array": - return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined; - case "Promise": - case "promise": - return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; - } - } - } - function getTypeFromJSDocNullableTypeNode(node) { - var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; - } - function getTypeFromTypeReference(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var symbol = void 0; - var type = void 0; - if (node.kind === 277) { - type = getPrimitiveTypeFromJSDocTypeReference(node); - if (!type) { - var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(typeReferenceName); - type = getTypeReferenceType(node, symbol); - } - } - else { - var typeNameOrExpression = node.kind === 159 - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - 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) { - links.resolvedType = getWidenedType(checkExpression(node.exprName)); - } - return links.resolvedType; - } - function getTypeOfGlobalSymbol(symbol, arity) { - function getTypeDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; - switch (declaration.kind) { - case 229: - case 230: - case 232: - return declaration; - } - } - } - if (!symbol) { - return arity ? emptyGenericType : emptyObjectType; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return arity ? emptyGenericType : emptyObjectType; - } - if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return arity ? emptyGenericType : emptyObjectType; - } - return type; - } - function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); - } - function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); - } - function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); - } - function getGlobalType(name, arity, reportErrors) { - var symbol = getGlobalTypeSymbol(name, reportErrors); - return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; - } - function getGlobalTypedPropertyDescriptorType() { - return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; - } - function getGlobalTemplateStringsArrayType() { - return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; - } - function getGlobalESSymbolConstructorSymbol(reportErrors) { - return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); - } - function getGlobalESSymbolType(reportErrors) { - return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; - } - function getGlobalPromiseType(reportErrors) { - return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; - } - function getGlobalPromiseConstructorSymbol(reportErrors) { - return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); - } - function getGlobalPromiseConstructorLikeType(reportErrors) { - return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; - } - function getGlobalAsyncIterableType(reportErrors) { - return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIteratorType(reportErrors) { - return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIterableIteratorType(reportErrors) { - return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableType(reportErrors) { - return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIteratorType(reportErrors) { - return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableIteratorType(reportErrors) { - return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalTypeOrUndefined(name, arity) { - if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064, undefined); - return symbol && getTypeOfGlobalSymbol(symbol, arity); - } - function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); - return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); - } - function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { - return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; - } - function createTypedPropertyDescriptorType(propertyType) { - return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); - } - function createAsyncIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); - } - function createAsyncIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); - } - function createIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); - } - function createIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); - } - function createArrayType(elementType) { - return createTypeFromGenericGlobalType(globalArrayType, [elementType]); - } - function getTypeFromArrayTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); - } - return links.resolvedType; - } - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); - typeParameters.push(typeParameter); - var property = createSymbol(4, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(8 | 4); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384); - type.thisType.isThisType = true; - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); - } - function getTypeFromTupleTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); - } - return links.resolvedType; - } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - var flags = type.flags; - if (flags & 65536) { - addTypesToUnion(typeSet, type.types); - } - else if (flags & 1) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && flags & 6144) { - if (flags & 2048) - typeSet.containsUndefined = true; - if (flags & 4096) - typeSet.containsNull = true; - if (!(flags & 2097152)) - typeSet.containsNonWideningType = true; - } - else if (!(flags & 8192)) { - if (flags & 2) - typeSet.containsString = true; - if (flags & 4) - typeSet.containsNumber = true; - if (flags & 96) - typeSet.containsStringOrNumberLiteral = true; - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } - } - } - function addTypesToUnion(typeSet, types) { - 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_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function isSubtypeOfAny(candidate, types) { - 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; - } - } - return false; - } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 256) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types) { - if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { - return; - } - var i = types.length; - while (i > 0) { - i--; - if (isSubtypeOfAny(types[i], types)) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function removeRedundantLiteralTypes(types) { - var i = types.length; - while (i > 0) { - i--; - var t = types[i]; - var remove = t.flags & 32 && types.containsString || - t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); - if (remove) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var typeSet = []; - addTypesToUnion(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsStringOrNumberLiteral) { - removeRedundantLiteralTypes(typeSet); - } - if (typeSet.length === 0) { - return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : - typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); - var type = unionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = createType(65536 | propagatedFlags); - unionTypes.set(id, type); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromUnionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { - typeSet.containsEmptyObject = true; - } - else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768) { - typeSet.containsObjectType = true; - } - if (type.flags & 65536 && typeSet.unionIndex === undefined) { - typeSet.unionIndex = typeSet.length; - } - if (!(type.flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.push(type); - } - } - } - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - addTypeToIntersection(typeSet, type); - } - } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } - var typeSet = []; - addTypesToIntersection(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { - typeSet.push(emptyObjectType); - } - if (typeSet.length === 1) { - return typeSet[0]; - } - var unionIndex = typeSet.unionIndex; - if (unionIndex !== undefined) { - var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); - } - var id = getTypeListId(typeSet); - var type = intersectionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = createType(131072 | propagatedFlags); - intersectionTypes.set(id, type); - type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromIntersectionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function getIndexTypeForGenericType(type) { - if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144); - type.resolvedIndexType.type = type; - } - return type.resolvedIndexType; - } - function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? - neverType : - getLiteralType(ts.unescapeIdentifier(prop.name)); - } - function getLiteralTypeFromPropertyNames(type) { - return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); - } - function getIndexType(type) { - return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : - type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : - getLiteralTypeFromPropertyNames(type); - } - function getIndexTypeOrString(type) { - var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; - } - function getTypeFromTypeOperatorNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); - } - return links.resolvedType; - } - function createIndexedAccessType(objectType, indexType) { - var type = createType(524288); - type.objectType = objectType; - type.indexType = indexType; - return type; - } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & 96 ? - "" + indexType.value : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : - undefined; - if (propName !== undefined) { - var prop = getPropertyOfType(objectType, propName); - if (prop) { - if (accessExpression) { - if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return unknownType; - } - if (cacheSymbol) { - getNodeLinks(accessNode).resolvedSymbol = prop; - } - } - return getTypeOfSymbol(prop); - } - } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { - if (isTypeAny(objectType)) { - return anyType; - } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || - getIndexInfoOfType(objectType, 0) || - undefined; - if (indexInfo) { - if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; - } - return indexInfo.type; - } - if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1)) { - error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); - } - } - return anyType; - } - } - 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.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)); - } - else { - error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); - } - return unknownType; - } - return anyType; - } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } - function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || - maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || - isGenericMappedType(objectType)) { - if (objectType.flags & 1) { - return objectType; - } - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - var id = objectType.id + "," + indexType.id; - var type = indexedAccessTypes.get(id); - if (!type) { - indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); - } - return type; - } - var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8190)) { - var propTypes = []; - for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { - var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); - if (propType === unknownType) { - return unknownType; - } - propTypes.push(propType); - } - return getUnionType(propTypes); - } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); - } - function getTypeFromIndexedAccessTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); - } - return links.resolvedType; - } - function getTypeFromMappedTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = createObjectType(32, node.symbol); - type.declaration = node; - type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - getConstraintTypeFromMappedType(type); - } - return links.resolvedType; - } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { - links.resolvedType = emptyTypeLiteralType; - } - else { - var type = createObjectType(16, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - } - } - return links.resolvedType; - } - function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; - } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); - return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; - } - function getSpreadType(left, right) { - if (left.flags & 1 || right.flags & 1) { - return anyType; - } - left = filterType(left, function (t) { return !(t.flags & 6144); }); - if (left.flags & 8192) { - return right; - } - right = filterType(right, function (t) { return !(t.flags & 6144); }); - if (right.flags & 8192) { - return left; - } - if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); - } - if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); - } - if (right.flags & 16777216) { - return emptyObjectType; - } - var members = ts.createMap(); - var skippedPrivateMembers = ts.createMap(); - var stringIndexInfo; - var numberIndexInfo; - if (left === emptyObjectType) { - stringIndexInfo = getIndexInfoOfType(right, 0); - numberIndexInfo = getIndexInfoOfType(right, 1); - } - else { - stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); - numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); - } - for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { - var rightProp = _a[_i]; - var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { - skippedPrivateMembers.set(rightProp.name, true); - } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { - members.set(rightProp.name, getNonReadonlySymbol(rightProp)); - } - } - for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { - var leftProp = _c[_b]; - if (leftProp.flags & 65536 && !(leftProp.flags & 32768) - || skippedPrivateMembers.has(leftProp.name) - || isClassMethod(leftProp)) { - continue; - } - if (members.has(leftProp.name)) { - var rightProp = members.get(leftProp.name); - var rightType = getTypeOfSymbol(rightProp); - 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), rightType]); - result.leftSpread = leftProp; - result.rightSpread = rightProp; - result.declarations = declarations; - members.set(leftProp.name, result); - } - } - else { - members.set(leftProp.name, getNonReadonlySymbol(leftProp)); - } - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { - return prop; - } - var flags = 4 | (prop.flags & 67108864); - var result = createSymbol(flags, prop.name); - result.type = getTypeOfSymbol(prop); - result.declarations = prop.declarations; - result.syntheticOrigin = prop; - return result; - } - function isClassMethod(prop) { - return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } - function createLiteralType(flags, value, symbol) { - var type = createType(flags); - 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.value, type.symbol); - freshType.regularType = type; - type.freshType = freshType; - } - return type.freshType; - } - return type; - } - function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; - } - 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) { - var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); - literalTypes.set(key, type = createLiteralType(flags, value, symbol)); - } - return type; - } - function getTypeFromLiteralTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); - } - return links.resolvedType; - } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; - } - return links.resolvedType; - } - function getTypeFromJSDocTupleType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); - links.resolvedType = createTupleType(types); - } - return links.resolvedType; - } - function getThisType(node) { - var container = ts.getThisContainer(node, false); - var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { - if (!(ts.getModifierFlags(container) & 32) && - (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { - return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; - } - } - error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); - return unknownType; - } - function getTypeFromThisTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getThisType(node); - } - return links.resolvedType; - } - function getTypeFromTypeNode(node) { - switch (node.kind) { - case 119: - case 268: - case 269: - return anyType; - case 136: - return stringType; - case 133: - return numberType; - case 122: - return booleanType; - case 137: - return esSymbolType; - case 105: - return voidType; - case 139: - return undefinedType; - case 95: - return nullType; - case 130: - return neverType; - case 134: - return nonPrimitiveType; - case 169: - case 99: - return getTypeFromThisTypeNode(node); - case 173: - return getTypeFromLiteralTypeNode(node); - case 293: - return getTypeFromLiteralTypeNode(node.literal); - case 159: - case 277: - return getTypeFromTypeReference(node); - case 158: - return booleanType; - case 201: - return getTypeFromTypeReference(node); - case 162: - return getTypeFromTypeQueryNode(node); - case 164: - case 270: - return getTypeFromArrayTypeNode(node); - case 165: - return getTypeFromTupleTypeNode(node); - case 166: - case 271: - return getTypeFromUnionTypeNode(node); - case 167: - return getTypeFromIntersectionTypeNode(node); - case 273: - return getTypeFromJSDocNullableTypeNode(node); - case 168: - case 274: - case 281: - case 282: - case 278: - return getTypeFromTypeNode(node.type); - case 275: - return getTypeFromTypeNode(node.literal); - case 160: - case 161: - case 163: - case 292: - case 279: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170: - return getTypeFromTypeOperatorNode(node); - case 171: - return getTypeFromIndexedAccessTypeNode(node); - case 172: - return getTypeFromMappedTypeNode(node); - case 71: - case 143: - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - case 272: - return getTypeFromJSDocTupleType(node); - case 280: - return getTypeFromJSDocVariadicType(node); - default: - return unknownType; - } - } - function instantiateList(items, mapper, instantiator) { - if (items && items.length) { - var result = []; - for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { - var v = items_1[_i]; - result.push(instantiator(v, mapper)); - } - return result; - } - return items; - } - function instantiateTypes(types, mapper) { - return instantiateList(types, mapper, instantiateType); - } - function instantiateSignatures(signatures, mapper) { - return instantiateList(signatures, mapper, instantiateSignature); - } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } - function makeUnaryTypeMapper(source, target) { - return function (t) { return t === source ? target : t; }; - } - function makeBinaryTypeMapper(source1, target1, source2, target2) { - return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; - } - function makeArrayTypeMapper(sources, targets) { - return function (t) { - for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) { - return targets ? targets[i] : anyType; - } - } - return t; - }; - } - function createTypeMapper(sources, targets) { - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : - sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : - makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; - } - function createTypeEraser(sources) { - return createTypeMapper(sources, undefined); - } - function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; - } - function getInferenceMapper(context) { - if (!context.mapper) { - var mapper = function (t) { - var typeParameters = context.signature.typeParameters; - for (var i = 0; i < typeParameters.length; i++) { - if (t === typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); - } - } - return t; - }; - mapper.mappedTypes = context.signature.typeParameters; - mapper.context = context; - context.mapper = mapper; - } - return context.mapper; - } - function identityMapper(type) { - return type; - } - function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; - } - function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; - } - function cloneTypeParameter(typeParameter) { - var result = createType(16384); - result.symbol = typeParameter.symbol; - result.target = typeParameter; - return result; - } - function cloneTypePredicate(predicate, mapper) { - if (ts.isIdentifierTypePredicate(predicate)) { - return { - kind: 1, - parameterName: predicate.parameterName, - parameterIndex: predicate.parameterIndex, - type: instantiateType(predicate.type, mapper) - }; - } - else { - return { - kind: 0, - type: instantiateType(predicate.type, mapper) - }; - } - } - function instantiateSignature(signature, mapper, eraseTypeParameters) { - var freshTypeParameters; - var freshTypePredicate; - if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); - mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); - for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { - var tp = freshTypeParameters_1[_i]; - tp.mapper = mapper; - } - } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); - result.target = signature; - result.mapper = mapper; - return result; - } - function instantiateSymbol(symbol, mapper) { - if (ts.getCheckFlags(symbol) & 1) { - var links = getSymbolLinks(symbol); - symbol = links.target; - mapper = combineTypeMappers(links.mapper, mapper); - } - var result = createSymbol(symbol.flags, symbol.name); - result.checkFlags = 1; - result.declarations = symbol.declarations; - result.parent = symbol.parent; - result.target = symbol; - result.mapper = mapper; - if (symbol.valueDeclaration) { - result.valueDeclaration = symbol.valueDeclaration; - } - return result; - } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 | 64, type.symbol); - result.target = type.objectFlags & 64 ? type.target : type; - result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function instantiateMappedType(type, mapper) { - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); - } - return t; - }); - } - } - } - return instantiateMappedObjectType(type, mapper); - } - function isMappableType(type) { - return type.flags & (16384 | 32768 | 131072 | 524288); - } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 | 64, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 || node.kind === 265) { - return "quit"; - } - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 229: - case 199: - case 230: - case 231: - var declaration = node; - if (declaration.typeParameters) { - for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { - var d = _a[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 279: - var func = node; - for (var _b = 0, _c = func.parameters; _b < _c.length; _b++) { - var p = _c[_b]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 || parentKind === 234; - } - return false; - } - function instantiateType(type, mapper) { - if (type && mapper !== identityMapper) { - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - return type; - } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384) { - return mapper(type); - } - if (type.flags & 32768) { - if (type.objectFlags & 16) { - return type.symbol && - type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; - } - if (type.objectFlags & 32) { - return instantiateCached(type, mapper, instantiateMappedType); - } - if (type.objectFlags & 4) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); - } - } - if (type.flags & 65536 && !(type.flags & 8190)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - return type; - } - function instantiateIndexInfo(info, mapper) { - return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); - } - function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - switch (node.kind) { - case 186: - case 187: - return isContextSensitiveFunctionLikeDeclaration(node); - case 178: - return ts.forEach(node.properties, isContextSensitive); - case 177: - return ts.forEach(node.elements, isContextSensitive); - case 195: - return isContextSensitive(node.whenTrue) || - isContextSensitive(node.whenFalse); - case 194: - return node.operatorToken.kind === 54 && - (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261: - return isContextSensitive(node.initializer); - case 151: - case 150: - return isContextSensitiveFunctionLikeDeclaration(node); - case 185: - return isContextSensitive(node.expression); - case 254: - return ts.forEach(node.properties, isContextSensitive); - case 253: - return node.initializer && isContextSensitive(node.initializer); - case 256: - return node.expression && isContextSensitive(node.expression); - } - return false; - } - function isContextSensitiveFunctionLikeDeclaration(node) { - if (node.typeParameters) { - return false; - } - if (ts.forEach(node.parameters, function (p) { return !p.type; })) { - return true; - } - if (node.kind === 187) { - return false; - } - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); - } - function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); - } - function getTypeWithoutSignatures(type) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { - var result = createObjectType(16, type.symbol); - result.members = resolved.members; - result.properties = resolved.properties; - result.callSignatures = emptyArray; - result.constructSignatures = emptyArray; - return result; - } - } - else if (type.flags & 131072) { - return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); - } - return type; - } - function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); - } - function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; - } - function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; - } - function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); - } - function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); - } - function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); - } - function areTypesComparable(type1, type2) { - return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); - } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); - } - function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; - } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { - if (source === target) { - return -1; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType && sourceThisType !== voidType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType, false) - || compareTypes(targetThisType, sourceThisType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); - } - return 0; - } - result &= related; - } - } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); - var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); - } - return 0; - } - result &= related; - } - if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) { - return result; - } - var sourceReturnType = getReturnTypeOfSignature(source); - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); - } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0; - } - } - else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || - compareTypes(sourceReturnType, targetReturnType, reportErrors); - } - } - return result; - } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { - if (source.kind !== target.kind) { - if (reportErrors) { - errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0; - } - if (source.kind === 1) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0; - } - } - var related = compareTypes(source.type, target.type, reportErrors); - if (related === 0 && reportErrors) { - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return related; - } - function isImplementationCompatibleWithOverload(implementation, overload) { - var erasedSource = getErasedSignature(implementation); - var erasedTarget = getErasedSignature(overload); - var sourceReturnType = getReturnTypeOfSignature(erasedSource); - var targetReturnType = getReturnTypeOfSignature(erasedTarget); - if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - return isSignatureAssignableTo(erasedSource, erasedTarget, true); - } - return false; - } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } - function isEmptyResolvedType(t) { - return t.properties.length === 0 && - t.callSignatures.length === 0 && - t.constructSignatures.length === 0 && - !t.stringIndexInfo && - !t.numberIndexInfo; - } - function isEmptyObjectType(type) { - return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : - false; - } - function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { - if (sourceSymbol === targetSymbol) { - return true; - } - var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); - var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; - } - if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { - enumRelation.set(id, false); - return false; - } - 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(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); - } - enumRelation.set(id, false); - return false; - } - } - } - enumRelation.set(id, true); - return true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - var s = source.flags; - var t = target.flags; - if (t & 8192) - return false; - if (t & 1 || s & 8192) - return true; - if (s & 262178 && t & 2) - return true; - if (s & 32 && s & 256 && - t & 32 && !(t & 256) && - source.value === target.value) - return true; - if (s & 84 && t & 4) - return true; - if (s & 64 && s & 256 && - t & 64 && !(t & 256) && - source.value === target.value) - return true; - if (s & 136 && t & 8) - return true; - if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; - 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 (s & 4096 && (!strictNullChecks || t & 4096)) - return true; - if (s & 32768 && t & 16777216) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1) - return true; - if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) - return true; - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 1048576) { - source = source.regularType; - } - if (target.flags & 96 && target.flags & 1048576) { - target = target.regularType; - } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 32768 && target.flags & 32768) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - return related === 1; - } - } - if (source.flags & 1032192 || target.flags & 1032192) { - return checkTypeRelatedTo(source, target, relation, undefined); - } - return false; - } - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { - var errorInfo; - var sourceStack; - var targetStack; - var maybeStack; - var expandingFlags; - var depth = 0; - var overflow = false; - ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, !!errorNode, headMessage); - if (overflow) { - error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); - } - else if (errorInfo) { - if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return result !== 0; - function reportError(message, arg0, arg1, arg2) { - ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - } - function reportRelationError(message, source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 128); - targetType = typeToString(target, undefined, 128); - } - if (!message) { - if (relation === comparableRelation) { - message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; - } - else if (sourceType === targetType) { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; - } - else { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; - } - } - reportError(message, sourceType, targetType); - } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType(false) === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } - function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608)) { - return false; - } - var seenNonNullable = false; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 6144) { - continue; - } - if (seenNonNullable) { - return true; - } - seenNonNullable = true; - } - return false; - } - function isRelatedTo(source, target, reportErrors, headMessage) { - var result; - if (source.flags & 96 && source.flags & 1048576) { - source = source.regularType; - } - if (target.flags & 96 && target.flags & 1048576) { - target = target.regularType; - } - if (source === target) - return -1; - if (relation === identityRelation) { - return isIdenticalTo(source, target); - } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1; - if (getObjectFlags(source) & 128 && source.flags & 1048576) { - if (hasExcessProperties(source, target, reportErrors)) { - if (reportErrors) { - reportRelationError(headMessage, source, target); - } - return 0; - } - if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { - source = getRegularTypeOfObjectLiteral(source); - } - } - var saveErrorInfo = errorInfo; - if (source.flags & 65536) { - if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); - } - else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); - } - if (result) { - return result; - } - } - else { - if (target.flags & 65536) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { - return result; - } - } - else if (target.flags & 131072) { - if (result = typeRelatedToEachType(source, target, reportErrors)) { - return result; - } - } - else if (source.flags & 131072) { - if (result = someTypeRelatedToType(source, target, false)) { - return result; - } - } - if (source.flags & 1032192 || target.flags & 1032192) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (reportErrors) { - if (source.flags & 32768 && target.flags & 8190) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 32768 && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - reportRelationError(headMessage, source, target); - } - return 0; - } - function isIdenticalTo(source, target) { - var result; - if (source.flags & 32768 && target.flags & 32768) { - return recursiveTypeRelatedTo(source, target, false); - } - if (source.flags & 65536 && target.flags & 65536 || - source.flags & 131072 && target.flags & 131072) { - if (result = eachTypeRelatedToSomeType(source, target)) { - if (result &= eachTypeRelatedToSomeType(target, source)) { - return result; - } - } - } - return 0; - } - function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { - var isComparingJsxAttributes = !!(source.flags & 33554432); - if ((relation === assignableRelation || relation === comparableRelation) && - (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { - return false; - } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { - if (reportErrors) { - ts.Debug.assert(!!errorNode); - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); - } - else { - errorNode = prop.valueDeclaration; - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); - } - } - return true; - } - } - } - return false; - } - function eachTypeRelatedToSomeType(source, target) { - var result = -1; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { - var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function typeRelatedToSomeType(source, target, reportErrors) { - var targetTypes = target.types; - if (target.flags & 65536 && containsType(targetTypes, source)) { - return -1; - } - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var type = targetTypes_1[_i]; - var related = isRelatedTo(source, type, false); - if (related) { - return related; - } - } - if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); - } - return 0; - } - function findMatchingDiscriminantType(source, target) { - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.name)) { - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); - if (targetType && isRelatedTo(sourceType, targetType)) { - return type; - } - } - } - } - } - } - function typeRelatedToEachType(source, target, reportErrors) { - var result = -1; - var targetTypes = target.types; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function someTypeRelatedToType(source, target, reportErrors) { - var sourceTypes = source.types; - if (source.flags & 65536 && containsType(sourceTypes, target)) { - return -1; - } - var len = sourceTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); - if (related) { - return related; - } - } - return 0; - } - function eachTypeRelatedToType(source, target, reportErrors) { - var result = -1; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; - var related = isRelatedTo(sourceType, target, reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function typeArgumentsRelatedTo(source, target, reportErrors) { - var sources = source.typeArguments || emptyArray; - var targets = target.typeArguments || emptyArray; - if (sources.length !== targets.length && relation === identityRelation) { - return 0; - } - var length = sources.length <= targets.length ? sources.length : targets.length; - var result = -1; - for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function recursiveTypeRelatedTo(source, target, reportErrors) { - if (overflow) { - return 0; - } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - if (reportErrors && related === 2) { - relation.set(id, 3); - } - else { - return related === 1 ? -1 : 0; - } - } - if (depth > 0) { - for (var i = 0; i < depth; i++) { - if (maybeStack[i].get(id)) { - return 1; - } - } - if (depth === 100) { - overflow = true; - return 0; - } - } - else { - sourceStack = []; - targetStack = []; - maybeStack = []; - expandingFlags = 0; - } - sourceStack[depth] = source; - targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); - maybeStack[depth].set(id, 1); - depth++; - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; - expandingFlags = saveExpandingFlags; - depth--; - if (result) { - var maybeCache = maybeStack[depth]; - var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyEntries(maybeCache, destinationCache); - } - else { - relation.set(id, reportErrors ? 3 : 2); - } - return result; - } - function structuredTypeRelatedTo(source, target, reportErrors) { - var result; - var saveErrorInfo = errorInfo; - if (target.flags & 16384) { - if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { - if (!source.declaration.questionToken) { - var templateType = getTemplateTypeFromMappedType(source); - var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); - if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { - return result; - } - } - } - } - else if (target.flags & 262144) { - if (source.flags & 262144) { - if (result = isRelatedTo(target.type, source.type, false)) { - return result; - } - } - var constraint = getConstraintOfType(target.type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { - return result; - } - } - } - else if (target.flags & 524288) { - var constraint = getConstraintOfType(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (source.flags & 16384) { - if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else { - var constraint = getConstraintOfTypeParameter(source); - if (constraint || !(target.flags & 16777216)) { - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; - } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - } - else if (source.flags & 524288) { - var constraint = getConstraintOfType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else if (target.flags & 524288 && source.indexType === target.indexType) { - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - return result; - } - } - } - else { - if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { - return result; - } - } - var sourceIsPrimitive = !!(source.flags & 8190); - if (relation !== identityRelation) { - source = getApparentType(source); - } - if (source.flags & (32768 | 131072) && target.flags & 32768) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isGenericMappedType(source) || isGenericMappedType(target)) { - result = mappedTypeRelatedTo(source, target, reportStructuralErrors); - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); - } - } - } - } - } - if (result) { - errorInfo = saveErrorInfo; - return result; - } - } - } - return 0; - } - function mappedTypeRelatedTo(source, target, reportErrors) { - if (isGenericMappedType(target)) { - if (isGenericMappedType(source)) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; - if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); - } - } - } - else if (target.declaration.questionToken && isEmptyObjectType(source)) { - return -1; - } - } - else if (relation !== identityRelation) { - var resolved = resolveStructuredTypeMembers(target); - if (isEmptyResolvedType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & 1) { - return -1; - } - } - return 0; - } - function propertiesRelatedTo(source, target, reportErrors) { - if (relation === identityRelation) { - return propertiesIdenticalTo(source, target); - } - var result = -1; - var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var targetProp = properties_4[_i]; - var sourceProp = getPropertyOfType(source, targetProp.name); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 67108864) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0; - } - } - else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); - if (sourcePropFlags & 8 || targetPropFlags & 8) { - 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)); - } - return 0; - } - if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { - if (reportErrors) { - if (sourcePropFlags & 8 && targetPropFlags & 8) { - reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); - } - else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); - } - } - return 0; - } - } - else if (targetPropFlags & 16) { - if (!isValidOverrideOf(sourceProp, targetProp)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); - } - return 0; - } - } - else if (sourcePropFlags & 16) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0; - } - var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); - } - return 0; - } - result &= related; - if (relation !== comparableRelation && sourceProp.flags & 67108864 && !(targetProp.flags & 67108864)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0; - } - } - } - } - return result; - } - function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 && target.flags & 32768)) { - return 0; - } - var sourceProperties = getPropertiesOfObjectType(source); - var targetProperties = getPropertiesOfObjectType(target); - if (sourceProperties.length !== targetProperties.length) { - return 0; - } - var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; - var targetProp = getPropertyOfObjectType(target, sourceProp.name); - if (!targetProp) { - return 0; - } - var related = compareProperties(sourceProp, targetProp, isRelatedTo); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function signaturesRelatedTo(source, target, kind, reportErrors) { - if (relation === identityRelation) { - return signaturesIdenticalTo(source, target, kind); - } - if (target === anyFunctionType || source === anyFunctionType) { - return -1; - } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (kind === 1 && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0; - } - if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { - return 0; - } - } - var result = -1; - var saveErrorInfo = errorInfo; - 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; - } - result &= related; - } - } - 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 result; - } - function signatureRelatedTo(source, target, reportErrors) { - return compareSignaturesRelated(source, target, false, false, reportErrors, reportError, isRelatedTo); - } - function signaturesIdenticalTo(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (sourceSignatures.length !== targetSignatures.length) { - return 0; - } - var result = -1; - for (var i = 0; i < sourceSignatures.length; i++) { - var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function eachPropertyRelatedTo(source, target, kind, reportErrors) { - var result = -1; - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.name)) { - var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); - } - return 0; - } - result &= related; - } - } - return result; - } - function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { - var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); - if (!related && reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return related; - } - function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(source, target, kind); - } - var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 && !sourceIsPrimitive) { - return -1; - } - var sourceInfo = getIndexInfoOfType(source, kind) || - kind === 1 && getIndexInfoOfType(source, 0); - if (sourceInfo) { - return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); - } - if (isObjectLiteralType(source)) { - var related = -1; - if (kind === 0) { - var sourceNumberInfo = getIndexInfoOfType(source, 1); - if (sourceNumberInfo) { - related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); - } - } - if (related) { - related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); - } - return related; - } - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0; - } - function indexTypesIdenticalTo(source, target, indexKind) { - var targetInfo = getIndexInfoOfType(target, indexKind); - var sourceInfo = getIndexInfoOfType(source, indexKind); - if (!sourceInfo && !targetInfo) { - return -1; - } - if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { - return isRelatedTo(sourceInfo.type, targetInfo.type); - } - return 0; - } - function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { - if (!sourceSignature.declaration || !targetSignature.declaration) { - return true; - } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; - if (targetAccessibility === 8) { - return true; - } - if (targetAccessibility === 16 && sourceAccessibility !== 8) { - return true; - } - if (targetAccessibility !== 16 && !sourceAccessibility) { - return true; - } - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); - } - return false; - } - } - function forEachProperty(prop, callback) { - 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); - var result = p && forEachProperty(p, callback); - if (result) { - return result; - } - } - return undefined; - } - return callback(prop); - } - function getDeclaringClass(prop) { - return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; - } - function isPropertyInClassDerivedFrom(prop, baseClass) { - return forEachProperty(prop, function (sp) { - var sourceClass = getDeclaringClass(sp); - return sourceClass ? hasBaseType(sourceClass, baseClass) : false; - }); - } - function isValidOverrideOf(sourceProp, targetProp) { - 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 ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? - !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; - } - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128) { - return true; - } - } - } - return false; - } - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 32768) { - var symbol = type.symbol; - if (symbol) { - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 32768 && t.symbol === symbol) { - count++; - if (count >= 5) - return true; - } - } - } - } - return false; - } - function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; - } - function compareProperties(sourceProp, targetProp, compareTypes) { - if (sourceProp === targetProp) { - return -1; - } - var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; - if (sourcePropAccessibility !== targetPropAccessibility) { - return 0; - } - if (sourcePropAccessibility) { - if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { - return 0; - } - } - else { - if ((sourceProp.flags & 67108864) !== (targetProp.flags & 67108864)) { - return 0; - } - } - if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { - return 0; - } - return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - function isMatchingSignature(source, target, partialMatch) { - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { - return true; - } - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { - return true; - } - return false; - } - function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { - if (source === target) { - return -1; - } - if (!(isMatchingSignature(source, target, partialMatch))) { - return 0; - } - if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { - return 0; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - if (!ignoreThisTypes) { - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType); - if (!related) { - return 0; - } - result &= related; - } - } - } - var targetLen = target.parameters.length; - for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); - var related = compareTypes(s, t); - if (!related) { - return 0; - } - result &= related; - } - if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - return result; - } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } - function isSupertypeOfEach(candidate, types) { - 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; - } - return true; - } - function literalTypesWithSameBaseType(types) { - var commonBaseType; - 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; - } - if (baseType === t || baseType !== commonBaseType) { - return false; - } - } - return true; - } - function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); - } - function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); - } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); - if (!primaryTypes.length) { - return getUnionType(types, true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - if (bestSupertypeScore === types.length - 1) { - break; - } - } - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); - } - function isArrayType(type) { - return getObjectFlags(type) & 4 && type.target === globalArrayType; - } - function isArrayLikeType(type) { - return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); - } - function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); - } - function isUnitType(type) { - return (type.flags & (224 | 2048 | 4096)) !== 0; - } - function isLiteralType(type) { - return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfLiteralType(type) { - 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 & 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) { - return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); - } - function getFalsyFlagsOfTypes(types) { - var result = 0; - 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.value === "" ? 32 : 0 : - type.flags & 64 ? type.value === 0 ? 64 : 0 : - type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; - } - 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; - } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && - getSignaturesOfType(type, 0).length === 0 && - getSignaturesOfType(type, 1).length === 0; - } - function createSymbolWithType(source, type) { - var symbol = createSymbol(source.flags, source.name); - symbol.declarations = source.declarations; - symbol.parent = source.parent; - symbol.type = type; - symbol.target = source; - if (source.valueDeclaration) { - symbol.valueDeclaration = source.valueDeclaration; - } - return symbol; - } - function transformTypeOfMembers(type, f) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var property = _a[_i]; - var original = getTypeOfSymbol(property); - var updated = f(original); - members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); - } - return members; - } - function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { - return type; - } - var regularType = type.regularType; - if (regularType) { - return regularType; - } - var resolved = type; - var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); - var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; - regularNew.objectFlags |= 128; - type.regularType = regularNew; - return regularNew; - } - function getWidenedProperty(prop) { - var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); - return widened === original ? prop : createSymbolWithType(prop, widened); - } - function getWidenedTypeOfObjectLiteral(type) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - members.set(prop.name, prop.flags & 4 ? getWidenedProperty(prop) : prop); - } - var stringIndexInfo = getIndexInfoOfType(type, 0); - var numberIndexInfo = getIndexInfoOfType(type, 1); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - } - function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); - } - function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 6144) { - return anyType; - } - if (getObjectFlags(type) & 128) { - return getWidenedTypeOfObjectLiteral(type); - } - if (type.flags & 65536) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); - } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); - } - } - return type; - } - function reportWideningErrorsInType(type) { - var errorReported = false; - if (type.flags & 65536) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (getObjectFlags(type) & 128) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); - } - errorReported = true; - } - } - } - return errorReported; - } - function reportImplicitAnyError(declaration, type) { - var typeAsString = typeToString(getWidenedType(type)); - var diagnostic; - switch (declaration.kind) { - case 149: - case 148: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; - break; - case 146: - diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; - break; - case 176: - diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; - break; - case 228: - case 151: - case 150: - case 153: - case 154: - case 186: - case 187: - if (!declaration.name) { - error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); - return; - } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; - break; - default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; - } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); - } - function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { - if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); - } - } - } - function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { - callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); - } - } - function createInferenceContext(signature, inferUnionTypes, useAnyForNoInferences) { - var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); - return { - signature: signature, - inferUnionTypes: inferUnionTypes, - inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length), - useAnyForNoInferences: useAnyForNoInferences - }; - } - function createTypeInferencesObject() { - return { - primary: undefined, - secondary: undefined, - topLevel: true, - isFixed: false, - }; - } - function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 || - objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || - objectFlags & 16 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - objectFlags & 32 || - type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); - } - function couldUnionOrIntersectionContainTypeVariables(type) { - if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); - } - return type.couldContainTypeVariables; - } - function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); - } - function inferTypeForHomomorphicMappedType(source, target) { - var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0); - if (properties.length === 0 && !indexInfo) { - return undefined; - } - var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var typeVariableArray = [typeVariable]; - var typeInferences = createTypeInferencesObject(); - var typeInferencesArray = [typeInferences]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 67108864; - 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)); - if (!inferredPropType) { - return undefined; - } - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.name); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; - inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; - members.set(prop.name, inferredProp); - } - if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - typeInferences.primary = undefined; - typeInferences.secondary = undefined; - inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); - var inferences = typeInferences.primary || typeInferences.secondary; - return inferences && getUnionType(inferences, true); - } - } - function inferTypesWithContext(context, originalSource, originalTarget) { - inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); - } - function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var symbolStack; - var visited; - var inferiority = 0; - inferFromTypes(originalSource, originalTarget); - function inferFromTypes(source, target) { - if (!couldContainTypeVariables(target)) { - return; - } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - var sourceTypes = source.aliasTypeArguments; - var targetTypes = target.aliasTypeArguments; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - return; - } - 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++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } - var matchingTypes = void 0; - for (var _b = 0, _c = source.types; _b < _c.length; _b++) { - var t = _c[_b]; - if (typeIdenticalToSomeType(t, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t); - inferFromTypes(t, t); - } - else if (t.flags & (64 | 32)) { - var b = getBaseTypeOfLiteralType(t); - if (typeIdenticalToSomeType(b, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t, b); - } - } - } - if (matchingTypes) { - source = removeTypesFromUnionOrIntersection(source, matchingTypes); - target = removeTypesFromUnionOrIntersection(target, matchingTypes); - } - } - if (target.flags & 540672) { - if (source.flags & 8388608) { - return; - } - for (var i = 0; i < typeVariables.length; i++) { - if (target === typeVariables[i]) { - var inferences = typeInferences[i]; - if (!inferences.isFixed) { - var candidates = inferiority ? - inferences.secondary || (inferences.secondary = []) : - inferences.primary || (inferences.primary = []); - if (!ts.contains(candidates, source)) { - candidates.push(source); - } - if (target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { - inferences.topLevel = false; - } - } - return; - } - } - } - else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - var sourceTypes = source.typeArguments || emptyArray; - var targetTypes = target.typeArguments || emptyArray; - var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; - for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 196608) { - var targetTypes = target.types; - var typeVariableCount = 0; - var typeVariable = void 0; - for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { - var t = targetTypes_3[_d]; - if (t.flags & 540672 && ts.contains(typeVariables, t)) { - typeVariable = t; - typeVariableCount++; - } - else { - inferFromTypes(source, t); - } - } - if (typeVariableCount === 1) { - inferiority++; - inferFromTypes(source, typeVariable); - inferiority--; - } - } - else if (source.flags & 196608) { - var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; - inferFromTypes(sourceType, target); - } - } - else { - source = getApparentType(source); - if (source.flags & 32768) { - var key = source.id + "," + target.id; - if (visited && visited.get(key)) { - return; - } - (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); - } - } - } - } - function inferFromObjectTypes(source, target) { - if (getObjectFlags(target) & 32) { - var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144) { - var index = ts.indexOf(typeVariables, constraintType.type); - if (index >= 0 && !typeInferences[index].isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - inferiority++; - inferFromTypes(inferredType, typeVariables[index]); - inferiority--; - } - } - return; - } - if (constraintType.flags & 16384) { - inferFromTypes(getIndexType(source), constraintType); - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); - return; - } - } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); - } - function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.name); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - } - } - function inferFromSignatures(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - var sourceLen = sourceSignatures.length; - var targetLen = targetSignatures.length; - var len = sourceLen < targetLen ? sourceLen : targetLen; - for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); - } - } - function inferFromParameterTypes(source, target) { - return inferFromTypes(source, target); - } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromParameterTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - } - function inferFromIndexTypes(source, target) { - var targetStringIndexType = getIndexTypeOfType(target, 0); - if (targetStringIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 0); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetStringIndexType); - } - } - var targetNumberIndexType = getIndexTypeOfType(target, 1); - if (targetNumberIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 1) || - getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 1); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetNumberIndexType); - } - } - } - } - function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function removeTypesFromUnionOrIntersection(type, typesToRemove) { - var reducedTypes = []; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!typeIdenticalToSomeType(t, typesToRemove)) { - reducedTypes.push(t); - } - } - return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); - } - function getInferenceCandidates(context, index) { - var inferences = context.inferences[index]; - return inferences.primary || inferences.secondary || emptyArray; - } - function hasPrimitiveConstraint(type) { - var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 | 262144); - } - function getInferredType(context, index) { - var inferredType = context.inferredTypes[index]; - var inferenceSucceeded; - if (!inferredType) { - var inferences = getInferenceCandidates(context, index); - if (inferences.length) { - var signature = context.signature; - var widenLiteralTypes = context.inferences[index].topLevel && - !hasPrimitiveConstraint(signature.typeParameters[index]) && - (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; - var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; - } - else { - var defaultType = getDefaultFromTypeParameter(context.signature.typeParameters[index]); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), getInferenceMapper(context))); - } - else { - inferredType = context.useAnyForNoInferences ? anyType : emptyObjectType; - } - inferenceSucceeded = true; - } - context.inferredTypes[index] = inferredType; - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - context.inferredTypes[index] = inferredType = instantiatedConstraint; - } - } - } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - context.failedTypeParameterIndex = index; - } - } - return inferredType; - } - function getInferredTypes(context) { - for (var i = 0; i < context.inferredTypes.length; i++) { - getInferredType(context, i); - } - return context.inferredTypes; - } - 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, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; - } - return links.resolvedSymbol; - } - function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); - } - function getFlowCacheKey(node) { - if (node.kind === 71) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 99) { - return "0"; - } - if (node.kind === 179) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + node.name.text; - } - return undefined; - } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71: - case 99: - return node; - case 179: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } - function isMatchingReference(source, target) { - switch (source.kind) { - case 71: - return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 || target.kind === 176) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99: - return target.kind === 99; - case 97: - return target.kind === 97; - case 179: - return target.kind === 179 && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } - return false; - } - function containsMatchingReference(source, target) { - while (source.kind === 179) { - source = source.expression; - if (isMatchingReference(source, target)) { - return true; - } - } - return false; - } - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 179) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } - function isOrContainsMatchingReference(source, target) { - return isMatchingReference(source, target) || containsMatchingReference(source, target); - } - function hasMatchingArgument(callExpression, reference) { - if (callExpression.arguments) { - for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isOrContainsMatchingReference(reference, argument)) { - return true; - } - } - } - if (callExpression.expression.kind === 179 && - isOrContainsMatchingReference(reference, callExpression.expression.expression)) { - return true; - } - return false; - } - function getFlowNodeId(flow) { - if (!flow.id) { - flow.id = nextFlowId; - nextFlowId++; - } - return flow.id; - } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } - function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 8192) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192)) { - return reducedType; - } - } - return declaredType; - } - function getTypeFactsOfTypes(types) { - var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); - } - function getTypeFacts(type) { - var flags = type.flags; - if (flags & 2) { - return strictNullChecks ? 4079361 : 4194049; - } - if (flags & 32) { - var isEmpty = type.value === ""; - return strictNullChecks ? - isEmpty ? 3030785 : 1982209 : - isEmpty ? 3145473 : 4194049; - } - if (flags & (4 | 16)) { - return strictNullChecks ? 4079234 : 4193922; - } - if (flags & 64) { - var isZero = type.value === 0; - return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; - } - if (flags & 8) { - return strictNullChecks ? 4078980 : 4193668; - } - if (flags & 136) { - return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; - } - if (flags & 32768) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; - } - if (flags & (1024 | 2048)) { - return 2457472; - } - if (flags & 4096) { - return 2340752; - } - if (flags & 512) { - return strictNullChecks ? 1981320 : 4193160; - } - if (flags & 16777216) { - return strictNullChecks ? 6166480 : 8378320; - } - if (flags & 540672) { - return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); - } - if (flags & 196608) { - return getTypeFactsOfTypes(type.types); - } - return 8388607; - } - function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); - } - function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072), defaultType]); - } - return type; - } - function getTypeOfDestructuredProperty(type, name) { - var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || - isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || - getIndexTypeOfType(type, 0) || - unknownType; - } - function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || - checkIteratedTypeOrElementType(type, undefined, false, false) || - unknownType; - } - function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); - } - function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); - return isDestructuringDefaultAssignment ? - getTypeWithDefault(getAssignedType(node), node.right) : - getTypeOfExpression(node.right); - } - function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 && parent.parent.left === parent || - parent.parent.kind === 216 && parent.parent.initializer === parent; - } - function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); - } - function getAssignedTypeOfSpreadExpression(node) { - return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); - } - function getAssignedTypeOfPropertyAssignment(node) { - return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); - } - function getAssignedTypeOfShorthandPropertyAssignment(node) { - return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); - } - function getAssignedType(node) { - var parent = node.parent; - switch (parent.kind) { - case 215: - return stringType; - case 216: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194: - return getAssignedTypeOfBinaryExpression(parent); - case 188: - return undefinedType; - case 177: - return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198: - return getAssignedTypeOfSpreadExpression(parent); - case 261: - return getAssignedTypeOfPropertyAssignment(parent); - case 262: - return getAssignedTypeOfShorthandPropertyAssignment(parent); - } - return unknownType; - } - function getInitialTypeOfBindingElement(node) { - var pattern = node.parent; - var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 ? - getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : - !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadExpression(parentType); - return getTypeWithDefault(type, node.initializer); - } - function getTypeOfInitializer(node) { - var links = getNodeLinks(node); - return links.resolvedType || getTypeOfExpression(node); - } - function getInitialTypeOfVariableDeclaration(node) { - if (node.initializer) { - return getTypeOfInitializer(node.initializer); - } - if (node.parent.parent.kind === 215) { - return stringType; - } - if (node.parent.parent.kind === 216) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; - } - return unknownType; - } - function getInitialType(node) { - return node.kind === 226 ? - getInitialTypeOfVariableDeclaration(node) : - getInitialTypeOfBindingElement(node); - } - function getInitialOrAssignedType(node) { - return node.kind === 226 || node.kind === 176 ? - getInitialType(node) : - getAssignedType(node); - } - function isEmptyArrayAssignment(node) { - return node.kind === 226 && node.initializer && - isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 && node.parent.kind === 194 && - isEmptyArrayLiteral(node.parent.right); - } - function getReferenceCandidate(node) { - switch (node.kind) { - case 185: - return getReferenceCandidate(node.expression); - case 194: - switch (node.operatorToken.kind) { - case 58: - return getReferenceCandidate(node.left); - case 26: - return getReferenceCandidate(node.right); - } - } - return node; - } - function getReferenceRoot(node) { - var parent = node.parent; - return parent.kind === 185 || - parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || - parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? - getReferenceRoot(parent) : node; - } - function getTypeOfSwitchClause(clause) { - if (clause.kind === 257) { - var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); - return isUnitType(caseType) ? caseType : undefined; - } - return neverType; - } - function getSwitchClauseTypes(switchStatement) { - var links = getNodeLinks(switchStatement); - if (!links.switchTypes) { - var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; - } - return links.switchTypes; - } - function eachTypeContainedIn(source, types) { - return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { - return true; - } - return containsType(target.types, source); - } - function forEachType(type, f) { - return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); - } - function filterType(type, f) { - if (type.flags & 65536) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; - } - function mapType(type, mapper) { - if (!(type.flags & 65536)) { - return mapper(type); - } - var types = type.types; - var mappedType; - var mappedTypes; - 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) { - mappedType = t; - } - else if (!mappedTypes) { - mappedTypes = [mappedType, t]; - } - else { - mappedTypes.push(t); - } - } - } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; - } - function extractTypesOfKind(type, kind) { - return filterType(type, function (t) { return (t.flags & kind) !== 0; }); - } - function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { - return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : - t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : - t; - }); - } - return typeWithPrimitives; - } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function createEvolvingArrayType(elementType) { - var result = createObjectType(256); - result.elementType = elementType; - return result; - } - function getEvolvingArrayType(elementType) { - return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); - } - function addEvolvingArrayElementType(evolvingArrayType, node) { - var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); - return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); - } - function createFinalArrayType(elementType) { - return elementType.flags & 8192 ? - autoArrayType : - createArrayType(elementType.flags & 65536 ? - getUnionType(elementType.types, true) : - elementType); - } - function getFinalArrayType(evolvingArrayType) { - return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); - } - function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; - } - function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? type.elementType : neverType; - } - function isEvolvingArrayTypeList(types) { - var hasEvolvingArrayType = false; - 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; - } - hasEvolvingArrayType = true; - } - } - return hasEvolvingArrayType; - } - function getUnionOrEvolvingArrayType(types, subtypeReduction) { - return isEvolvingArrayTypeList(types) ? - getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : - getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); - } - function isEvolvingArrayOperationTarget(node) { - var root = getReferenceRoot(node); - var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.text === "length" || - parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 && - parent.expression === root && - parent.parent.kind === 194 && - parent.parent.operatorToken.kind === 58 && - parent.parent.left === parent && - !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); - return isLengthPushOrUnshift || isElementAssignment; - } - function maybeTypePredicateCall(node) { - var links = getNodeLinks(node); - if (links.maybeTypePredicate === undefined) { - links.maybeTypePredicate = getMaybeTypePredicate(node); - } - return links.maybeTypePredicate; - } - function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97) { - var funcType = checkNonNullExpression(node.expression); - if (funcType !== silentNeverType) { - var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } - } - } - return false; - } - function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { - if (initialType === void 0) { initialType = declaredType; } - var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { - return declaredType; - } - var visitedFlowStart = visitedFlowCount; - var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; - var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { - return declaredType; - } - return resultType; - function getTypeAtFlowNode(flow) { - while (true) { - if (flow.flags & 1024) { - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; - } - } - } - var type = void 0; - if (flow.flags & 4096) { - flow.locked = true; - type = getTypeAtFlowNode(flow.antecedent); - flow.locked = false; - } - else if (flow.flags & 2048) { - flow = flow.antecedent; - continue; - } - else if (flow.flags & 16) { - type = getTypeAtFlowAssignment(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 96) { - type = getTypeAtFlowCondition(flow); - } - else if (flow.flags & 128) { - type = getTypeAtSwitchClause(flow); - } - else if (flow.flags & 12) { - if (flow.antecedents.length === 1) { - flow = flow.antecedents[0]; - continue; - } - type = flow.flags & 4 ? - getTypeAtFlowBranchLabel(flow) : - getTypeAtFlowLoopLabel(flow); - } - else if (flow.flags & 256) { - type = getTypeAtFlowArrayMutation(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 2) { - var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { - flow = container.flowNode; - continue; - } - type = initialType; - } - else { - type = convertAutoToAny(declaredType); - } - if (flow.flags & 1024) { - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; - } - return type; - } - } - function getTypeAtFlowAssignment(flow) { - var node = flow.node; - if (isMatchingReference(reference, node)) { - if (ts.getAssignmentTargetKind(node) === 2) { - var flowType = getTypeAtFlowNode(flow.antecedent); - return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); - } - if (declaredType === autoType || declaredType === autoArrayType) { - if (isEmptyArrayAssignment(node)) { - return getEvolvingArrayType(neverType); - } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); - return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; - } - if (declaredType.flags & 65536) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); - } - return declaredType; - } - if (containsMatchingReference(reference, node)) { - return declaredType; - } - return undefined; - } - function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { - var evolvedType_1 = type; - if (node.kind === 181) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); - } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); - } - } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); - } - return flowType; - } - return undefined; - } - function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (type.flags & 8192) { - return flowType; - } - var assumeTrue = (flow.flags & 32) !== 0; - var nonEvolvingType = finalizeEvolvingArrayType(type); - var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); - if (narrowedType === nonEvolvingType) { - return flowType; - } - var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; - return createFlowType(resultType, incomplete); - } - function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); - } - function getTypeAtFlowBranchLabel(flow) { - var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - if (antecedent.flags & 2048 && antecedent.lock.locked) { - continue; - } - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); - if (type === declaredType && declaredType === initialType) { - return type; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } - } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); - } - function getTypeAtFlowLoopLabel(flow) { - var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); - if (!key) { - key = getFlowCacheKey(reference); - } - var cached = cache.get(key); - if (cached) { - return cached; - } - for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); - } - } - var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; - flowLoopNodes[flowLoopCount] = flow; - flowLoopKeys[flowLoopCount] = key; - flowLoopTypes[flowLoopCount] = antecedentTypes; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); - flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); - var cached_1 = cache.get(key); - if (cached_1) { - return cached_1; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (type === declaredType) { - break; - } - } - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, true); - } - cache.set(key, result); - return result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 179 && - declaredType.flags & 65536 && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); - } - function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; - } - function narrowTypeByBinaryExpression(type, expr, assumeTrue) { - switch (expr.operatorToken.kind) { - case 58: - return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32: - case 33: - case 34: - case 35: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 && right_1.kind === 9) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); - } - if (right_1.kind === 189 && left_1.kind === 9) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); - } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); - } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); - } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); - } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; - } - break; - case 93: - return narrowTypeByInstanceof(type, expr, assumeTrue); - case 26: - return narrowType(type, expr.right, assumeTrue); - } - return type; - } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1) { - return type; - } - if (operator === 33 || operator === 35) { - assumeTrue = !assumeTrue; - } - var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 32 || operator === 33; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - value.kind === 95 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); - } - if (type.flags & 16810497) { - return type; - } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); - } - if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); - } - return type; - } - function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceCandidate(typeOfExpr.expression); - if (!isMatchingReference(reference, target)) { - if (containsMatchingReference(reference, target)) { - return declaredType; - } - return type; - } - if (operator === 33 || operator === 35) { - assumeTrue = !assumeTrue; - } - if (assumeTrue && !(type.flags & 65536)) { - var targetType = typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & 540672) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } - } - } - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; - return getTypeWithFacts(type, facts); - } - function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - var switchTypes = getSwitchClauseTypes(switchStatement); - if (!switchTypes.length) { - return type; - } - var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); - if (!hasDefaultClause) { - return caseType; - } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); - } - function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { - return declaredType; - } - return type; - } - var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { - return type; - } - var targetType; - var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (prototypeProperty) { - var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (!isTypeAny(prototypePropertyType)) { - targetType = prototypePropertyType; - } - } - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } - if (!targetType) { - var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (getObjectFlags(rightType) & 16) { - constructSignatures = getSignaturesOfType(rightType, 1); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } - } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); - } - return type; - } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { - if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); - } - if (type.flags & 65536) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192)) { - return assignableType; - } - } - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); - } - function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { - return type; - } - var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; - if (!predicate) { - return type; - } - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; - if (predicateArgument) { - if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } - } - } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } - return type; - } - function narrowType(type, expr, assumeTrue) { - switch (expr.kind) { - case 71: - case 99: - case 97: - case 179: - return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181: - return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185: - return narrowType(type, expr.expression, assumeTrue); - case 194: - return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192: - if (expr.operator === 51) { - return narrowType(type, expr.operand, !assumeTrue); - } - break; - } - return type; - } - } - function getTypeOfSymbolAtLocation(symbol, location) { - if (location.kind === 71) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { - location = location.parent; - } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { - var type = getTypeOfExpression(location); - if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { - return type; - } - } - } - return getTypeOfSymbol(symbol); - } - function getControlFlowContainer(node) { - return ts.findAncestor(node.parent, function (node) { - return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 || - node.kind === 265 || - node.kind === 149; - }); - } - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); - } - function markParameterAssignments(node) { - if (node.kind === 71) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); - } - } - function isConstVariable(symbol) { - return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; - } - function removeOptionalityFromDeclaredType(declaredType, declaration) { - var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 && - declaration.initializer && - getFalsyFlags(declaredType) & 2048 && - !(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) { - return unknownType; - } - if (symbol === argumentsSymbol) { - var container = ts.getContainingFunction(node); - if (languageVersion < 2) { - if (container.kind === 187) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); - } - else if (ts.hasModifier(container, 256)) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); - } - } - getNodeLinks(container).flags |= 8192; - return getTypeOfSymbol(symbol); - } - if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); - } - var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (localOrExportSymbol.flags & 32) { - var declaration_1 = localOrExportSymbol.valueDeclaration; - if (declaration_1.kind === 229 - && ts.nodeIsDecorated(declaration_1)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === declaration_1 && container.name !== node) { - getNodeLinks(declaration_1).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; - break; - } - container = ts.getContainingClass(container); - } - } - else if (declaration_1.kind === 199) { - var container = ts.getThisContainer(node, false); - while (container !== undefined) { - if (container.parent === declaration_1) { - if (container.kind === 149 && ts.hasModifier(container, 32)) { - getNodeLinks(declaration_1).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; - } - break; - } - container = ts.getThisContainer(container, false); - } - } - } - checkCollisionWithCapturedSuperVariable(node, node); - checkCollisionWithCapturedThisVariable(node, node); - checkCollisionWithCapturedNewTargetVariable(node, node); - checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); - var declaration = localOrExportSymbol.valueDeclaration; - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); - return unknownType; - } - if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); - return unknownType; - } - } - if (!(localOrExportSymbol.flags & 3) || assignmentKind === 1 || !declaration) { - return type; - } - var isParameter = ts.getRootDeclaration(declaration).kind === 146; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || - flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && - (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - var assumeInitialized = isParameter || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || - ts.isInAmbientContext(declaration); - var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : - type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048); - var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); - if (type === autoType || type === autoArrayType) { - if (flowType === autoType || flowType === autoArrayType) { - if (noImplicitAny) { - 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); - } - } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - return type; - } - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); - } - function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 || - (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 260) { - return; - } - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { - getNodeLinks(current).flags |= 65536; - } - if (container.kind === 214 && - ts.getAncestor(symbol.valueDeclaration, 227).parent === container && - isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152; - } - getNodeLinks(symbol.valueDeclaration).flags |= 262144; - } - if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072; - } - } - function isAssignedInBodyOfForStatement(node, container) { - var current = node; - while (current.parent.kind === 185) { - current = current.parent; - } - var isAssigned = false; - if (ts.isAssignmentTarget(current)) { - isAssigned = true; - } - else if ((current.parent.kind === 192 || current.parent.kind === 193)) { - var expr = current.parent; - isAssigned = expr.operator === 43 || expr.operator === 44; - } - if (!isAssigned) { - return false; - } - return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); - } - function captureLexicalThis(node, container) { - getNodeLinks(node).flags |= 2; - if (container.kind === 149 || container.kind === 152) { - var classNode = container.parent; - getNodeLinks(classNode).flags |= 4; - } - else { - getNodeLinks(container).flags |= 4; - } - } - function findFirstSuperCall(n) { - if (ts.isSuperCall(n)) { - return n; - } - else if (ts.isFunctionLike(n)) { - return undefined; - } - return ts.forEachChild(n, findFirstSuperCall); - } - function getSuperCallInConstructor(constructor) { - var links = getNodeLinks(constructor); - if (links.hasSuperCall === undefined) { - links.superCall = findFirstSuperCall(constructor.body); - links.hasSuperCall = links.superCall ? true : false; - } - return links.superCall; - } - function classDeclarationExtendsNull(classDecl) { - var classSymbol = getSymbolOfNode(classDecl); - var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); - return baseConstructorType === nullWideningType; - } - function checkThisBeforeSuper(node, container, diagnosticMessage) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, diagnosticMessage); - } - } - } - function checkThisExpression(node) { - var container = ts.getThisContainer(node, true); - var needToCaptureLexicalThis = false; - if (container.kind === 152) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - if (container.kind === 187) { - container = ts.getThisContainer(container, false); - needToCaptureLexicalThis = (languageVersion < 2); - } - switch (container.kind) { - case 233: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); - break; - case 232: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - break; - case 152: - if (isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); - } - break; - case 149: - case 148: - if (ts.getModifierFlags(container) & 32) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); - } - break; - case 144: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); - break; - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node, container); - } - if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 186 && - container.parent.kind === 194 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; - var classSymbol = checkExpression(className).symbol; - if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { - return getInferredClassType(classSymbol); - } - } - var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); - if (thisType) { - return thisType; - } - } - if (ts.isClassLike(container.parent)) { - var symbol = getSymbolOfNode(container.parent); - var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type); - } - if (ts.isInJavaScriptFile(node)) { - var type = getTypeForThisExpressionFromJSDoc(container); - if (type && type !== unknownType) { - return type; - } - } - if (noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; - } - function getTypeForThisExpressionFromJSDoc(node) { - var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 279) { - var jsDocFunctionType = jsdocType; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 282) { - return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); - } - } - } - function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); - } - function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; - var container = ts.getSuperContainer(node, true); - var needToCaptureLexicalThis = false; - if (!isCallExpression) { - while (container && container.kind === 187) { - container = ts.getSuperContainer(container, true); - needToCaptureLexicalThis = languageVersion < 2; - } - } - var canUseSuperExpression = isLegalUsageOfSuperExpression(container); - var nodeCheckFlag = 0; - if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); - if (current && current.kind === 144) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); - } - else if (isCallExpression) { - error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); - } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); - } - else { - error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); - } - return unknownType; - } - if (!isCallExpression && container.kind === 152) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); - } - if ((ts.getModifierFlags(container) & 32) || isCallExpression) { - nodeCheckFlag = 512; - } - else { - nodeCheckFlag = 256; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.getModifierFlags(container) & 256) { - if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096; - } - else { - getNodeLinks(container).flags |= 2048; - } - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node.parent, container); - } - if (container.parent.kind === 178) { - if (languageVersion < 2) { - error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); - return unknownType; - } - else { - return anyType; - } - } - var classLikeDeclaration = container.parent; - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } - if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); - return unknownType; - } - return nodeCheckFlag === 512 - ? getBaseConstructorTypeOfClass(classType) - : getTypeWithThisArgument(baseClassType, classType.thisType); - function isLegalUsageOfSuperExpression(container) { - if (!container) { - return false; - } - if (isCallExpression) { - return container.kind === 152; - } - else { - if (ts.isClassLike(container.parent) || container.parent.kind === 178) { - if (ts.getModifierFlags(container) & 32) { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154; - } - else { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154 || - container.kind === 149 || - container.kind === 148 || - container.kind === 152; - } - } - } - return false; - } - } - function getContainingObjectLiteral(func) { - return (func.kind === 151 || - func.kind === 153 || - func.kind === 154) && func.parent.kind === 178 ? func.parent : - func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : - undefined; - } - function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; - } - function getThisTypeFromContextualType(type) { - return mapType(type, function (t) { - return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); - }); - } - function getContextualThisParameterType(func) { - if (func.kind === 187) { - return undefined; - } - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var thisParameter = contextualSignature.thisParameter; - if (thisParameter) { - return getTypeOfSymbol(thisParameter); - } - } - } - if (noImplicitThis) { - var containingLiteral = getContainingObjectLiteral(func); - if (containingLiteral) { - var contextualType = getApparentTypeOfContextualType(containingLiteral); - var literal = containingLiteral; - var type = contextualType; - while (type) { - var thisType = getThisTypeFromContextualType(type); - if (thisType) { - return instantiateType(thisType, getContextualMapper(containingLiteral)); - } - if (literal.parent.kind !== 261) { - break; - } - literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); - } - return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); - } - if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { - var target = func.parent.left; - if (target.kind === 179 || target.kind === 180) { - return checkExpressionCached(target.expression); - } - } - } - return undefined; - } - function getContextuallyTypedParameterType(parameter) { - var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; - } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; - } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } - } - } - return undefined; - } - function getContextualTypeForInitializerExpression(node) { - var declaration = node.parent; - if (node === declaration.initializer) { - if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.kind === 146) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true, false); - } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176 && - parentDeclaration.type && - !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); - } - } - } - } - return undefined; - } - function getContextualTypeForReturnExpression(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return undefined; - } - var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) - : contextualReturnType; - } - return undefined; - } - function getContextualTypeForYieldOperand(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); - if (contextualReturnType) { - return node.asteriskToken - ? contextualReturnType - : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); - } - } - return undefined; - } - function isInParameterInitializerBeforeContainingFunction(node) { - while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } - function getContextualReturnType(functionDecl) { - if (functionDecl.type || - functionDecl.kind === 152 || - functionDecl.kind === 153 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 154))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); - } - var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { - return getReturnTypeOfSignature(signature); - } - return undefined; - } - function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); - if (argIndex >= 0) { - var signature = getResolvedOrAnySignature(callTarget); - return getTypeAtPosition(signature, argIndex); - } - return undefined; - } - function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183) { - return getContextualTypeForArgument(template.parent, substitutionExpression); - } - return undefined; - } - function getContextualTypeForBinaryOperand(node) { - var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (operator >= 58 && operator <= 70) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { - return undefined; - } - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } - } - else if (operator === 54) { - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); - } - return type; - } - else if (operator === 53 || operator === 26) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } - } - return undefined; - } - function getTypeOfPropertyOfContextualType(type, name) { - return mapType(type, function (t) { - var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; - }); - } - function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); - } - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } - function getContextualTypeForObjectLiteralMethod(node) { - ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { - return undefined; - } - return getContextualTypeForObjectLiteralElement(node); - } - function getContextualTypeForObjectLiteralElement(element) { - var objectLiteral = element.parent; - var type = getApparentTypeOfContextualType(objectLiteral); - if (type) { - if (!ts.hasDynamicName(element)) { - var symbolName = getSymbolOfNode(element).name; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); - if (propertyType) { - return propertyType; - } - } - return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || - getIndexTypeOfContextualType(type, 0); - } - return undefined; - } - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1) - || getIteratedTypeOrElementType(type, undefined, false, false, false); - } - return undefined; - } - function getContextualTypeForConditionalOperand(node) { - var conditional = node.parent; - return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; - } - function getContextualTypeForJsxExpression(node) { - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - node.parent.openingElement.attributes; - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfType(attributesType, node.parent.name.text); - } - else if (node.parent.kind === 249) { - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - return attributesType; - } - } - function getContextualTypeForJsxAttribute(attribute) { - var attributesType = getContextualType(attribute.parent); - if (ts.isJsxAttribute(attribute)) { - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - return getTypeOfPropertyOfType(attributesType, attribute.name.text); - } - else { - return attributesType; - } - } - function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); - } - function getContextualType(node) { - if (isInsideWithStatementBody(node)) { - return undefined; - } - if (node.contextualType) { - return node.contextualType; - } - var parent = node.parent; - switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 176: - return getContextualTypeForInitializerExpression(node); - case 187: - case 219: - return getContextualTypeForReturnExpression(node); - case 197: - return getContextualTypeForYieldOperand(parent); - case 181: - case 182: - return getContextualTypeForArgument(parent, node); - case 184: - case 202: - return getTypeFromTypeNode(parent.type); - case 194: - return getContextualTypeForBinaryOperand(node); - case 261: - case 262: - return getContextualTypeForObjectLiteralElement(parent); - case 263: - return getApparentTypeOfContextualType(parent.parent); - case 177: - return getContextualTypeForElementExpression(node); - case 195: - return getContextualTypeForConditionalOperand(node); - case 205: - ts.Debug.assert(parent.parent.kind === 196); - return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: - return getContextualType(parent); - case 256: - return getContextualTypeForJsxExpression(parent); - case 253: - case 255: - return getContextualTypeForJsxAttribute(parent); - case 251: - case 250: - return getAttributesTypeFromJsxOpeningLikeElement(parent); - } - return undefined; - } - function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; - } - function getNonGenericSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!signature.typeParameters && !isAritySmaller(signature, node)) { - return signature; - } - } - } - function isAritySmaller(signature, target) { - var targetParameterCount = 0; - for (; targetParameterCount < target.parameters.length; targetParameterCount++) { - var param = target.parameters[targetParameterCount]; - if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { - break; - } - } - if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { - targetParameterCount--; - } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; - } - function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 || node.kind === 187; - } - function getContextualSignatureForFunctionLikeDeclaration(node) { - return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) - ? getContextualSignature(node) - : undefined; - } - function getContextualTypeForFunctionLikeDeclaration(node) { - return ts.isObjectLiteralMethod(node) ? - getContextualTypeForObjectLiteralMethod(node) : - getApparentTypeOfContextualType(node); - } - function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); - if (!type) { - return undefined; - } - if (!(type.flags & 65536)) { - return getNonGenericSignature(type, node); - } - var signatureList; - var types = type.types; - 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) { - signatureList = [signature]; - } - else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { - return undefined; - } - else { - signatureList.push(signature); - } - } - } - var result; - if (signatureList) { - result = cloneSignature(signatureList[0]); - result.resolvedReturnType = undefined; - result.unionSignatures = signatureList; - } - return result; - } - function checkSpreadExpression(node, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 1536); - } - var arrayOrIterableType = checkExpression(node.expression, checkMode); - return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); - } - function hasDefaultValue(node) { - return (node.kind === 176 && !!node.initializer) || - (node.kind === 194 && node.operatorToken.kind === 58); - } - function checkArrayLiteral(node, checkMode) { - var elements = node.elements; - var hasSpreadElement = false; - var elementTypes = []; - var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 198) { - var restArrayType = checkExpression(e.expression, checkMode); - var restElementType = getIndexTypeOfType(restArrayType, 1) || - getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); - if (restElementType) { - elementTypes.push(restElementType); - } - } - else { - var type = checkExpressionForMutableLocation(e, checkMode); - elementTypes.push(type); - } - hasSpreadElement = hasSpreadElement || e.kind === 198; - } - if (!hasSpreadElement) { - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); - type.pattern = node; - return type; - } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { - var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else { - if (patternElement.kind !== 200) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(unknownType); - } - } - } - if (elementTypes.length) { - return createTupleType(elementTypes); - } - } - } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); - } - function isNumericName(name) { - return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); - } - function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); - } - function isInfinityOrNaNString(name) { - return name === "Infinity" || name === "-Infinity" || name === "NaN"; - } - function isNumericLiteralName(name) { - return (+name).toString() === name; - } - function checkComputedPropertyName(node) { - var links = getNodeLinks(node.expression); - if (!links.resolvedType) { - links.resolvedType = checkExpression(node.expression); - 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 { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); - } - } - return links.resolvedType; - } - function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { - var propTypes = []; - for (var i = 0; i < properties.length; i++) { - if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { - propTypes.push(getTypeOfSymbol(properties[i])); - } - } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; - return createIndexInfo(unionType, false); - } - function checkObjectLiteral(node, checkMode) { - var inDestructuringPattern = ts.isAssignmentTarget(node); - checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); - var propertiesArray = []; - var spread = emptyObjectType; - var propagatedFlags = 0; - var contextualType = getApparentTypeOfContextualType(node); - var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); - var typeFlags = 0; - var patternWithComputedProperties = false; - var hasComputedStringProperty = false; - var hasComputedNumberProperty = false; - var offset = 0; - for (var i = 0; i < node.properties.length; i++) { - var memberDecl = node.properties[i]; - var member = memberDecl.symbol; - if (memberDecl.kind === 261 || - memberDecl.kind === 262 || - ts.isObjectLiteralMethod(memberDecl)) { - var type = void 0; - if (memberDecl.kind === 261) { - type = checkPropertyAssignment(memberDecl, checkMode); - } - else if (memberDecl.kind === 151) { - type = checkObjectLiteralMethod(memberDecl, checkMode); - } - else { - ts.Debug.assert(memberDecl.kind === 262); - type = checkExpressionForMutableLocation(memberDecl.name, checkMode); - } - typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, member.name); - if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); - if (isOptional) { - prop.flags |= 67108864; - } - if (ts.hasDynamicName(memberDecl)) { - patternWithComputedProperties = true; - } - } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { - var impliedProp = getPropertyOfType(contextualType, member.name); - if (impliedProp) { - prop.flags |= impliedProp.flags & 67108864; - } - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { - error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); - } - } - prop.declarations = member.declarations; - prop.parent = member.parent; - if (member.valueDeclaration) { - prop.valueDeclaration = member.valueDeclaration; - } - prop.type = type; - prop.target = member; - member = prop; - } - else if (memberDecl.kind === 263) { - if (languageVersion < 2) { - checkExternalEmitHelpers(memberDecl, 2); - } - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - propertiesArray = []; - propertiesTable = ts.createMap(); - hasComputedStringProperty = false; - hasComputedNumberProperty = false; - typeFlags = 0; - } - var type = checkExpression(memberDecl.expression); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return unknownType; - } - spread = getSpreadType(spread, type); - offset = i + 1; - continue; - } - else { - ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); - checkNodeDeferred(memberDecl); - } - if (ts.hasDynamicName(memberDecl)) { - if (isNumericName(memberDecl.name)) { - hasComputedNumberProperty = true; - } - else { - hasComputedStringProperty = true; - } - } - else { - propertiesTable.set(member.name, member); - } - propertiesArray.push(member); - } - if (contextualTypeHasPattern) { - for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 67108864)) { - error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - propertiesTable.set(prop.name, prop); - propertiesArray.push(prop); - } - } - } - if (spread !== emptyObjectType) { - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; - } - return spread; - } - return createObjectLiteralType(); - function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); - result.objectFlags |= 128; - if (patternWithComputedProperties) { - result.objectFlags |= 512; - } - if (inDestructuringPattern) { - result.pattern = node; - } - if (!(result.flags & 6144)) { - propagatedFlags |= (result.flags & 14680064); - } - return result; - } - } - function isValidSpreadType(type) { - return !!(type.flags & (1 | 4096 | 2048 | 16777216) || - type.flags & 32768 && !isGenericMappedType(type) || - type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); - } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); - return getJsxGlobalElementType() || anyType; - } - function checkJsxElement(node) { - checkJsxOpeningLikeElement(node.openingElement); - if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { - getIntrinsicTagSymbol(node.closingElement); - } - else { - checkExpression(node.closingElement.tagName); - } - return getJsxGlobalElementType() || anyType; - } - function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; - } - function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 179 || tagName.kind === 99) { - return false; - } - else { - return ts.isIntrinsicJsxName(tagName.text); - } - } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { - var attributes = openingLikeElement.attributes; - 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; - if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; - var attributeSymbol = createSymbol(4 | 134217728 | member.flags, member.name); - attributeSymbol.declarations = member.declarations; - attributeSymbol.parent = member.parent; - if (member.valueDeclaration) { - attributeSymbol.valueDeclaration = member.valueDeclaration; - } - attributeSymbol.type = exprType; - 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); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - var exprType = checkExpression(attributeDecl.expression); - if (isTypeAny(exprType)) { - hasSpreadAnyType = true; - } - if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); - } - else { - typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; - } - } - } - if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - } - attributesArray = getPropertiesOfType(spread); - } - 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 _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - if (child.kind === 10) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } - 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); - childrenPropSymbol.type = childrenTypes.length === 1 ? - childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); - } - } - 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); - result.flags |= 33554432 | 4194304; - result.objectFlags |= 128; - return result; - } - } - function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); - } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; - } - function getIntrinsicTagSymbol(node) { - var links = getNodeLinks(node); - if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); - if (intrinsicProp) { - links.jsxFlags |= 1; - return links.resolvedSymbol = intrinsicProp; - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - links.jsxFlags |= 2; - return links.resolvedSymbol = intrinsicElementsType.symbol; - } - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return links.resolvedSymbol = unknownSymbol; - } - else { - if (noImplicitAny) { - error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); - } - return links.resolvedSymbol = unknownSymbol; - } - } - return links.resolvedSymbol; - } - function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536)); - if (isTypeAny(valueType)) { - return anyType; - } - var signatures = getSignaturesOfType(valueType, 1); - if (signatures.length === 0) { - signatures = getSignaturesOfType(valueType, 0); - if (signatures.length === 0) { - error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); - return unknownType; - } - } - 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); - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); - var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); - var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); - if (propertiesOfJsxElementAttribPropInterface) { - if (propertiesOfJsxElementAttribPropInterface.length === 0) { - return ""; - } - else if (propertiesOfJsxElementAttribPropInterface.length === 1) { - return propertiesOfJsxElementAttribPropInterface[0].name; - } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { - error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, nameOfAttribPropContainer); - } - } - return undefined; - } - function getJsxElementPropertiesName() { - if (!_hasComputedJsxElementPropertiesName) { - _hasComputedJsxElementPropertiesName = true; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; - } - function getJsxElementChildrenPropertyname() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - 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)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); - 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) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - 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++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.text) && - !getPropertyOfType(paramType, attribute.name.text)) { - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - if (!result) { - result = allMatchingAttributesType; - } - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttributes !== unknownType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } - if (elementType.flags & 65536) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), true); - } - if (elementType.flags & 2) { - return anyType; - } - else if (elementType.flags & 32) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - return anyType; - } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - return anyType; - } - else if (propsName === "") { - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - return attributesType; - } - else { - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } - } - function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { - ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var symbol = getIntrinsicTagSymbol(node); - if (links.jsxFlags & 1) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); - } - else if (links.jsxFlags & 2) { - return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; - } - else { - return links.resolvedJsxElementAttributesType = unknownType; - } - } - return links.resolvedJsxElementAttributesType; - } - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); - } - return links.resolvedJsxElementAttributesType; - } - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, true); - } - } - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, false); - } - } - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.text); - return prop || unknownSymbol; - } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; - } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; - } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } - } - return deferredJsxStatelessElementType; - } - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); - return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; - } - function checkJsxPreconditions(errorNode) { - if ((compilerOptions.jsx || 0) === 0) { - error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); - } - if (getJsxGlobalElementType() === undefined) { - if (noImplicitAny) { - error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); - } - } - } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); - checkJsxPreconditions(node); - var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); - if (reactSym) { - reactSym.isReferenced = true; - if (reactSym.flags & 8388608 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { - markAliasSymbolAsReferenced(reactSym); - } - } - 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) : - getCustomJsxElementAttributesType(openingLikeElement, false); - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.name) || !!(getPropertyOfType(targetAttributesType, attribute.name)); - }); - if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); - } - else { - 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) { - if (node.expression) { - var type = checkExpression(node.expression, checkMode); - if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); - } - return type; - } - else { - return unknownType; - } - } - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149; - } - function getDeclarationNodeFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; - } - function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); - } - function checkPropertyAccessibility(node, left, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 || node.kind === 226 ? - node.name : - node.right; - 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; - } - if (left.kind === 97) { - if (languageVersion < 2) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 && propKind !== 150; - }); - if (hasNonMethodDeclaration) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - return false; - } - } - if (flags & 128) { - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - } - if (!(flags & 24)) { - return true; - } - if (flags & 8) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - return true; - } - if (left.kind === 97) { - return true; - } - var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { - var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; - }); - if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); - return false; - } - if (flags & 32) { - return true; - } - if (type.flags & 16384 && type.isThisType) { - type = getConstraintOfTypeParameter(type); - } - if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); - return false; - } - return true; - } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); - } - function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; - if (kind) { - error(errorNode, kind & 2048 ? kind & 4096 ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); - var t = getNonNullableType(type); - return t.flags & (6144 | 8192) ? unknownType : t; - } - return type; - } - function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); - } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); - } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { - return propType; - } - 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 - : node.left; - var type = checkExpression(left); - if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop) { - return checkPropertyAccessibility(node, left, type, prop); - } - } - return true; - } - function getForInVariableSymbol(node) { - var initializer = node.initializer; - if (initializer.kind === 227) { - var variable = initializer.declarations[0]; - if (variable && !ts.isBindingPattern(variable.name)) { - return getSymbolOfNode(variable); - } - } - else if (initializer.kind === 71) { - return getResolvedSymbol(initializer); - } - return undefined; - } - function hasNumericPropertyNames(type) { - return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); - } - function isForInVariableForNumericPropertyNames(expr) { - var e = ts.skipParentheses(expr); - if (e.kind === 71) { - var symbol = getResolvedSymbol(e); - if (symbol.flags & 3) { - var child = expr; - var node = expr.parent; - while (node) { - if (node.kind === 215 && - child === node.statement && - getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(getTypeOfExpression(node.expression))) { - return true; - } - child = node; - node = node.parent; - } - } - } - return false; - } - function checkIndexedAccess(node) { - var objectType = checkNonNullExpression(node.expression); - var indexExpression = node.argumentExpression; - if (!indexExpression) { - var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 && node.parent.expression === node) { - var start = ts.skipTrivia(sourceFile.text, node.expression.end); - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); - } - else { - var start = node.end - "]".length; - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); - } - return unknownType; - } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); - if (objectType === unknownType || objectType === silentNeverType) { - return objectType; - } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { - error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); - return unknownType; - } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === unknownType) { - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - if ((expressionType.flags & 512) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); - if (!globalESSymbol) { - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - 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); - } - else if (node.kind !== 147) { - ts.forEach(node.arguments, function (argument) { - checkExpression(argument); - }); - } - return anySignature; - } - function resolveErrorCall(node) { - resolveUntypedCall(node); - return unknownSignature; - } - function reorderCandidates(signatures, result) { - var lastParent; - var lastSymbol; - var cutoffIndex = 0; - var index; - var specializedIndex = -1; - var spliceIndex; - ts.Debug.assert(!result.length); - 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) { - if (lastParent && parent === lastParent) { - index++; - } - else { - lastParent = parent; - index = cutoffIndex; - } - } - else { - index = cutoffIndex = result.length; - lastParent = parent; - } - lastSymbol = symbol; - if (signature.hasLiteralTypes) { - specializedIndex++; - spliceIndex = specializedIndex; - cutoffIndex++; - } - else { - spliceIndex = index; - } - result.splice(spliceIndex, 0, signature); - } - } - function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 198) { - return i; - } - } - return -1; - } - function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; - var typeArguments; - var callIsIncomplete; - var isDecorator; - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - return true; - } - if (node.kind === 183) { - var tagExpression = node; - argCount = args.length; - typeArguments = undefined; - if (tagExpression.template.kind === 196) { - var templateExpression = tagExpression.template; - var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); - ts.Debug.assert(lastSpan !== undefined); - callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; - } - else { - var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 13); - callIsIncomplete = !!templateLiteral.isUnterminated; - } - } - else if (node.kind === 147) { - isDecorator = true; - typeArguments = undefined; - argCount = getEffectiveArgumentCount(node, undefined, signature); - } - else { - var callExpression = node; - if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 182); - return signature.minArgumentCount === 0; - } - argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; - callIsIncomplete = callExpression.arguments.end === callExpression.end; - typeArguments = callExpression.typeArguments; - spreadArgIndex = getSpreadArgumentIndex(args); - } - var numTypeParameters = ts.length(signature.typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { - return false; - } - if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; - } - if (!signature.hasRestParameter && argCount > signature.parameters.length) { - return false; - } - var hasEnoughArguments = argCount >= signature.minArgumentCount; - return callIsIncomplete || hasEnoughArguments; - } - function getSingleCallSignature(type) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - return resolved.callSignatures[0]; - } - } - return undefined; - } - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, true, false); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - inferTypesWithContext(context, instantiateType(source, contextualMapper), target); - }); - return getSignatureInstantiation(signature, getInferredTypes(context)); - } - function inferTypeArguments(node, signature, args, excludeArgument, context) { - var typeParameters = signature.typeParameters; - var inferenceMapper = getInferenceMapper(context); - for (var i = 0; i < typeParameters.length; i++) { - if (!context.inferences[i].isFixed) { - context.inferredTypes[i] = undefined; - } - } - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } - var thisType = getThisTypeOfSignature(signature); - if (thisType) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypesWithContext(context, thisArgumentType, thisType); - } - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } - inferTypesWithContext(context, argType, paramType); - } - } - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); - } - } - } - getInferredTypes(context); - } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { - var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; - var mapper; - for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } - } - } - return typeArgumentsAreAssignable; - } - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - var callIsIncomplete = node.attributes.end === node.end; - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.name) && isUnhyphenatedJsxName(arg.name)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); - } - function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); - } - var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; - var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { - return false; - } - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - } - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { - return false; - } - } - } - return true; - } - function getThisArgumentOfCall(node) { - if (node.kind === 181) { - var callee = node.expression; - if (callee.kind === 179) { - return callee.expression; - } - else if (callee.kind === 180) { - return callee.expression; - } - } - } - function getEffectiveCallArguments(node) { - var args; - if (node.kind === 183) { - var template = node.template; - args = [undefined]; - if (template.kind === 196) { - ts.forEach(template.templateSpans, function (span) { - args.push(span.expression); - }); - } - } - else if (node.kind === 147) { - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - args = node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; - } - else { - args = node.arguments || emptyArray; - } - return args; - } - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147) { - switch (node.parent.kind) { - case 229: - case 199: - return 1; - case 149: - return 2; - case 151: - case 153: - case 154: - if (languageVersion === 0) { - return 2; - } - return signature.parameters.length >= 3 ? 3 : 2; - case 146: - return 3; - } - } - else { - return args.length; - } - } - function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 229) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 146) { - node = node.parent; - if (node.kind === 152) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 229) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return unknownType; - } - if (node.kind === 146) { - node = node.parent; - if (node.kind === 152) { - return anyType; - } - } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - var element = node; - switch (element.name.kind) { - case 71: - case 8: - case 9: - return getLiteralType(element.name.text); - case 144: - var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return unknownType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 229) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 146) { - return numberType; - } - if (node.kind === 149) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return unknownType; - } - function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 147) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 183) { - return getGlobalTemplateStringsArrayType(); - } - return undefined; - } - function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 147 || - (argIndex === 0 && node.kind === 183)) { - return undefined; - } - return args[argIndex]; - } - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147) { - return node.expression; - } - else if (argIndex === 0 && node.kind === 183) { - return node.template; - } - else { - return arg; - } - } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183; - var isDecorator = node.kind === 147; - var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); - var typeArguments; - if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { - typeArguments = node.typeArguments; - if (node.expression.kind !== 97) { - ts.forEach(typeArguments, checkSourceElement); - } - } - if (signatures.length === 1) { - var declaration = signatures[0].declaration; - if (declaration && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration)) { - if (containsArgumentsReference(declaration)) { - var signatureWithRest = cloneSignature(signatures[0]); - var syntheticArgsSymbol = createSymbol(3, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - signatureWithRest.parameters = ts.concatenate(signatureWithRest.parameters, [syntheticArgsSymbol]); - signatureWithRest.hasRestParameter = true; - signatures = [signatureWithRest]; - } - } - } - var candidates = candidatesOutArray || []; - reorderCandidates(signatures, candidates); - if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); - return resolveErrorCall(node); - } - var args = getEffectiveCallArguments(node); - var excludeArgument; - if (!isDecorator) { - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - } - } - } - var candidateForArgumentError; - var candidateForTypeArgumentError; - var resultOfFailedInference; - var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; - if (candidates.length > 1) { - result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); - } - if (!result) { - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; - result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); - } - if (result) { - return result; - } - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - return candidateForArgumentError; - } - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); - } - else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - 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 (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } - } - 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 _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)); - } - return candidate; - } - } - } - return resolveErrorCall(node); - function chooseOverload(candidates, relation, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { - var originalCandidate = candidates_2[_i]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { - continue; - } - var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, false, ts.isInJavaScriptFile(node)) - : undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); - } - else { - inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentTypes = inferenceContext.inferredTypes; - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; - } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { - break; - } - var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; - if (index < 0) { - return candidate; - } - excludeArgument[index] = false; - } - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } - } - return undefined; - } - } - function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 97) { - var superType = checkSuperExpression(node.expression); - if (superType !== unknownType) { - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - if (baseTypeNode) { - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); - } - } - return resolveUntypedCall(node); - } - var funcType = checkNonNullExpression(node.expression); - if (funcType === silentNeverType) { - return silentNeverSignature; - } - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - if (funcType !== unknownType && node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - if (constructSignatures.length) { - error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); - } - else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - } - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 65536) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } - function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 1) { - var spreadIndex = getSpreadArgumentIndex(node.arguments); - if (spreadIndex >= 0) { - error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); - } - } - var expressionType = checkNonNullExpression(node.expression); - if (expressionType === silentNeverType) { - return silentNeverSignature; - } - expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { - return resolveErrorCall(node); - } - 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(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } - if (isTypeAny(expressionType)) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - var constructSignatures = getSignaturesOfType(expressionType, 1); - if (constructSignatures.length) { - if (!isConstructorAccessible(node, constructSignatures[0])) { - return resolveErrorCall(node); - } - return resolveCall(node, constructSignatures, candidatesOutArray); - } - var callSignatures = getSignaturesOfType(expressionType, 0); - if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); - } - return signature; - } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); - return resolveErrorCall(node); - } - function isConstructorAccessible(node, signature) { - if (!signature || !signature.declaration) { - return true; - } - var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - if (!(modifiers & 24)) { - return true; - } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); - var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); - } - } - if (modifiers & 8) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - if (modifiers & 16) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - return false; - } - return true; - } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { - var tagType = checkExpression(node.tag); - var apparentType = getApparentType(tagType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - function getDiagnosticHeadMessageForDecoratorResolution(node) { - switch (node.parent.kind) { - case 229: - case 199: - return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146: - return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151: - case 153: - case 154: - return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; - } - } - function resolveDecorator(node, candidatesOutArray) { - var funcType = checkExpression(node.expression); - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); - } - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; - } - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 65536) { - var types = elementType.types; - var result = void 0; - 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; - } - var callSignatures = elementType && getSignaturesOfType(elementType, 0); - if (callSignatures && callSignatures.length > 0) { - var callSignature = void 0; - callSignature = resolveCall(openingLikeElement, callSignatures, candidatesOutArray); - return callSignature; - } - return undefined; - } - function resolveSignature(node, candidatesOutArray) { - switch (node.kind) { - case 181: - return resolveCallExpression(node, candidatesOutArray); - case 182: - return resolveNewExpression(node, candidatesOutArray); - case 183: - return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147: - return resolveDecorator(node, candidatesOutArray); - case 251: - case 250: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); - } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); - } - function getResolvedSignature(node, candidatesOutArray) { - var links = getNodeLinks(node); - var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { - return cached; - } - links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); - links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; - return result; - } - function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); - } - function getInferredClassType(symbol) { - var links = getSymbolLinks(symbol); - if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); - } - return links.inferredClassType; - } - function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - var signature = getResolvedSignature(node); - if (node.expression.kind === 97) { - return voidType; - } - if (node.kind === 182) { - var declaration = signature.declaration; - if (declaration && - declaration.kind !== 152 && - declaration.kind !== 156 && - declaration.kind !== 161 && - !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 71 ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.members && funcSymbol.flags & 16) { - return getInferredClassType(funcSymbol); - } - else if (noImplicitAny) { - error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); - } - return anyType; - } - } - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { - return resolveExternalModuleTypeByLiteral(node.arguments[0]); - } - return getReturnTypeOfSignature(signature); - } - function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, true)) { - return false; - } - var resolvedRequire = resolveName(node.expression, node.expression.text, 107455, undefined, undefined); - if (!resolvedRequire) { - return true; - } - if (resolvedRequire.flags & 8388608) { - return false; - } - var targetDeclarationKind = resolvedRequire.flags & 16 - ? 228 - : resolvedRequire.flags & 3 - ? 226 - : 0; - if (targetDeclarationKind !== 0) { - var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - return ts.isInAmbientContext(decl); - } - return false; - } - function checkTaggedTemplateExpression(node) { - return getReturnTypeOfSignature(getResolvedSignature(node)); - } - function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); - checkSourceElement(node.type); - var targetType = getTypeFromTypeNode(node.type); - if (produceDiagnostics && targetType !== unknownType) { - var widenedType = getWidenedType(exprType); - if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, node, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); - } - } - return targetType; - } - function checkNonNullAssertion(node) { - return getNonNullableType(checkExpression(node.expression)); - } - function checkMetaProperty(node) { - checkGrammarMetaProperty(node); - var container = ts.getNewTargetContainer(node); - if (!container) { - error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); - return unknownType; - } - else if (container.kind === 152) { - var symbol = getSymbolOfNode(container.parent); - return getTypeOfSymbol(symbol); - } - else { - var symbol = getSymbolOfNode(container); - return getTypeOfSymbol(symbol); - } - } - function getTypeOfParameter(symbol) { - var type = getTypeOfSymbol(symbol); - if (strictNullChecks) { - var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { - return getNullableType(type, 2048); - } - } - return type; - } - function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; - } - function getTypeOfFirstParameterOfSignature(signature) { - return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; - } - function assignContextualParameterTypes(signature, context, mapper, checkMode) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (checkMode === 2) { - for (var i = 0; i < len; i++) { - var declaration = signature.parameters[i].valueDeclaration; - if (declaration.type) { - inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); - } - } - } - if (context.thisParameter) { - var parameter = signature.thisParameter; - if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { - if (!parameter) { - signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper, checkMode); - } - } - for (var i = 0; i < len; i++) { - var parameter = signature.parameters[i]; - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - var parameter = ts.lastOrUndefined(signature.parameters); - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - } - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); - } - } - } - } - function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper, checkMode) { - var links = getSymbolLinks(parameter); - if (!links.type) { - links.type = instantiateType(contextualType, mapper); - var name = ts.getNameOfDeclaration(parameter.valueDeclaration); - if (links.type === emptyObjectType && - (name.kind === 174 || name.kind === 175)) { - links.type = getTypeFromBindingPattern(name); - } - assignBindingElementTypes(parameter.valueDeclaration); - } - else if (checkMode === 2) { - inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); - } - } - function getReturnTypeFromJSDocComment(func) { - var returnTag = ts.getJSDocReturnTag(func); - if (returnTag && returnTag.typeExpression) { - return getTypeFromTypeNode(returnTag.typeExpression.type); - } - return undefined; - } - function createPromiseType(promisedType) { - var globalPromiseType = getGlobalPromiseType(true); - if (globalPromiseType !== emptyGenericType) { - promisedType = getAwaitedType(promisedType) || emptyObjectType; - return createTypeReference(globalPromiseType, [promisedType]); - } - return emptyObjectType; - } - function createPromiseReturnType(func, promisedType) { - var promiseType = createPromiseType(promisedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); - return unknownType; - } - else if (!getGlobalPromiseConstructorSymbol(true)) { - error(func, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - return promiseType; - } - function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!func.body) { - return unknownType; - } - var functionFlags = ts.getFunctionFlags(func); - var type; - if (func.body.kind !== 207) { - type = checkExpressionCached(func.body, checkMode); - if (functionFlags & 2) { - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - } - else { - var types = void 0; - if (functionFlags & 1) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); - if (!types || types.length === 0) { - var iterableIteratorAny = functionFlags & 2 - ? createAsyncIterableIteratorType(anyType) - : createIterableIteratorType(anyType); - if (noImplicitAny) { - error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); - } - return iterableIteratorAny; - } - } - else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (!types) { - return functionFlags & 2 - ? createPromiseReturnType(func, neverType) - : neverType; - } - if (types.length === 0) { - return functionFlags & 2 - ? createPromiseReturnType(func, voidType) - : voidType; - } - } - type = getUnionType(types, true); - if (functionFlags & 1) { - type = functionFlags & 2 - ? createAsyncIterableIteratorType(type) - : createIterableIteratorType(type); - } - } - if (!contextualSignature) { - reportErrorsFromWidening(func, type); - } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); - } - var widenedType = getWidenedType(type); - return (functionFlags & 3) === 2 - ? createPromiseReturnType(func, widenedType) - : widenedType; - } - function checkAndAggregateYieldOperandTypes(func, checkMode) { - var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); - ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); - } - if (functionFlags & 2) { - type = checkAwaitedType(type, expr, yieldExpression.asteriskToken - ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - }); - return aggregatedTypes; - } - function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { - return false; - } - var type = getTypeOfExpression(node.expression); - if (!isLiteralType(type)) { - return false; - } - var switchTypes = getSwitchClauseTypes(node); - if (!switchTypes.length) { - return false; - } - return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); - } - function functionHasImplicitReturn(func) { - if (!(func.flags & 128)) { - return false; - } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { - return false; - } - return true; - } - function checkAndAggregateReturnExpressionTypes(func, checkMode) { - var functionFlags = ts.getFunctionFlags(func); - var aggregatedTypes = []; - var hasReturnWithNoExpression = functionHasImplicitReturn(func); - var hasReturnOfTypeNever = false; - ts.forEachReturnStatement(func.body, function (returnStatement) { - var expr = returnStatement.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (functionFlags & 2) { - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (type.flags & 8192) { - hasReturnOfTypeNever = true; - } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - else { - hasReturnWithNoExpression = true; - } - }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 || func.kind === 187)) { - return undefined; - } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } - } - return aggregatedTypes; - } - function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { - if (!produceDiagnostics) { - return; - } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { - return; - } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { - return; - } - var hasExplicitReturn = func.flags & 256; - if (returnType && returnType.flags & 8192) { - error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); - } - else if (returnType && !hasExplicitReturn) { - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); - } - else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { - error(func.type, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); - } - else if (compilerOptions.noImplicitReturns) { - if (!returnType) { - if (!hasExplicitReturn) { - return; - } - var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { - return; - } - } - error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { - checkGrammarForGenerator(node); - } - if (checkMode === 1 && isContextSensitive(node)) { - checkNodeDeferred(node); - return anyFunctionType; - } - var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); - var contextSensitive = isContextSensitive(node); - var mightFixTypeParameters = contextSensitive && checkMode === 2; - if (mightFixTypeParameters || !(links.flags & 1024)) { - var contextualSignature = getContextualSignature(node); - var contextChecked = !!(links.flags & 1024); - if (mightFixTypeParameters || !contextChecked) { - links.flags |= 1024; - if (contextualSignature) { - var signature = getSignaturesOfType(type, 0)[0]; - if (contextSensitive) { - assignContextualParameterTypes(signature, contextualSignature, getContextualMapper(node), checkMode); - } - if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { - var returnType = getReturnTypeFromBody(node, checkMode); - if (!signature.resolvedReturnType) { - signature.resolvedReturnType = returnType; - } - } - } - if (!contextChecked) { - checkSignatureDeclaration(node); - checkNodeDeferred(node); - } - } - } - if (produceDiagnostics && node.kind !== 151) { - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - } - return type; - } - function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var functionFlags = ts.getFunctionFlags(node); - var returnOrPromisedType = node.type && - ((functionFlags & 3) === 2 ? - checkAsyncFunctionReturnType(node) : - getTypeFromTypeNode(node.type)); - if ((functionFlags & 1) === 0) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (node.body) { - if (!node.type) { - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - if (node.body.kind === 207) { - checkSourceElement(node.body); - } - else { - var exprType = checkExpression(node.body); - if (returnOrPromisedType) { - if ((functionFlags & 3) === 2) { - 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); - } - else { - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); - } - } - } - registerForUnusedIdentifiersCheck(node); - } - } - function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { - error(operand, diagnostic); - return false; - } - return true; - } - function isReadonlySymbol(symbol) { - 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); - } - function isReferenceToReadonlyEntity(expr, symbol) { - if (isReadonlySymbol(symbol)) { - if (symbol.flags & 4 && - (expr.kind === 179 || expr.kind === 180) && - expr.expression.kind === 99) { - var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152)) - return true; - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); - } - return true; - } - return false; - } - function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 || expr.kind === 180) { - var node = ts.skipParentheses(expr.expression); - if (node.kind === 71) { - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol.flags & 8388608) { - var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240; - } - } - } - return false; - } - function checkReferenceExpression(expr, invalidReferenceMessage) { - var node = ts.skipParentheses(expr); - if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { - error(expr, invalidReferenceMessage); - return false; - } - return true; - } - function checkDeleteExpression(node) { - checkExpression(node.expression); - var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 && expr.kind !== 180) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); - return booleanType; - } - var links = getNodeLinks(expr); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); - } - return booleanType; - } - function checkTypeOfExpression(node) { - checkExpression(node.expression); - return typeofType; - } - function checkVoidExpression(node) { - checkExpression(node.expression); - return undefinedWideningType; - } - function checkAwaitExpression(node) { - if (produceDiagnostics) { - if (!(node.flags & 16384)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - var operandType = checkExpression(node.expression); - return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkPrefixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - switch (node.operator) { - case 37: - case 38: - case 52: - checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512)) { - error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); - } - return numberType; - case 51: - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : - booleanType; - case 43: - case 44: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - return unknownType; - } - function checkPostfixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - function maybeTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 196608) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (maybeTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 65536) { - var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; - } - if (type.flags & 131072) { - var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); - } - function isConstEnumSymbol(symbol) { - return (symbol.flags & 128) !== 0; - } - function checkInstanceOfExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (isTypeOfKind(leftType, 8190)) { - error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0).length || - getSignaturesOfType(rightType, 1).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); - } - return booleanType; - } - function checkInExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - 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)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - return booleanType; - } - function checkObjectLiteralAssignment(node, sourceType) { - var properties = node.properties; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); - } - return sourceType; - } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 || property.kind === 262) { - var name = property.name; - if (name.kind === 144) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || - getIndexTypeOfType(objectLiteralType, 0); - if (type) { - if (property.kind === 262) { - return checkDestructuringAssignment(property, type); - } - else { - return checkDestructuringAssignment(property.initializer, type); - } - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); - } - } - else if (property.kind === 263) { - if (languageVersion < 5) { - checkExternalEmitHelpers(property, 4); - } - var nonRestNames = []; - if (allProperties) { - for (var i = 0; i < allProperties.length - 1; i++) { - nonRestNames.push(allProperties[i].name); - } - } - var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); - return checkDestructuringAssignment(property.expression, type); - } - else { - error(property, ts.Diagnostics.Property_assignment_expected); - } - } - function checkArrayLiteralAssignment(node, sourceType, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); - } - var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || unknownType; - var elements = node.elements; - for (var i = 0; i < elements.length; i++) { - checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); - } - return sourceType; - } - function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { - var elements = node.elements; - var element = elements[elementIndex]; - if (element.kind !== 200) { - if (element.kind !== 198) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; - if (type) { - return checkDestructuringAssignment(element, type, checkMode); - } - else { - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } - } - } - else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - else { - var restExpression = element.expression; - if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); - } - } - } - } - return undefined; - } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { - var target; - if (exprOrAssignment.kind === 262) { - var prop = exprOrAssignment; - if (prop.objectAssignmentInitializer) { - if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { - sourceType = getTypeWithFacts(sourceType, 131072); - } - checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); - } - target = exprOrAssignment.name; - } - else { - target = exprOrAssignment; - } - if (target.kind === 194 && target.operatorToken.kind === 58) { - checkBinaryExpression(target, checkMode); - target = target.left; - } - if (target.kind === 178) { - return checkObjectLiteralAssignment(target, sourceType); - } - if (target.kind === 177) { - return checkArrayLiteralAssignment(target, sourceType, checkMode); - } - return checkReferenceAssignment(target, sourceType, checkMode); - } - function checkReferenceAssignment(target, sourceType, checkMode) { - var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 ? - ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : - ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, undefined); - } - return sourceType; - } - function isSideEffectFree(node) { - node = ts.skipParentheses(node); - switch (node.kind) { - case 71: - case 9: - case 12: - case 183: - case 196: - case 13: - case 8: - case 101: - case 86: - case 95: - case 139: - case 186: - case 199: - case 187: - case 177: - case 178: - case 189: - case 203: - case 250: - case 249: - return true; - case 195: - return isSideEffectFree(node.whenTrue) && - isSideEffectFree(node.whenFalse); - case 194: - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return false; - } - return isSideEffectFree(node.left) && - isSideEffectFree(node.right); - case 192: - case 193: - switch (node.operator) { - case 51: - case 37: - case 38: - case 52: - return true; - } - return false; - case 190: - case 184: - case 202: - default: - return false; - } - } - function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); - } - function checkBinaryExpression(node, checkMode) { - return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); - } - function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { - var operator = operatorToken.kind; - if (operator === 58 && (left.kind === 178 || left.kind === 177)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); - } - var leftType = checkExpression(left, checkMode); - var rightType = checkExpression(right, checkMode); - switch (operator) { - case 39: - case 40: - case 61: - case 62: - case 41: - case 63: - case 42: - case 64: - case 38: - case 60: - case 45: - case 65: - case 46: - case 66: - case 47: - case 67: - case 49: - case 69: - case 50: - case 70: - case 48: - case 68: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - var suggestedOperator = void 0; - if ((leftType.flags & 136) && - (rightType.flags & 136) && - (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { - error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); - } - else { - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); - } - } - return numberType; - case 37: - case 59: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - } - var resultType = void 0; - if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { - resultType = numberType; - } - else { - if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } - } - if (!resultType) { - reportOperatorError(); - return anyType; - } - if (operator === 59) { - checkAssignmentOperator(resultType); - } - return resultType; - case 27: - case 29: - case 30: - case 31: - if (checkForDisallowedESSymbolOperand(operator)) { - leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); - rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { - reportOperatorError(); - } - } - return booleanType; - case 32: - case 33: - case 34: - case 35: - var leftIsLiteral = isLiteralType(leftType); - var rightIsLiteral = isLiteralType(rightType); - if (!leftIsLiteral || !rightIsLiteral) { - leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; - rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; - } - if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { - reportOperatorError(); - } - return booleanType; - case 93: - return checkInstanceOfExpression(left, right, leftType, rightType); - case 92: - return checkInExpression(left, right, leftType, rightType); - case 53: - return getTypeFacts(leftType) & 1048576 ? - getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : - leftType; - case 54: - return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; - case 58: - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); - case 26: - if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { - error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); - } - return rightType; - } - function isEvalNode(node) { - return node.kind === 71 && node.text === "eval"; - } - function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : - undefined; - if (offendingSymbolOperand) { - error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); - return false; - } - return true; - } - function getSuggestedBooleanOperator(operator) { - switch (operator) { - case 49: - case 69: - return 54; - case 50: - case 70: - return 35; - case 48: - case 68: - return 53; - default: - return undefined; - } - } - function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 58 && operator <= 70) { - if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { - checkTypeAssignableTo(valueType, leftType, left, undefined); - } - } - } - function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); - } - } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } - function checkYieldExpression(node) { - if (produceDiagnostics) { - if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - if (node.expression) { - var func = ts.getContainingFunction(node); - var functionFlags = func && ts.getFunctionFlags(func); - if (node.asteriskToken) { - if ((functionFlags & 3) === 3 && - languageVersion < 5) { - checkExternalEmitHelpers(node, 26624); - } - if ((functionFlags & 3) === 1 && - languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256); - } - } - if (functionFlags & 1) { - var expressionType = checkExpressionCached(node.expression, undefined); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); - } - if (func.type) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(func.type), (functionFlags & 2) !== 0) || anyType; - if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 - ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionElementType, signatureElementType, node.expression, undefined); - } - else { - checkTypeAssignableTo(functionFlags & 2 - ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionType, signatureElementType, node.expression, undefined); - } - } - } - } - return anyType; - } - function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); - var type1 = checkExpression(node.whenTrue, checkMode); - var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); - } - function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8: - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: - return trueType; - case 86: - return falseType; - } - } - function checkTemplateExpression(node) { - ts.forEach(node.templateSpans, function (templateSpan) { - checkExpression(templateSpan.expression); - }); - return stringType; - } - function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; - var checkMode = contextualMapper === identityMapper ? 1 : - contextualMapper ? 2 : 0; - var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; - return result; - } - function checkExpressionCached(node, checkMode) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var saveFlowLoopStart = flowLoopStart; - flowLoopStart = flowLoopCount; - links.resolvedType = checkExpression(node, checkMode); - flowLoopStart = saveFlowLoopStart; - } - return links.resolvedType; - } - function isTypeAssertion(node) { - node = ts.skipParentheses(node); - return node.kind === 184 || node.kind === 202; - } - function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, true); - return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); - } - function isLiteralContextualType(contextualType) { - if (contextualType) { - if (contextualType.flags & 540672) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - if (constraint.flags & (2 | 4 | 8 | 16)) { - return true; - } - contextualType = constraint; - } - return maybeTypeOfKind(contextualType, (224 | 262144)); - } - return false; - } - function checkExpressionForMutableLocation(node, checkMode) { - var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); - } - function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - return checkExpressionForMutableLocation(node.initializer, checkMode); - } - function checkObjectLiteralMethod(node, checkMode) { - checkGrammarMethod(node); - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { - if (checkMode === 2) { - var signature = getSingleCallSignature(type); - if (signature && signature.typeParameters) { - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType) { - var contextualSignature = getSingleCallSignature(contextualType); - if (contextualSignature && !contextualSignature.typeParameters) { - return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); - } - } - } - } - return type; - } - function getTypeOfExpression(node, cache) { - if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { - var funcType = checkNonNullExpression(node.expression); - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return getReturnTypeOfSignature(signature); - } - } - return cache ? checkExpressionCached(node) : checkExpression(node); - } - function getContextFreeTypeOfExpression(node) { - var saveContextualType = node.contextualType; - node.contextualType = anyType; - var type = getTypeOfExpression(node); - node.contextualType = saveContextualType; - return type; - } - function checkExpression(node, checkMode) { - var type; - if (node.kind === 143) { - type = checkQualifiedName(node); - } - else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); - type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 179 && node.parent.expression === node) || - (node.parent.kind === 180 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); - if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); - } - } - return type; - } - function checkExpressionWorker(node, checkMode) { - switch (node.kind) { - case 71: - return checkIdentifier(node); - case 99: - return checkThisExpression(node); - case 97: - return checkSuperExpression(node); - case 95: - return nullWideningType; - case 9: - case 8: - case 101: - case 86: - return checkLiteralExpression(node); - case 196: - return checkTemplateExpression(node); - case 13: - return stringType; - case 12: - return globalRegExpType; - case 177: - return checkArrayLiteral(node, checkMode); - case 178: - return checkObjectLiteral(node, checkMode); - case 179: - return checkPropertyAccessExpression(node); - case 180: - return checkIndexedAccess(node); - case 181: - case 182: - return checkCallExpression(node); - case 183: - return checkTaggedTemplateExpression(node); - case 185: - return checkExpression(node.expression, checkMode); - case 199: - return checkClassExpression(node); - case 186: - case 187: - return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189: - return checkTypeOfExpression(node); - case 184: - case 202: - return checkAssertion(node); - case 203: - return checkNonNullAssertion(node); - case 204: - return checkMetaProperty(node); - case 188: - return checkDeleteExpression(node); - case 190: - return checkVoidExpression(node); - case 191: - return checkAwaitExpression(node); - case 192: - return checkPrefixUnaryExpression(node); - case 193: - return checkPostfixUnaryExpression(node); - case 194: - return checkBinaryExpression(node, checkMode); - case 195: - return checkConditionalExpression(node, checkMode); - case 198: - return checkSpreadExpression(node, checkMode); - case 200: - return undefinedWideningType; - case 197: - return checkYieldExpression(node); - case 256: - return checkJsxExpression(node, checkMode); - case 249: - return checkJsxElement(node); - case 250: - return checkJsxSelfClosingElement(node); - case 254: - return checkJsxAttributes(node, checkMode); - case 251: - ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); - } - return unknownType; - } - function checkTypeParameter(node) { - if (node.expression) { - grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); - } - checkSourceElement(node.constraint); - checkSourceElement(node.default); - var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); - } - var constraintType = getConstraintOfTypeParameter(typeParameter); - var defaultType = getDefaultFromTypeParameter(typeParameter); - if (constraintType && defaultType) { - checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); - } - } - function checkParameter(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkVariableLikeDeclaration(node); - var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { - error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); - } - } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { - error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); - } - if (node.name.text === "this") { - if (ts.indexOf(func.parameters, node) !== 0) { - error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); - } - if (func.kind === 152 || func.kind === 156 || func.kind === 161) { - error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); - } - } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { - error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); - } - } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 && - param.name.text === parameter.text) { - return i; - } - } - } - return -1; - } - function checkTypePredicate(node) { - var parent = getTypePredicateParent(node); - if (!parent) { - error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - return; - } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; - if (!typePredicate) { - return; - } - var parameterName = node.parameterName; - if (ts.isThisTypePredicate(typePredicate)) { - getTypeFromThisTypeNode(parameterName); - } - else { - if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { - error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); - } - else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); - } - } - else if (parameterName) { - var hasReportedError = false; - for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name = _a[_i].name; - if (ts.isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { - hasReportedError = true; - break; - } - } - if (!hasReportedError) { - error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); - } - } - } - } - function getTypePredicateParent(node) { - switch (node.parent.kind) { - case 187: - case 155: - case 228: - case 186: - case 160: - case 151: - case 150: - var parent = node.parent; - if (node === parent.type) { - return parent; - } - } - } - function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (ts.isOmittedExpression(element)) { - continue; - } - var name = element.name; - if (name.kind === 71 && - name.text === predicateVariableName) { - error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); - return true; - } - else if (name.kind === 175 || - name.kind === 174) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { - return true; - } - } - } - } - function checkSignatureDeclaration(node) { - if (node.kind === 157) { - checkGrammarIndexSignature(node); - } - else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || - node.kind === 155 || node.kind === 152 || - node.kind === 156) { - checkGrammarFunctionLikeDeclaration(node); - } - var functionFlags = ts.getFunctionFlags(node); - if (!(functionFlags & 4)) { - if ((functionFlags & 3) === 3 && languageVersion < 5) { - checkExternalEmitHelpers(node, 6144); - } - if ((functionFlags & 3) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - } - if ((functionFlags & 3) !== 0 && languageVersion < 2) { - checkExternalEmitHelpers(node, 128); - } - } - checkTypeParameters(node.typeParameters); - ts.forEach(node.parameters, checkParameter); - if (node.type) { - checkSourceElement(node.type); - } - if (produceDiagnostics) { - checkCollisionWithArgumentsInGeneratedCode(node); - if (noImplicitAny && !node.type) { - switch (node.kind) { - case 156: - error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - case 155: - error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - } - } - if (node.type) { - var functionFlags_1 = ts.getFunctionFlags(node); - 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); - } - else { - var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; - var iterableIteratorInstantiation = functionFlags_1 & 2 - ? createAsyncIterableIteratorType(generatorElementType) - : createIterableIteratorType(generatorElementType); - checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); - } - } - else if ((functionFlags_1 & 3) === 2) { - checkAsyncFunctionReturnType(node); - } - } - if (noUnusedIdentifiers && !node.body) { - checkUnusedTypeParameters(node); - } - } - } - 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++) { - var member = _a[_i]; - if (member.kind === 152) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var param = _c[_b]; - if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3); - } - } - } - else { - var isStatic = ts.getModifierFlags(member) & 32; - var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { - switch (member.kind) { - case 153: - addName(names, member.name, memberName, 1); - break; - case 154: - addName(names, member.name, memberName, 2); - break; - case 149: - addName(names, member.name, memberName, 3); - break; - case 151: - addName(names, member.name, memberName, 4); - break; - } - } - } - } - function addName(names, location, name, meaning) { - var prev = names.get(name); - if (prev) { - if (prev & 4) { - if (meaning !== 4) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - else { - names.set(name, prev | meaning); - } - } - else { - names.set(name, meaning); - } - } - } - function checkClassForStaticPropertyNameConflicts(node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32; - if (isStatic && memberNameNode) { - var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); - switch (memberName) { - case "name": - case "length": - case "caller": - case "arguments": - case "prototype": - var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); - error(memberNameNode, message, memberName, className); - break; - } - } - } - } - function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148) { - var memberName = void 0; - switch (member.name.kind) { - case 9: - case 8: - case 71: - memberName = member.name.text; - break; - default: - continue; - } - if (names.get(memberName)) { - error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); - error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); - } - else { - names.set(memberName, true); - } - } - } - } - function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230) { - var nodeSymbol = getSymbolOfNode(node); - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { - return; - } - } - var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { - var seenNumericIndexer = false; - var seenStringIndexer = false; - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var declaration = decl; - if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type.kind) { - case 136: - if (!seenStringIndexer) { - seenStringIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_string_index_signature); - } - break; - case 133: - if (!seenNumericIndexer) { - seenNumericIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_number_index_signature); - } - break; - } - } - } - } - } - function checkPropertyDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); - checkVariableLikeDeclaration(node); - } - function checkMethodDeclaration(node) { - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - checkFunctionOrMethodDeclaration(node); - if (ts.getModifierFlags(node) & 128 && node.body) { - error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); - } - } - function checkConstructorDeclaration(node) { - checkSignatureDeclaration(node); - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - var symbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(symbol); - } - if (ts.nodeIsMissing(node.body)) { - return; - } - if (!produceDiagnostics) { - return; - } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } - function markThisReferencesAsErrors(n) { - if (n.kind === 99) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 && n.kind !== 228) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } - function isInstancePropertyWithInitializer(n) { - return n.kind === 149 && - !(ts.getModifierFlags(n) & 32) && - !!n.initializer; - } - var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - captureLexicalThis(node.parent, containingClassDecl); - var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); - var superCall = getSuperCallInConstructor(node); - if (superCall) { - if (classExtendsNull) { - error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); - } - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); - if (superCallShouldBeFirst) { - var statements = node.body.statements; - var superCallStatement = void 0; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { - superCallStatement = statement; - break; - } - if (!ts.isPrologueDirective(statement)) { - break; - } - } - if (!superCallStatement) { - error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); - } - } - } - else if (!classExtendsNull) { - error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); - } - } - } - function checkAccessorDeclaration(node) { - if (produceDiagnostics) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - checkDecorators(node); - checkSignatureDeclaration(node); - if (node.kind === 153) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { - if (!(node.flags & 256)) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); - } - } - } - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 153 ? 154 : 153; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); - if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); - } - if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); - } - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); - } - } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } - } - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } - } - function checkMissingDeclaration(node) { - checkDecorators(node); - } - function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var typeArguments; - var mapper; - var result = true; - for (var i = 0; i < typeParameters.length; i++) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); - mapper = createTypeMapper(typeParameters, typeArguments); - } - var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - } - return result; - } - function checkTypeReferenceNode(node) { - checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReference(node); - if (type !== unknownType) { - if (node.typeArguments) { - ts.forEach(node.typeArguments, checkSourceElement); - if (produceDiagnostics) { - var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; - checkTypeArgumentConstraints(typeParameters, node.typeArguments); - } - } - 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)); - } - } - } - function checkTypeQuery(node) { - getTypeFromTypeQueryNode(node); - } - function checkTypeLiteral(node) { - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - checkObjectTypeForDuplicateDeclarations(node); - } - } - function checkArrayType(node) { - checkSourceElement(node.elementType); - } - function checkTupleType(node) { - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); - } - ts.forEach(node.elementTypes, checkSourceElement); - } - function checkUnionOrIntersectionType(node) { - ts.forEach(node.types, checkSourceElement); - } - function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288)) { - return type; - } - var objectType = type.objectType; - var indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - return type; - } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1)) { - return type; - } - } - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); - return type; - } - function checkIndexedAccessType(node) { - checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); - } - function checkMappedType(node) { - checkSourceElement(node.typeParameter); - checkSourceElement(node.type); - var type = getTypeFromMappedTypeNode(node); - var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); - } - function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); - } - function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 230 && - n.parent.kind !== 229 && - n.parent.kind !== 199 && - ts.isInAmbientContext(n)) { - if (!(flags & 2)) { - flags |= 1; - } - flags |= 2; - } - return flags & flagsToCheck; - } - function checkFunctionOrConstructorSymbol(symbol) { - if (!produceDiagnostics) { - return; - } - function getCanonicalOverload(overloads, implementation) { - var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; - return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; - } - function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { - var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; - if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); - ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; - if (deviation & 1) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - } - else if (deviation & 2) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - } - else if (deviation & (8 | 16)) { - error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - } - else if (deviation & 128) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); - } - }); - } - } - function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { - if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); - ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; - if (deviation) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); - } - }); - } - } - var flagsToCheck = 1 | 2 | 8 | 16 | 128; - var someNodeFlags = 0; - var allNodeFlags = flagsToCheck; - var someHaveQuestionToken = false; - var allHaveQuestionToken = true; - var hasOverloads = false; - var bodyDeclaration; - var lastSeenNonAmbientDeclaration; - var previousDeclaration; - var declarations = symbol.declarations; - var isConstructor = (symbol.flags & 16384) !== 0; - function reportImplementationExpectedError(node) { - if (node.name && ts.nodeIsMissing(node.name)) { - return; - } - var seen = false; - var subsequentNode = ts.forEachChild(node.parent, function (c) { - if (seen) { - return c; - } - else { - seen = c === node; - } - }); - if (subsequentNode && subsequentNode.pos === node.end) { - if (subsequentNode.kind === node.kind) { - var errorNode_1 = subsequentNode.name || subsequentNode; - if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 151 || node.kind === 150) && - (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); - if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); - } - return; - } - else if (ts.nodeIsPresent(subsequentNode.body)) { - error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); - return; - } - } - } - var errorNode = node.name || node; - if (isConstructor) { - error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); - } - else { - if (ts.getModifierFlags(node) & 128) { - error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); - } - else { - error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); - } - } - } - var duplicateFunctionDeclaration = false; - var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; - var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; - if (inAmbientContextOrInterface) { - previousDeclaration = undefined; - } - if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - if (ts.nodeIsPresent(node.body) && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; - } - else { - duplicateFunctionDeclaration = true; - } - } - else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (ts.nodeIsPresent(node.body)) { - if (!bodyDeclaration) { - bodyDeclaration = node; - } - } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } - } - } - if (multipleConstructorImplementation) { - ts.forEach(declarations, function (declaration) { - error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); - }); - } - if (duplicateFunctionDeclaration) { - ts.forEach(declarations, function (declaration) { - error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); - }); - } - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { - reportImplementationExpectedError(lastSeenNonAmbientDeclaration); - } - if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); - if (bodyDeclaration) { - var signatures = getSignaturesOfSymbol(symbol); - var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - 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; - } - } - } - } - } - function checkExportsOnMergedDeclarations(node) { - if (!produceDiagnostics) { - return; - } - var symbol = node.localSymbol; - if (!symbol) { - symbol = getSymbolOfNode(node); - if (!(symbol.flags & 7340032)) { - return; - } - } - if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { - return; - } - var exportedDeclarationSpaces = 0; - var nonExportedDeclarationSpaces = 0; - var defaultExportedDeclarationSpaces = 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var d = _a[_i]; - var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); - if (effectiveDeclarationFlags & 1) { - if (effectiveDeclarationFlags & 512) { - defaultExportedDeclarationSpaces |= declarationSpaces; - } - else { - exportedDeclarationSpaces |= declarationSpaces; - } - } - else { - nonExportedDeclarationSpaces |= declarationSpaces; - } - } - var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; - var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; - var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; - if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { - 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); - } - } - } - function getDeclarationSpaces(d) { - switch (d.kind) { - case 230: - return 2097152; - case 233: - return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 - ? 4194304 | 1048576 - : 4194304; - case 229: - case 232: - return 2097152 | 1048576; - case 237: - var result_3 = 0; - var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - default: - return 1048576; - } - } - } - function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { - var promisedType = getPromisedTypeOfPromise(type, errorNode); - return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); - } - function getPromisedTypeOfPromise(promise, errorNode) { - if (isTypeAny(promise)) { - return undefined; - } - var typeAsPromise = promise; - if (typeAsPromise.promisedTypeOfPromise) { - return typeAsPromise.promisedTypeOfPromise; - } - if (isReferenceToType(promise, getGlobalPromiseType(false))) { - return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; - } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (isTypeAny(thenFunction)) { - return undefined; - } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; - if (thenSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); - } - return undefined; - } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); - if (isTypeAny(onfulfilledParameterType)) { - return undefined; - } - var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); - if (onfulfilledParameterSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); - } - return undefined; - } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); - } - function checkAwaitedType(type, errorNode, diagnosticMessage) { - return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; - } - function getAwaitedType(type, errorNode, diagnosticMessage) { - var typeAsAwaitable = type; - if (typeAsAwaitable.awaitedTypeOfType) { - return typeAsAwaitable.awaitedTypeOfType; - } - if (isTypeAny(type)) { - return typeAsAwaitable.awaitedTypeOfType = type; - } - if (type.flags & 65536) { - var types = void 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituentType = _a[_i]; - types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); - } - if (!types) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); - } - var promisedType = getPromisedTypeOfPromise(type); - if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); - } - return undefined; - } - awaitedTypeStack.push(type.id); - var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); - awaitedTypeStack.pop(); - if (!awaitedType) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = awaitedType; - } - var thenFunction = getTypeOfPropertyOfType(type, "then"); - if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { - if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); - error(errorNode, diagnosticMessage); - } - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = type; - } - function checkAsyncFunctionReturnType(node) { - var returnType = getTypeFromTypeNode(node.type); - if (languageVersion >= 2) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(true); - if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { - error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return unknownType; - } - } - else { - markTypeNodeAsReferenced(node.type); - if (returnType === unknownType) { - return unknownType; - } - var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); - if (promiseConstructorName === undefined) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return unknownType; - } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); - var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; - if (promiseConstructorType === unknownType) { - if (promiseConstructorName.kind === 71 && promiseConstructorName.text === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { - error(node.type, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - else { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - } - return unknownType; - } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); - if (globalPromiseConstructorLikeType === emptyObjectType) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return unknownType; - } - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.text, 107455); - if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - } - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkDecorator(node) { - var signature = getResolvedSignature(node); - var returnType = getReturnTypeOfSignature(signature); - if (returnType.flags & 1) { - return; - } - var expectedReturnType; - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - var errorInfo; - switch (node.parent.kind) { - case 229: - var classSymbol = getSymbolOfNode(node.parent); - var classConstructorType = getTypeOfSymbol(classSymbol); - expectedReturnType = getUnionType([classConstructorType, voidType]); - break; - case 146: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); - break; - case 149: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); - break; - case 151: - case 153: - case 154: - var methodType = getTypeOfNode(node.parent); - var descriptorType = createTypedPropertyDescriptorType(methodType); - expectedReturnType = getUnionType([descriptorType, voidType]); - break; - } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); - } - function markTypeNodeAsReferenced(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 - && rootSymbol.flags & 8388608 - && symbolIsValue(rootSymbol) - && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - 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; - } - function checkDecorators(node) { - if (!node.decorators) { - return; - } - if (!ts.nodeCanBeDecorated(node)) { - return; - } - if (!compilerOptions.experimentalDecorators) { - error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); - } - var firstDecorator = node.decorators[0]; - checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 146) { - checkExternalEmitHelpers(firstDecorator, 32); - } - if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16); - switch (node.kind) { - case 229: - var constructor = ts.getFirstConstructorWithBody(node); - if (constructor) { - for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - } - break; - case 151: - case 153: - case 154: - for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - case 149: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); - break; - case 146: - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - } - } - ts.forEach(node.decorators, checkDecorator); - } - function checkFunctionDeclaration(node) { - if (produceDiagnostics) { - checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function checkFunctionOrMethodDeclaration(node) { - checkDecorators(node); - checkSignatureDeclaration(node); - var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - var symbol = getSymbolOfNode(node); - var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.forEach(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? - declaration : undefined; }); - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(localSymbol); - } - if (symbol.parent) { - if (ts.getDeclarationOfKind(symbol, node.kind) === node) { - checkFunctionOrConstructorSymbol(symbol); - } - } - } - checkSourceElement(node.body); - if ((functionFlags & 1) === 0) { - var returnOrPromisedType = node.type && (functionFlags & 2 - ? checkAsyncFunctionReturnType(node) - : getTypeFromTypeNode(node.type)); - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (produceDiagnostics && !node.type) { - if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); - } - if (functionFlags & 1 && ts.nodeIsPresent(node.body)) { - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - } - registerForUnusedIdentifiersCheck(node); - } - function registerForUnusedIdentifiersCheck(node) { - if (deferredUnusedIdentifierNodes) { - deferredUnusedIdentifierNodes.push(node); - } - } - function checkUnusedIdentifiers() { - if (deferredUnusedIdentifierNodes) { - for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { - var node = deferredUnusedIdentifierNodes_1[_i]; - switch (node.kind) { - case 265: - case 233: - checkUnusedModuleMembers(node); - break; - case 229: - case 199: - checkUnusedClassMembers(node); - checkUnusedTypeParameters(node); - break; - case 230: - checkUnusedTypeParameters(node); - break; - case 207: - case 235: - case 214: - case 215: - case 216: - checkUnusedLocalsAndParameters(node); - break; - case 152: - case 186: - case 228: - case 187: - case 151: - case 153: - case 154: - if (node.body) { - checkUnusedLocalsAndParameters(node); - } - checkUnusedTypeParameters(node); - break; - case 150: - case 155: - case 156: - case 157: - case 160: - case 161: - checkUnusedTypeParameters(node); - break; - } - } - } - } - function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - 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(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(ts.getNameOfDeclaration(d) || d, local.name); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } - function errorUnusedLocal(node, name) { - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 && - (declaration.parent.parent.kind === 215 || - declaration.parent.parent.kind === 216)) { - return; - } - } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); - } - } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && node.text.charCodeAt(0) === 95; - } - function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 151 || member.kind === 149) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); - } - } - else if (member.kind === 152) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); - } - } - } - } - } - } - } - function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.typeParameters) { - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } - for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { - var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); - } - } - } - } - } - function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); - } - } - } - }); - } - } - function checkBlock(node) { - if (node.kind === 207) { - checkGrammarStatementInAmbientContext(node); - } - ts.forEach(node.statements, checkSourceElement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { - return; - } - ts.forEach(node.parameters, function (p) { - if (p.name && !ts.isBindingPattern(p.name) && p.name.text === argumentsSymbol.name) { - error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); - } - }); - } - function needCollisionCheckForIdentifier(node, identifier, name) { - if (!(identifier && identifier.text === name)) { - return false; - } - if (node.kind === 149 || - node.kind === 148 || - node.kind === 151 || - node.kind === 150 || - node.kind === 153 || - node.kind === 154) { - return false; - } - if (ts.isInAmbientContext(node)) { - return false; - } - var root = ts.getRootDeclaration(node); - if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { - return false; - } - return true; - } - function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { - potentialThisCollisions.push(node); - } - } - function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { - potentialNewTargetCollisions.push(node); - } - } - function checkIfThisIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 71; - if (isDeclaration_1) { - 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); - } - return true; - } - }); - } - function checkIfNewTargetIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 8) { - var isDeclaration_2 = node.kind !== 71; - if (isDeclaration_2) { - 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); - } - return true; - } - }); - } - function checkCollisionWithCapturedSuperVariable(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "_super")) { - return; - } - var enclosingClass = ts.getContainingClass(node); - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { - return; - } - if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71; - if (isDeclaration_3) { - error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); - } - else { - error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); - } - } - } - function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - if (modulekind >= ts.ModuleKind.ES2015) { - return; - } - if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { - return; - } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { - return; - } - var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { - return; - } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { - return; - } - var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { - return; - } - if (node.kind === 226 && !node.initializer) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol.flags & 1) { - var localDeclarationSymbol = resolveName(node, node.name.text, 3, undefined, undefined); - if (localDeclarationSymbol && - localDeclarationSymbol !== symbol && - localDeclarationSymbol.flags & 2) { - if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); - var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent - ? varDeclList.parent.parent - : undefined; - var namesShareScope = container && - (container.kind === 207 && ts.isFunctionLike(container.parent) || - container.kind === 234 || - container.kind === 233 || - container.kind === 265); - if (!namesShareScope) { - var name = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); - } - } - } - } - } - function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146) { - return; - } - var func = ts.getContainingFunction(node); - visit(node.initializer); - function visit(n) { - if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { - return; - } - if (n.kind === 179) { - return visit(n.expression); - } - else if (n.kind === 71) { - var symbol = resolveName(n, n.text, 107455 | 8388608, undefined, undefined); - if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { - return; - } - if (symbol.valueDeclaration === node) { - error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); - return; - } - var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 || - symbol.valueDeclaration.kind === 176) { - if (symbol.valueDeclaration.pos < node.pos) { - return; - } - if (ts.findAncestor(n, function (current) { - if (current === node.initializer) { - return "quit"; - } - return ts.isFunctionLike(current.parent) || - (current.parent.kind === 149 && - !(ts.hasModifier(current.parent, 32)) && - ts.isClassLike(current.parent.parent)); - })) { - return; - } - } - error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); - } - } - else { - return ts.forEachChild(n, visit); - } - } - } - function convertAutoToAny(type) { - return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; - } - function checkVariableLikeDeclaration(node) { - checkDecorators(node); - checkSourceElement(node.type); - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - if (node.initializer) { - checkExpressionCached(node.initializer); - } - } - if (node.kind === 176) { - if (node.parent.kind === 174 && languageVersion < 5) { - checkExternalEmitHelpers(node, 4); - } - if (node.propertyName && node.propertyName.kind === 144) { - checkComputedPropertyName(node.propertyName); - } - var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); - var name = node.propertyName || node.name; - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); - } - } - if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); - } - ts.forEach(node.name.elements, checkSourceElement); - } - if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { - error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); - return; - } - if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); - checkParameterInitializer(node); - } - return; - } - var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); - if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); - checkParameterInitializer(node); - } - } - else { - var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.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(node.name), typeToString(type), typeToString(declarationType)); - } - if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); - } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - 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)); - } - } - if (node.kind !== 149 && node.kind !== 148) { - checkExportsOnMergedDeclarations(node); - if (node.kind === 226 || node.kind === 176) { - checkVarDeclaredNamesNotShadowed(node); - } - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 && right.kind === 226) || - (left.kind === 226 && right.kind === 146)) { - return true; - } - if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { - return false; - } - var interestingFlags = 8 | - 16 | - 256 | - 128 | - 64 | - 32; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); - } - function checkVariableDeclaration(node) { - checkGrammarVariableDeclaration(node); - return checkVariableLikeDeclaration(node); - } - function checkBindingElement(node) { - checkGrammarBindingElement(node); - return checkVariableLikeDeclaration(node); - } - function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); - ts.forEach(node.declarationList.declarations, checkSourceElement); - } - function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 178) { - if (ts.getFunctionFlags(node) & 2) { - if (node.modifiers.length > 1) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - } - function checkExpressionStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - } - function checkIfStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209) { - error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); - } - checkSourceElement(node.elseStatement); - } - function checkDoStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkSourceElement(node.statement); - checkExpression(node.expression); - } - function checkWhileStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.statement); - } - function checkForStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227) { - checkGrammarVariableDeclarationList(node.initializer); - } - } - if (node.initializer) { - if (node.initializer.kind === 227) { - ts.forEach(node.initializer.declarations, checkVariableDeclaration); - } - else { - checkExpression(node.initializer); - } - } - if (node.condition) - checkExpression(node.condition); - if (node.incrementor) - checkExpression(node.incrementor); - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForOfStatement(node) { - checkGrammarForInOrForOfStatement(node); - if (node.kind === 216) { - if (node.awaitModifier) { - var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { - checkExternalEmitHelpers(node, 16384); - } - } - else if (compilerOptions.downlevelIteration && languageVersion < 2) { - checkExternalEmitHelpers(node, 256); - } - } - if (node.initializer.kind === 227) { - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - if (varExpr.kind === 177 || varExpr.kind === 178) { - checkDestructuringAssignment(varExpr, iteratedType || unknownType); - } - else { - var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); - if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); - } - } - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInStatement(node) { - checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); - if (node.initializer.kind === 227) { - var variable = node.initializer.declarations[0]; - if (variable && ts.isBindingPattern(variable.name)) { - error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 || varExpr.kind === 178) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); - } - else { - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); - } - } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { - error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInOrForOfVariableDeclaration(iterationStatement) { - var variableDeclarationList = iterationStatement.initializer; - if (variableDeclarationList.declarations.length >= 1) { - var decl = variableDeclarationList.declarations[0]; - checkVariableDeclaration(decl); - } - } - function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { - var expressionType = checkNonNullExpression(rhsExpression); - return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); - } - function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable) { - if (isTypeAny(inputType)) { - return inputType; - } - return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, true) || anyType; - } - function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, checkAssignability) { - var uplevelIteration = languageVersion >= 2; - var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; - if (uplevelIteration || downlevelIteration || allowAsyncIterable) { - var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterable, allowAsyncIterable, checkAssignability); - if (iteratedType || uplevelIteration) { - return iteratedType; - } - } - var arrayType = inputType; - var reportedError = false; - var hasStringConstituent = false; - if (allowStringInput) { - if (arrayType.flags & 65536) { - var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); - if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, true); - } - } - else if (arrayType.flags & 262178) { - arrayType = neverType; - } - hasStringConstituent = arrayType !== inputType; - if (hasStringConstituent) { - if (languageVersion < 1) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); - reportedError = true; - } - } - if (arrayType.flags & 8192) { - return stringType; - } - } - } - if (!isArrayLikeType(arrayType)) { - if (errorNode && !reportedError) { - var diagnostic = !allowStringInput || hasStringConstituent - ? downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type - : downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; - error(errorNode, diagnostic, typeToString(arrayType)); - } - return hasStringConstituent ? stringType : undefined; - } - var arrayElementType = getIndexTypeOfType(arrayType, 1); - if (hasStringConstituent && arrayElementType) { - if (arrayElementType.flags & 262178) { - return stringType; - } - return getUnionType([arrayElementType, stringType], true); - } - return arrayElementType; - } - function getIteratedTypeOfIterable(type, errorNode, isAsyncIterable, allowNonAsyncIterables, checkAssignability) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterable = type; - if (isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable) { - return isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable; - } - if (isAsyncIterable) { - if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || - isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { - return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; - } - } - if (!isAsyncIterable || allowNonAsyncIterables) { - if (isReferenceToType(type, getGlobalIterableType(false)) || - isReferenceToType(type, getGlobalIterableIteratorType(false))) { - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0] - : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; - } - } - var iteratorMethodSignatures; - var isNonAsyncIterable = false; - if (isAsyncIterable) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0); - } - if (!isAsyncIterable || (allowNonAsyncIterables && !ts.some(iteratorMethodSignatures))) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0); - isNonAsyncIterable = true; - } - if (ts.some(iteratorMethodSignatures)) { - var iteratorMethodReturnType = getUnionType(ts.map(iteratorMethodSignatures, getReturnTypeOfSignature), true); - var iteratedType = getIteratedTypeOfIterator(iteratorMethodReturnType, errorNode, !isNonAsyncIterable); - if (checkAssignability && errorNode && iteratedType) { - checkTypeAssignableTo(type, isNonAsyncIterable - ? createIterableType(iteratedType) - : createAsyncIterableType(iteratedType), errorNode); - } - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; - } - if (errorNode) { - error(errorNode, isAsyncIterable - ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); - } - return undefined; - } - function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterator = type; - if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { - return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; - } - var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; - if (isReferenceToType(type, getIteratorType(false))) { - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] - : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; - } - var nextMethod = getTypeOfPropertyOfType(type, "next"); - if (isTypeAny(nextMethod)) { - return undefined; - } - var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : emptyArray; - if (nextMethodSignatures.length === 0) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.An_async_iterator_must_have_a_next_method - : ts.Diagnostics.An_iterator_must_have_a_next_method); - } - return undefined; - } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); - if (isTypeAny(nextResult)) { - return undefined; - } - if (isAsyncIterator) { - nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); - if (isTypeAny(nextResult)) { - return undefined; - } - } - var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); - if (!nextValue) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property - : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue - : typeAsIterator.iteratedTypeOfIterator = nextValue; - } - function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { - if (isTypeAny(returnType)) { - return undefined; - } - return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, false, false) - || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); - } - function checkBreakOrContinueStatement(node) { - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); - } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 153 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154))); - } - function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 - ? getPromisedTypeOfPromise(returnType) - : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); - } - function checkReturnStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } - } - var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return; - } - if (func.kind === 154) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } - } - else if (func.kind === 152) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); - } - } - } - else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - } - function checkWithStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 16384) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); - } - } - checkExpression(node.expression); - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; - var end = node.statement.pos; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); - } - } - function checkSwitchStatement(node) { - checkGrammarStatementInAmbientContext(node); - var firstDefaultClause; - var hasDuplicateDefaultClause = false; - var expressionType = checkExpression(node.expression); - var expressionIsLiteral = isLiteralType(expressionType); - ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 258 && !hasDuplicateDefaultClause) { - if (firstDefaultClause === undefined) { - firstDefaultClause = clause; - } - else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); - hasDuplicateDefaultClause = true; - } - } - if (produceDiagnostics && clause.kind === 257) { - var caseClause = clause; - var caseType = checkExpression(caseClause.expression); - var caseIsLiteral = isLiteralType(caseType); - var comparedExpressionType = expressionType; - if (!caseIsLiteral || !expressionIsLiteral) { - caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; - comparedExpressionType = getBaseTypeOfLiteralType(expressionType); - } - if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { - checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); - } - } - ts.forEach(clause.statements, checkSourceElement); - }); - if (node.caseBlock.locals) { - registerForUnusedIdentifiersCheck(node.caseBlock); - } - } - function checkLabeledStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - ts.findAncestor(node.parent, function (current) { - if (ts.isFunctionLike(current)) { - return "quit"; - } - if (current.kind === 222 && current.label.text === node.label.text) { - var sourceFile = ts.getSourceFileOfNode(node); - grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); - return true; - } - }); - } - checkSourceElement(node.statement); - } - function checkThrowStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.expression === undefined) { - grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); - } - } - if (node.expression) { - checkExpression(node.expression); - } - } - function checkTryStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkBlock(node.tryBlock); - var catchClause = node.catchClause; - if (catchClause) { - if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.type) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); - } - else if (catchClause.variableDeclaration.initializer) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); - } - else { - var blockLocals_1 = catchClause.block.locals; - if (blockLocals_1) { - ts.forEachKey(catchClause.locals, function (caughtName) { - var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2) !== 0) { - grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); - } - }); - } - } - } - checkBlock(catchClause.block); - } - if (node.finallyBlock) { - checkBlock(node.finallyBlock); - } - } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); - var stringIndexType = getIndexTypeOfType(type, 0); - var numberIndexType = getIndexTypeOfType(type, 1); - if (stringIndexType || numberIndexType) { - ts.forEach(getPropertiesOfObjectType(type), function (prop) { - var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); - }); - if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); - } - } - } - } - var errorNode; - if (stringIndexType && numberIndexType) { - errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (getObjectFlags(type) & 2)) { - var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; - } - } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { - error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); - } - function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { - return; - } - var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { - return; - } - var errorNode; - if (propDeclaration && - (propDeclaration.kind === 194 || - ts.getNameOfDeclaration(propDeclaration).kind === 144 || - prop.parent === containingType.symbol)) { - errorNode = propDeclaration; - } - else if (indexDeclaration) { - errorNode = indexDeclaration; - } - else if (getObjectFlags(containingType) & 2) { - var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; - } - if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 - ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 - : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; - error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); - } - } - } - function checkTypeNameIsReserved(name, message) { - switch (name.text) { - case "any": - case "number": - case "boolean": - case "string": - case "symbol": - case "void": - case "object": - error(name, message, name.text); - } - } - function checkTypeParameters(typeParameterDeclarations) { - if (typeParameterDeclarations) { - var seenDefault = false; - for (var i = 0; i < typeParameterDeclarations.length; i++) { - var node = typeParameterDeclarations[i]; - checkTypeParameter(node); - if (produceDiagnostics) { - if (node.default) { - seenDefault = true; - } - else if (seenDefault) { - error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); - } - for (var j = 0; j < i; j++) { - if (typeParameterDeclarations[j].symbol === node.symbol) { - error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); - } - } - } - } - } - } - function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { - return; - } - var links = getSymbolLinks(symbol); - if (!links.typeParametersChecked) { - links.typeParametersChecked = true; - var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { - return; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { - var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); - } - } - } - } - function areTypeParametersIdentical(declarations, typeParameters) { - var maxTypeArgumentCount = ts.length(typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - var numTypeParameters = ts.length(declaration.typeParameters); - if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { - return false; - } - for (var i = 0; i < numTypeParameters; i++) { - var source = declaration.typeParameters[i]; - var target = typeParameters[i]; - if (source.name.text !== target.symbol.name) { - return false; - } - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; - } - var sourceDefault = source.default && getTypeFromTypeNode(source.default); - var targetDefault = getDefaultFromTypeParameter(target); - if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { - return false; - } - } - } - return true; - } - function checkClassExpression(node) { - checkClassLikeDeclaration(node); - checkNodeDeferred(node); - return getTypeOfSymbol(getSymbolOfNode(node)); - } - function checkClassExpressionDeferred(node) { - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); - } - checkClassLikeDeclaration(node); - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassLikeDeclaration(node) { - checkGrammarClassLikeDeclaration(node); - checkDecorators(node); - if (node.name) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkTypeParameters(node.typeParameters); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - var staticType = getTypeOfSymbol(symbol); - checkTypeParameterListsIdentical(symbol); - checkClassForDuplicateDeclarations(node); - if (!ts.isInAmbientContext(node)) { - checkClassForStaticPropertyNameConflicts(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - if (languageVersion < 2) { - checkExternalEmitHelpers(baseTypeNode.parent, 1); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length && produceDiagnostics) { - var baseType_1 = baseTypes[0]; - var baseConstructorType = getBaseConstructorTypeOfClass(type); - var staticBaseType = getApparentType(baseConstructorType); - checkBaseTypeAccessibility(staticBaseType, baseTypeNode); - checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { - ts.forEach(baseTypeNode.typeArguments, checkSourceElement); - for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { - var constructor = _a[_i]; - if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { - break; - } - } - } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { - error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); - } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { - var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); - } - } - checkKindsOfPropertyMemberOverrides(type, baseType_1); - } - } - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); - if (implementedTypeNodes) { - for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { - var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { - error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(typeRefNode); - if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); - if (t !== unknownType) { - if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); - } - else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); - } - } - } - } - } - if (produceDiagnostics) { - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - } - } - function checkBaseTypeAccessibility(type, node) { - var signatures = getSignaturesOfType(type, 1); - if (signatures.length) { - var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); - } - } - } - } - function getTargetSymbol(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; }); - } - function getClassOrInterfaceDeclarationsOfSymbol(symbol) { - return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 || d.kind === 230; - }); - } - function checkKindsOfPropertyMemberOverrides(type, baseType) { - var baseProperties = getPropertiesOfType(baseType); - for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; - var base = getTargetSymbol(baseProperty); - if (base.flags & 16777216) { - continue; - } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - 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) { - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { - if (derivedClassDecl.kind === 199) { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); - } - else { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); - } - } - } - else { - var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { - continue; - } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { - continue; - } - var errorMessage = void 0; - if (isMethodLike(base)) { - if (derived.flags & 98304) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; - } - } - else if (base.flags & 4) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; - } - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); - } - } - } - } - function isAccessor(kind) { - return kind === 153 || kind === 154; - } - function checkInheritedPropertiesAreIdentical(type, typeNode) { - var baseTypes = getBaseTypes(type); - if (baseTypes.length < 2) { - return true; - } - var seen = ts.createMap(); - ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.name, { prop: p, containingType: type }); }); - var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; - var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; - var existing = seen.get(prop.name); - if (!existing) { - seen.set(prop.name, { prop: prop, containingType: base }); - } - else { - var isInheritedProperty = existing.containingType !== type; - if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { - ok = false; - var typeName1 = typeToString(existing.containingType); - var typeName2 = typeToString(base); - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); - } - } - } - } - return ok; - } - function checkInterfaceDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); - checkTypeParameters(node.typeParameters); - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); - if (node === firstInterfaceDecl) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - if (checkInheritedPropertiesAreIdentical(type, node.name)) { - for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { - var baseType = _a[_i]; - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); - } - checkIndexConstraints(type); - } - } - checkObjectTypeForDuplicateDeclarations(node); - } - ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { - error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(heritageElement); - }); - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); - } - } - function checkTypeAliasDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); - checkTypeParameters(node.typeParameters); - checkSourceElement(node.type); - } - function computeEnumMemberValues(node) { - var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 16384)) { - nodeLinks.flags |= 16384; - var autoValue = 0; - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var value = computeMemberValue(member, autoValue); - getNodeLinks(member).enumMemberValue = value; - autoValue = typeof value === "number" ? value + 1 : undefined; - } - } - } - 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); - } - } - 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; - } - } - 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; - case 47: return left >>> right; - case 45: return left << right; - case 50: return left ^ right; - case 39: return left * right; - case 41: return left / right; - case 37: return left + right; - case 38: return left - right; - case 42: return left % right; - } - } - 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); - } - } - 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; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkExportsOnMergedDeclarations(node); - computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); - } - var enumSymbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); - if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { - ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); - } - }); - } - var seenEnumMissingInitialInitializer_1 = false; - ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 232) { - return false; - } - var enumDeclaration = declaration; - if (!enumDeclaration.members.length) { - return false; - } - var firstEnumMember = enumDeclaration.members[0]; - if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer_1) { - error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); - } - else { - seenEnumMissingInitialInitializer_1 = true; - } - } - }); - } - } - function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 229 || - (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { - return declaration; - } - } - return undefined; - } - function inSameLexicalScope(node1, node2) { - var container1 = ts.getEnclosingBlockScopeContainer(node1); - var container2 = ts.getEnclosingBlockScopeContainer(node2); - if (isGlobalSourceFile(container1)) { - return isGlobalSourceFile(container2); - } - else if (isGlobalSourceFile(container2)) { - return false; - } - else { - return container1 === container2; - } - } - function checkModuleDeclaration(node) { - if (produceDiagnostics) { - var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); - if (isGlobalAugmentation && !inAmbientContext) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); - } - var isAmbientExternalModule = ts.isAmbientModule(node); - var contextErrorMessage = isAmbientExternalModule - ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file - : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; - if (checkGrammarModuleElementContext(node, contextErrorMessage)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9) { - grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - } - if (ts.isIdentifier(node.name)) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - if (symbol.flags & 512 - && symbol.declarations.length > 1 - && !inAmbientContext - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { - var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); - if (firstNonAmbientClassOrFunc) { - if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); - } - else if (node.pos < firstNonAmbientClassOrFunc.pos) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); - } - } - var mergedClass = ts.getDeclarationOfKind(symbol, 229); - if (mergedClass && - inSameLexicalScope(node, mergedClass)) { - getNodeLinks(node).flags |= 32768; - } - } - if (isAmbientExternalModule) { - if (ts.isExternalModuleAugmentation(node)) { - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728); - if (checkBody && node.body) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - checkModuleAugmentationElement(statement, isGlobalAugmentation); - } - } - } - else if (isGlobalSourceFile(node.parent)) { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); - } - } - else { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else { - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); - } - } - } - } - if (node.body) { - checkSourceElement(node.body); - if (!ts.isGlobalScopeAugmentation(node)) { - registerForUnusedIdentifiersCheck(node); - } - } - } - function checkModuleAugmentationElement(node, isGlobalAugmentation) { - switch (node.kind) { - case 208: - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - checkModuleAugmentationElement(decl, isGlobalAugmentation); - } - break; - case 243: - case 244: - grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); - break; - case 237: - case 238: - grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); - break; - case 176: - case 226: - var name = node.name; - if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; - checkModuleAugmentationElement(el, isGlobalAugmentation); - } - break; - } - case 229: - case 232: - case 228: - case 230: - case 233: - case 231: - if (isGlobalAugmentation) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol) { - var reportError = !(symbol.flags & 134217728); - if (!reportError) { - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } - break; - } - } - function getFirstIdentifier(node) { - switch (node.kind) { - case 71: - return node; - case 143: - do { - node = node.left; - } while (node.kind !== 71); - return node; - case 179: - do { - node = node.expression; - } while (node.kind !== 71); - return node; - } - } - function checkExternalImportOrExportDeclaration(node) { - var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { - error(moduleName, ts.Diagnostics.String_literal_expected); - return false; - } - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 ? - ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : - ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); - return false; - } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - if (!isTopLevelInExternalModuleAugmentation(node)) { - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; - } - } - return true; - } - function checkAliasSymbol(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793064 ? 793064 : 0) | - (symbol.flags & 1920 ? 1920 : 0); - if (target.flags & excludedMeanings) { - var message = node.kind === 246 ? - ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : - 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) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkAliasSymbol(node); - } - function checkImportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); - } - if (checkExternalImportOrExportDeclaration(node)) { - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - checkImportBinding(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { - checkImportBinding(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, checkImportBinding); - } - } - } - } - } - function checkImportEqualsDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - return; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { - checkImportBinding(node); - if (ts.getModifierFlags(node) & 1) { - markExportAsReferenced(node); - } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveAlias(getSymbolOfNode(node)); - if (target !== unknownSymbol) { - if (target.flags & 107455) { - var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { - error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); - } - } - if (target.flags & 793064) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); - } - } - } - else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - grammarErrorOnNode(node, ts.Diagnostics.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); - } - } - } - } - function checkExportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); - } - if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { - error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); - } - } - else { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); - } - } - } - } - function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; - if (!isInAppropriateContext) { - grammarErrorOnFirstToken(node, errorMessage); - } - return !isInAppropriateContext; - } - function checkExportSpecifier(node) { - checkAliasSymbol(node); - if (!node.parent.parent.moduleSpecifier) { - var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); - } - else { - markExportAsReferenced(node); - } - } - } - function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { - return; - } - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { - if (node.isExportEquals) { - error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); - } - else { - error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); - } - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); - } - if (node.expression.kind === 71) { - markExportAsReferenced(node); - } - else { - checkExpressionCached(node.expression); - } - checkExternalModuleExports(container); - if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); - } - else if (modulekind === ts.ModuleKind.System) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); - } - } - } - function hasExportedMembers(moduleSymbol) { - return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); - } - function checkExternalModuleExports(node) { - var moduleSymbol = getSymbolOfNode(node); - var links = getSymbolLinks(moduleSymbol); - if (!links.exportsChecked) { - var exportEqualsSymbol = moduleSymbol.exports.get("export="); - if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { - var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration)) { - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); - } - } - var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - if (flags & (1920 | 64 | 384)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); - if (flags & 524288 && exportedDeclarationsCount <= 2) { - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); - } - } - } - }); - links.exportsChecked = true; - } - function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || - !!declaration.body; - } - } - function checkSourceElement(node) { - if (!node) { - return; - } - var kind = node.kind; - if (cancellationToken) { - switch (kind) { - case 233: - case 229: - case 230: - case 228: - cancellationToken.throwIfCancellationRequested(); - } - } - switch (kind) { - case 145: - return checkTypeParameter(node); - case 146: - return checkParameter(node); - case 149: - case 148: - return checkPropertyDeclaration(node); - case 160: - case 161: - case 155: - case 156: - return checkSignatureDeclaration(node); - case 157: - return checkSignatureDeclaration(node); - case 151: - case 150: - return checkMethodDeclaration(node); - case 152: - return checkConstructorDeclaration(node); - case 153: - case 154: - return checkAccessorDeclaration(node); - case 159: - return checkTypeReferenceNode(node); - case 158: - return checkTypePredicate(node); - case 162: - return checkTypeQuery(node); - case 163: - return checkTypeLiteral(node); - case 164: - return checkArrayType(node); - case 165: - return checkTupleType(node); - case 166: - case 167: - return checkUnionOrIntersectionType(node); - case 168: - case 170: - return checkSourceElement(node.type); - case 171: - return checkIndexedAccessType(node); - case 172: - return checkMappedType(node); - case 228: - return checkFunctionDeclaration(node); - case 207: - case 234: - return checkBlock(node); - case 208: - return checkVariableStatement(node); - case 210: - return checkExpressionStatement(node); - case 211: - return checkIfStatement(node); - case 212: - return checkDoStatement(node); - case 213: - return checkWhileStatement(node); - case 214: - return checkForStatement(node); - case 215: - return checkForInStatement(node); - case 216: - return checkForOfStatement(node); - case 217: - case 218: - return checkBreakOrContinueStatement(node); - case 219: - return checkReturnStatement(node); - case 220: - return checkWithStatement(node); - case 221: - return checkSwitchStatement(node); - case 222: - return checkLabeledStatement(node); - case 223: - return checkThrowStatement(node); - case 224: - return checkTryStatement(node); - case 226: - return checkVariableDeclaration(node); - case 176: - return checkBindingElement(node); - case 229: - return checkClassDeclaration(node); - case 230: - return checkInterfaceDeclaration(node); - case 231: - return checkTypeAliasDeclaration(node); - case 232: - return checkEnumDeclaration(node); - case 233: - return checkModuleDeclaration(node); - case 238: - return checkImportDeclaration(node); - case 237: - return checkImportEqualsDeclaration(node); - case 244: - return checkExportDeclaration(node); - case 243: - return checkExportAssignment(node); - case 209: - checkGrammarStatementInAmbientContext(node); - return; - case 225: - checkGrammarStatementInAmbientContext(node); - return; - case 247: - return checkMissingDeclaration(node); - } - } - function checkNodeDeferred(node) { - if (deferredNodes) { - deferredNodes.push(node); - } - } - function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; - switch (node.kind) { - case 186: - case 187: - case 151: - case 150: - checkFunctionExpressionOrObjectLiteralMethodDeferred(node); - break; - case 153: - case 154: - checkAccessorDeclaration(node); - break; - case 199: - checkClassExpressionDeferred(node); - break; - } - } - } - function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); - checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); - } - function checkSourceFileWorker(node) { - var links = getNodeLinks(node); - if (!(links.flags & 1)) { - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { - return; - } - checkGrammarSourceFile(node); - potentialThisCollisions.length = 0; - potentialNewTargetCollisions.length = 0; - deferredNodes = []; - deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; - ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); - if (ts.isExternalModule(node)) { - registerForUnusedIdentifiersCheck(node); - } - if (!node.isDeclarationFile) { - checkUnusedIdentifiers(); - } - deferredNodes = undefined; - deferredUnusedIdentifierNodes = undefined; - if (ts.isExternalOrCommonJsModule(node)) { - checkExternalModuleExports(node); - } - if (potentialThisCollisions.length) { - ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); - potentialThisCollisions.length = 0; - } - if (potentialNewTargetCollisions.length) { - ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); - potentialNewTargetCollisions.length = 0; - } - links.flags |= 1; - } - } - function getDiagnostics(sourceFile, ct) { - try { - cancellationToken = ct; - return getDiagnosticsWorker(sourceFile); - } - finally { - cancellationToken = undefined; - } - } - function getDiagnosticsWorker(sourceFile) { - throwIfNonDiagnosticsProducing(); - if (sourceFile) { - var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; - checkSourceFile(sourceFile); - var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); - var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { - var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); - return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); - } - else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { - return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); - } - return semanticDiagnostics; - } - ts.forEach(host.getSourceFiles(), checkSourceFile); - return diagnostics.getDiagnostics(); - } - function getGlobalDiagnostics() { - throwIfNonDiagnosticsProducing(); - return diagnostics.getGlobalDiagnostics(); - } - function throwIfNonDiagnosticsProducing() { - if (!produceDiagnostics) { - throw new Error("Trying to get diagnostics from a type checker that does not produce them."); - } - } - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } - function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { - return []; - } - var symbols = ts.createMap(); - var memberFlags = 0; - populateSymbols(); - return symbolsToArray(symbols); - function populateSymbols() { - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - case 233: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); - break; - case 232: - copySymbols(getSymbolOfNode(location).exports, meaning & 8); - break; - case 199: - var className = location.name; - if (className) { - copySymbol(location.symbol, meaning); - } - case 229: - case 230: - if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); - } - break; - case 186: - var funcName = location.name; - if (funcName) { - copySymbol(location.symbol, meaning); - } - break; - } - if (ts.introducesArgumentsExoticObject(location)) { - copySymbol(argumentsSymbol, meaning); - } - memberFlags = ts.getModifierFlags(location); - location = location.parent; - } - copySymbols(globals, meaning); - } - function copySymbol(symbol, meaning) { - if (symbol.flags & meaning) { - var id = symbol.name; - if (!symbols.has(id)) { - symbols.set(id, symbol); - } - } - } - function copySymbols(source, meaning) { - if (meaning) { - source.forEach(function (symbol) { - copySymbol(symbol, meaning); - }); - } - } - } - function isTypeDeclarationName(name) { - return name.kind === 71 && - isTypeDeclaration(name.parent) && - name.parent.name === name; - } - function isTypeDeclaration(node) { - switch (node.kind) { - case 145: - case 229: - case 230: - case 231: - case 232: - return true; - } - } - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 143) { - node = node.parent; - } - return node.parent && (node.parent.kind === 159 || node.parent.kind === 277); - } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 179) { - node = node.parent; - } - return node.parent && node.parent.kind === 201; - } - function forEachEnclosingClass(node, callback) { - var result; - while (true) { - node = ts.getContainingClass(node); - if (!node) - break; - if (result = callback(node)) - break; - } - return result; - } - function isNodeWithinClass(node, classDeclaration) { - return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); - } - function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143) { - nodeOnRightSide = nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 237) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 243) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; - } - return undefined; - } - function isInRightSideOfImportOrExportAssignment(node) { - return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; - } - function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); - switch (specialPropertyAssignmentKind) { - case 1: - case 3: - return getSymbolOfNode(entityName.parent); - case 4: - case 2: - case 5: - return getSymbolOfNode(entityName.parent.parent); - } - } - function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { - if (ts.isDeclarationName(entityName)) { - return getSymbolOfNode(entityName.parent); - } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 && - entityName.parent === entityName.parent.parent.left) { - var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); - if (specialPropertyAssignmentSymbol) { - return specialPropertyAssignmentSymbol; - } - } - if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); - } - if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 237); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); - } - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = 0; - if (entityName.parent.kind === 201) { - meaning = 793064; - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455; - } - } - else { - meaning = 1920; - } - meaning |= 8388608; - var entityNameSymbol = resolveEntityName(entityName, meaning); - if (entityNameSymbol) { - return entityNameSymbol; - } - } - if (ts.isPartOfExpression(entityName)) { - if (ts.nodeIsMissing(entityName)) { - return undefined; - } - if (entityName.kind === 71) { - if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { - return getIntrinsicTagSymbol(entityName.parent); - } - return resolveEntityName(entityName, 107455, false, true); - } - else if (entityName.kind === 179) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkPropertyAccessExpression(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - else if (entityName.kind === 143) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkQualifiedName(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - } - else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 159 || entityName.parent.kind === 277) ? 793064 : 1920; - return resolveEntityName(entityName, meaning, false, true); - } - else if (entityName.parent.kind === 253) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 158) { - return resolveEntityName(entityName, 1); - } - return undefined; - } - function getSymbolAtLocation(node) { - if (node.kind === 265) { - return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; - } - if (isInsideWithStatementBody(node)) { - return undefined; - } - if (isDeclarationNameOrImportPropertyName(node)) { - return getSymbolOfNode(node.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); - } - if (node.kind === 71) { - if (isInRightSideOfImportOrExportAssignment(node)) { - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - } - else if (node.parent.kind === 176 && - node.parent.parent.kind === 174 && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); - if (propertyDeclaration) { - return propertyDeclaration; - } - } - } - switch (node.kind) { - case 71: - case 179: - case 143: - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99: - var container = ts.getThisContainer(node, false); - if (ts.isFunctionLike(container)) { - var sig = getSignatureFromDeclaration(container); - if (sig.thisParameter) { - return sig.thisParameter; - } - } - case 97: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; - case 169: - return getTypeFromTypeNode(node).symbol; - case 123: - var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152) { - return constructorDeclaration.parent.symbol; - } - return undefined; - case 9: - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { - return resolveExternalModuleName(node, node); - } - case 8: - if (node.parent.kind === 180 && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); - } - break; - } - return undefined; - } - function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 262) { - return resolveEntityName(location.name, 107455 | 8388608); - } - return undefined; - } - function getExportSpecifierLocalTargetSymbol(node) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); - } - function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { - return unknownType; - } - if (ts.isPartOfTypeNode(node)) { - var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; - } - if (ts.isPartOfExpression(node)) { - return getRegularTypeOfExpression(node); - } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); - } - if (isTypeDeclaration(node)) { - var symbol = getSymbolOfNode(node); - return getDeclaredTypeOfSymbol(symbol); - } - if (isTypeDeclarationName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - } - if (ts.isDeclaration(node)) { - var symbol = getSymbolOfNode(node); - return getTypeOfSymbol(symbol); - } - if (isDeclarationNameOrImportPropertyName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); - } - if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, true); - } - if (isInRightSideOfImportOrExportAssignment(node)) { - var symbol = getSymbolAtLocation(node); - var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); - return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); - } - return unknownType; - } - function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 || expr.kind === 177); - if (expr.parent.kind === 216) { - var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - if (expr.parent.kind === 194) { - var iteratedType = getTypeOfExpression(expr.parent.right); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - if (expr.parent.kind === 261) { - var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); - } - ts.Debug.assert(expr.parent.kind === 177); - var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); - } - function getPropertySymbolOfDestructuringAssignment(location) { - var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); - return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); - } - function getRegularTypeOfExpression(expr) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { - expr = expr.parent; - } - return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); - } - function getParentTypeOfClassElement(node) { - var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 - ? getTypeOfSymbol(classSymbol) - : getDeclaredTypeOfSymbol(classSymbol); - } - function getAugmentedPropertiesOfType(type) { - type = getApparentType(type); - var propsByName = createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName.has(p.name)) { - propsByName.set(p.name, p); - } - }); - } - return getNamedMembers(propsByName); - } - function getRootSymbols(symbol) { - 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_4.push(symbol); - } - }); - return symbols_4; - } - else if (symbol.flags & 134217728) { - if (symbol.leftSpread) { - var links = symbol; - return getRootSymbols(links.leftSpread).concat(getRootSymbols(links.rightSpread)); - } - if (symbol.syntheticOrigin) { - return getRootSymbols(symbol.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } - } - return [symbol]; - } - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; - return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; - } - } - return false; - } - function moduleExportsSomeValue(moduleReferenceExpression) { - var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return true; - } - var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - var symbolLinks = getSymbolLinks(moduleSymbol); - if (symbolLinks.exportsSomeValue === undefined) { - symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455) - : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); - } - return symbolLinks.exportsSomeValue; - function isValue(s) { - s = resolveSymbol(s); - return s && !!(s.flags & 107455); - } - } - function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; - } - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); - if (symbol) { - if (symbol.flags & 1048576) { - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol_1 = getParentOfSymbol(symbol); - if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { - var symbolFile = parentSymbol_1.valueDeclaration; - var referenceFile = ts.getSourceFileOfNode(node); - var symbolIsUmdExport = symbolFile !== referenceFile; - return symbolIsUmdExport ? undefined : symbolFile; - } - return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); - } - } - } - } - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && symbol.flags & 8388608) { - return getDeclarationOfAliasSymbol(symbol); - } - } - return undefined; - } - function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418) { - var links = getSymbolLinks(symbol); - if (links.isDeclarationWithCollidingName === undefined) { - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (ts.isStatementWithLocals(container)) { - var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.name, 107455, undefined, undefined)) { - links.isDeclarationWithCollidingName = true; - } - else if (nodeLinks_1.flags & 131072) { - var isDeclaredInLoop = nodeLinks_1.flags & 262144; - var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); - links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); - } - else { - links.isDeclarationWithCollidingName = false; - } - } - } - return links.isDeclarationWithCollidingName; - } - return false; - } - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { - return symbol.valueDeclaration; - } - } - } - return undefined; - } - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); - if (node) { - var symbol = getSymbolOfNode(node); - if (symbol) { - return isSymbolOfDeclarationWithCollidingName(symbol); - } - } - return false; - } - function isValueAliasDeclaration(node) { - switch (node.kind) { - case 237: - case 239: - case 240: - case 242: - case 246: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244: - var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243: - return node.expression - && node.expression.kind === 71 - ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) - : true; - } - return false; - } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { - return false; - } - var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); - return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); - } - function isAliasResolvedToValue(symbol) { - var target = resolveAlias(symbol); - if (target === unknownSymbol) { - return true; - } - return target.flags & 107455 && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); - } - function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; - } - function isReferencedAliasDeclaration(node, checkChildren) { - if (ts.isAliasSymbolDeclaration(node)) { - var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { - return true; - } - } - if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); - } - return false; - } - function isImplementationOfOverload(node) { - if (ts.nodeIsPresent(node.body)) { - var symbol = getSymbolOfNode(node); - var signaturesOfSymbol = getSignaturesOfSymbol(symbol); - return signaturesOfSymbol.length > 1 || - (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); - } - return false; - } - function isRequiredInitializedParameter(parameter) { - return strictNullChecks && - !isOptionalParameter(parameter) && - parameter.initializer && - !(ts.getModifierFlags(parameter) & 92); - } - function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; - } - function getEnumMemberValue(node) { - computeEnumMemberValues(node.parent); - return getNodeLinks(node).enumMemberValue; - } - function canHaveConstantValue(node) { - switch (node.kind) { - case 264: - case 179: - case 180: - return true; - } - return false; - } - function getConstantValue(node) { - if (node.kind === 264) { - return getEnumMemberValue(node); - } - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol && (symbol.flags & 8)) { - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); - } - } - return undefined; - } - function isFunctionType(type) { - return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; - } - function getTypeReferenceSerializationKind(typeName, location) { - var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); - var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); - if (valueSymbol && valueSymbol === typeSymbol) { - var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); - if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { - return ts.TypeReferenceSerializationKind.Promise; - } - var constructorType = getTypeOfSymbol(valueSymbol); - if (constructorType && isConstructorType(constructorType)) { - return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; - } - } - if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - var type = getDeclaredTypeOfSymbol(typeSymbol); - if (type === unknownType) { - return ts.TypeReferenceSerializationKind.Unknown; - } - else if (type.flags & 1) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { - return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; - } - else if (isTypeOfKind(type, 136)) { - return ts.TypeReferenceSerializationKind.BooleanType; - } - else if (isTypeOfKind(type, 84)) { - return ts.TypeReferenceSerializationKind.NumberLikeType; - } - else if (isTypeOfKind(type, 262178)) { - return ts.TypeReferenceSerializationKind.StringLikeType; - } - else if (isTupleType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else if (isTypeOfKind(type, 512)) { - return ts.TypeReferenceSerializationKind.ESSymbolType; - } - else if (isFunctionType(type)) { - return ts.TypeReferenceSerializationKind.TypeWithCallSignature; - } - else if (isArrayType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else { - return ts.TypeReferenceSerializationKind.ObjectType; - } - } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { - var symbol = getSymbolOfNode(declaration); - var type = symbol && !(symbol.flags & (2048 | 131072)) - ? getWidenedLiteralType(getTypeOfSymbol(symbol)) - : unknownType; - if (flags & 4096) { - type = getNullableType(type, 2048); - } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { - var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); - } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name) { - return globals.has(name); - } - function getReferencedValueSymbol(reference, startInDeclarationContainer) { - var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; - if (resolvedSymbol) { - return resolvedSymbol; - } - var location = reference; - if (startInDeclarationContainer) { - var parent = reference.parent; - if (ts.isDeclaration(parent) && reference === parent.name) { - location = getDeclarationContainer(parent); - } - } - return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); - } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); - if (reference) { - var symbol = getReferencedValueSymbol(reference); - if (symbol) { - return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; - } - } - } - return undefined; - } - function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 1048576); - } - return false; - } - function writeLiteralConstValue(node, writer) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); - } - function createResolver() { - var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); - var fileToDirective; - if (resolvedTypeReferenceDirectives) { - fileToDirective = ts.createFileMap(); - resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { - if (!resolvedDirective) { - return; - } - var file = host.getSourceFile(resolvedDirective.resolvedFileName); - fileToDirective.set(file.path, key); - }); - } - return { - getReferencedExportContainer: getReferencedExportContainer, - getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, - isDeclarationWithCollidingName: isDeclarationWithCollidingName, - isValueAliasDeclaration: function (node) { - node = ts.getParseTreeNode(node); - return node ? isValueAliasDeclaration(node) : true; - }, - hasGlobalName: hasGlobalName, - isReferencedAliasDeclaration: function (node, checkChildren) { - node = ts.getParseTreeNode(node); - return node ? isReferencedAliasDeclaration(node, checkChildren) : true; - }, - getNodeCheckFlags: function (node) { - node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; - }, - isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, - isDeclarationVisible: isDeclarationVisible, - isImplementationOfOverload: isImplementationOfOverload, - isRequiredInitializedParameter: isRequiredInitializedParameter, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, - isSymbolAccessible: isSymbolAccessible, - isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - collectLinkedAliases: collectLinkedAliases, - getReferencedValueDeclaration: getReferencedValueDeclaration, - getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, - isOptionalParameter: isOptionalParameter, - moduleExportsSomeValue: moduleExportsSomeValue, - isArgumentsLocalBinding: isArgumentsLocalBinding, - getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, - getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, - isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } - }; - function getTypeReferenceDirectivesForEntityName(node) { - if (!fileToDirective) { - return undefined; - } - var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) - ? 107455 | 1048576 - : 793064 | 1920; - var symbol = resolveEntityName(node, meaning, true); - return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; - } - function getTypeReferenceDirectivesForSymbol(symbol, meaning) { - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { - return undefined; - } - var typeReferenceDirectives; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); - if (typeReferenceDirective) { - (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); - } - else { - return undefined; - } - } - } - return typeReferenceDirectives; - } - function isSymbolFromTypeDeclarationFile(symbol) { - if (!symbol.declarations) { - return false; - } - var current = symbol; - while (true) { - var parent = getParentOfSymbol(current); - if (parent) { - current = parent; - } - else { - break; - } - } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { - return false; - } - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.contains(file.path)) { - return true; - } - } - return false; - } - } - function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); - if (!moduleSymbol) { - return undefined; - } - return ts.getDeclarationOfKind(moduleSymbol, 265); - } - function initializeTypeChecker() { - for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); - } - var augmentations; - for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); - } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); - } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); - } - if (file.symbol && file.symbol.globalExports) { - var source = file.symbol.globalExports; - source.forEach(function (sourceSymbol, id) { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); - } - }); - } - } - if (augmentations) { - for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { - var list = augmentations_1[_d]; - for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { - var augmentation = list_1[_e]; - mergeModuleAugmentation(augmentation); - } - } - } - addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); - getSymbolLinks(undefinedSymbol).type = undefinedWideningType; - getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); - getSymbolLinks(unknownSymbol).type = unknownType; - globalArrayType = getGlobalType("Array", 1, true); - globalObjectType = getGlobalType("Object", 0, true); - globalFunctionType = getGlobalType("Function", 0, true); - globalStringType = getGlobalType("String", 0, true); - globalNumberType = getGlobalType("Number", 0, true); - globalBooleanType = getGlobalType("Boolean", 0, true); - globalRegExpType = getGlobalType("RegExp", 0, true); - anyArrayType = createArrayType(anyType); - autoArrayType = createArrayType(autoType); - globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); - anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined("ThisType", 1); - } - function checkExternalEmitHelpers(location, helpers) { - if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { - var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { - var helpersModule = resolveHelpersModule(sourceFile, location); - if (helpersModule !== unknownSymbol) { - var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 16384; helper <<= 1) { - if (uncheckedHelpers & helper) { - var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); - if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); - } - } - } - } - requestedExternalEmitHelpers |= helpers; - } - } - } - function getHelperName(helper) { - switch (helper) { - case 1: return "__extends"; - case 2: return "__assign"; - case 4: return "__rest"; - case 8: return "__decorate"; - case 16: return "__metadata"; - case 32: return "__param"; - case 64: return "__awaiter"; - case 128: return "__generator"; - case 256: return "__values"; - case 512: return "__read"; - case 1024: return "__spread"; - case 2048: return "__await"; - case 4096: return "__asyncGenerator"; - case 8192: return "__asyncDelegator"; - case 16384: return "__asyncValues"; - default: ts.Debug.fail("Unrecognized helper."); - } - } - function resolveHelpersModule(node, errorNode) { - if (!externalHelpersModule) { - externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; - } - return externalHelpersModule; - } - function checkGrammarDecorators(node) { - if (!node.decorators) { - return false; - } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); - } - } - else if (node.kind === 153 || node.kind === 154) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); - } - } - return false; - } - function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; - } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; - var flags = 0; - for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { - var modifier = _a[_i]; - if (modifier.kind !== 131) { - if (node.kind === 148 || node.kind === 150) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); - } - if (node.kind === 157) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); - } - } - switch (modifier.kind) { - case 76: - if (node.kind !== 232 && node.parent.kind === 229) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); - } - break; - case 114: - case 113: - case 112: - var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113) { - lastProtected = modifier; - } - else if (modifier.kind === 112) { - lastPrivate = modifier; - } - if (flags & 28) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); - } - else if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); - } - else if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); - } - else if (node.parent.kind === 234 || node.parent.kind === 265) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); - } - else if (flags & 128) { - if (modifier.kind === 112) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); - } - else { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); - } - } - flags |= ts.modifierToFlag(modifier.kind); - break; - case 115: - if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); - } - else if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); - } - else if (node.parent.kind === 234 || node.parent.kind === 265) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); - } - else if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - flags |= 32; - lastStatic = modifier; - break; - case 131: - if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); - } - else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); - } - flags |= 64; - lastReadonly = modifier; - break; - case 84: - if (flags & 1) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); - } - else if (flags & 2) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); - } - else if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); - } - else if (node.parent.kind === 229) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); - } - flags |= 1; - break; - case 124: - if (flags & 2) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.parent.kind === 229) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); - } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { - return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); - } - flags |= 2; - lastDeclare = modifier; - break; - case 117: - if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); - } - if (node.kind !== 229) { - if (node.kind !== 151 && - node.kind !== 149 && - node.kind !== 153 && - node.kind !== 154) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); - } - if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); - } - if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - if (flags & 8) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); - } - } - flags |= 128; - break; - case 120: - if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); - } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); - } - flags |= 256; - lastAsync = modifier; - break; - } - } - if (node.kind === 152) { - if (flags & 32) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); - } - if (flags & 128) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); - } - else if (flags & 256) { - return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); - } - else if (flags & 64) { - return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); - } - return; - } - else if ((node.kind === 238 || node.kind === 237) && flags & 2) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); - } - else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); - } - else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); - } - if (flags & 256) { - return checkGrammarAsyncModifier(node, lastAsync); - } - } - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 153: - case 154: - case 152: - case 149: - case 148: - case 151: - case 150: - case 157: - case 233: - case 238: - case 237: - case 244: - case 243: - case 186: - case 187: - case 146: - return false; - default: - if (node.parent.kind === 234 || node.parent.kind === 265) { - return false; - } - switch (node.kind) { - case 228: - return nodeHasAnyModifiersExcept(node, 120); - case 229: - return nodeHasAnyModifiersExcept(node, 117); - case 230: - case 208: - case 231: - return true; - case 232: - return nodeHasAnyModifiersExcept(node, 76); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } - function checkGrammarAsyncModifier(node, asyncModifier) { - switch (node.kind) { - case 151: - case 228: - case 186: - case 187: - return false; - } - return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); - } - function checkGrammarForDisallowedTrailingComma(list) { - if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } - if (typeParameters && typeParameters.length === 0) { - var start = typeParameters.pos - "<".length; - var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; - return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); - } - } - function checkGrammarParameterList(parameters) { - var seenOptionalParameter = false; - var parameterCount = parameters.length; - for (var i = 0; i < parameterCount; i++) { - var parameter = parameters[i]; - if (parameter.dotDotDotToken) { - if (i !== (parameterCount - 1)) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); - } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); - } - } - else if (parameter.questionToken) { - seenOptionalParameter = true; - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); - } - } - else if (seenOptionalParameter && !parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); - } - } - } - function checkGrammarFunctionLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); - } - function checkGrammarClassLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); - } - function checkGrammarArrowFunction(node, file) { - if (node.kind === 187) { - var arrowFunction = node; - var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; - var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; - if (startLine !== endLine) { - return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); - } - } - return false; - } - function checkGrammarIndexSignatureParameters(node) { - var parameter = node.parameters[0]; - if (node.parameters.length !== 1) { - if (parameter) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - else { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - } - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); - } - if (ts.getModifierFlags(parameter) !== 0) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); - } - if (!parameter.type) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); - } - if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); - } - if (!node.type) { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); - } - } - function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); - } - function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { - if (typeArguments && typeArguments.length === 0) { - var sourceFile = ts.getSourceFileOfNode(node); - var start = typeArguments.pos - "<".length; - var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function checkGrammarTypeArguments(node, typeArguments) { - return checkGrammarForDisallowedTrailingComma(typeArguments) || - checkGrammarForAtLeastOneTypeArgument(node, typeArguments); - } - function checkGrammarForOmittedArgument(node, args) { - if (args) { - var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { - var arg = args_4[_i]; - if (arg.kind === 200) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); - } - } - } - } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); - } - function checkGrammarHeritageClause(node) { - var types = node.types; - if (checkGrammarForDisallowedTrailingComma(types)) { - return true; - } - if (types && types.length === 0) { - var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); - } - } - function checkGrammarClassDeclarationHeritageClauses(node) { - var seenExtendsClause = false; - var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); - } - if (heritageClause.types.length > 1) { - return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108); - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); - } - seenImplementsClause = true; - } - checkGrammarHeritageClause(heritageClause); - } - } - } - function checkGrammarInterfaceDeclaration(node) { - var seenExtendsClause = false; - if (node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108); - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); - } - checkGrammarHeritageClause(heritageClause); - } - } - return false; - } - function checkGrammarComputedPropertyName(node) { - if (node.kind !== 144) { - return false; - } - var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { - return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); - } - } - function checkGrammarForGenerator(node) { - if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 || - node.kind === 186 || - node.kind === 151); - if (ts.isInAmbientContext(node)) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); - } - if (!node.body) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); - } - } - } - function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } - } - function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 263) { - continue; - } - var name = prop.name; - if (name.kind === 144) { - checkGrammarComputedPropertyName(name); - } - if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); - } - if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { - var mod = _c[_b]; - if (mod.kind !== 120 || prop.kind !== 151) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); - } - } - } - var currentKind = void 0; - if (prop.kind === 261 || prop.kind === 262) { - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151) { - currentKind = Property; - } - else if (prop.kind === 153) { - currentKind = GetAccessor; - } - else if (prop.kind === 154) { - currentKind = SetAccessor; - } - else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); - } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name); - if (effectiveName === undefined) { - continue; - } - var existingKind = seen.get(effectiveName); - if (!existingKind) { - seen.set(effectiveName, currentKind); - } - else { - if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); - } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen.set(effectiveName, currentKind | existingKind); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); - } - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); - } - } - } - } - function checkGrammarJsxElement(node) { - var seen = ts.createMap(); - for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { - var attr = _a[_i]; - if (attr.kind === 255) { - continue; - } - var jsxAttr = attr; - var name = jsxAttr.name; - if (!seen.get(name.text)) { - seen.set(name.text, true); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); - } - var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 && !initializer.expression) { - return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); - } - } - } - function checkGrammarForInOrForOfStatement(forInOrOfStatement) { - if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { - return true; - } - if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 16384) === 0) { - return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - } - } - if (forInOrOfStatement.initializer.kind === 227) { - var variableList = forInOrOfStatement.initializer; - if (!checkGrammarVariableDeclarationList(variableList)) { - var declarations = variableList.declarations; - if (!declarations.length) { - return false; - } - if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement - : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; - return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); - } - var firstDeclaration = declarations[0]; - if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer - : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; - return grammarErrorOnNode(firstDeclaration.name, diagnostic); - } - if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation - : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; - return grammarErrorOnNode(firstDeclaration, diagnostic); - } - } - } - return false; - } - function checkGrammarAccessor(accessor) { - var kind = accessor.kind; - if (languageVersion < 1) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); - } - else if (ts.isInAmbientContext(accessor)) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); - } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - else if (accessor.body && ts.getModifierFlags(accessor) & 128) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); - } - else if (accessor.typeParameters) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); - } - else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 ? - ts.Diagnostics.A_get_accessor_cannot_have_parameters : - ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); - } - else if (kind === 154) { - if (accessor.type) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); - } - else { - var parameter = accessor.parameters[0]; - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); - } - else if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); - } - else if (parameter.initializer) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); - } - } - } - } - function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); - } - function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { - return ts.getThisParameter(accessor); - } - } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { - return grammarErrorOnNode(node, message); - } - } - function checkGrammarMethod(node) { - if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || - checkGrammarFunctionLikeDeclaration(node) || - checkGrammarForGenerator(node)) { - return true; - } - if (node.parent.kind === 178) { - if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { - return true; - } - else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - } - if (ts.isClassLike(node.parent)) { - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); - } - else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); - } - } - else if (node.parent.kind === 230) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); - } - else if (node.parent.kind === 163) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); - } - } - function checkGrammarBreakOrContinueStatement(node) { - var current = node; - while (current) { - if (ts.isFunctionLike(current)) { - return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); - } - switch (current.kind) { - case 222: - if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 217 - && !ts.isIterationStatement(current.statement, true); - if (isMisplacedContinueLabel) { - return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); - } - return false; - } - break; - case 221: - if (node.kind === 218 && !node.label) { - return false; - } - break; - default: - if (ts.isIterationStatement(current, false) && !node.label) { - return false; - } - break; - } - current = current.parent; - } - if (node.label) { - var message = node.kind === 218 - ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement - : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - else { - var message = node.kind === 218 - ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement - : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - } - function checkGrammarBindingElement(node) { - if (node.dotDotDotToken) { - var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - if (node.name.kind === 175 || node.name.kind === 174) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (node.initializer) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - } - } - function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && - expr.operand.kind === 8; - } - function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { - if (ts.isInAmbientContext(node)) { - if (node.initializer) { - if (ts.isConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - else if (!node.initializer) { - if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); - } - if (ts.isConst(node)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); - } - } - } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { - checkESModuleMarker(node.name); - } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); - return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); - } - function checkESModuleMarker(name) { - if (name.kind === 71) { - if (ts.unescapeIdentifier(name.text) === "__esModule") { - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; - if (!ts.isOmittedExpression(element)) { - return checkESModuleMarker(element.name); - } - } - } - } - function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71) { - if (name.originalKeywordKind === 110) { - return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; - if (!ts.isOmittedExpression(element)) { - checkGrammarNameInLetOrConstDeclarations(element.name); - } - } - } - } - function checkGrammarVariableDeclarationList(declarationList) { - var declarations = declarationList.declarations; - if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { - return true; - } - if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); - } - } - function allowLetAndConstDeclarations(parent) { - switch (parent.kind) { - case 211: - case 212: - case 213: - case 220: - case 214: - case 215: - case 216: - return false; - case 222: - return allowLetAndConstDeclarations(parent.parent); - } - return true; - } - function checkGrammarForDisallowedLetOrConstStatement(node) { - if (!allowLetAndConstDeclarations(node.parent)) { - if (ts.isLet(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); - } - else if (ts.isConst(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); - } - } - } - function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94) { - if (node.name.text !== "target") { - return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.text, ts.tokenToString(node.keywordToken), "target"); - } - } - } - function hasParseDiagnostics(sourceFile) { - return sourceFile.parseDiagnostics.length > 0; - } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorOnNode(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); - return true; - } - } - function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarProperty(node) { - if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - } - else if (node.parent.kind === 230) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); - } - } - else if (node.parent.kind === 163) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); - } - } - if (ts.isInAmbientContext(node) && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 230 || - node.kind === 231 || - node.kind === 238 || - node.kind === 237 || - node.kind === 244 || - node.kind === 243 || - node.kind === 236 || - ts.getModifierFlags(node) & (2 | 1 | 512)) { - return false; - } - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); - } - function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { - for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208) { - if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { - return true; - } - } - } - } - function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); - } - function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { - if (isAccessor(node.parent.kind)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = true; - } - var links = getNodeLinks(node); - if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); - } - if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { - var links_1 = getNodeLinks(node.parent); - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); - } - } - else { - } - } - } - function checkGrammarNumericLiteral(node) { - if (node.numericLiteralFlags & 4) { - var diagnosticMessage = void 0; - if (languageVersion >= 1) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 173)) { - diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 264)) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; - } - if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; - var literal = (withMinus ? "-" : "") + "0o" + node.text; - return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); - } - } - } - function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); - return true; - } - } - function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(global); - } - }); - return result; - } - } - 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) { @@ -41322,11 +41037,11 @@ var ts; 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)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), 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 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)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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: @@ -41334,9 +41049,9 @@ var ts; 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)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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: @@ -41344,9 +41059,9 @@ var ts; 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)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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: @@ -41366,7 +41081,7 @@ var ts; case 171: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); case 172: - 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)); + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), 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 174: @@ -41394,9 +41109,9 @@ var ts; case 185: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 186: - return ts.updateFunctionExpression(node, 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)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 188: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189: @@ -41420,7 +41135,7 @@ var ts; case 198: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); case 199: - return ts.updateClassExpression(node, 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)); + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 201: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 202: @@ -41470,13 +41185,13 @@ var ts; case 227: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 228: - 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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: @@ -41543,9 +41258,9 @@ var ts; return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); case 265: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 296: + case 288: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297: + case 289: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -41583,7 +41298,7 @@ var ts; case 209: case 200: case 225: - case 295: + case 287: break; case 143: result = reduceNode(node.left, cbNode, result); @@ -41743,9 +41458,6 @@ var ts; result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 203: - result = reduceNode(node.expression, cbNode, result); - break; case 205: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); @@ -41944,10 +41656,10 @@ var ts; case 265: result = reduceNodes(node.statements, cbNodes, result); break; - case 296: + case 288: result = reduceNode(node.expression, cbNode, result); break; - case 297: + case 289: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -42013,46 +41725,210 @@ var ts; } var Debug; (function (Debug) { + var isDebugInfoEnabled = false; Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } : ts.noop; Debug.assertEachNode = Debug.shouldAssert(1) - ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; Debug.assertNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } : ts.noop; Debug.assertOptionalNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } : ts.noop; Debug.assertOptionalToken = Debug.shouldAssert(1) - ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } : ts.noop; Debug.assertMissingNode = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; - function getFunctionName(func) { - if (typeof func !== "function") { - return ""; - } - else if (func.hasOwnProperty("name")) { - return func.name; - } - else { - var text = Function.prototype.toString.call(func); - var match = /^function\s+([\w\$]+)\s*\(/.exec(text); - return match ? match[1] : ""; + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, + "__debugObjectFlags": { get: function () { return this.flags & 32768 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, + "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + "__debugGetText": { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } } + isDebugInfoEnabled = true; } + Debug.enableDebugInfo = enableDebugInfo; })(Debug = ts.Debug || (ts.Debug = {})); })(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 getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 238: + externalImports.push(node); + break; + case 237: + if (node.moduleReference.kind === 248) { + externalImports.push(node); + } + break; + case 244: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 243: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 208: + if (ts.hasModifier(node, 1)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 228: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 229: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + } + } + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { + uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } +})(ts || (ts = {})); +var ts; +(function (ts) { function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) { var location = node; var value; @@ -42297,11 +42173,11 @@ var ts; } else if (ts.isStringOrNumericLiteral(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); - argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); return ts.createPropertyAccess(value, name); } } @@ -42372,12 +42248,6 @@ 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(); @@ -42558,6 +42428,7 @@ var ts; case 147: case 231: case 149: + case 236: return undefined; case 152: return visitConstructor(node); @@ -42629,32 +42500,71 @@ var ts; function shouldEmitDecorateCallForParameter(parameter) { return parameter.decorators !== undefined && parameter.decorators.length > 0; } + function getClassFacts(node, staticProperties) { + var facts = 0; + if (ts.some(staticProperties)) + facts |= 1; + if (ts.getClassExtendsHeritageClauseElement(node)) + facts |= 64; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2; + if (ts.childIsDecorated(node)) + facts |= 4; + if (isExportOfNamespace(node)) + facts |= 8; + else if (isDefaultExternalModuleExport(node)) + facts |= 32; + else if (isNamedExternalModuleExport(node)) + facts |= 16; + if (languageVersion <= 1 && (facts & 7)) + facts |= 128; + return facts; + } function visitClassDeclaration(node) { var staticProperties = getInitializedProperties(node, true); - var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; - var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var name = node.name; - if (!name && (staticProperties.length > 0 || ts.childIsDecorated(node))) { - name = ts.getGeneratedNameForNode(node); + var facts = getClassFacts(node, staticProperties); + if (facts & 128) { + context.startLexicalEnvironment(); } - var classStatement = isDecoratedClass - ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) - : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var name = node.name || (facts & 5 ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; - if (staticProperties.length) { - addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); + if (facts & 1) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 ? ts.getInternalName(node) : ts.getLocalName(node)); } addClassElementDecorationStatements(statements, node, false); addClassElementDecorationStatements(statements, node, true); addConstructorDecorationStatement(statements, node); - if (isNamespaceExport(node)) { + if (facts & 128) { + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18); + var localName = ts.getInternalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 | 384); + statements.push(statement); + ts.addRange(statements, context.endLexicalEnvironment()); + var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + if (facts & 8) { addExportMemberAssignment(statements, node); } - else if (isDecoratedClass) { - if (isDefaultExternalModuleExport(node)) { + else if (facts & 128 || facts & 2) { + if (facts & 32) { statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); } - else if (isNamedExternalModuleExport(node)) { + else if (facts & 16) { statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); } } @@ -42664,10 +42574,13 @@ var ts; } return ts.singleOrMany(statements); } - function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { - var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause)); + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + var modifiers = !(facts & 128) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration(undefined, modifiers, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64) !== 0)); var emitFlags = ts.getEmitFlags(node); - if (hasStaticProperties) { + if (facts & 1) { emitFlags |= 32; } ts.setTextRange(classDeclaration, node); @@ -42675,12 +42588,12 @@ var ts; ts.setEmitFlags(classDeclaration, emitFlags); return classDeclaration; } - function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { + function createClassDeclarationHeadWithDecorators(node, name, facts) { var location = ts.moveRangePastDecorators(node); var classAlias = getClassAliasIfNeeded(node); var declName = ts.getLocalName(node, false, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, hasExtendsClause); + var members = transformClassMembers(node, (facts & 64) !== 0); var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -42934,8 +42847,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -43089,7 +43002,7 @@ var ts; var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { continue; } if (parameter.dotDotDotToken) { @@ -43189,13 +43102,13 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { return serializedIndividual; } else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || - serializedUnion.text !== serializedIndividual.text) { + serializedUnion.escapedText !== serializedIndividual.escapedText) { return ts.createIdentifier("Object"); } } @@ -43276,7 +43189,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeIdentifier(name.text)); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.getSynthesizedClone(name); @@ -43357,7 +43270,7 @@ var ts; return ts.createNotEmittedStatement(node); } var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var statements = [updated]; addExportMemberAssignment(statements, node); return statements; @@ -43388,7 +43301,7 @@ var ts; return parameter; } function visitVariableStatement(node) { - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); if (variables.length === 0) { return undefined; @@ -43505,16 +43418,16 @@ var ts; return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function hasNamespaceQualifiedExportName(node) { - return isNamespaceExport(node) + return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createMap(); + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); } if (!currentScopeFirstDeclarationsOfName.has(name)) { currentScopeFirstDeclarationsOfName.set(name, node); @@ -43523,7 +43436,7 @@ var ts; } function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { return currentScopeFirstDeclarationsOfName.get(name) === node; } @@ -43699,7 +43612,7 @@ var ts; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); ts.setEmitFlags(moduleReference, 1536 | 2048); - if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) ])), node), node); @@ -43708,7 +43621,7 @@ var ts; return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); } } - function isNamespaceExport(node) { + function isExportOfNamespace(node) { return currentNamespace !== undefined && ts.hasModifier(node, 1); } function isExternalModuleExport(node) { @@ -43727,7 +43640,7 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); - ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); var statement = ts.createStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); @@ -43752,7 +43665,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeIdentifier(node.name.text) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -43856,10 +43769,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_2 = ts.getSynthesizedClone(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; } } } @@ -43958,10 +43871,6 @@ 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(); @@ -44133,7 +44042,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -44203,10 +44112,6 @@ 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(); @@ -44423,8 +44328,10 @@ 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 createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 + ? ts.createYield(undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); @@ -44443,7 +44350,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ 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); + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, createDownlevelAwait(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -44452,7 +44359,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -44630,7 +44537,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -44888,8 +44795,8 @@ var ts; } else { var name = node.tagName; - if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.text)) { - return ts.createLiteral(name.text); + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.createExpressionFromEntityName(name); @@ -44898,11 +44805,11 @@ var ts; } function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(name.text)) { + if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { return name; } else { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } } function visitJsxExpression(node) { @@ -45230,75 +45137,6 @@ 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(); @@ -45339,11 +45177,58 @@ var ts; && node.kind === 219 && !node.expression; } + function isClassLikeVariableStatement(node) { + if (!ts.isVariableStatement(node)) + return false; + var variable = ts.singleOrUndefined(node.declarationList.declarations); + return variable + && variable.initializer + && ts.isIdentifier(variable.name) + && (ts.isClassLike(variable.initializer) + || (ts.isAssignmentExpression(variable.initializer) + && ts.isIdentifier(variable.initializer.left) + && ts.isClassLike(variable.initializer.right))); + } + function isTypeScriptClassWrapper(node) { + var call = ts.tryCast(node, ts.isCallExpression); + if (!call || ts.isParseTreeNode(call) || + ts.some(call.typeArguments) || + ts.some(call.arguments)) { + return false; + } + var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + if (!func || ts.isParseTreeNode(func) || + ts.some(func.typeParameters) || + ts.some(func.parameters) || + func.type || + !func.body) { + return false; + } + var statements = func.body.statements; + if (statements.length < 2) { + return false; + } + var firstStatement = statements[0]; + if (ts.isParseTreeNode(firstStatement) || + !ts.isClassLike(firstStatement) && + !isClassLikeVariableStatement(firstStatement)) { + return false; + } + var lastStatement = ts.elementAt(statements, -1); + var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); + if (!returnStatement || + !returnStatement.expression || + !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { + return false; + } + return true; + } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && ts.isStatement(node)) - || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); + || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) + || isTypeScriptClassWrapper(node); } function visitor(node) { if (shouldVisitNode(node)) { @@ -45528,7 +45413,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return node; } - if (node.text !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { return node; } return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); @@ -45536,7 +45421,7 @@ var ts; function visitBreakOrContinueStatement(node) { if (convertedLoopState) { var jump = node.kind === 218 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(node.label.text)) || + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; @@ -45552,12 +45437,12 @@ var ts; } else { if (node.kind === 218) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); + labelMarker = "break-" + node.label.escapedText; + setLabeledJump(convertedLoopState, true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); + labelMarker = "continue-" + node.label.escapedText; + setLabeledJump(convertedLoopState, false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -46200,9 +46085,9 @@ var ts; if (node.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 + var declarations = ts.flatMap(node.declarations, node.flags & 1 ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); + : visitVariableDeclaration); var declarationList = ts.createVariableDeclarationList(declarations); ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); @@ -46240,9 +46125,9 @@ var ts; return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_3 = ts.getMutableClone(node); - clone_3.initializer = ts.createVoidZero(); - return clone_3; + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; } return ts.visitEachChild(node, visitor, context); } @@ -46259,10 +46144,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(node.label.text, node.label.text); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); } function resetLabel(node) { - convertedLoopState.labels.set(node.label.text, undefined); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -46581,13 +46466,13 @@ var ts; loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); } else { - var clone_4 = ts.getMutableClone(node); - clone_4.statement = undefined; - clone_4 = ts.visitEachChild(clone_4, visitor, context); - clone_4.statement = ts.createBlock(convertedLoopBodyStatements, true); - clone_4.transformFlags = 0; - ts.aggregateTransformFlags(clone_4); - loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_3 = ts.getMutableClone(node); + clone_3.statement = undefined; + clone_3 = ts.visitEachChild(clone_3, visitor, context); + clone_3.statement = ts.createBlock(convertedLoopBodyStatements, true); + clone_3.transformFlags = 0; + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -46689,7 +46574,7 @@ var ts; else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeIdentifier(name.text)); + var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -46819,11 +46704,49 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { + if (isTypeScriptClassWrapper(node)) { + return visitTypeScriptClassWrapper(node); + } if (node.transformFlags & 64) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } + function visitTypeScriptClassWrapper(node) { + var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); + var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + ts.addRange(statements, remainingStatements); + ts.addRange(statements, classStatements, 1); + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, undefined, undefined, undefined, undefined, func.parameters, undefined, ts.updateBlock(func.body, statements))), undefined, call.arguments)))); + } function visitImmediateSuperCallInBody(node) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } @@ -46867,7 +46790,7 @@ var ts; if (ts.isCallExpression(firstSegment) && ts.isIdentifier(firstSegment.expression) && (ts.getEmitFlags(firstSegment.expression) & 4096) - && firstSegment.expression.text === "___spread") { + && firstSegment.expression.escapedText === "___spread") { return segments[0]; } } @@ -46876,7 +46799,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 177 + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -46884,7 +46807,7 @@ var ts; } } function partitionSpread(node) { - return ts.isSpreadExpression(node) + return ts.isSpreadElement(node) ? visitSpanOfSpreads : visitSpanOfNonSpreads; } @@ -46986,7 +46909,7 @@ var ts; : ts.createIdentifier("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 && node.name.text === "target") { + if (node.keywordToken === 94 && node.name.escapedText === "target") { if (hierarchyFacts & 8192) { hierarchyFacts |= 32768; } @@ -47087,8 +47010,7 @@ var ts; return false; } if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { - return currentNode.kind !== 149 - || (ts.getModifierFlags(currentNode) & 32) === 0; + return true; } currentNode = currentNode.parent; } @@ -47130,7 +47052,7 @@ var ts; return false; } var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression.text === "arguments"; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; } } ts.transformES2015 = transformES2015; @@ -47209,7 +47131,7 @@ var ts; return node; } function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); if (token >= 72 && token <= 107) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -47220,51 +47142,6 @@ 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"; @@ -47528,7 +47405,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } function visitBinaryExpression(node) { @@ -47594,10 +47471,10 @@ var ts; else if (node.operatorToken.kind === 26) { return visitCommaExpression(node); } - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -47724,10 +47601,10 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -47843,7 +47720,7 @@ var ts; return undefined; } function transformInitializedVariable(node) { - return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); } function transformAndEmitIfStatement(node) { if (containsYield(node)) { @@ -48030,13 +47907,13 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? node.label.text : undefined); + var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); emitBreak(label, node); } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && node.label.text); + var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, node); } @@ -48044,13 +47921,13 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? node.label.text : undefined); + var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); emitBreak(label, node); } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && node.label.text); + var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, node); } @@ -48145,7 +48022,7 @@ var ts; } function transformAndEmitLabeledStatement(node) { if (containsYield(node)) { - beginLabeledBlock(node.label.text); + beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -48155,7 +48032,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(node.label.text); + beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -48210,17 +48087,17 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(node.text)) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_7 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_7, node); - ts.setCommentRange(clone_7, node); - return clone_7; + var clone_6 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -48327,7 +48204,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = variable.name.text; + var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -48391,7 +48268,7 @@ var ts; kind: 3, isScript: false, breakLabel: breakLabel, - continueLabel: continueLabel + continueLabel: continueLabel, }); return breakLabel; } @@ -48415,7 +48292,7 @@ var ts; beginBlock({ kind: 2, isScript: false, - breakLabel: breakLabel + breakLabel: breakLabel, }); return breakLabel; } @@ -48923,9 +48800,10 @@ var ts; var currentSourceFile; var currentModuleInfo; var noSubstitution; + var needUMDDynamicImportHelper; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864)) { return node; } currentSourceFile = node; @@ -48935,6 +48813,7 @@ var ts; var updated = transformModule(node); currentSourceFile = undefined; currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; return ts.aggregateTransformFlags(updated); } function shouldEmitUnderscoreUnderscoreESModule() { @@ -48956,9 +48835,10 @@ var ts; addExportEqualsIfNeeded(statements, false); ts.addRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); } + ts.addEmitHelpers(updated, context.readEmitHelpers()); return updated; } function transformAMDModule(node) { @@ -49051,9 +48931,12 @@ var ts; addExportEqualsIfNeeded(statements, true); ts.addRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } return body; } function addExportEqualsIfNeeded(statements, emitAsReturn) { @@ -49088,14 +48971,49 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 298: + case 290: return visitMergeDeclarationMarker(node); - case 299: + case 291: return visitEndOfDeclarationMarker(node); default: - return node; + return ts.visitEachChild(node, importCallExpressionVisitor, context); } } + function importCallExpressionVisitor(node) { + if (!(node.transformFlags & 67108864)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else { + return ts.visitEachChild(node, importCallExpressionVisitor, context); + } + } + function visitImportCallExpression(node) { + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return transformImportCallExpressionAMD(node); + case ts.ModuleKind.UMD: + return transformImportCallExpressionUMD(node); + case ts.ModuleKind.CommonJS: + default: + return transformImportCallExpressionCommonJS(node); + } + } + function transformImportCallExpressionUMD(node) { + needUMDDynamicImportHelper = true; + return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); + } + function transformImportCallExpressionAMD(node) { + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + } + function transformImportCallExpressionCommonJS(node) { + return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); + } function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); @@ -49186,11 +49104,7 @@ var ts; return ts.singleOrMany(statements); } else { - return ts.setTextRange(ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ])), node); + return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } function visitExportAssignment(node) { @@ -49211,10 +49125,10 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, node.parameters, undefined, node.body), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49228,10 +49142,10 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, node.heritageClauses, node.members), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49268,7 +49182,7 @@ var ts; } } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49281,10 +49195,10 @@ var ts; } function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(node, undefined, context, 0, false, createExportExpression); + return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), undefined, context, 0, false, createExportExpression); } else { - return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), node.initializer); + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); } } function visitMergeDeclarationMarker(node) { @@ -49381,7 +49295,7 @@ var ts; } function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -49562,7 +49476,18 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), undefined, [module]); + } + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; })(ts || (ts = {})); var ts; @@ -49594,7 +49519,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; } var id = ts.getOriginalNodeId(node); @@ -49699,7 +49624,7 @@ var ts; if (moduleInfo.exportedNames) { for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { var exportedLocalName = _c[_b]; - if (exportedLocalName.text === "default") { + if (exportedLocalName.escapedText === "default") { continue; } exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); @@ -49716,7 +49641,7 @@ var ts; } for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -49773,7 +49698,7 @@ var ts; var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, true)]))); } @@ -49832,7 +49757,7 @@ var ts; if (node.isExportEquals) { return undefined; } - var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); @@ -49844,10 +49769,10 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); } else { - hoistedStatements = ts.append(hoistedStatements, node); + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49862,7 +49787,7 @@ var ts; var statements; var name = ts.getLocalName(node); hoistVariableDeclaration(name); - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement)), node))), node)); + statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); @@ -49874,7 +49799,7 @@ var ts; } function visitVariableStatement(node) { if (!shouldHoistVariableDeclarationList(node.declarationList)) { - return ts.visitNode(node, destructuringVisitor, ts.isStatement); + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); } var expressions; var isExportedDeclaration = ts.hasModifier(node, 1); @@ -49922,8 +49847,8 @@ var ts; function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) - ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); } function createExportedVariableAssignment(name, value, location) { return createVariableAssignment(name, value, location, true); @@ -50018,7 +49943,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = decl.name.text; + excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -50032,7 +49957,7 @@ var ts; if (ts.hasModifier(decl, 1)) { var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); - excludeName = exportName.text; + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); } if (decl.name) { statements = appendExportsOfDeclaration(statements, decl, excludeName); @@ -50044,11 +49969,11 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; - if (exportSpecifier.name.text !== excludeName) { + if (exportSpecifier.name.escapedText !== excludeName) { statements = appendExportStatement(statements, exportSpecifier.name, name); } } @@ -50107,32 +50032,32 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 298: + case 290: return visitMergeDeclarationMarker(node); - case 299: + case 291: return visitEndOfDeclarationMarker(node); default: - return destructuringVisitor(node); + return destructuringAndImportCallVisitor(node); } } function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -50157,19 +50082,19 @@ var ts; } } function visitDoStatement(node) { - return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } function visitWhileStatement(node) { - return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitLabeledStatement(node) { return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitWithStatement(node) { - return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitSwitchStatement(node) { - return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); } function visitCaseBlock(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; @@ -50179,7 +50104,7 @@ var ts; return node; } function visitCaseClause(node) { - return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); } function visitDefaultClause(node) { return ts.visitEachChild(node, nestedElementVisitor, context); @@ -50201,29 +50126,35 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } - function destructuringVisitor(node) { + function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 && node.kind === 194) { return visitDestructuringAssignment(node); } - else if (node.transformFlags & 2048) { - return ts.visitEachChild(node, destructuringVisitor, context); + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048) || (node.transformFlags & 67108864)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { return node; } } + function visitImportCallExpression(node) { + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); + } function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { - return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, true); + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, true); } - return ts.visitEachChild(node, destructuringVisitor, context); + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } function hasExportedReferenceInDestructuringTarget(node) { if (ts.isAssignmentExpression(node, true)) { return hasExportedReferenceInDestructuringTarget(node.left); } - else if (ts.isSpreadExpression(node)) { + else if (ts.isSpreadElement(node)) { return hasExportedReferenceInDestructuringTarget(node.expression); } else if (ts.isObjectLiteralExpression(node)) { @@ -50463,6 +50394,7 @@ var ts; (function (ts) { function getModuleTransformer(moduleKind) { switch (moduleKind) { + case ts.ModuleKind.ESNext: case ts.ModuleKind.ES2015: return ts.transformES2015Module; case ts.ModuleKind.System: @@ -50471,18 +50403,6 @@ 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); @@ -50515,7 +50435,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300); + var enabledSyntaxKindFeatures = new Array(292); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -50609,7 +50529,7 @@ var ts; function hoistVariableDeclaration(name) { ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); - var decl = ts.createVariableDeclaration(name); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64); if (!lexicalEnvironmentVariableDeclarations) { lexicalEnvironmentVariableDeclarations = [decl]; } @@ -50721,7 +50641,7 @@ var ts; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSourceFile; + var currentSource; var currentSourceText; var sourceMapDir; var sourceMapSourceIndex; @@ -50741,6 +50661,9 @@ var ts; getText: getText, getSourceMappingURL: getSourceMappingURL, }; + function skipSourceTrivia(pos) { + return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); + } function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { if (disabled) { return; @@ -50748,7 +50671,7 @@ var ts; if (sourceMapData) { reset(); } - currentSourceFile = undefined; + currentSource = undefined; currentSourceText = undefined; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; @@ -50791,7 +50714,7 @@ var ts; if (disabled) { return; } - currentSourceFile = undefined; + currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; lastRecordedSourceMapSpan = undefined; @@ -50834,7 +50757,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("beforeSourcemap"); } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); sourceLinePos.line++; sourceLinePos.character++; var emittedLine = writer.getLine(); @@ -50871,12 +50794,21 @@ var ts; if (node) { var emitNode = node.emitNode; var emitFlags = emitNode && emitNode.flags; - var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; - if (node.kind !== 295 + var range = emitNode && emitNode.sourceMapRange; + var _a = range || node, pos = _a.pos, end = _a.end; + var source = range && range.source; + var oldSource = currentSource; + if (source === oldSource) + source = undefined; + if (source) + setSourceFile(source); + if (node.kind !== 287 && (emitFlags & 16) === 0 && pos >= 0) { - emitPos(ts.skipTrivia(currentSourceText, pos)); + emitPos(skipSourceTrivia(pos)); } + if (source) + setSourceFile(oldSource); if (emitFlags & 64) { disabled = true; emitCallback(hint, node); @@ -50885,11 +50817,15 @@ var ts; else { emitCallback(hint, node); } - if (node.kind !== 295 + if (source) + setSourceFile(source); + if (node.kind !== 287 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); } + if (source) + setSourceFile(oldSource); } } function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { @@ -50899,7 +50835,7 @@ var ts; var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128) === 0 && tokenPos >= 0) { emitPos(tokenPos); } @@ -50915,17 +50851,17 @@ var ts; if (disabled) { return; } - currentSourceFile = sourceFile; - currentSourceText = currentSourceFile.text; + currentSource = sourceFile; + currentSourceText = currentSource.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); - sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSource.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSource.text); } } } @@ -51025,9 +50961,9 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295; - var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0; + var isEmittedNode = node.kind !== 287; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { emitLeadingComments(pos, isEmittedNode); } @@ -51440,7 +51376,7 @@ var ts; var writer = ts.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; @@ -51537,10 +51473,10 @@ var ts; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } - function reportIllegalExtends() { + function reportPrivateInBaseOfClassExpression(propertyName) { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleThisError() { @@ -51553,14 +51489,17 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); var shouldUseResolverType = declaration.kind === 146 && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { emitType(type); } else { errorNameNode = declaration.name; - var format = 2 | 1024 | - (shouldUseResolverType ? 4096 : 0); + var format = 4 | + 16384 | + 2048 | + (shouldUseResolverType ? 8192 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -51573,7 +51512,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 2048 | 16384, writer); errorNameNode = undefined; } } @@ -51803,7 +51742,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 2048 | 16384, writer); write(";"); writeLine(); return tempVarName; @@ -52268,7 +52207,7 @@ var ts; if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { tempVarName = baseTypeNode.expression.kind === 95 ? "null" : - emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name @@ -52888,6 +52827,50 @@ var ts; (function (ts) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getOutputExtension(sourceFile, options) { + if (options.jsx === 1) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + return ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + return ".jsx"; + } + } + return ".js"; + } + function getOriginalSourceFileOrBundle(sourceFileOrBundle) { + if (sourceFileOrBundle.kind === 266) { + return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); + } + return ts.getOriginalSourceFile(sourceFileOrBundle); + } function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -52914,7 +52897,7 @@ var ts; onSetSourceFile: setSourceFile, }); ts.performance.mark("beforePrint"); - ts.forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); transform.dispose(); return { @@ -52934,7 +52917,7 @@ var ts; emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -53330,6 +53313,8 @@ var ts; return emitModuleBlock(node); case 235: return emitCaseBlock(node); + case 236: + return emitNamespaceExportDeclaration(node); case 237: return emitImportEqualsDeclaration(node); case 238: @@ -53409,6 +53394,7 @@ var ts; case 97: case 101: case 99: + case 91: writeTokenNode(node); return; case 177: @@ -53469,9 +53455,9 @@ var ts; return emitJsxElement(node); case 250: return emitJsxSelfClosingElement(node); - case 296: + case 288: return emitPartiallyEmittedExpression(node); - case 297: + case 289: return emitCommaList(node); } } @@ -53548,6 +53534,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -53567,6 +53554,7 @@ var ts; emitModifiers(node, node.modifiers); writeIfPresent(node.asteriskToken, "*"); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -53626,7 +53614,7 @@ var ts; function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); - emitParametersForArrow(node, node.parameters); + emitParameters(node, node.parameters); write(" => "); emit(node.type); } @@ -53714,7 +53702,7 @@ var ts; } else { write("{"); - emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); + emitList(node, elements, 432); write("}"); } } @@ -54386,6 +54374,11 @@ var ts; } write(";"); } + function emitNamespaceExportDeclaration(node) { + write("export as namespace "); + emit(node.name); + write(";"); + } function emitNamedExports(node) { emitNamedImportsOrExports(node); } @@ -54485,6 +54478,9 @@ var ts; (ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (statements.length > 0) { + emitTrailingCommentsOfPosition(statements.pos); + } if (emitAsSingleStatement) { write(" "); emit(statements[0]); @@ -54574,7 +54570,7 @@ var ts; } emit(statement); if (seenPrologueDirectives) { - seenPrologueDirectives.set(statement.expression.text, statement.expression.text); + seenPrologueDirectives.set(statement.expression.text, true); } } } @@ -54618,7 +54614,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 256); + emitList(node, modifiers, 131328); write(" "); } } @@ -54664,11 +54660,24 @@ var ts; function emitParameters(parentNode, parameters) { emitList(parentNode, parameters, 1360); } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos + && !(ts.isArrowFunction(parentNode) && parentNode.type) + && !ts.some(parentNode.decorators) + && !ts.some(parentNode.modifiers) + && !ts.some(parentNode.typeParameters) + && !ts.some(parameter.decorators) + && !ts.some(parameter.modifiers) + && !parameter.dotDotDotToken + && !parameter.questionToken + && !parameter.type + && !parameter.initializer + && ts.isIdentifier(parameter.name); + } function emitParametersForArrow(parentNode, parameters) { - if (parameters && - parameters.length === 1 && - parameters[0].type === undefined && - parameters[0].pos === parentNode.pos) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { emit(parameters[0]); } else { @@ -54983,7 +54992,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeIdentifier(node.text); + return ts.unescapeLeadingUnderscores(node.escapedText); } else if (node.kind === 9 && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -55021,12 +55030,12 @@ var ts; } else { var autoGenerateId = name.autoGenerateId; - return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(makeName(name))); + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } function generateNameCached(node) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); } function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) @@ -55036,8 +55045,8 @@ var ts; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { - var local = node.locals.get(name); - if (local && local.flags & (107455 | 1048576 | 8388608)) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + if (local && local.flags & (107455 | 1048576 | 2097152)) { return false; } } @@ -55073,7 +55082,7 @@ var ts; while (true) { var generatedName = baseName + i; if (isUniqueName(generatedName)) { - generatedNames.set(generatedName, generatedName); + generatedNames.set(generatedName, true); return generatedName; } i++; @@ -55085,8 +55094,8 @@ var ts; } function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); } function generateNameForExportDefault() { @@ -55132,7 +55141,7 @@ var ts; case 2: return makeTempVariableName(268435456); case 3: - return makeUniqueName(ts.unescapeIdentifier(name.text)); + return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -55178,81 +55187,9 @@ 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) { - var emptyArray = []; var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -55465,9 +55402,9 @@ var ts; 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 start = diagnostic.start, length_6 = 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 _b = ts.getLineAndCharacterOfPosition(file, start + length_6), 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; @@ -55510,6 +55447,7 @@ var ts; 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); + output += ts.sys.newLine; } return output; } @@ -55578,11 +55516,12 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { if (!resolved || resolved.extension !== undefined) { return resolved; } @@ -55594,18 +55533,18 @@ var ts; else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); }; } else { var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } - var filesByName = ts.createFileMap(); - var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; + var filesByName = ts.createMap(); + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); @@ -55630,6 +55569,7 @@ var ts; } } } + var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); moduleResolutionCache = undefined; oldProgram = undefined; program = { @@ -55637,6 +55577,7 @@ var ts; getSourceFile: getSourceFile, getSourceFileByPath: getSourceFileByPath, getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, getOptionsDiagnostics: getOptionsDiagnostics, @@ -55663,6 +55604,9 @@ var ts; ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function getCommonSourceDirectory() { if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); @@ -55681,7 +55625,7 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); @@ -55737,7 +55681,7 @@ var ts; } var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) - : emptyArray; + : ts.emptyArray; if (!result) { ts.Debug.assert(resolutions.length === moduleNames.length); return resolutions; @@ -55822,6 +55766,9 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { oldProgram.structureIsReused = 1; } + if ((oldSourceFile.flags & 524288) !== (newSourceFile.flags & 524288)) { + oldProgram.structureIsReused = 1; + } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { oldProgram.structureIsReused = 1; } @@ -55865,13 +55812,20 @@ var ts; if (oldProgram.structureIsReused !== 2) { return oldProgram.structureIsReused; } + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 1; + } + for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { + var p = _e[_d]; + filesByName.set(p, undefined); + } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { - var modifiedFile = modifiedSourceFiles_2[_d]; + for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { + var modifiedFile = modifiedSourceFiles_2[_f]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -55908,7 +55862,7 @@ var ts; return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); } function isEmitBlocked(emitFileName) { - return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; @@ -55938,7 +55892,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return getSourceFileByPath(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { return filesByName.get(path); @@ -55947,14 +55901,12 @@ var ts; if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } - var allDiagnostics = []; - ts.forEach(program.getSourceFiles(), function (sourceFile) { + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } - ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); - }); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return getDiagnostics(sourceFile, cancellationToken); + })); } function getSyntacticDiagnostics(sourceFile, cancellationToken) { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); @@ -55975,6 +55927,9 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + if (ts.isCheckJsEnabledForFile(sourceFile, options)) { + sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); + } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -55998,13 +55953,13 @@ var ts; function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { - return emptyArray; + return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var bindDiagnostics = sourceFile.bindDiagnostics; - var includeCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); - var checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : []; + var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); @@ -56054,7 +56009,6 @@ var ts; case 186: case 228: case 187: - case 228: case 226: if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -56090,10 +56044,14 @@ var ts; case 232: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 184: - var typeAssertionExpression = node; - diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + case 203: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; + case 202: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 184: + ts.Debug.fail(); } var prevParent = parent; parent = node; @@ -56114,7 +56072,6 @@ var ts; case 186: case 228: case 187: - case 228: if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; @@ -56202,10 +56159,10 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; if (sourceFile) { if (!cache.perFile) { - cache.perFile = ts.createFileMap(); + cache.perFile = ts.createMap(); } cache.perFile.set(sourceFile.path, result); } @@ -56218,15 +56175,10 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); - ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); } function getGlobalDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { processSourceFile(ts.normalizePath(fileName), isDefaultLib); @@ -56261,13 +56213,13 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, false); - if (isJavaScriptFile) { - collectRequireCalls(node); + if ((file.flags & 524288) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(node); } } - file.imports = imports || emptyArray; - file.moduleAugmentations = moduleAugmentations || emptyArray; - file.ambientModuleNames = ambientModules || emptyArray; + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { @@ -56275,7 +56227,7 @@ var ts; case 237: case 244: var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || moduleNameExpr.kind !== 9) { + if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; } if (!moduleNameExpr.text) { @@ -56288,12 +56240,13 @@ var ts; case 233: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { if (file.isDeclarationFile) { - (ambientModules || (ambientModules = [])).push(moduleName.text); + (ambientModules || (ambientModules = [])).push(nameText); } var body = node.body; if (body) { @@ -56306,17 +56259,20 @@ var ts; } } } - function collectRequireCalls(node) { + function collectDynamicImportOrRequireCalls(node) { if (ts.isRequireCall(node, true)) { (imports || (imports = [])).push(node.arguments[0]); } + else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9) { + (imports || (imports = [])).push(node.arguments[0]); + } else { - ts.forEachChild(node, collectRequireCalls); + ts.forEachChild(node, collectDynamicImportOrRequireCalls); } } } function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -56351,7 +56307,7 @@ var ts; } } 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) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -56369,7 +56325,7 @@ var ts; } } function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(path)) { + if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); @@ -56404,12 +56360,13 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { - var existingFile = filesByNameIgnoreCase.get(path); + var pathLowerCase = path.toLowerCase(); + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(path, file); + filesByNameIgnoreCase.set(pathLowerCase, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -56517,7 +56474,7 @@ var ts; modulesWithElidedImports.set(file.path, true); } else if (shouldAddFile) { - var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); } @@ -56560,28 +56517,28 @@ var ts; function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); } if (options.noEmitOnError) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); } if (options.out) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); } if (options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); } } if (options.inlineSourceMap) { if (options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); } if (options.mapRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); } } if (options.paths && options.baseUrl === undefined) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } if (options.paths) { for (var key in options.paths) { @@ -56589,64 +56546,65 @@ var ts; continue; } if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + createDiagnosticForOptionPaths(true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); } - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var subst = _a[_i]; + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); } } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); } } } if (!options.sourceMap && !options.inlineSourceMap) { if (options.inlineSources) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); } if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); } } if (options.out && options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } if (options.mapRoot && !options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); } if (options.declarationDir) { if (!options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); } if (options.out || options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.lib && options.noLib) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; 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)); + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { @@ -56660,7 +56618,7 @@ var ts; } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); @@ -56672,33 +56630,33 @@ var ts; options.mapRoot) { var dir = getCommonSourceDirectory(); if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } if (!options.noEmit && options.allowJs && options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } if (options.jsxFactory) { if (options.reactNamespace) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); } if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); } } else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); } if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); @@ -56706,8 +56664,8 @@ var ts; } function verifyEmitFilePath(emitFileName, emitFilesSeen) { if (emitFileName) { - var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); - if (filesByName.contains(emitFilePath)) { + var emitFilePath = toPath(emitFileName); + if (filesByName.has(emitFilePath)) { var chain_1; if (!options.configFilePath) { chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); @@ -56715,17 +56673,96 @@ var ts; chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } - if (emitFilesSeen.contains(emitFilePath)) { + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + if (emitFilesSeen.has(emitFileKey)) { blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { - emitFilesSeen.set(emitFilePath, true); + emitFilesSeen.set(emitFileKey, true); } } } } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + if (ts.isArrayLiteralExpression(keyProps.initializer) && + keyProps.initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionPathsSyntax() { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + } + return ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2) { + createDiagnosticForOption(true, option1, option2, message, option1, option2); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(false, option1, undefined, message, arg0); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; + if (options.configFile && options.configFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + } + return !!props.length; + } function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } } @@ -56733,14 +56770,14 @@ var ts; function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { - case ts.Extension.Ts: - case ts.Extension.Dts: + case ".ts": + case ".d.ts": return undefined; - case ts.Extension.Tsx: + case ".tsx": return needJsx(); - case ts.Extension.Jsx: + case ".jsx": return needJsx() || needAllowJs(); - case ts.Extension.Js: + case ".js": return needAllowJs(); } function needJsx() { @@ -56751,6 +56788,10 @@ var ts; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; + function checkAllDefined(names) { + ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); + return names; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -56844,11 +56885,12 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES2015, "es2015": ts.ModuleKind.ES2015, + "esnext": ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, }, { name: "lib", @@ -57341,6 +57383,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, { name: "plugins", type: "list", @@ -57411,12 +57459,14 @@ var ts; optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; return optionNameMapCache; } - ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } function parseCustomTypeOption(opt, value, errors) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } @@ -57445,7 +57495,6 @@ var ts; var options = {}; var fileNames = []; var errors = []; - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; parseStrings(commandLine); return { options: options, @@ -57461,12 +57510,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - var short = shortOptionNames.get(s); - if (short !== undefined) { - s = short; - } - var opt = optionNameMap.get(s); + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -57550,36 +57594,234 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } function readConfigFile(fileName, readFile) { - var text = ""; + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; try { text = readFile(fileName); } catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return parseConfigFileTextToJson(fileName, text); + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; } - ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } - try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]); } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; + return _tsconfigRootOptions; + } + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, undefined, undefined); + } + ts.convertToObject = convertToObject; + function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.jsonObject) { + return {}; + } + return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 261) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined" && typeof value !== "undefined") { + result[keyText] = value; + if (jsonConversionNotifier && + (parentOption || knownOptions === knownRootOptions)) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (knownOptions === knownRootOptions) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 86: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95: + reportInvalidOptionValue(!!option); + return null; + case 9: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + var text = valueExpression.text; + if (option && typeof option.type !== "string") { + var customOption = option; + if (!customOption.type.has(text)) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 178: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); + } + case 177: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + if (option) { + reportInvalidOptionValue(true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + } + } + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + typeof option.type === "string" ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = typeof option.type === "string" ? option.type : "string"; + return typeof value === expectedType; } } - ts.parseConfigFileTextToJson = parseConfigFileTextToJson; function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition) { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { @@ -57600,35 +57842,33 @@ var ts; }); } function serializeCompilerOptions(options) { - var result = {}; + var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name in options) { + var _loop_5 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - continue; + return "continue"; } var value = options[name]; var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - result[name] = value; + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + result.set(name, value); } else { if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name] = convertedValue; + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { - result[name] = getNameOfCompilerOptionValue(value, customTypeMap); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } + }; + for (var name in options) { + _loop_5(name); } return result; } @@ -57645,37 +57885,37 @@ var ts; case "object": return {}; default: - return ts.arrayFrom(option.type.keys())[0]; + return option.type.keys().next().value; } } function makePadding(paddingLength) { return Array(paddingLength + 1).join(" "); } function writeConfigurations() { - var categorizedOptions = ts.reduceLeft(ts.filter(ts.optionDeclarations, function (o) { return o.category !== ts.Diagnostics.Command_line_Options && o.category !== ts.Diagnostics.Advanced_Options; }), function (memo, value) { - if (value.category) { - var name = ts.getLocaleSpecificMessage(value.category); - (memo[name] || (memo[name] = [])).push(value); + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); } - return memo; - }, {}); + } var marginLength = 0; var seenKnownKeys = 0; var nameColumn = []; var descriptionColumn = []; - var knownKeysCount = ts.getOwnKeys(configurations.compilerOptions).length; - for (var category in categorizedOptions) { + categorizedOptions.forEach(function (options, category) { if (nameColumn.length !== 0) { nameColumn.push(""); descriptionColumn.push(""); } nameColumn.push("/* " + category + " */"); descriptionColumn.push(""); - for (var _i = 0, _a = categorizedOptions[category]; _i < _a.length; _i++) { - var option = _a[_i]; + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; var optionName = void 0; - if (ts.hasProperty(configurations.compilerOptions, option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(configurations.compilerOptions[option.name]) + ((seenKnownKeys += 1) === knownKeysCount ? "" : ","); + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); } else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; @@ -57684,7 +57924,7 @@ var ts; descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); marginLength = Math.max(optionName.length, marginLength); } - } + }); var tab = makePadding(2); var result = []; result.push("{"); @@ -57692,13 +57932,13 @@ var ts; for (var i = 0; i < nameColumn.length; i++) { var optionName = nameColumn[i]; var description = descriptionColumn[i]; - result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description); + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); } - if (configurations.files && configurations.files.length) { + if (fileNames.length) { result.push(tab + "},"); result.push(tab + "\"files\": ["); - for (var i = 0; i < configurations.files.length; i++) { - result.push("" + tab + tab + JSON.stringify(configurations.files[i]) + (i === configurations.files.length - 1 ? "" : ",")); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); } result.push(tab + "]"); } @@ -57710,169 +57950,250 @@ var ts; } } ts.generateTSConfig = generateTSConfig; - function removeComments(jsonText) { - var output = ""; - var scanner = ts.createScanner(1, false, 0, jsonText); - var token; - while ((token = scanner.scan()) !== 1) { - switch (token) { - case 2: - case 3: - output += scanner.getTokenText().replace(/\S/g, " "); - break; - default: - output += scanner.getTokenText(); - break; - } - } - return output; - } function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - 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); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + setConfigFileInOptions(options, sourceFile); var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typeAcquisition: typeAcquisition, - raw: json, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + compileOnSave: !!raw.compileOnSave }; function getFileNames() { var fileNames; - if (ts.hasProperty(json, "files")) { - if (ts.isArray(json["files"])) { - fileNames = json["files"]; + if (ts.hasProperty(raw, "files")) { + if (ts.isArray(raw["files"])) { + fileNames = raw["files"]; if (fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); } } var includeSpecs; - if (ts.hasProperty(json, "include")) { - if (ts.isArray(json["include"])) { - includeSpecs = json["include"]; + if (ts.hasProperty(raw, "include")) { + if (ts.isArray(raw["include"])) { + includeSpecs = raw["include"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(json, "exclude")) { - if (ts.isArray(json["exclude"])) { - excludeSpecs = json["exclude"]; + if (ts.hasProperty(raw, "exclude")) { + if (ts.isArray(raw["exclude"])) { + excludeSpecs = raw["exclude"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; + var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - excludeSpecs.push(outDir); + specs.push(outDir); } + excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); - if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } return result; } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } } - ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + function parseConfig(json, sourceFile, 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 }; + return { raw: json || convertToObject(sourceFile, errors) }; } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + if (ownConfig.extendedConfigPath) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { 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; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; 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); + if (typeof json.extends !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } - return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - 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")); + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); 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); + 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, extended)); + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return undefined; } } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); 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 }; + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; + return undefined; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); if (typeof result === "boolean" && result) { @@ -57880,7 +58201,6 @@ var ts; } return false; } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -57893,15 +58213,23 @@ var ts; return { options: options, errors: errors }; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultCompilerOptions(configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultTypeAcquisition(configFileName) { var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return options; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; @@ -57910,7 +58238,7 @@ var ts; if (!jsonOptions) { return; } - var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); + var optionNameMap = commandLineOptionsToMap(optionDeclarations); for (var id in jsonOptions) { var opt = optionNameMap.get(id); if (opt) { @@ -57922,28 +58250,41 @@ var ts; } } function convertJsonOption(opt, value, basePath, errors) { - var optType = opt.type; - var expectedType = typeof optType === "string" ? optType : "string"; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); - } - else if (typeof value === expectedType) { - if (typeof optType !== "string") { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (typeof optType !== "string") { return convertJsonOptionOfCustomType(opt, value, errors); } - else { - if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; - } - } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType)); + else if (typeof option.type !== "string") { + return option.type.get(value); } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); @@ -57966,16 +58307,16 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); if (include) { - include = validateSpecs(include, errors, false); + include = validateSpecs(include, errors, false, jsonSourceFile, "include"); } if (exclude) { - exclude = validateSpecs(exclude, errors, true); + exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); @@ -57987,7 +58328,7 @@ var ts; } } if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { var file = _b[_a]; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; @@ -58006,24 +58347,40 @@ var ts; wildcardDirectories: wildcardDirectories }; } - function validateSpecs(specs, errors, allowTrailingRecursion) { + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { var validSpecs = []; for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { var spec = specs_1[_i]; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else { validSpecs.push(spec); } } return validSpecs; + function createDiagnostic(message, spec) { + if (jsonSourceFile && jsonSourceFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isArrayLiteralExpression(property.initializer)) { + for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (ts.isStringLiteral(element) && element.text === spec) { + return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); + } + } + } + } + } + return ts.createCompilerDiagnostic(message, spec); + } } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); @@ -58049,7 +58406,7 @@ var ts; } } } - for (var key in wildcardDirectories) + for (var key in wildcardDirectories) { if (ts.hasProperty(wildcardDirectories, key)) { for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { var recursiveKey = recursiveKeys_1[_a]; @@ -58058,6 +58415,7 @@ var ts; } } } + } } return wildcardDirectories; } @@ -58101,6 +58459,40 @@ var ts; function caseInsensitiveKeyMapper(key) { return key.toLowerCase(); } + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": + return ""; + case "string": + return ""; + case "number": + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -58149,7 +58541,7 @@ var ts; ts.sys.write(ts.formatDiagnostics([diagnostic], host)); } function reportDiagnosticWithColorAndContext(diagnostic, host) { - ts.sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + ts.sys.newLine + ts.sys.newLine); + ts.sys.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + ts.sys.newLine); } function reportWatchDiagnostic(diagnostic) { var output = new Date().toLocaleTimeString() + " - "; @@ -58280,20 +58672,11 @@ var ts; ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); return; } - var result = ts.parseConfigFileTextToJson(configFileName, cachedConfigFileText); - var configObject = result.config; - if (!configObject) { - reportDiagnostics([result.error], undefined); - ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; - } + var result = ts.parseJsonText(configFileName, cachedConfigFileText); + reportDiagnostics(result.parseDiagnostics, undefined); var cwd = ts.sys.getCurrentDirectory(); - var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd)); - if (configParseResult.errors.length > 0) { - reportDiagnostics(configParseResult.errors, undefined); - ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; - } + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, ts.sys, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), commandLine.options, ts.getNormalizedAbsolutePath(configFileName, cwd)); + reportDiagnostics(configParseResult.errors, undefined); if (ts.isWatchSet(configParseResult.options)) { if (!ts.sys.watchFile) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), undefined); @@ -58333,6 +58716,15 @@ var ts; } setCachedProgram(compileResult.program); reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); + var missingPaths = compileResult.program.getMissingFilePaths(); + missingPaths.forEach(function (path) { + var fileWatcher = ts.sys.watchFile(path, function (_fileName, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Created) { + fileWatcher.close(); + startTimerForRecompilation(); + } + }); + }); } function cachedFileExists(fileName) { var fileExists = cachedExistingFiles.get(fileName); @@ -58350,7 +58742,7 @@ var ts; } var sourceFile = hostGetSourceFile(fileName, languageVersion, onError); if (sourceFile && ts.isWatchSet(compilerOptions) && ts.sys.watchFile) { - sourceFile.fileWatcher = ts.sys.watchFile(sourceFile.fileName, function (_fileName, removed) { return sourceFileChanged(sourceFile, removed); }); + sourceFile.fileWatcher = ts.sys.watchFile(sourceFile.fileName, function (_fileName, eventKind) { return sourceFileChanged(sourceFile, eventKind); }); } return sourceFile; } @@ -58368,10 +58760,10 @@ var ts; } cachedProgram = program; } - function sourceFileChanged(sourceFile, removed) { + function sourceFileChanged(sourceFile, eventKind) { sourceFile.fileWatcher.close(); sourceFile.fileWatcher = undefined; - if (removed) { + if (eventKind === ts.FileWatcherEventKind.Deleted) { ts.unorderedRemoveItem(rootFileNames, sourceFile.fileName); } startTimerForRecompilation(); @@ -58612,9 +59004,10 @@ var ts; return; } })(ts || (ts = {})); +if (ts.Debug.isDebugging) { + ts.Debug.enableDebugInfo(); +} if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { ts.sys.tryEnableSourceMapsForHost(); } ts.executeCommandLine(ts.sys.args); - -//# sourceMappingURL=tsc.js.map diff --git a/lib/tsserver.js b/lib/tsserver.js index 0e99abde9da..e5ab8924285 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -13,6 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +"use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; @@ -305,37 +306,29 @@ var ts; 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["JSDocNullableType"] = 270] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -362,9 +355,9 @@ var ts; 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[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -388,6 +381,8 @@ var ts; NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -504,18 +499,20 @@ var ts; (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[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -577,13 +574,11 @@ var ts; 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["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -608,14 +603,13 @@ var ts; 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["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "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 = {})); @@ -638,6 +632,25 @@ var ts; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); var NodeCheckFlags; (function (NodeCheckFlags) { NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; @@ -734,6 +747,18 @@ var ts; IndexKind[IndexKind["String"] = 0] = "String"; IndexKind[IndexKind["Number"] = 1] = "Number"; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; + InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; @@ -762,6 +787,7 @@ var ts; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); var JsxEmit; (function (JsxEmit) { @@ -783,6 +809,7 @@ var ts; ScriptKind[ScriptKind["TS"] = 3] = "TS"; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -938,12 +965,11 @@ var ts; })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { - Extension[Extension["Ts"] = 0] = "Ts"; - Extension[Extension["Tsx"] = 1] = "Tsx"; - Extension[Extension["Dts"] = 2] = "Dts"; - Extension[Extension["Js"] = 3] = "Js"; - Extension[Extension["Jsx"] = 4] = "Jsx"; - Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; })(Extension = ts.Extension || (ts.Extension = {})); var TransformFlags; (function (TransformFlags) { @@ -976,6 +1002,7 @@ var ts; TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; @@ -1050,13 +1077,14 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; 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[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1127,7 +1155,8 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.0"; + ts.versionMajorMinor = "2.5"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { var Ternary; @@ -1148,12 +1177,28 @@ var ts; return new MapCtr(); } ts.createMap = createMap; + function createUnderscoreEscapedMap() { + return new MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function createSymbolTable(symbols) { + var result = createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; function createMapFromTemplate(template) { var map = new MapCtr(); - for (var key in template) + for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); } + } return map; } ts.createMapFromTemplate = createMapFromTemplate; @@ -1223,45 +1268,6 @@ var ts; return class_1; }()); } - function createFileMap(keyMapper) { - var files = createMap(); - return { - get: get, - set: set, - contains: contains, - remove: remove, - forEachValue: forEachValueInMap, - getKeys: getKeys, - clear: clear, - }; - function forEachValueInMap(f) { - files.forEach(function (file, key) { - f(key, file); - }); - } - function getKeys() { - return arrayFrom(files.keys()); - } - function get(path) { - return files.get(toKey(path)); - } - function set(path, value) { - files.set(toKey(path), value); - } - function contains(path) { - return files.has(toKey(path)); - } - function remove(path) { - files.delete(toKey(path)); - } - function clear() { - files.clear(); - } - function toKey(path) { - return keyMapper ? keyMapper(path) : path; - } - } - ts.createFileMap = createFileMap; function toPath(fileName, basePath, getCanonicalFileName) { var nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) @@ -1456,6 +1462,10 @@ var ts; array.length = outIndex; } ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; function map(array, f) { var result; if (array) { @@ -1525,6 +1535,19 @@ var ts; return result; } ts.flatMap = flatMap; + function flatMapIter(iter, mapfn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapfn(value); + if (res) + result.push.apply(result, res); + } + return result; + } + ts.flatMapIter = flatMapIter; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1547,6 +1570,18 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapDefined(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } + } + return result; + } + ts.mapDefined = mapDefined; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1740,12 +1775,21 @@ var ts; return to; } ts.append = append; - function addRange(to, from) { + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { if (from === undefined) return to; - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - to = append(to, v); + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + var v = from[i]; + if (v !== undefined) { + to.push(from[i]); + } } return to; } @@ -1768,16 +1812,22 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; function firstOrUndefined(array) { - return array && array.length > 0 - ? array[0] - : undefined; + return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { @@ -1882,10 +1932,11 @@ var ts; ts.getProperty = getProperty; function getOwnKeys(map) { var keys = []; - for (var key in map) + for (var key in map) { if (hasOwnProperty.call(map, key)) { keys.push(key); } + } return keys; } ts.getOwnKeys = getOwnKeys; @@ -1898,15 +1949,6 @@ var ts; var _b; } ts.arrayFrom = arrayFrom; - function convertToArray(iterator, f) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(f(value)); - } - return result; - var _b; - } - ts.convertToArray = convertToArray; function forEachEntry(map, callback) { var iterator = map.entries(); for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { @@ -1945,10 +1987,11 @@ var ts; } for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var arg = args_1[_a]; - for (var p in arg) + for (var p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; } + } } return t; } @@ -1958,18 +2001,20 @@ var ts; return true; if (!left || !right) return false; - for (var key in left) + for (var key in left) { if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } - for (var key in right) + } + for (var key in right) { if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } + } return true; } ts.equalOwnProperties = equalOwnProperties; @@ -1982,6 +2027,10 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToSet(array, makeKey) { + return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2000,14 +2049,16 @@ var ts; ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) + for (var id in second) { if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - for (var id in first) + } + for (var id in first) { if (hasOwnProperty.call(first, id)) { result[id] = first[id]; } + } return result; } ts.extend = extend; @@ -2041,6 +2092,16 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; function noop() { } ts.noop = noop; function notImplemented() { @@ -2358,10 +2419,18 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); + return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function moduleHasNonRelativeName(moduleName) { + return !isExternalModuleNameRelative(moduleName); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2464,7 +2533,7 @@ var ts; var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - directoryComponents.length--; + directoryComponents.pop(); } var joinStartIndex; for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { @@ -2588,7 +2657,7 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsAny(path, extensions) { + function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; if (fileExtensionIs(path, extension)) { @@ -2597,7 +2666,7 @@ var ts; } return false; } - ts.fileExtensionIsAny = fileExtensionIsAny; + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; @@ -2700,7 +2769,7 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -2712,17 +2781,16 @@ var ts; var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } return flatten(results); - function visitDirectory(path, absolutePath) { + function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; files = files.slice().sort(comparer); - directories = directories.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; @@ -2740,13 +2808,20 @@ var ts; var current = files_1[_i]; _loop_1(current); } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + directories = directories.slice().sort(comparer); for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { var current = directories_1[_b]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName); + visitDirectory(name, absoluteName, depth); } } } @@ -2784,7 +2859,7 @@ var ts; return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } function ensureScriptKind(fileName, scriptKind) { - return (scriptKind || getScriptKindFromFileName(fileName)) || 3; + return scriptKind || getScriptKindFromFileName(fileName) || 3; } ts.ensureScriptKind = ensureScriptKind; function getScriptKindFromFileName(fileName) { @@ -2798,6 +2873,8 @@ var ts; return 3; case ".tsx": return 4; + case ".json": + return 6; default: return 0; } @@ -2906,11 +2983,14 @@ var ts; ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; this.declarations = undefined; } - function Type(_checker, flags) { + function Type(checker, flags) { this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } } function Signature() { } @@ -2925,6 +3005,11 @@ var ts; this.parent = undefined; this.original = undefined; } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, getTokenConstructor: function () { return Node; }, @@ -2932,7 +3017,8 @@ var ts; getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, - getSignatureConstructor: function () { return Signature; } + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; var AssertionLevel; (function (AssertionLevel) { @@ -2944,25 +3030,43 @@ var ts; var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; + Debug.isDebugging = false; function shouldAssert(level) { return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo) { + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { - var verboseDebugString = ""; if (verboseDebugInfo) { - verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); } - debugger; - throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; - function fail(message) { - Debug.assert(false, message); + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; } Debug.fail = fail; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; })(Debug = ts.Debug || (ts.Debug = {})); function orderedRemoveItem(array, item) { for (var i = 0; i < array.length; i++) { @@ -3063,7 +3167,7 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; function extensionIsTypeScript(ext) { - return ext <= ts.Extension.LastTypeScriptExtension; + return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } ts.extensionIsTypeScript = extensionIsTypeScript; function extensionFromPath(path) { @@ -3075,21 +3179,7 @@ var ts; } ts.extensionFromPath = extensionFromPath; function tryGetExtensionFromPath(path) { - if (fileExtensionIs(path, ".d.ts")) { - return ts.Extension.Dts; - } - if (fileExtensionIs(path, ".ts")) { - return ts.Extension.Ts; - } - if (fileExtensionIs(path, ".tsx")) { - return ts.Extension.Tsx; - } - if (fileExtensionIs(path, ".js")) { - return ts.Extension.Js; - } - if (fileExtensionIs(path, ".jsx")) { - return ts.Extension.Jsx; - } + return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3099,6 +3189,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -3171,7 +3267,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName); + fileCallback(fileName, FileWatcherEventKind.Changed); } } } @@ -3184,7 +3280,13 @@ var ts; if (platform === "win32" || platform === "win64") { return false; } - return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + return !fileExists(swapCase(__filename)); + } + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); @@ -3257,8 +3359,8 @@ var ts; return { files: [], directories: [] }; } } - function readDirectory(path, extensions, excludes, includes) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -3310,10 +3412,19 @@ var ts; }; } function fileChanged(curr, prev) { - if (+curr.mtime <= +prev.mtime) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { return; } - callback(fileName); + callback(fileName, eventKind); } }, watchDirectory: function (directoryName, callback, recursive) { @@ -3333,9 +3444,7 @@ var ts; } }); }, - resolvePath: function (path) { - return _path.resolve(path); - }, + resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { @@ -3389,6 +3498,7 @@ var ts; realpath: function (path) { return _fs.realpathSync(path); }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { try { require("source-map-support").install(); @@ -3425,7 +3535,7 @@ var ts; getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), - readDirectory: function (path, extensions, excludes, includes) { + readDirectory: function (path, extensions, excludes, includes, _depth) { var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, @@ -3467,910 +3577,933 @@ var ts; ? 1 : 0; } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } })(ts || (ts = {})); var ts; (function (ts) { + function diag(code, category, key, message) { + return { code: code, category: category, key: key, message: message }; + } ts.Diagnostics = { - Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated_string_literal_1002", message: "Unterminated string literal." }, - Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_1003", message: "Identifier expected." }, - _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "_0_expected_1005", message: "'{0}' expected." }, - A_file_cannot_have_a_reference_to_itself: { code: 1006, category: ts.DiagnosticCategory.Error, key: "A_file_cannot_have_a_reference_to_itself_1006", message: "A file cannot have a reference to itself." }, - Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing_comma_not_allowed_1009", message: "Trailing comma not allowed." }, - Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "Asterisk_Slash_expected_1010", message: "'*/' expected." }, - Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_1012", message: "Unexpected token." }, - A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_last_in_a_parameter_list_1014", message: "A rest parameter must be last in a parameter list." }, - Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: ts.DiagnosticCategory.Error, key: "Parameter_cannot_have_question_mark_and_initializer_1015", message: "Parameter cannot have question mark and initializer." }, - A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: ts.DiagnosticCategory.Error, key: "A_required_parameter_cannot_follow_an_optional_parameter_1016", message: "A required parameter cannot follow an optional parameter." }, - An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: ts.DiagnosticCategory.Error, key: "An_index_signature_cannot_have_a_rest_parameter_1017", message: "An index signature cannot have a rest parameter." }, - An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", message: "An index signature parameter cannot have an accessibility modifier." }, - An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_a_question_mark_1019", message: "An index signature parameter cannot have a question mark." }, - An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_initializer_1020", message: "An index signature parameter cannot have an initializer." }, - An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, - An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, - An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, - readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, - Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, - _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, - _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, - _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_class_element_1031", message: "'{0}' modifier cannot appear on a class element." }, - super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: ts.DiagnosticCategory.Error, key: "super_must_be_followed_by_an_argument_list_or_member_access_1034", message: "'super' must be followed by an argument list or member access." }, - Only_ambient_modules_can_use_quoted_names: { code: 1035, category: ts.DiagnosticCategory.Error, key: "Only_ambient_modules_can_use_quoted_names_1035", message: "Only ambient modules can use quoted names." }, - Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: ts.DiagnosticCategory.Error, key: "Statements_are_not_allowed_in_ambient_contexts_1036", message: "Statements are not allowed in ambient contexts." }, - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", message: "A 'declare' modifier cannot be used in an already ambient context." }, - Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: ts.DiagnosticCategory.Error, key: "Initializers_are_not_allowed_in_ambient_contexts_1039", message: "Initializers are not allowed in ambient contexts." }, - _0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_in_an_ambient_context_1040", message: "'{0}' modifier cannot be used in an ambient context." }, - _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, - _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, - _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, - A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, - A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, - A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, - A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_have_an_initializer_1048", message: "A rest parameter cannot have an initializer." }, - A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_must_have_exactly_one_parameter_1049", message: "A 'set' accessor must have exactly one parameter." }, - A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_an_optional_parameter_1051", message: "A 'set' accessor cannot have an optional parameter." }, - A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, - A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, - A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, - An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, - The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", message: "The return type of an async function must either be a valid promise or must not contain a callable 'then' member." }, - A_promise_must_have_a_then_method: { code: 1059, category: ts.DiagnosticCategory.Error, key: "A_promise_must_have_a_then_method_1059", message: "A promise must have a 'then' method." }, - The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: { code: 1060, category: ts.DiagnosticCategory.Error, key: "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", message: "The first parameter of the 'then' method of a promise must be a callback." }, - Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, - Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, - An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, - In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, - Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, - _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, - _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, - A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, - Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." }, - An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_be_declared_in_an_ambient_context_1086", message: "An accessor cannot be declared in an ambient context." }, - _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", message: "'{0}' modifier cannot appear on a constructor declaration." }, - _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_parameter_1090", message: "'{0}' modifier cannot appear on a parameter." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", message: "Only a single variable declaration is allowed in a 'for...in' statement." }, - Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: ts.DiagnosticCategory.Error, key: "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", message: "Type parameters cannot appear on a constructor declaration." }, - Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: ts.DiagnosticCategory.Error, key: "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", message: "Type annotation cannot appear on a constructor declaration." }, - An_accessor_cannot_have_type_parameters: { code: 1094, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_have_type_parameters_1094", message: "An accessor cannot have type parameters." }, - A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_a_return_type_annotation_1095", message: "A 'set' accessor cannot have a return type annotation." }, - An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_exactly_one_parameter_1096", message: "An index signature must have exactly one parameter." }, - _0_list_cannot_be_empty: { code: 1097, category: ts.DiagnosticCategory.Error, key: "_0_list_cannot_be_empty_1097", message: "'{0}' list cannot be empty." }, - Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type_parameter_list_cannot_be_empty_1098", message: "Type parameter list cannot be empty." }, - Type_argument_list_cannot_be_empty: { code: 1099, category: ts.DiagnosticCategory.Error, key: "Type_argument_list_cannot_be_empty_1099", message: "Type argument list cannot be empty." }, - Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_in_strict_mode_1100", message: "Invalid use of '{0}' in strict mode." }, - with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_strict_mode_1101", message: "'with' statements are not allowed in strict mode." }, - delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", message: "'delete' cannot be called on an identifier in strict mode." }, - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: { code: 1103, category: ts.DiagnosticCategory.Error, key: "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", message: "A 'for-await-of' statement is only allowed within an async function or async generator." }, - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", message: "A 'continue' statement can only be used within an enclosing iteration statement." }, - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", message: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, - Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump_target_cannot_cross_function_boundary_1107", message: "Jump target cannot cross function boundary." }, - A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: ts.DiagnosticCategory.Error, key: "A_return_statement_can_only_be_used_within_a_function_body_1108", message: "A 'return' statement can only be used within a function body." }, - Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." }, - Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." }, - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", message: "A 'default' clause cannot appear more than once in a 'switch' statement." }, - Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'." }, - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", message: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", message: "A 'break' statement can only jump to a label of an enclosing statement." }, - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", message: "An object literal cannot have multiple properties with the same name in strict mode." }, - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", message: "An object literal cannot have multiple get/set accessors with the same name." }, - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", message: "An object literal cannot have property and accessor with the same name." }, - An_export_assignment_cannot_have_modifiers: { code: 1120, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_have_modifiers_1120", message: "An export assignment cannot have modifiers." }, - Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_strict_mode_1121", message: "Octal literals are not allowed in strict mode." }, - A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: ts.DiagnosticCategory.Error, key: "A_tuple_type_element_list_cannot_be_empty_1122", message: "A tuple type element list cannot be empty." }, - Variable_declaration_list_cannot_be_empty: { code: 1123, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_list_cannot_be_empty_1123", message: "Variable declaration list cannot be empty." }, - Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit_expected_1124", message: "Digit expected." }, - Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal_digit_expected_1125", message: "Hexadecimal digit expected." }, - Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected_end_of_text_1126", message: "Unexpected end of text." }, - Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid_character_1127", message: "Invalid character." }, - Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration_or_statement_expected_1128", message: "Declaration or statement expected." }, - Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement_expected_1129", message: "Statement expected." }, - case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "case_or_default_expected_1130", message: "'case' or 'default' expected." }, - Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property_or_signature_expected_1131", message: "Property or signature expected." }, - Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum_member_expected_1132", message: "Enum member expected." }, - Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_expected_1134", message: "Variable declaration expected." }, - Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument_expression_expected_1135", message: "Argument expression expected." }, - Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property_assignment_expected_1136", message: "Property assignment expected." }, - Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression_or_comma_expected_1137", message: "Expression or comma expected." }, - Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter_declaration_expected_1138", message: "Parameter declaration expected." }, - Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type_parameter_declaration_expected_1139", message: "Type parameter declaration expected." }, - Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type_argument_expected_1140", message: "Type argument expected." }, - String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, - Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, - or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, - Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, - File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing." }, - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, - const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized." }, - const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "const_declarations_can_only_be_declared_inside_a_block_1156", message: "'const' declarations can only be declared inside a block." }, - let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "let_declarations_can_only_be_declared_inside_a_block_1157", message: "'let' declarations can only be declared inside a block." }, - Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." }, - Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated_regular_expression_literal_1161", message: "Unterminated regular expression literal." }, - An_object_member_cannot_be_declared_optional: { code: 1162, category: ts.DiagnosticCategory.Error, key: "An_object_member_cannot_be_declared_optional_1162", message: "An object member cannot be declared optional." }, - A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: ts.DiagnosticCategory.Error, key: "A_yield_expression_is_only_allowed_in_a_generator_body_1163", message: "A 'yield' expression is only allowed in a generator body." }, - Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "Computed_property_names_are_not_allowed_in_enums_1164", message: "Computed property names are not allowed in enums." }, - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", message: "A computed property name in an ambient context must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", message: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", message: "A computed property name in a method overload must directly refer to a built-in symbol." }, - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", message: "A computed property name in an interface must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", message: "A computed property name in a type literal must directly refer to a built-in symbol." }, - A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: ts.DiagnosticCategory.Error, key: "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", message: "A comma expression is not allowed in a computed property name." }, - extends_clause_already_seen: { code: 1172, category: ts.DiagnosticCategory.Error, key: "extends_clause_already_seen_1172", message: "'extends' clause already seen." }, - extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "extends_clause_must_precede_implements_clause_1173", message: "'extends' clause must precede 'implements' clause." }, - Classes_can_only_extend_a_single_class: { code: 1174, category: ts.DiagnosticCategory.Error, key: "Classes_can_only_extend_a_single_class_1174", message: "Classes can only extend a single class." }, - implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "implements_clause_already_seen_1175", message: "'implements' clause already seen." }, - Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface_declaration_cannot_have_implements_clause_1176", message: "Interface declaration cannot have 'implements' clause." }, - Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary_digit_expected_1177", message: "Binary digit expected." }, - Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal_digit_expected_1178", message: "Octal digit expected." }, - Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_expected_1179", message: "Unexpected token. '{' expected." }, - Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property_destructuring_pattern_expected_1180", message: "Property destructuring pattern expected." }, - Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array_element_destructuring_pattern_expected_1181", message: "Array element destructuring pattern expected." }, - A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: ts.DiagnosticCategory.Error, key: "A_destructuring_declaration_must_have_an_initializer_1182", message: "A destructuring declaration must have an initializer." }, - An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1183, category: ts.DiagnosticCategory.Error, key: "An_implementation_cannot_be_declared_in_ambient_contexts_1183", message: "An implementation cannot be declared in ambient contexts." }, - Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, - Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, - A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, - The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, - The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, - An_import_declaration_cannot_have_modifiers: { code: 1191, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_cannot_have_modifiers_1191", message: "An import declaration cannot have modifiers." }, - Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, - An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, - Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, - Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, - An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, - Unterminated_Unicode_escape_sequence: { code: 1199, category: ts.DiagnosticCategory.Error, key: "Unterminated_Unicode_escape_sequence_1199", message: "Unterminated Unicode escape sequence." }, - 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." }, - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", message: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." }, - Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", message: "Invalid use of '{0}'. Class definitions are automatically in strict mode." }, - A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, - Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, - Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, - Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, - Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, - Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: ts.DiagnosticCategory.Error, key: "Generators_are_not_allowed_in_an_ambient_context_1221", message: "Generators are not allowed in an ambient context." }, - An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, - _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "_0_tag_already_specified_1223", message: "'{0}' tag already specified." }, - Signature_0_must_have_a_type_predicate: { code: 1224, category: ts.DiagnosticCategory.Error, key: "Signature_0_must_have_a_type_predicate_1224", message: "Signature '{0}' must have a type predicate." }, - Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot_find_parameter_0_1225", message: "Cannot find parameter '{0}'." }, - Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: ts.DiagnosticCategory.Error, key: "Type_predicate_0_is_not_assignable_to_1_1226", message: "Type predicate '{0}' is not assignable to '{1}'." }, - Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: ts.DiagnosticCategory.Error, key: "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", message: "Parameter '{0}' is not in the same position as parameter '{1}'." }, - A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", message: "A type predicate is only allowed in return type position for functions and methods." }, - A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_a_rest_parameter_1229", message: "A type predicate cannot reference a rest parameter." }, - A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", message: "A type predicate cannot reference element '{0}' in a binding pattern." }, - An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_can_only_be_used_in_a_module_1231", message: "An export assignment can only be used in a module." }, - An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", message: "An import declaration can only be used in a namespace or module." }, - An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_can_only_be_used_in_a_module_1233", message: "An export declaration can only be used in a module." }, - An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", message: "An ambient module declaration is only allowed at the top level in a file." }, - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", message: "A namespace declaration is only allowed in a namespace or module." }, - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", message: "The return type of a property decorator function must be either 'void' or 'any'." }, - The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", message: "The return type of a parameter decorator function must be either 'void' or 'any'." }, - Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", message: "Unable to resolve signature of class decorator when called as an expression." }, - Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, - Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, - Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, - _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, - Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, - Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, - An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, - A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, - A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, - A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: { code: 1250, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, - _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, - with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, - await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, - The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, - Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, - Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, - Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, - A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, - An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, - A_default_export_can_only_be_used_in_an_ECMAScript_style_module: { code: 1319, category: ts.DiagnosticCategory.Error, key: "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", message: "A default export can only be used in an ECMAScript-style module." }, - Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1320, category: ts.DiagnosticCategory.Error, key: "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", message: "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1321, category: ts.DiagnosticCategory.Error, key: "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", message: "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1322, category: ts.DiagnosticCategory.Error, key: "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", message: "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member." }, - Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, - Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, - Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, - Circular_definition_of_import_alias_0: { code: 2303, category: ts.DiagnosticCategory.Error, key: "Circular_definition_of_import_alias_0_2303", message: "Circular definition of import alias '{0}'." }, - Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_2304", message: "Cannot find name '{0}'." }, - Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, - File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, - Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, - Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, - An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, - Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, - A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, - An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, - Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, - Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, - Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, - Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_have_1_type_parameter_s_2317", message: "Global type '{0}' must have {1} type parameter(s)." }, - Cannot_find_global_type_0: { code: 2318, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_type_0_2318", message: "Cannot find global type '{0}'." }, - Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: ts.DiagnosticCategory.Error, key: "Named_property_0_of_types_1_and_2_are_not_identical_2319", message: "Named property '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, - Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, - Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, - Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, - Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, - Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: ts.DiagnosticCategory.Error, key: "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", message: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: ts.DiagnosticCategory.Error, key: "Types_of_parameters_0_and_1_are_incompatible_2328", message: "Types of parameters '{0}' and '{1}' are incompatible." }, - Index_signature_is_missing_in_type_0: { code: 2329, category: ts.DiagnosticCategory.Error, key: "Index_signature_is_missing_in_type_0_2329", message: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index_signatures_are_incompatible_2330", message: "Index signatures are incompatible." }, - this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", message: "'this' cannot be referenced in a module or namespace body." }, - this_cannot_be_referenced_in_current_location: { code: 2332, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_current_location_2332", message: "'this' cannot be referenced in current location." }, - this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_constructor_arguments_2333", message: "'this' cannot be referenced in constructor arguments." }, - this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_static_property_initializer_2334", message: "'this' cannot be referenced in a static property initializer." }, - super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_a_derived_class_2335", message: "'super' can only be referenced in a derived class." }, - super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_constructor_arguments_2336", message: "'super' cannot be referenced in constructor arguments." }, - Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: ts.DiagnosticCategory.Error, key: "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", message: "Super calls are not permitted outside constructors or in nested functions inside constructors." }, - super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: ts.DiagnosticCategory.Error, key: "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", message: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." }, - Property_0_does_not_exist_on_type_1: { code: 2339, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_2339", message: "Property '{0}' does not exist on type '{1}'." }, - Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, - Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, - An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, - 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}'." }, - 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." }, - Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, - Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, - Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, - Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, - The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, - The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter." }, - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, - Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, - Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, - Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'." }, - A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", message: "A parameter property is only allowed in a constructor implementation." }, - A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_of_an_array_type_2370", message: "A rest parameter must be of an array type." }, - A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", message: "A parameter initializer is only allowed in a function or constructor implementation." }, - Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: ts.DiagnosticCategory.Error, key: "Parameter_0_cannot_be_referenced_in_its_initializer_2372", message: "Parameter '{0}' cannot be referenced in its initializer." }, - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: ts.DiagnosticCategory.Error, key: "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", message: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, - Duplicate_string_index_signature: { code: 2374, category: ts.DiagnosticCategory.Error, key: "Duplicate_string_index_signature_2374", message: "Duplicate string index signature." }, - Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, - Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, - Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, - get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, - A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, - Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, - Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, - Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, - Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, - Function_overload_must_be_static: { code: 2387, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_be_static_2387", message: "Function overload must be static." }, - Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_not_be_static_2388", message: "Function overload must not be static." }, - Function_implementation_name_must_be_0: { code: 2389, category: ts.DiagnosticCategory.Error, key: "Function_implementation_name_must_be_0_2389", message: "Function implementation name must be '{0}'." }, - Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor_implementation_is_missing_2390", message: "Constructor implementation is missing." }, - Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: ts.DiagnosticCategory.Error, key: "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", message: "Function implementation is missing or not immediately following the declaration." }, - Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: ts.DiagnosticCategory.Error, key: "Multiple_constructor_implementations_are_not_allowed_2392", message: "Multiple constructor implementations are not allowed." }, - Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate_function_implementation_2393", message: "Duplicate function implementation." }, - Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, - Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, - Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, - Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, - Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, - Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, - Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", message: "Expression resolves to '_super' that compiler uses to capture base class reference." }, - Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, - The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, - The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, - Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, - Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class." }, - The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, - Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, - Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, - Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, - Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'." }, - Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, - A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, - Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'." }, - All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, - Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'." }, - In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, - A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged." }, - A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged." }, - Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", message: "Ambient modules cannot be nested in other modules or namespaces." }, - Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient_module_declaration_cannot_specify_relative_module_name_2436", message: "Ambient module declaration cannot specify relative module name." }, - Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name." }, - Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'." }, - Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", message: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." }, - Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." }, - Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types_have_separate_declarations_of_a_private_property_0_2442", message: "Types have separate declarations of a private property '{0}'." }, - Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", message: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." }, - Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", message: "Property '{0}' is protected in type '{1}' but public in type '{2}'." }, - Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", message: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, - The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, - Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - Class_0_used_before_its_declaration: { code: 2449, category: ts.DiagnosticCategory.Error, key: "Class_0_used_before_its_declaration_2449", message: "Class '{0}' used before its declaration." }, - Enum_0_used_before_its_declaration: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Enum_0_used_before_its_declaration_2450", message: "Enum '{0}' used before its declaration." }, - Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, - An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, - The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, - Variable_0_is_used_before_being_assigned: { code: 2454, category: ts.DiagnosticCategory.Error, key: "Variable_0_is_used_before_being_assigned_2454", message: "Variable '{0}' is used before being assigned." }, - Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", message: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, - Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type_alias_0_circularly_references_itself_2456", message: "Type alias '{0}' circularly references itself." }, - Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'." }, - An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An_AMD_module_cannot_have_multiple_name_assignments_2458", message: "An AMD module cannot have multiple name assignments." }, - Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, - Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, - Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern." }, - A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, - A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, - this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, - super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_a_computed_property_name_2466", message: "'super' cannot be referenced in a computed property name." }, - A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", message: "A computed property name cannot reference a type parameter from its containing type." }, - Cannot_find_global_value_0: { code: 2468, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_value_0_2468", message: "Cannot find global value '{0}'." }, - The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: ts.DiagnosticCategory.Error, key: "The_0_operator_cannot_be_applied_to_type_symbol_2469", message: "The '{0}' operator cannot be applied to type 'symbol'." }, - Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: ts.DiagnosticCategory.Error, key: "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", message: "'Symbol' reference does not refer to the global Symbol constructor object." }, - A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", message: "A computed property name of the form '{0}' must be of type 'symbol'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", message: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." }, - Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: ts.DiagnosticCategory.Error, key: "Enum_declarations_must_all_be_const_or_non_const_2473", message: "Enum declarations must all be const or non-const." }, - In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: ts.DiagnosticCategory.Error, key: "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", message: "In 'const' enum declarations member initializer must be constant expression." }, - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: ts.DiagnosticCategory.Error, key: "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", message: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." }, - A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: ts.DiagnosticCategory.Error, key: "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", message: "A const enum member can only be accessed using a string literal." }, - const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", message: "'const' enum member initializer was evaluated to a non-finite value." }, - const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", message: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, - Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_const_enum_1_2479", message: "Property '{0}' does not exist on 'const' enum '{1}'." }, - let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", message: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." }, - Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, - The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, - Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'." }, - The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, - An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, - The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", message: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." }, - Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause." }, - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", message: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." }, - Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", message: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." }, - Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_2495", message: "Type '{0}' is not an array type or a string type." }, - The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", message: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." }, - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: ts.DiagnosticCategory.Error, key: "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", message: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." }, - Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: ts.DiagnosticCategory.Error, key: "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", message: "Module '{0}' uses 'export =' and cannot be used with 'export *'." }, - An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", message: "An interface can only extend an identifier/qualified-name with optional type arguments." }, - A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", message: "A class can only implement an identifier/qualified-name with optional type arguments." }, - A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, - _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, - Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: { code: 2504, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", message: "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator." }, - A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, - _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, - Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, - No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: ts.DiagnosticCategory.Error, key: "No_base_constructor_has_the_specified_number_of_type_arguments_2508", message: "No base constructor has the specified number of type arguments." }, - Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, - Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, - Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, - Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, - Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, - Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, - All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, - Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, - A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, - An_async_iterator_must_have_a_next_method: { code: 2519, category: ts.DiagnosticCategory.Error, key: "An_async_iterator_must_have_a_next_method_2519", message: "An async iterator must have a 'next()' method." }, - Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, - Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, - yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, - await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, - A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, - A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, - Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, - Object_is_possibly_null: { code: 2531, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_2531", message: "Object is possibly 'null'." }, - Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, - Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, - A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, - Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, - Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, - Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, - Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, - The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, - Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, - Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, - Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, - A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, - The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: { code: 2547, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", message: "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property." }, - Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { 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." }, - Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'." }, - JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", message: "JSX element type '{0}' does not have any construct or call signatures." }, - JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", message: "JSX element type '{0}' is not a constructor function for JSX elements." }, - Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", message: "Property '{0}' of JSX spread attribute is not assignable to target property." }, - JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property." }, - The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property." }, - JSX_spread_child_must_be_an_array_type: { code: 2609, category: ts.DiagnosticCategory.Error, key: "JSX_spread_child_must_be_an_array_type_2609", message: "JSX spread child must be an array type." }, - Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: { code: 2649, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", message: "Cannot augment module '{0}' with value exports because it resolves to a non-module entity." }, - Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React." }, - A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", message: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." }, - Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", message: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, - Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", message: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." }, - Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, - Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, - JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element." }, - Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'." }, - super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, - super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, - Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", message: "Cannot export '{0}'. Only local declarations can be exported from a module." }, - Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, - Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, - Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, - Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, - Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, - Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, - export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, - Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, - Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, - Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, - Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, - Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, - Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, - Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, - Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, - A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: { code: 2677, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", message: "A type predicate's type must be assignable to its parameter's type." }, - Type_0_is_not_comparable_to_type_1: { code: 2678, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_comparable_to_type_1_2678", message: "Type '{0}' is not comparable to type '{1}'." }, - A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: { code: 2679, category: ts.DiagnosticCategory.Error, key: "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", message: "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'." }, - A_this_parameter_must_be_the_first_parameter: { code: 2680, category: ts.DiagnosticCategory.Error, key: "A_this_parameter_must_be_the_first_parameter_2680", message: "A 'this' parameter must be the first parameter." }, - A_constructor_cannot_have_a_this_parameter: { code: 2681, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_have_a_this_parameter_2681", message: "A constructor cannot have a 'this' parameter." }, - get_and_set_accessor_must_have_the_same_this_type: { code: 2682, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_this_type_2682", message: "'get' and 'set' accessor must have the same 'this' type." }, - this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, - The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, - The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, - All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, - Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, - Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, - Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, - The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, - Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, - Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: { code: 2699, category: ts.DiagnosticCategory.Error, key: "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", message: "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'." }, - Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, - The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, - The_operand_of_a_delete_operator_must_be_a_property_reference: { code: 2703, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", message: "The operand of a delete operator must be a property reference." }, - The_operand_of_a_delete_operator_cannot_be_a_read_only_property: { code: 2704, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", message: "The operand of a delete operator cannot be a read-only property." }, - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: { code: 2705, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", message: "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option." }, - Required_type_parameters_may_not_follow_optional_type_parameters: { code: 2706, category: ts.DiagnosticCategory.Error, key: "Required_type_parameters_may_not_follow_optional_type_parameters_2706", message: "Required type parameters may not follow optional type parameters." }, - Generic_type_0_requires_between_1_and_2_type_arguments: { code: 2707, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_between_1_and_2_type_arguments_2707", message: "Generic type '{0}' requires between {1} and {2} type arguments." }, - Cannot_use_namespace_0_as_a_value: { code: 2708, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_value_2708", message: "Cannot use namespace '{0}' as a value." }, - Cannot_use_namespace_0_as_a_type: { code: 2709, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_type_2709", message: "Cannot use namespace '{0}' as a type." }, - _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: { code: 2710, category: ts.DiagnosticCategory.Error, key: "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", message: "'{0}' are specified twice. The attribute named '{0}' will be overwritten." }, - Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, - Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, - Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", message: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", message: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", message: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", message: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", message: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", message: "Type parameter '{0}' of exported function has or is using private name '{1}'." }, - Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", message: "Implements clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "'extends' clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "'extends' clause of exported interface '{0}' has or is using private name '{1}'." }, - Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", message: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." }, - Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", message: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." }, - Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_private_name_1_4025", message: "Exported variable '{0}' has or is using private name '{1}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", message: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", message: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", message: "Public static property '{0}' of exported class has or is using private name '{1}'." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", message: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", message: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", message: "Public property '{0}' of exported class has or is using private name '{1}'." }, - Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", message: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." }, - Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", message: "Property '{0}' of exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", message: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", message: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", message: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", message: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", message: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", message: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", message: "Return type of public static property getter from exported class has or is using private name '{0}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", message: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", message: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", message: "Return type of public property getter from exported class has or is using private name '{0}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", message: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", message: "Return type of constructor signature from exported interface has or is using private name '{0}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", message: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", message: "Return type of call signature from exported interface has or is using private name '{0}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", message: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", message: "Return type of index signature from exported interface has or is using private name '{0}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", message: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", message: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", message: "Return type of public static method from exported class has or is using private name '{0}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", message: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", message: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", message: "Return type of public method from exported class has or is using private name '{0}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", message: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", message: "Return type of method from exported interface has or is using private name '{0}'." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", message: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", message: "Return type of exported function has or is using name '{0}' from private module '{1}'." }, - Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", message: "Return type of exported function has or is using private name '{0}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", message: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", message: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", message: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", message: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", message: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", message: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", message: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", message: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", message: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", message: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", message: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, - Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, - Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced: { code: 4093, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced_4093", message: "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced." }, - The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, - Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, - File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, - Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}." }, - Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, - Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "Unknown compiler option '{0}'." }, - Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_requires_a_value_of_type_1_5024", message: "Compiler option '{0}' requires a value of type {1}." }, - Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}." }, - Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", message: "Option 'project' cannot be mixed with source files on a command line." }, - Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher." }, - Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", message: "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." }, - Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, - Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, - A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, - Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, - Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, - Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'." }, - The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'." }, - Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, - Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, - Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character." }, - Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character." }, - Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, - Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, - File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, - Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, - Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, - Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, - Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, - Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", message: "Specify the location where debugger should locate TypeScript files instead of source locations." }, - Watch_input_files: { code: 6005, category: ts.DiagnosticCategory.Message, key: "Watch_input_files_6005", message: "Watch input files." }, - Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect_output_structure_to_the_directory_6006", message: "Redirect output structure to the directory." }, - Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: ts.DiagnosticCategory.Message, key: "Do_not_erase_const_enum_declarations_in_generated_code_6007", message: "Do not erase const enum declarations in generated code." }, - Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, - Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, - Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, - Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, - Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'." }, - Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'." }, - Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, - Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, - Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", message: "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'." }, - Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" }, - options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" }, - file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" }, - Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples_Colon_0_6026", message: "Examples: {0}" }, - Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options_Colon_6027", message: "Options:" }, - Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version_0_6029", message: "Version {0}" }, - Insert_command_line_options_and_files_from_a_file: { code: 6030, category: ts.DiagnosticCategory.Message, key: "Insert_command_line_options_and_files_from_a_file_6030", message: "Insert command line options and files from a file." }, - File_change_detected_Starting_incremental_compilation: { code: 6032, category: ts.DiagnosticCategory.Message, key: "File_change_detected_Starting_incremental_compilation_6032", message: "File change detected. Starting incremental compilation..." }, - KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND_6034", message: "KIND" }, - FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE_6035", message: "FILE" }, - VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, - LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, - DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, - STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, - FILE_OR_DIRECTORY: { code: 6040, category: ts.DiagnosticCategory.Message, key: "FILE_OR_DIRECTORY_6040", message: "FILE OR DIRECTORY" }, - Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, - Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, - Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, - Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}." }, - Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, - Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, - Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." }, - Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted_locale_file_0_6051", message: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", message: "Raise error on expressions and declarations with an implied 'any' type." }, - File_0_not_found: { code: 6053, category: ts.DiagnosticCategory.Error, key: "File_0_not_found_6053", message: "File '{0}' not found." }, - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: ts.DiagnosticCategory.Error, key: "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", message: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, - Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: ts.DiagnosticCategory.Message, key: "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", message: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, - Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", message: "Do not emit declarations for code that has an '@internal' annotation." }, - Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: ts.DiagnosticCategory.Message, key: "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", message: "Specify the root directory of input files. Use to control the output directory structure with --outDir." }, - File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", message: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, - Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", message: "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, - NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, - Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, - Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, - Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, - Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, - Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: { code: 6069, category: ts.DiagnosticCategory.Message, key: "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", message: "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)." }, - Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, - Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, - Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context (experimental)." }, - Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, - Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, - Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, - Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, - Specify_library_files_to_be_included_in_the_compilation_Colon: { code: 6079, category: ts.DiagnosticCategory.Message, key: "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", message: "Specify library files to be included in the compilation: " }, - Specify_JSX_code_generation_Colon_preserve_react_native_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", message: "Specify JSX code generation: 'preserve', 'react-native', or 'react'." }, - File_0_has_an_unsupported_extension_so_skipping_it: { code: 6081, category: ts.DiagnosticCategory.Message, key: "File_0_has_an_unsupported_extension_so_skipping_it_6081", message: "File '{0}' has an unsupported extension, so skipping it." }, - Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, - Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, - Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", message: "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit" }, - Enable_tracing_of_the_name_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_name_resolution_process_6085", message: "Enable tracing of the name resolution process." }, - Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, - Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, - Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, - Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, - Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, - paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, - Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, - Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, - Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, - Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", message: "Loading module as file / folder, candidate module location '{0}', target file type '{1}'." }, - File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, - File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, - Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, - Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, - package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, - Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, - Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, - Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, - Expected_type_of_0_field_in_package_json_to_be_string_got_1: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", message: "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'." }, - baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'." }, - rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'." }, - Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'." }, - Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'." }, - Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'." }, - Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed." }, - Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, - Enable_strict_null_checks: { code: 6113, category: ts.DiagnosticCategory.Message, key: "Enable_strict_null_checks_6113", message: "Enable strict null checks." }, - Unknown_option_excludes_Did_you_mean_exclude: { code: 6114, category: ts.DiagnosticCategory.Error, key: "Unknown_option_excludes_Did_you_mean_exclude_6114", message: "Unknown option 'excludes'. Did you mean 'exclude'?" }, - Raise_error_on_this_expressions_with_an_implied_any_type: { code: 6115, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_this_expressions_with_an_implied_any_type_6115", message: "Raise error on 'this' expressions with an implied 'any' type." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_2: { code: 6116, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========" }, - Resolving_using_primary_search_paths: { code: 6117, category: ts.DiagnosticCategory.Message, key: "Resolving_using_primary_search_paths_6117", message: "Resolving using primary search paths..." }, - Resolving_from_node_modules_folder: { code: 6118, category: ts.DiagnosticCategory.Message, key: "Resolving_from_node_modules_folder_6118", message: "Resolving from node_modules folder..." }, - Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: { code: 6119, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", message: "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========" }, - Type_reference_directive_0_was_not_resolved: { code: 6120, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_not_resolved_6120", message: "======== Type reference directive '{0}' was not resolved. ========" }, - Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'." }, - Root_directory_cannot_be_determined_skipping_primary_search_paths: { code: 6122, category: ts.DiagnosticCategory.Message, key: "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", message: "Root directory cannot be determined, skipping primary search paths." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: { code: 6123, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========" }, - Type_declaration_files_to_be_included_in_compilation: { code: 6124, category: ts.DiagnosticCategory.Message, key: "Type_declaration_files_to_be_included_in_compilation_6124", message: "Type declaration files to be included in compilation." }, - Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'." }, - Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: { code: 6126, category: ts.DiagnosticCategory.Message, key: "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", message: "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder." }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: { code: 6127, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", message: "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========" }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, - The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, - Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'." }, - Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, - File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it." }, - _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - 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}'." }, - Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file." }, - Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, - Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, - Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, - Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, - Resolution_for_module_0_was_found_in_cache: { code: 6147, category: ts.DiagnosticCategory.Message, key: "Resolution_for_module_0_was_found_in_cache_6147", message: "Resolution for module '{0}' was found in cache." }, - Directory_0_does_not_exist_skipping_all_lookups_in_it: { code: 6148, category: ts.DiagnosticCategory.Message, key: "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", message: "Directory '{0}' does not exist, skipping all lookups in it." }, - Show_diagnostic_information: { code: 6149, category: ts.DiagnosticCategory.Message, key: "Show_diagnostic_information_6149", message: "Show diagnostic information." }, - Show_verbose_diagnostic_information: { code: 6150, category: ts.DiagnosticCategory.Message, key: "Show_verbose_diagnostic_information_6150", message: "Show verbose diagnostic information." }, - Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: { code: 6151, category: ts.DiagnosticCategory.Message, key: "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", message: "Emit a single file with source maps instead of having a separate file." }, - Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: { code: 6152, category: ts.DiagnosticCategory.Message, key: "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", message: "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set." }, - Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: { code: 6153, category: ts.DiagnosticCategory.Message, key: "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", message: "Transpile each file as a separate module (similar to 'ts.transpileModule')." }, - Print_names_of_generated_files_part_of_the_compilation: { code: 6154, category: ts.DiagnosticCategory.Message, key: "Print_names_of_generated_files_part_of_the_compilation_6154", message: "Print names of generated files part of the compilation." }, - Print_names_of_files_part_of_the_compilation: { code: 6155, category: ts.DiagnosticCategory.Message, key: "Print_names_of_files_part_of_the_compilation_6155", message: "Print names of files part of the compilation." }, - The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: { code: 6156, category: ts.DiagnosticCategory.Message, key: "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", message: "The locale used when displaying messages to the user (e.g. 'en-us')" }, - Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: { code: 6157, category: ts.DiagnosticCategory.Message, key: "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", message: "Do not generate custom helper functions like '__extends' in compiled output." }, - Do_not_include_the_default_library_file_lib_d_ts: { code: 6158, category: ts.DiagnosticCategory.Message, key: "Do_not_include_the_default_library_file_lib_d_ts_6158", message: "Do not include the default library file (lib.d.ts)." }, - Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: { code: 6159, category: ts.DiagnosticCategory.Message, key: "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", message: "Do not add triple-slash references or imported modules to the list of compiled files." }, - Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: { code: 6160, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", message: "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files." }, - List_of_folders_to_include_type_definitions_from: { code: 6161, category: ts.DiagnosticCategory.Message, key: "List_of_folders_to_include_type_definitions_from_6161", message: "List of folders to include type definitions from." }, - Disable_size_limitations_on_JavaScript_projects: { code: 6162, category: ts.DiagnosticCategory.Message, key: "Disable_size_limitations_on_JavaScript_projects_6162", message: "Disable size limitations on JavaScript projects." }, - The_character_set_of_the_input_files: { code: 6163, category: ts.DiagnosticCategory.Message, key: "The_character_set_of_the_input_files_6163", message: "The character set of the input files." }, - Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: { code: 6164, category: ts.DiagnosticCategory.Message, key: "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", message: "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files." }, - Do_not_truncate_error_messages: { code: 6165, category: ts.DiagnosticCategory.Message, key: "Do_not_truncate_error_messages_6165", message: "Do not truncate error messages." }, - Output_directory_for_generated_declaration_files: { code: 6166, category: ts.DiagnosticCategory.Message, key: "Output_directory_for_generated_declaration_files_6166", message: "Output directory for generated declaration files." }, - A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: { code: 6167, category: ts.DiagnosticCategory.Message, key: "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", message: "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'." }, - List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: { code: 6168, category: ts.DiagnosticCategory.Message, key: "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", message: "List of root folders whose combined content represents the structure of the project at runtime." }, - Show_all_compiler_options: { code: 6169, category: ts.DiagnosticCategory.Message, key: "Show_all_compiler_options_6169", message: "Show all compiler options." }, - Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: { code: 6170, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", message: "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file" }, - Command_line_Options: { code: 6171, category: ts.DiagnosticCategory.Message, key: "Command_line_Options_6171", message: "Command-line Options" }, - Basic_Options: { code: 6172, category: ts.DiagnosticCategory.Message, key: "Basic_Options_6172", message: "Basic Options" }, - Strict_Type_Checking_Options: { code: 6173, category: ts.DiagnosticCategory.Message, key: "Strict_Type_Checking_Options_6173", message: "Strict Type-Checking Options" }, - Module_Resolution_Options: { code: 6174, category: ts.DiagnosticCategory.Message, key: "Module_Resolution_Options_6174", message: "Module Resolution Options" }, - Source_Map_Options: { code: 6175, category: ts.DiagnosticCategory.Message, key: "Source_Map_Options_6175", message: "Source Map Options" }, - Additional_Checks: { code: 6176, category: ts.DiagnosticCategory.Message, key: "Additional_Checks_6176", message: "Additional Checks" }, - Experimental_Options: { code: 6177, category: ts.DiagnosticCategory.Message, key: "Experimental_Options_6177", message: "Experimental Options" }, - Advanced_Options: { code: 6178, category: ts.DiagnosticCategory.Message, key: "Advanced_Options_6178", message: "Advanced Options" }, - Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: { code: 6179, category: ts.DiagnosticCategory.Message, key: "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", message: "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'." }, - 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." }, - new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: ts.DiagnosticCategory.Error, key: "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", message: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, - _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, - Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, - Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, - Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, - Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, - Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, - Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", message: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." }, - _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: { code: 7023, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", message: "'{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." }, - 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: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "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." }, - Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, - JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists." }, - Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, - Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, - Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, - Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, - Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, - Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: { code: 7035, category: ts.DiagnosticCategory.Error, key: "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", message: "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`" }, - You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, - You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, - import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, - export_can_only_be_used_in_a_ts_file: { code: 8003, category: ts.DiagnosticCategory.Error, key: "export_can_only_be_used_in_a_ts_file_8003", message: "'export=' can only be used in a .ts file." }, - type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: ts.DiagnosticCategory.Error, key: "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", message: "'type parameter declarations' can only be used in a .ts file." }, - implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: ts.DiagnosticCategory.Error, key: "implements_clauses_can_only_be_used_in_a_ts_file_8005", message: "'implements clauses' can only be used in a .ts file." }, - interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: ts.DiagnosticCategory.Error, key: "interface_declarations_can_only_be_used_in_a_ts_file_8006", message: "'interface declarations' can only be used in a .ts file." }, - module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: ts.DiagnosticCategory.Error, key: "module_declarations_can_only_be_used_in_a_ts_file_8007", message: "'module declarations' can only be used in a .ts file." }, - type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: ts.DiagnosticCategory.Error, key: "type_aliases_can_only_be_used_in_a_ts_file_8008", message: "'type aliases' can only be used in a .ts file." }, - _0_can_only_be_used_in_a_ts_file: { code: 8009, category: ts.DiagnosticCategory.Error, key: "_0_can_only_be_used_in_a_ts_file_8009", message: "'{0}' can only be used in a .ts file." }, - types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, - type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, - parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, - type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, - Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, - JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, - JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, - Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, - JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "JSX attribute expected." }, - Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, - A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'." }, - An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, - super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, - super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, - _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: { code: 17012, category: ts.DiagnosticCategory.Error, key: "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", message: "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" }, - Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: { code: 17013, category: ts.DiagnosticCategory.Error, key: "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", message: "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." }, - Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, - The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, - No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, - Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, - Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, - Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'." }, - Remove_declaration_for_Colon_0: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_declaration_for_Colon_0_90004", message: "Remove declaration for: '{0}'." }, - Implement_interface_0: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_0_90006", message: "Implement interface '{0}'." }, - Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class." }, - Add_this_to_unresolved_variable: { code: 90008, category: ts.DiagnosticCategory.Message, key: "Add_this_to_unresolved_variable_90008", message: "Add 'this.' to unresolved variable." }, - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig." }, - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, - Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}." }, - Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}." }, - Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}." }, - Add_declaration_for_missing_property_0: { code: 90016, category: ts.DiagnosticCategory.Message, key: "Add_declaration_for_missing_property_0_90016", message: "Add declaration for missing property '{0}'." }, - Add_index_signature_for_missing_property_0: { code: 90017, category: ts.DiagnosticCategory.Message, key: "Add_index_signature_for_missing_property_0_90017", message: "Add index signature for missing property '{0}'." }, - Disable_checking_for_this_file: { code: 90018, category: ts.DiagnosticCategory.Message, key: "Disable_checking_for_this_file_90018", message: "Disable checking for this file." }, - 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." }, + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), + A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), + A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), + A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), + A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "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: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "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: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "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: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "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: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), + Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "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: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _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: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{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."), + 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), }; })(ts || (ts = {})); var ts; @@ -4402,10 +4535,6 @@ var ts; failedLookupLocations: failedLookupLocations }; } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); @@ -4472,11 +4601,7 @@ var ts; var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: traceEnabled - }; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -4583,7 +4708,7 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createFileMap(); + var directoryToModuleNameMap = ts.createMap(); var moduleNameToDirectoryMap = ts.createMap(); return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { @@ -4596,7 +4721,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (!moduleHasNonRelativeName(nonRelativeModuleName)) { + if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { return undefined; } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); @@ -4607,14 +4732,14 @@ var ts; return perModuleNameCache; } function createPerModuleNameCache() { - var directoryPathMap = ts.createFileMap(); + var directoryPathMap = ts.createMap(); return { get: get, set: set }; function get(directory) { return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); } function set(directory, result) { var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); - if (directoryPathMap.contains(path)) { + if (directoryPathMap.has(path)) { return; } directoryPathMap.set(path, result); @@ -4623,7 +4748,7 @@ var ts; var current = path; while (true) { var parent = ts.getDirectoryPath(current); - if (parent === current || directoryPathMap.contains(parent)) { + if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); @@ -4707,7 +4832,7 @@ var ts; } ts.resolveModuleName = resolveModuleName; function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); } else { @@ -4802,10 +4927,12 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } - var tsExtension = ts.tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); - return path_1 && { path: path_1, extension: tsExtension }; + if (path_1 !== undefined) { + return { path: path_1, extension: extension }; + } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); }); @@ -4846,7 +4973,7 @@ var ts; if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } @@ -4927,14 +5054,14 @@ var ts; } switch (extensions) { case Extensions.DtsOnly: - return tryExtension(".d.ts", ts.Extension.Dts); + return tryExtension(".d.ts"); case Extensions.TypeScript: - return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); case Extensions.JavaScript: - return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + return tryExtension(".js") || tryExtension(".jsx"); } - function tryExtension(ext, extension) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + function tryExtension(extension) { + var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); return path && { path: path, extension: extension }; } } @@ -5004,11 +5131,11 @@ var ts; function extensionIsOk(extensions, extension) { switch (extensions) { case Extensions.JavaScript: - return extension === ts.Extension.Js || extension === ts.Extension.Jsx; + return extension === ".js" || extension === ".jsx"; case Extensions.TypeScript: - return extension === ts.Extension.Ts || extension === ts.Extension.Tsx || extension === ts.Extension.Dts; + return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; case Extensions.DtsOnly: - return extension === ts.Extension.Dts; + return extension === ".d.ts"; } } function pathToPackageJson(directory) { @@ -5060,9 +5187,10 @@ var ts; return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); } } + var mangledScopedPackageSeparator = "__"; function mangleScopedPackage(moduleName, state) { if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, "__"); + var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== moduleName) { var mangled = replaceSlash.slice(1); if (state.traceEnabled) { @@ -5073,6 +5201,16 @@ var ts; } return moduleName; } + function getPackageNameFromAtTypesDirectory(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -5095,7 +5233,7 @@ var ts; return { value: resolvedUsingSettings }; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { @@ -5148,6 +5286,8 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.emptyArray = []; + ts.emptyMap = ts.createMap(); ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -5175,48 +5315,49 @@ var ts; return undefined; } ts.findDeclaration = findDeclaration; - var stringWriters = []; - function getSingleLineStringWriter() { - if (stringWriters.length === 0) { - var str_1 = ""; - var writeText = function (text) { return str_1 += text; }; - return { - string: function () { return str_1; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { return str_1 = ""; }, - trackSymbol: ts.noop, - reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop - }; + var stringWriter = createSingleLineStringWriter(); + var stringWriterAcquired = false; + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + string: function () { return str; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function usingSingleLineStringWriter(action) { + try { + ts.Debug.assert(!stringWriterAcquired); + stringWriterAcquired = true; + action(stringWriter); + return stringWriter.string(); + } + finally { + stringWriter.clear(); + stringWriterAcquired = false; } - return stringWriters.pop(); } - ts.getSingleLineStringWriter = getSingleLineStringWriter; - function releaseStringWriter(writer) { - writer.clear(); - stringWriters.push(writer); - } - ts.releaseStringWriter = releaseStringWriter; + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; function getFullWidth(node) { return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText)); - } - ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { - return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined; + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); } ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { @@ -5341,34 +5482,22 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function isToken(n) { - return n.kind >= 0 && n.kind <= 142; - } - ts.isToken = isToken; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { if (nodeIsMissing(node)) { return node.pos; } - if (isJSDocNode(node)) { + if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); } if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { return getTokenPosOfNode(node.jsDoc[0]); } - if (node.kind === 294 && node._children.length > 0) { + if (node.kind === 286 && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; - function isJSDocNode(node) { - return node.kind >= 267 && node.kind <= 293; - } - ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 283 && node.kind <= 293; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -5397,11 +5526,16 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; switch (node.kind) { case 9: return '"' + escapeText(node.text) + '"'; @@ -5423,8 +5557,12 @@ var ts; return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } ts.getTextOfConstantValue = getTextOfConstantValue; + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; function escapeIdentifier(identifier) { - return identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier; + return identifier; } ts.escapeIdentifier = escapeIdentifier; function makeIdentifierFromModuleName(moduleName) { @@ -5446,6 +5584,10 @@ var ts; (node.name.kind === 9 || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); } @@ -5456,7 +5598,7 @@ var ts; function isBlockScopedContainerTopLevel(node) { return node.kind === 265 || node.kind === 233 || - isFunctionLike(node); + ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { @@ -5498,7 +5640,7 @@ var ts; case 187: return true; case 207: - return parentNode && !isFunctionLike(parentNode); + return parentNode && !ts.isFunctionLike(parentNode); } return false; } @@ -5524,13 +5666,13 @@ var ts; function getTextOfPropertyName(name) { switch (name.kind) { case 71: - return name.text; + return name.escapedText; case 9: case 8: - return name.text; + return escapeLeadingUnderscores(name.text); case 144: if (isStringOrNumericLiteral(name.expression)) { - return name.expression.text; + return escapeLeadingUnderscores(name.expression.text); } } return undefined; @@ -5539,7 +5681,7 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71: - return getFullWidth(name) === 0 ? ts.unescapeIdentifier(name.text) : getTextOfNode(name); + return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); case 143: return entityNameToString(name.left) + "." + entityNameToString(name.right); case 179: @@ -5646,6 +5788,10 @@ var ts; return n.kind === 181 && n.expression.kind === 97; } ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 181 && n.expression.kind === 91; + } + ts.isImportCall = isImportCall; function isPrologueDirective(node) { return node.kind === 210 && node.expression.kind === 9; @@ -5663,7 +5809,8 @@ var ts; var commentRanges = (node.kind === 146 || node.kind === 145 || node.kind === 186 || - node.kind === 187) ? + node.kind === 187 || + node.kind === 185) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); return ts.filter(commentRanges, function (comment) { @@ -5756,10 +5903,6 @@ var ts; return false; } ts.isChildOfNodeWithKind = isChildOfNodeWithKind; - function isPrefixUnaryExpression(node) { - return node.kind === 192; - } - ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { @@ -5805,7 +5948,7 @@ var ts; case 199: return; default: - if (isFunctionLike(node)) { + if (ts.isFunctionLike(node)) { var name = node.name; if (name && name.kind === 144) { traverse(name.expression); @@ -5848,47 +5991,6 @@ var ts; return false; } ts.isVariableLike = isVariableLike; - function isAccessor(node) { - return node && (node.kind === 153 || node.kind === 154); - } - ts.isAccessor = isAccessor; - function isClassLike(node) { - return node && (node.kind === 229 || node.kind === 199); - } - ts.isClassLike = isClassLike; - function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); - } - ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { - switch (kind) { - case 152: - case 186: - case 228: - case 187: - case 151: - case 150: - case 153: - case 154: - case 155: - case 156: - case 157: - case 160: - case 161: - return true; - } - 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: @@ -5903,20 +6005,6 @@ var ts; return false; } ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; - function isIterationStatement(node, lookInLabeledStatements) { - switch (node.kind) { - case 214: - case 215: - case 216: - case 212: - case 213: - return true; - case 222: - return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); - } - return false; - } - ts.isIterationStatement = isIterationStatement; function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { while (true) { if (beforeUnwrapLabelCallback) { @@ -5930,7 +6018,7 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 && isFunctionLike(node.parent); + return node && node.kind === 207 && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { @@ -5951,10 +6039,19 @@ var ts; return predicate && predicate.kind === 0; } ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return ts.filter(objectLiteral.properties, function (property) { + if (property.kind === 261) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (key2 && key2 === propName); + } + }); + } + ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { while (true) { node = node.parent; - if (!node || isFunctionLike(node)) { + if (!node || ts.isFunctionLike(node)) { return node; } } @@ -5963,7 +6060,7 @@ var ts; function getContainingClass(node) { while (true) { node = node.parent; - if (!node || isClassLike(node)) { + if (!node || ts.isClassLike(node)) { return node; } } @@ -5977,16 +6074,16 @@ var ts; } switch (node.kind) { case 144: - if (isClassLike(node.parent.parent)) { + if (ts.isClassLike(node.parent.parent)) { return node; } node = node.parent; break; case 147: - if (node.parent.kind === 146 && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { node = node.parent; } break; @@ -6052,10 +6149,10 @@ var ts; case 154: return node; case 147: - if (node.parent.kind === 146 && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { node = node.parent; } break; @@ -6086,7 +6183,6 @@ var ts; function getEntityNameFromTypeNode(node) { switch (node.kind) { case 159: - case 277: return node.typeName; case 201: return isEntityNameExpression(node.expression) @@ -6099,29 +6195,11 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; - function isCallLikeExpression(node) { - switch (node.kind) { - case 251: - case 250: - case 181: - case 182: - case 183: - case 147: - return true; - default: - return false; - } - } - 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; } - else if (isJsxOpeningLikeElement(node)) { + else if (ts.isJsxOpeningLikeElement(node)) { return node.tagName; } return node.expression; @@ -6179,7 +6257,6 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 99: case 97: case 95: case 101: @@ -6247,7 +6324,6 @@ var ts; case 221: case 257: case 223: - case 221: return parent.expression === node; case 214: var forStatement = parent; @@ -6282,12 +6358,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isInstantiatedModule(node, preserveConstEnums) { - var moduleState = ts.getModuleInstanceState(node); - return moduleState === 1 || - (preserveConstEnums && moduleState === 2); - } - ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 && node.moduleReference.kind === 248; } @@ -6309,12 +6379,16 @@ var ts; return node && !!(node.flags & 65536); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJSDoc(node) { + return node && !!(node.flags & 1048576); + } + ts.isInJSDoc = isInJSDoc; function isRequireCall(callExpression, checkArgumentIsStringLiteral) { if (callExpression.kind !== 181) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 || expression.text !== "require") { + if (expression.kind !== 71 || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -6344,11 +6418,11 @@ var ts; } ts.getRightMostAssignedExpression = getRightMostAssignedExpression; function isExportsIdentifier(node) { - return isIdentifier(node) && node.text === "exports"; + return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; function isModuleExportsPropertyAccessExpression(node) { - return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports"; + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; function getSpecialPropertyAssignmentKind(expression) { @@ -6362,10 +6436,10 @@ var ts; var lhs = expr.left; if (lhs.expression.kind === 71) { var lhsId = lhs.expression; - if (lhsId.text === "exports") { + if (lhsId.escapedText === "exports") { return 1; } - else if (lhsId.text === "module" && lhs.name.text === "exports") { + else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { return 2; } else { @@ -6379,10 +6453,10 @@ var ts; var innerPropertyAccess = lhs.expression; if (innerPropertyAccess.expression.kind === 71) { var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { + if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { return 1; } - if (innerPropertyAccess.name.text === "prototype") { + if (innerPropertyAccess.name.escapedText === "prototype") { return 3; } } @@ -6441,52 +6515,40 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 279 && + return node.kind === 273 && node.parameters.length > 0 && - node.parameters[0].type.kind === 281; + node.parameters[0].name && + node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getCommentsFromJSDoc(node) { - return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); - } - ts.getCommentsFromJSDoc = getCommentsFromJSDoc; function hasJSDocParameterTags(node) { - var parameterTags = getJSDocTags(node, 286); - return parameterTags && parameterTags.length > 0; + return !!getFirstJSDocTag(node, 279); } ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getJSDocTags(node, kind) { - var docs = getJSDocs(node); - if (docs) { - var result = []; - for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { - var doc = docs_1[_i]; - if (doc.kind === 286) { - if (doc.kind === kind) { - result.push(doc); - } - } - else { - var tags = doc.tags; - if (tags) { - result.push.apply(result, ts.filter(tags, function (tag) { return tag.kind === kind; })); - } - } - } - return result; - } - } function getFirstJSDocTag(node, kind) { - return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); } - function getJSDocs(node) { - var cache = node.jsDocCache; - if (!cache) { - getJSDocsWorker(node); - node.jsDocCache = cache; + function getAllJSDocs(node) { + if (ts.isJSDocTypedefTag(node)) { + return [node.parent]; } - return cache; - function getJSDocsWorker(node) { + return getJSDocCommentsAndTags(node); + } + ts.getAllJSDocs = getAllJSDocs; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getJSDocCommentsAndTags(node) { + var result; + getJSDocCommentsAndTagsWorker(node); + return result || ts.emptyArray; + function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && parent.initializer === node && @@ -6497,55 +6559,65 @@ var ts; isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - getJSDocsWorker(variableStatementNode); + getJSDocCommentsAndTagsWorker(variableStatementNode); } var isSourceOfAssignmentExpressionStatement = parent && parent.parent && parent.kind === 194 && parent.operatorToken.kind === 58 && parent.parent.kind === 210; if (isSourceOfAssignmentExpressionStatement) { - getJSDocsWorker(parent.parent); + getJSDocCommentsAndTagsWorker(parent.parent); } var isModuleDeclaration = node.kind === 233 && parent && parent.kind === 233; var isPropertyAssignmentExpression = parent && parent.kind === 261; if (isModuleDeclaration || isPropertyAssignmentExpression) { - getJSDocsWorker(parent); + getJSDocCommentsAndTagsWorker(parent); } if (node.kind === 146) { - cache = ts.concatenate(cache, getJSDocParameterTags(node)); + result = ts.addRange(result, getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer) { - cache = ts.concatenate(cache, node.initializer.jsDoc); + result = ts.addRange(result, node.initializer.jsDoc); } - cache = ts.concatenate(cache, node.jsDoc); + result = ts.addRange(result, node.jsDoc); } } - ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } - var func = param.parent; - var tags = getJSDocTags(func, 286); - if (!param.name) { - var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 286; }); - if (paramTags && 0 <= i && i < paramTags.length) { - return [paramTags[i]]; - } - } - else if (param.name.kind === 71) { - var name_1 = param.name.text; - return ts.filter(tags, function (tag) { return tag.kind === 286 && tag.parameterName.text === name_1; }); - } - else { - return undefined; + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); } + return undefined; } ts.getJSDocParameterTags = getJSDocParameterTags; + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + ts.Debug.assert(node.parent.kind === 275); + var func = node.parent.parent; + if (!ts.isFunctionLike(func)) { + return undefined; + } + var parameter = ts.find(func.parameters, function (p) { + return p.name.kind === 71 && p.name.escapedText === name; + }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 288); + var tag = getFirstJSDocTag(node, 281); if (!tag && node.kind === 146) { var paramTags = getJSDocParameterTags(node); if (paramTags) { @@ -6556,15 +6628,24 @@ var ts; } ts.getJSDocType = getJSDocType; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285); + return getFirstJSDocTag(node, 277); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 287); + return getFirstJSDocTag(node, 280); } ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 289); + return getFirstJSDocTag(node, 282); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { @@ -6576,9 +6657,9 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 65536)) { - if (node.type && node.type.kind === 280 || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 280; })) { + if (isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 274 || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { return true; } } @@ -6674,46 +6755,31 @@ var ts; case 71: case 9: case 8: - return isDeclaration(name.parent) && name.parent.name === name; + return ts.isDeclaration(name.parent) && name.parent.name === name; default: 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; + function isAnyDeclarationName(name) { + switch (name.kind) { + case 71: + case 9: + case 8: + if (ts.isDeclaration(name.parent)) { + return name.parent.name === name; + } + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + default: + return false; } } - ts.getNameOfDeclaration = getNameOfDeclaration; + ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && - isDeclaration(node.parent.parent); + ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; function isIdentifierName(node) { @@ -6741,6 +6807,7 @@ var ts; case 242: return parent.propertyName === node; case 246: + case 253: return true; } return false; @@ -6889,10 +6956,6 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isNumericLiteral(node) { - return node.kind === 8; - } - ts.isNumericLiteral = isNumericLiteral; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 9 @@ -6900,7 +6963,7 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - var name = getNameOfDeclaration(declaration); + var name = ts.getNameOfDeclaration(declaration); return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; @@ -6911,56 +6974,67 @@ var ts; } ts.isDynamicName = isDynamicName; function isWellKnownSymbolSyntactically(node) { - return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 || name.kind === 9 || name.kind === 8 || name.kind === 146) { - return name.text; + if (name.kind === 71) { + return name.escapedText; + } + if (name.kind === 9 || name.kind === 8) { + return escapeLeadingUnderscores(name.text); } if (name.kind === 144) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.text; - return getPropertyNameForKnownSymbolName(rightHandSideName); + var rightHandSideName = nameExpression.name.escapedText; + return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); } else if (nameExpression.kind === 9 || nameExpression.kind === 8) { - return nameExpression.text; + return escapeLeadingUnderscores(nameExpression.text); } } return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return ts.unescapeLeadingUnderscores(node.escapedText); + } + if (node.kind === 9 || + node.kind === 8) { + return node.text; + } + } + return undefined; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return node.escapedText; + } + if (node.kind === 9 || + node.kind === 8) { + return escapeLeadingUnderscores(node.text); + } + } + return undefined; + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; function isESSymbolIdentifier(node) { - return node.kind === 71 && node.text === "Symbol"; + return node.kind === 71 && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { - return node.text === "push" || node.text === "unshift"; + return node.escapedText === "push" || node.escapedText === "unshift"; } ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; - function isModifierKind(token) { - switch (token) { - case 117: - case 120: - case 76: - case 124: - case 79: - case 84: - case 114: - case 112: - case 113: - case 131: - case 115: - return true; - } - return false; - } - ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 146; @@ -6991,25 +7065,14 @@ var ts; || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile)); - } - return getOriginalSourceFile(sourceFileOrBundle); - } - ts.getOriginalSourceFileOrBundle = getOriginalSourceFileOrBundle; function getOriginalSourceFile(sourceFile) { - return ts.getParseTreeNode(sourceFile, isSourceFile) || sourceFile; + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } + ts.getOriginalSourceFile = getOriginalSourceFile; function getOriginalSourceFiles(sourceFiles) { return ts.sameMap(sourceFiles, getOriginalSourceFile); } ts.getOriginalSourceFiles = getOriginalSourceFiles; - function getOriginalNodeId(node) { - node = ts.getOriginalNode(node); - return node ? ts.getNodeId(node) : 0; - } - ts.getOriginalNodeId = getOriginalNodeId; var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; @@ -7176,7 +7239,7 @@ var ts; return 2; case 198: return 1; - case 297: + case 289: return 0; default: return -1; @@ -7431,44 +7494,6 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { - var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); - var options = host.getCompilerOptions(); - if (options.outFile || options.out) { - if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); - } - } - else { - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); - } - } - } - ts.forEachEmittedFile = forEachEmittedFile; - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } - function getOutputExtension(sourceFile, options) { - if (options.jsx === 1) { - if (isSourceFileJavaScript(sourceFile)) { - if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { - return ".jsx"; - } - } - else if (sourceFile.languageVariant === 1) { - return ".jsx"; - } - } - return ".js"; - } function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); var commonSourceDirectory = host.getCommonSourceDirectory(); @@ -7499,12 +7524,16 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; - function getSetAccessorTypeAnnotationNode(accessor) { + function getSetAccessorValueParameter(accessor) { if (accessor && accessor.parameters.length > 0) { var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); - return accessor.parameters[hasThis ? 1 : 0].type; + return accessor.parameters[hasThis ? 1 : 0]; } } + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { if (signature.parameters.length) { @@ -7575,6 +7604,39 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + function getEffectiveTypeAnnotationNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocType(node); + } + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getEffectiveReturnTypeNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocReturnType(node); + } + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getEffectiveTypeParameterDeclarations(node) { + if (node.typeParameters) { + return node.typeParameters; + } + if (isInJavaScriptFile(node)) { + var templateTag = getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); } @@ -7736,6 +7798,12 @@ var ts; if (node.modifierFlagsCache & 536870912) { return node.modifierFlagsCache & ~536870912; } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { var flags = 0; if (node.modifiers) { for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { @@ -7746,10 +7814,9 @@ var ts; if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) { flags |= 1; } - node.modifierFlagsCache = flags | 536870912; return flags; } - ts.getModifierFlags = getModifierFlags; + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { case 115: return 32; @@ -7780,17 +7847,17 @@ var ts; function tryGetClassExtendingExpressionWithTypeArguments(node) { if (node.kind === 201 && node.parent.token === 85 && - isClassLike(node.parent.parent)) { + ts.isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { - return isBinaryExpression(node) + return ts.isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 58 : isAssignmentOperator(node.operatorToken.kind)) - && isLeftHandSideExpression(node.left); + && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { @@ -7810,7 +7877,7 @@ var ts; if (node.kind === 71) { return true; } - else if (isPropertyAccessExpression(node)) { + else if (ts.isPropertyAccessExpression(node)) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -7827,7 +7894,7 @@ var ts; && node.parent && node.parent.token === 108 && node.parent.parent - && isClassLike(node.parent.parent); + && ts.isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { @@ -7851,11 +7918,11 @@ var ts; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined; + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isExportDefaultSymbol(symbol) { - return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512); + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); } function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -7995,27 +8062,74 @@ var ts; } return false; } - var syntaxKindCache = []; - function formatSyntaxKind(kind) { - var syntaxKindEnum = ts.SyntaxKind; - if (syntaxKindEnum) { - var cached = syntaxKindCache[kind]; - if (cached !== undefined) { - return cached; - } - for (var name in syntaxKindEnum) { - if (syntaxKindEnum[name] === kind) { - var result = kind + " (" + name + ")"; - syntaxKindCache[kind] = result; - return result; + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; } } + if (remainingFlags === 0) { + return result; + } } else { - return kind.toString(); + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, false); } ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, true); + } + ts.formatObjectFlags = formatObjectFlags; function getRangePos(range) { return range ? range.pos : -1; } @@ -8132,630 +8246,12 @@ var ts; return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; } ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; - function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); - } - ts.isNodeArray = isNodeArray; - function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13; - } - ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; - function isLiteralKind(kind) { - return 8 <= kind && kind <= 13; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 || kind === 13; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isLiteralExpression(node) { - return isLiteralKind(node.kind); - } - ts.isLiteralExpression = isLiteralExpression; - function isTemplateLiteralKind(kind) { - return 13 <= kind && kind <= 16; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateHead(node) { - return node.kind === 14; - } - ts.isTemplateHead = isTemplateHead; - function isTemplateMiddleOrTemplateTail(node) { - var kind = node.kind; - return kind === 15 - || kind === 16; - } - ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; - function isIdentifier(node) { - return node.kind === 71; - } - ts.isIdentifier = isIdentifier; - function isGeneratedIdentifier(node) { - return isIdentifier(node) && node.autoGenerateKind > 0; - } - ts.isGeneratedIdentifier = isGeneratedIdentifier; - function isModifier(node) { - return isModifierKind(node.kind); - } - ts.isModifier = isModifier; - function isQualifiedName(node) { - return node.kind === 143; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 144; - } - ts.isComputedPropertyName = isComputedPropertyName; - function isEntityName(node) { - var kind = node.kind; - return kind === 143 - || kind === 71; - } - ts.isEntityName = isEntityName; - function isPropertyName(node) { - var kind = node.kind; - return kind === 71 - || kind === 9 - || kind === 8 - || kind === 144; - } - ts.isPropertyName = isPropertyName; - function isModuleName(node) { - var kind = node.kind; - return kind === 71 - || kind === 9; - } - ts.isModuleName = isModuleName; - function isBindingName(node) { - var kind = node.kind; - return kind === 71 - || kind === 174 - || kind === 175; - } - ts.isBindingName = isBindingName; - function isTypeParameter(node) { - return node.kind === 145; - } - ts.isTypeParameter = isTypeParameter; - function isParameter(node) { - return node.kind === 146; - } - ts.isParameter = isParameter; - function isDecorator(node) { - return node.kind === 147; - } - ts.isDecorator = isDecorator; - function isMethodDeclaration(node) { - return node.kind === 151; - } - ts.isMethodDeclaration = isMethodDeclaration; - function isClassElement(node) { - var kind = node.kind; - return kind === 152 - || kind === 149 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 157 - || 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 - || kind === 262 - || kind === 263 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 247; - } - ts.isObjectLiteralElementLike = isObjectLiteralElementLike; - function isTypeNodeKind(kind) { - return (kind >= 158 && kind <= 173) - || kind === 119 - || kind === 133 - || kind === 134 - || kind === 122 - || kind === 136 - || kind === 137 - || kind === 99 - || kind === 105 - || kind === 139 - || kind === 95 - || kind === 130 - || kind === 201; - } - function isTypeNode(node) { - return isTypeNodeKind(node.kind); - } - ts.isTypeNode = isTypeNode; - function isArrayBindingPattern(node) { - return node.kind === 175; - } - ts.isArrayBindingPattern = isArrayBindingPattern; - function isObjectBindingPattern(node) { - return node.kind === 174; - } - ts.isObjectBindingPattern = isObjectBindingPattern; - function isBindingPattern(node) { - if (node) { - var kind = node.kind; - return kind === 175 - || kind === 174; - } - return false; - } - ts.isBindingPattern = isBindingPattern; - function isAssignmentPattern(node) { - var kind = node.kind; - return kind === 177 - || kind === 178; - } - ts.isAssignmentPattern = isAssignmentPattern; - function isBindingElement(node) { - return node.kind === 176; - } - ts.isBindingElement = isBindingElement; - function isArrayBindingElement(node) { - var kind = node.kind; - return kind === 176 - || kind === 200; - } - ts.isArrayBindingElement = isArrayBindingElement; - function isDeclarationBindingElement(bindingElement) { - switch (bindingElement.kind) { - case 226: - case 146: - case 176: - return true; - } - return false; - } - ts.isDeclarationBindingElement = isDeclarationBindingElement; - function isBindingOrAssignmentPattern(node) { - return isObjectBindingOrAssignmentPattern(node) - || isArrayBindingOrAssignmentPattern(node); - } - ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; - function isObjectBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 174: - case 178: - return true; - } - return false; - } - ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; - function isArrayBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 175: - case 177: - return true; - } - return false; - } - ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; - function isArrayLiteralExpression(node) { - return node.kind === 177; - } - ts.isArrayLiteralExpression = isArrayLiteralExpression; - function isObjectLiteralExpression(node) { - return node.kind === 178; - } - ts.isObjectLiteralExpression = isObjectLiteralExpression; - function isPropertyAccessExpression(node) { - return node.kind === 179; - } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isPropertyAccessOrQualifiedName(node) { - var kind = node.kind; - return kind === 179 - || kind === 143; - } - ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; - function isElementAccessExpression(node) { - return node.kind === 180; - } - ts.isElementAccessExpression = isElementAccessExpression; - function isBinaryExpression(node) { - return node.kind === 194; - } - ts.isBinaryExpression = isBinaryExpression; - function isConditionalExpression(node) { - return node.kind === 195; - } - ts.isConditionalExpression = isConditionalExpression; - function isCallExpression(node) { - return node.kind === 181; - } - ts.isCallExpression = isCallExpression; - function isTemplateLiteral(node) { - var kind = node.kind; - return kind === 196 - || kind === 13; - } - ts.isTemplateLiteral = isTemplateLiteral; - function isSpreadExpression(node) { - return node.kind === 198; - } - ts.isSpreadExpression = isSpreadExpression; - function isExpressionWithTypeArguments(node) { - return node.kind === 201; - } - ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 - || kind === 180 - || kind === 182 - || kind === 181 - || kind === 249 - || kind === 250 - || kind === 183 - || kind === 177 - || kind === 185 - || kind === 178 - || kind === 199 - || kind === 186 - || kind === 71 - || kind === 12 - || kind === 8 - || kind === 9 - || kind === 13 - || kind === 196 - || kind === 86 - || kind === 95 - || kind === 99 - || kind === 101 - || kind === 97 - || kind === 203 - || kind === 204; - } - function isLeftHandSideExpression(node) { - return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 - || kind === 193 - || kind === 188 - || kind === 189 - || kind === 190 - || kind === 191 - || kind === 184 - || isLeftHandSideExpressionKind(kind); - } - function isUnaryExpression(node) { - return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isUnaryExpression = isUnaryExpression; - function isExpressionKind(kind) { - return kind === 195 - || kind === 197 - || kind === 187 - || kind === 194 - || kind === 198 - || kind === 202 - || kind === 200 - || kind === 297 - || isUnaryExpressionKind(kind); - } - function isExpression(node) { - return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isExpression = isExpression; - function isAssertionExpression(node) { - var kind = node.kind; - return kind === 184 - || kind === 202; - } - ts.isAssertionExpression = isAssertionExpression; - function isPartiallyEmittedExpression(node) { - return node.kind === 296; - } - ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; - function isNotEmittedStatement(node) { - return node.kind === 295; - } - ts.isNotEmittedStatement = isNotEmittedStatement; - function isNotEmittedOrPartiallyEmittedNode(node) { - return isNotEmittedStatement(node) - || isPartiallyEmittedExpression(node); - } - ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - function isOmittedExpression(node) { - return node.kind === 200; - } - ts.isOmittedExpression = isOmittedExpression; - function isTemplateSpan(node) { - return node.kind === 205; - } - ts.isTemplateSpan = isTemplateSpan; - function isBlock(node) { - return node.kind === 207; - } - ts.isBlock = isBlock; - function isConciseBody(node) { - return isBlock(node) - || isExpression(node); - } - ts.isConciseBody = isConciseBody; - function isFunctionBody(node) { - return isBlock(node); - } - ts.isFunctionBody = isFunctionBody; - function isForInitializer(node) { - return isVariableDeclarationList(node) - || isExpression(node); - } - ts.isForInitializer = isForInitializer; - function isVariableDeclaration(node) { - return node.kind === 226; - } - ts.isVariableDeclaration = isVariableDeclaration; - function isVariableDeclarationList(node) { - return node.kind === 227; - } - ts.isVariableDeclarationList = isVariableDeclarationList; - function isCaseBlock(node) { - return node.kind === 235; - } - ts.isCaseBlock = isCaseBlock; - function isModuleBody(node) { - var kind = node.kind; - return kind === 234 - || kind === 233 - || kind === 71; - } - ts.isModuleBody = isModuleBody; - function isNamespaceBody(node) { - var kind = node.kind; - return kind === 234 - || kind === 233; - } - ts.isNamespaceBody = isNamespaceBody; - function isJSDocNamespaceBody(node) { - var kind = node.kind; - return kind === 71 - || kind === 233; - } - ts.isJSDocNamespaceBody = isJSDocNamespaceBody; - function isImportEqualsDeclaration(node) { - return node.kind === 237; - } - ts.isImportEqualsDeclaration = isImportEqualsDeclaration; - function isImportDeclaration(node) { - return node.kind === 238; - } - ts.isImportDeclaration = isImportDeclaration; - function isImportClause(node) { - return node.kind === 239; - } - ts.isImportClause = isImportClause; - function isNamedImportBindings(node) { - var kind = node.kind; - return kind === 241 - || kind === 240; - } - ts.isNamedImportBindings = isNamedImportBindings; - function isImportSpecifier(node) { - return node.kind === 242; - } - ts.isImportSpecifier = isImportSpecifier; - function isNamedExports(node) { - return node.kind === 245; - } - ts.isNamedExports = isNamedExports; - function isExportSpecifier(node) { - 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; - } - ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; - function isDeclarationKind(kind) { - return kind === 187 - || kind === 176 - || kind === 229 - || kind === 199 - || kind === 152 - || kind === 232 - || kind === 264 - || kind === 246 - || kind === 228 - || kind === 186 - || kind === 153 - || kind === 239 - || kind === 237 - || kind === 242 - || kind === 230 - || kind === 253 - || kind === 151 - || kind === 150 - || kind === 233 - || kind === 236 - || kind === 240 - || kind === 146 - || kind === 261 - || kind === 149 - || kind === 148 - || kind === 154 - || kind === 262 - || kind === 231 - || kind === 145 - || kind === 226 - || kind === 290; - } - function isDeclarationStatementKind(kind) { - return kind === 228 - || kind === 247 - || kind === 229 - || kind === 230 - || kind === 231 - || kind === 232 - || kind === 233 - || kind === 238 - || kind === 237 - || kind === 244 - || kind === 243 - || kind === 236; - } - function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 - || kind === 217 - || kind === 225 - || kind === 212 - || kind === 210 - || kind === 209 - || kind === 215 - || kind === 216 - || kind === 214 - || kind === 211 - || kind === 222 - || kind === 219 - || kind === 221 - || kind === 223 - || kind === 224 - || kind === 208 - || kind === 213 - || kind === 220 - || kind === 295 - || kind === 299 - || kind === 298; - } - function isDeclaration(node) { - return isDeclarationKind(node.kind); - } - ts.isDeclaration = isDeclaration; - function isDeclarationStatement(node) { - return isDeclarationStatementKind(node.kind); - } - ts.isDeclarationStatement = isDeclarationStatement; - function isStatementButNotDeclaration(node) { - return isStatementKindButNotDeclarationKind(node.kind); - } - ts.isStatementButNotDeclaration = isStatementButNotDeclaration; - function isStatement(node) { - var kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) - || isDeclarationStatementKind(kind) - || kind === 207; - } - ts.isStatement = isStatement; - function isModuleReference(node) { - var kind = node.kind; - return kind === 248 - || kind === 143 - || kind === 71; - } - ts.isModuleReference = isModuleReference; - function isJsxOpeningElement(node) { - return node.kind === 251; - } - ts.isJsxOpeningElement = isJsxOpeningElement; - function isJsxClosingElement(node) { - return node.kind === 252; - } - ts.isJsxClosingElement = isJsxClosingElement; - function isJsxTagNameExpression(node) { - var kind = node.kind; - return kind === 99 - || kind === 71 - || kind === 179; - } - ts.isJsxTagNameExpression = isJsxTagNameExpression; - function isJsxChild(node) { - var kind = node.kind; - return kind === 249 - || kind === 256 - || kind === 250 - || kind === 10; - } - ts.isJsxChild = isJsxChild; - function isJsxAttributes(node) { - var kind = node.kind; - return kind === 254; - } - ts.isJsxAttributes = isJsxAttributes; - function isJsxAttributeLike(node) { - var kind = node.kind; - return kind === 253 - || kind === 255; - } - ts.isJsxAttributeLike = isJsxAttributeLike; - function isJsxSpreadAttribute(node) { - return node.kind === 255; - } - ts.isJsxSpreadAttribute = isJsxSpreadAttribute; - function isJsxAttribute(node) { - return node.kind === 253; - } - ts.isJsxAttribute = isJsxAttribute; - function isStringLiteralOrJsxExpression(node) { - var kind = node.kind; - return kind === 9 - || kind === 256; - } - ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; - function isJsxOpeningLikeElement(node) { - var kind = node.kind; - return kind === 251 - || kind === 250; - } - ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; - function isCaseOrDefaultClause(node) { - var kind = node.kind; - return kind === 257 - || kind === 258; - } - ts.isCaseOrDefaultClause = isCaseOrDefaultClause; - function isHeritageClause(node) { - return node.kind === 259; - } - ts.isHeritageClause = isHeritageClause; - function isCatchClause(node) { - return node.kind === 260; - } - ts.isCatchClause = isCatchClause; - function isPropertyAssignment(node) { - return node.kind === 261; - } - ts.isPropertyAssignment = isPropertyAssignment; - function isShorthandPropertyAssignment(node) { - return node.kind === 262; - } - ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; - function isEnumMember(node) { - return node.kind === 264; - } - ts.isEnumMember = isEnumMember; - function isSourceFile(node) { - return node.kind === 265; - } - ts.isSourceFile = isSourceFile; function isWatchSet(options) { return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; function getCheckFlags(symbol) { - return symbol.flags & 134217728 ? symbol.checkFlags : 0; + return symbol.flags & 33554432 ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; function getDeclarationModifierFlagsFromSymbol(s) { @@ -8771,7 +8267,7 @@ var ts; var staticModifier = checkFlags & 512 ? 32 : 0; return accessModifier | staticModifier; } - if (s.flags & 16777216) { + if (s.flags & 4194304) { return 4 | 32; } return 0; @@ -8796,6 +8292,14 @@ var ts; return previous[previous.length - 1]; } ts.levenshtein = levenshtein; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -9051,10 +8555,1222 @@ var ts; return undefined; } ts.getParseTreeNode = getParseTreeNode; - function unescapeIdentifier(identifier) { - return identifier.length >= 3 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 && identifier.charCodeAt(2) === 95 ? identifier.substr(1) : identifier; + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function unescapeIdentifier(id) { + return id; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { + return declaration.name.right; + } + if (declaration.kind === 194) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; +})(ts || (ts = {})); +(function (ts) { + function isNumericLiteral(node) { + return node.kind === 8; + } + ts.isNumericLiteral = isNumericLiteral; + function isStringLiteral(node) { + return node.kind === 9; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 10; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 12; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 13; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isTemplateHead(node) { + return node.kind === 14; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 15; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 16; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 71; + } + ts.isIdentifier = isIdentifier; + function isQualifiedName(node) { + return node.kind === 143; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 144; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isTypeParameterDeclaration(node) { + return node.kind === 145; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 146; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 147; + } + ts.isDecorator = isDecorator; + function isPropertySignature(node) { + return node.kind === 148; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 149; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 150; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 151; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 152; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 153; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 154; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 155; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 156; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 157; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isTypePredicateNode(node) { + return node.kind === 158; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 159; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 160; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 161; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 162; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 163; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 164; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 165; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 166; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 167; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 168; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 169; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 170; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 171; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 172; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 173; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isObjectBindingPattern(node) { + return node.kind === 174; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 175; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 176; + } + ts.isBindingElement = isBindingElement; + function isArrayLiteralExpression(node) { + return node.kind === 177; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 178; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 179; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 180; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 181; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 182; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 183; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 184; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 185; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 186; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 187; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 188; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 191; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 190; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 191; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 192; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 193; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 194; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 195; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 196; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 197; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 198; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 199; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 200; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 201; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 202; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 203; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 204; + } + ts.isMetaProperty = isMetaProperty; + function isTemplateSpan(node) { + return node.kind === 205; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 206; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + function isBlock(node) { + return node.kind === 207; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 208; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 209; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 210; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 211; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 212; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 213; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 214; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 215; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 216; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 217; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 218; + } + ts.isBreakStatement = isBreakStatement; + function isReturnStatement(node) { + return node.kind === 219; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 220; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 221; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 222; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 223; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 224; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 225; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 226; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 227; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 228; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 229; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 230; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 231; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 232; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 233; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 234; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 235; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 236; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 237; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 239; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 240; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 241; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 242; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 244; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 245; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 246; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 247; + } + ts.isMissingDeclaration = isMissingDeclaration; + function isExternalModuleReference(node) { + return node.kind === 248; + } + ts.isExternalModuleReference = isExternalModuleReference; + function isJsxElement(node) { + return node.kind === 249; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 250; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 251; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 252; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxAttribute(node) { + return node.kind === 253; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 254; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 255; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 256; + } + ts.isJsxExpression = isJsxExpression; + function isCaseClause(node) { + return node.kind === 257; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 258; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 259; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 260; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 261; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 262; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 263; + } + ts.isSpreadAssignment = isSpreadAssignment; + function isEnumMember(node) { + return node.kind === 264; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 265; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 266; + } + ts.isBundle = isBundle; + function isJSDocTypeExpression(node) { + return node.kind === 267; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 268; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 269; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 270; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 271; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 272; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 273; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 274; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 275; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 277; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocParameterTag(node) { + return node.kind === 279; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 280; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 281; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 282; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 283; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 284; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 284 || node.kind === 279; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 285; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; +})(ts || (ts = {})); +(function (ts) { + function isSyntaxList(n) { + return n.kind === 286; + } + ts.isSyntaxList = isSyntaxList; + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + function isNodeKind(kind) { + return kind >= 143; + } + ts.isNodeKind = isNodeKind; + function isToken(n) { + return n.kind >= 0 && n.kind <= 142; + } + ts.isToken = isToken; + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 13; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 13 <= kind && kind <= 16; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 15 + || kind === 16; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isStringTextContainingNode(node) { + switch (node.kind) { + case 9: + case 14: + case 15: + case 16: + case 13: + return true; + default: + return false; + } + } + ts.isStringTextContainingNode = isStringTextContainingNode; + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && node.autoGenerateKind > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifierKind(token) { + switch (token) { + case 117: + case 120: + case 76: + case 124: + case 79: + case 84: + case 114: + case 112: + case 113: + case 131: + case 115: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 143 + || kind === 71; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 71 + || kind === 9 + || kind === 8 + || kind === 144; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 71 + || kind === 174 + || kind === 175; + } + ts.isBindingName = isBindingName; + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 152: + case 186: + case 228: + case 187: + case 151: + case 150: + case 153: + case 154: + case 155: + case 156: + case 157: + case 160: + case 273: + case 161: + return true; + } + return false; + } + ts.isFunctionLikeKind = isFunctionLikeKind; + function isClassElement(node) { + var kind = node.kind; + return kind === 152 + || kind === 149 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 157 + || kind === 206 + || kind === 247; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 229 || node.kind === 199); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 153 || node.kind === 154); + } + ts.isAccessor = isAccessor; + 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 + || kind === 262 + || kind === 263 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 247; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNodeKind(kind) { + return (kind >= 158 && kind <= 173) + || kind === 119 + || kind === 133 + || kind === 134 + || kind === 122 + || kind === 136 + || kind === 137 + || kind === 99 + || kind === 105 + || kind === 139 + || kind === 95 + || kind === 130 + || kind === 201; + } + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 175 + || kind === 174; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 177 + || kind === 178; + } + ts.isAssignmentPattern = isAssignmentPattern; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 176 + || kind === 200; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 226: + case 146: + case 176: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 174: + case 178: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 175: + case 177: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 179 + || kind === 143; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 251: + case 250: + case 181: + case 182: + case 183: + case 147: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 196 + || kind === 13; + } + ts.isTemplateLiteral = isTemplateLiteral; + function isLeftHandSideExpressionKind(kind) { + return kind === 179 + || kind === 180 + || kind === 182 + || kind === 181 + || kind === 249 + || kind === 250 + || kind === 183 + || kind === 177 + || kind === 185 + || kind === 178 + || kind === 199 + || kind === 186 + || kind === 71 + || kind === 12 + || kind === 8 + || kind === 9 + || kind === 13 + || kind === 196 + || kind === 86 + || kind === 95 + || kind === 99 + || kind === 101 + || kind === 97 + || kind === 91 + || kind === 203 + || kind === 204; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 192 + || kind === 193 + || kind === 188 + || kind === 189 + || kind === 190 + || kind === 191 + || kind === 184 + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 195 + || kind === 197 + || kind === 187 + || kind === 194 + || kind === 198 + || kind === 202 + || kind === 200 + || kind === 289 + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 184 + || kind === 202; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 214: + case 215: + case 216: + case 212: + case 213: + return true; + case 222: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + function isForInOrOfStatement(node) { + return node.kind === 215 || node.kind === 216; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isModuleBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233 + || kind === 71; + } + ts.isModuleBody = isModuleBody; + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233; + } + ts.isNamespaceBody = isNamespaceBody; + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 71 + || kind === 233; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 241 + || kind === 240; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isModuleOrEnumDeclaration(node) { + return node.kind === 233 || node.kind === 232; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 187 + || kind === 176 + || kind === 229 + || kind === 199 + || kind === 152 + || kind === 232 + || kind === 264 + || kind === 246 + || kind === 228 + || kind === 186 + || kind === 153 + || kind === 239 + || kind === 237 + || kind === 242 + || kind === 230 + || kind === 253 + || kind === 151 + || kind === 150 + || kind === 233 + || kind === 236 + || kind === 240 + || kind === 146 + || kind === 261 + || kind === 149 + || kind === 148 + || kind === 154 + || kind === 262 + || kind === 231 + || kind === 145 + || kind === 226 + || kind === 283; + } + function isDeclarationStatementKind(kind) { + return kind === 228 + || kind === 247 + || kind === 229 + || kind === 230 + || kind === 231 + || kind === 232 + || kind === 233 + || kind === 238 + || kind === 237 + || kind === 244 + || kind === 243 + || kind === 236; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 218 + || kind === 217 + || kind === 225 + || kind === 212 + || kind === 210 + || kind === 209 + || kind === 215 + || kind === 216 + || kind === 214 + || kind === 211 + || kind === 222 + || kind === 219 + || kind === 221 + || kind === 223 + || kind === 224 + || kind === 208 + || kind === 213 + || kind === 220 + || kind === 287 + || kind === 291 + || kind === 290; + } + function isDeclaration(node) { + if (node.kind === 145) { + return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 207; + } + ts.isStatement = isStatement; + function isModuleReference(node) { + var kind = node.kind; + return kind === 248 + || kind === 143 + || kind === 71; + } + ts.isModuleReference = isModuleReference; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 99 + || kind === 71 + || kind === 179; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 249 + || kind === 256 + || kind === 250 + || kind === 10; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 253 + || kind === 255; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 + || kind === 256; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 251 + || kind === 250; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 257 + || kind === 258; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isJSDocNode(node) { + return node.kind >= 267 && node.kind <= 285; + } + ts.isJSDocNode = isJSDocNode; + function isJSDocCommentContainingNode(node) { + return node.kind === 275 || isJSDocTag(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + function isJSDocTag(node) { + return node.kind >= 276 && node.kind <= 285; + } + ts.isJSDocTag = isJSDocTag; })(ts || (ts = {})); var ts; (function (ts) { @@ -9271,12 +9987,19 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; - function computePositionOfLineAndCharacter(lineStarts, line, character) { + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { ts.Debug.assert(line >= 0 && line < lineStarts.length); - return lineStarts[line] + character; + var res = lineStarts[line] + character; + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res < debugText.length); + } + return res; } ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; function getLineStarts(sourceFile) { @@ -9343,6 +10066,7 @@ var ts; case 32: case 47: case 60: + case 124: case 61: case 62: return true; @@ -9404,6 +10128,7 @@ var ts; } break; case 60: + case 124: case 61: case 62: if (isConflictMarkerTrivia(text, pos)) { @@ -9457,10 +10182,10 @@ var ts; } } else { - ts.Debug.assert(ch === 61); + ts.Debug.assert(ch === 124 || ch === 61); while (pos < len) { - var ch_1 = text.charCodeAt(pos); - if (ch_1 === 62 && isConflictMarkerTrivia(text, pos)) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 || currentChar === 62) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { break; } pos++; @@ -10140,13 +10865,13 @@ var ts; pos += 2; var commentClosed = false; while (pos < end) { - var ch_2 = text.charCodeAt(pos); - if (ch_2 === 42 && text.charCodeAt(pos + 1) === 47) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) { pos += 2; commentClosed = true; break; } - if (isLineBreak(ch_2)) { + if (isLineBreak(ch_1)) { precedingLineBreak = true; } pos++; @@ -10301,6 +11026,15 @@ var ts; pos++; return token = 17; case 124: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 54; } @@ -10635,6 +11369,27383 @@ var ts; ts.createScanner = createScanner; })(ts || (ts = {})); var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 265) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 71) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 142) { + return; + } + switch (node.kind) { + case 143: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 145: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 262: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 263: + return visitNode(cbNode, node.expression); + case 146: + case 149: + case 148: + case 261: + case 226: + case 176: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 160: + case 161: + case 155: + case 156: + case 157: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 151: + case 150: + case 152: + case 153: + case 154: + case 186: + case 228: + case 187: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 159: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 158: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 162: + return visitNode(cbNode, node.exprName); + case 163: + return visitNodes(cbNode, cbNodes, node.members); + case 164: + return visitNode(cbNode, node.elementType); + case 165: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 166: + case 167: + return visitNodes(cbNode, cbNodes, node.types); + case 168: + case 170: + return visitNode(cbNode, node.type); + case 171: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 172: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 173: + return visitNode(cbNode, node.literal); + case 174: + case 175: + return visitNodes(cbNode, cbNodes, node.elements); + case 177: + return visitNodes(cbNode, cbNodes, node.elements); + case 178: + return visitNodes(cbNode, cbNodes, node.properties); + case 179: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 180: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 181: + case 182: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 183: + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.template); + case 184: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 185: + return visitNode(cbNode, node.expression); + case 188: + return visitNode(cbNode, node.expression); + case 189: + return visitNode(cbNode, node.expression); + case 190: + return visitNode(cbNode, node.expression); + case 192: + return visitNode(cbNode, node.operand); + case 197: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 191: + return visitNode(cbNode, node.expression); + case 193: + return visitNode(cbNode, node.operand); + case 194: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 202: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 203: + return visitNode(cbNode, node.expression); + case 204: + return visitNode(cbNode, node.name); + case 195: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 198: + return visitNode(cbNode, node.expression); + case 207: + case 234: + return visitNodes(cbNode, cbNodes, node.statements); + case 265: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 208: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 227: + return visitNodes(cbNode, cbNodes, node.declarations); + case 210: + return visitNode(cbNode, node.expression); + case 211: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 212: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 213: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 215: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 216: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 217: + case 218: + return visitNode(cbNode, node.label); + case 219: + return visitNode(cbNode, node.expression); + case 220: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 221: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 235: + return visitNodes(cbNode, cbNodes, node.clauses); + case 257: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 258: + return visitNodes(cbNode, cbNodes, node.statements); + case 222: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 223: + return visitNode(cbNode, node.expression); + case 224: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 260: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 147: + return visitNode(cbNode, node.expression); + case 229: + case 199: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 230: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 231: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 232: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 264: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 233: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 237: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 238: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 239: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 236: + return visitNode(cbNode, node.name); + case 240: + return visitNode(cbNode, node.name); + case 241: + case 245: + return visitNodes(cbNode, cbNodes, node.elements); + case 244: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 242: + case 246: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 243: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 196: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 205: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 144: + return visitNode(cbNode, node.expression); + case 259: + return visitNodes(cbNode, cbNodes, node.types); + case 201: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 248: + return visitNode(cbNode, node.expression); + case 247: + return visitNodes(cbNode, cbNodes, node.decorators); + case 289: + return visitNodes(cbNode, cbNodes, node.elements); + case 249: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 250: + case 251: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.attributes); + case 254: + return visitNodes(cbNode, cbNodes, node.properties); + case 253: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 255: + return visitNode(cbNode, node.expression); + case 256: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 252: + return visitNode(cbNode, node.tagName); + case 267: + return visitNode(cbNode, node.type); + case 271: + return visitNode(cbNode, node.type); + case 270: + return visitNode(cbNode, node.type); + case 272: + return visitNode(cbNode, node.type); + case 273: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 274: + return visitNode(cbNode, node.type); + case 275: + return visitNodes(cbNode, cbNodes, node.tags); + case 279: + case 284: + if (node.isNameFirst) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression); + } + else { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name); + } + case 280: + return visitNode(cbNode, node.typeExpression); + case 281: + return visitNode(cbNode, node.typeExpression); + case 277: + return visitNode(cbNode, node.typeExpression); + case 282: + return visitNodes(cbNode, cbNodes, node.typeParameters); + case 283: + if (node.typeExpression && + node.typeExpression.kind === 267) { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName); + } + else { + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + } + case 285: + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } + return; + case 288: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + newSourceFile.flags |= (sourceFile.flags & 524288); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + var Parser; + (function (Parser) { + var scanner = ts.createScanner(5, true); + var disallowInAndDecoratorContext = 2048 | 8192; + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + var contextFlags; + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + initializeState(sourceText, 2, undefined, 6); + sourceFile = createSourceFile(fileName, 2, 6); + var result = sourceFile; + nextToken(); + if (token() === 1) { + sourceFile.endOfFileToken = parseTokenNode(); + } + else if (token() === 17 || + lookAhead(function () { return token() === 9; })) { + result.jsonObject = parseObjectLiteralExpression(); + sourceFile.endOfFileToken = parseExpectedToken(1, false, ts.Diagnostics.Unexpected_token); + } + else { + parseExpected(17); + } + sourceFile.parseDiagnostics = parseDiagnostics; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 || scriptKind === 6 ? 1 : 0; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + parseErrorBeforeNextFinishedNode = false; + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + scanner.setText(""); + scanner.setOnError(undefined); + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; + nextToken(); + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0, parseStatement); + ts.Debug.assert(token() === 1); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + } + function addJSDocComment(node) { + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; + } + if (!node.jsDoc) { + node.jsDoc = []; + } + node.jsDoc.push(jsDoc); + } + } + return node; + } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind) { + var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048); + } + function setYieldContext(val) { + setContextFlag(val, 4096); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192); + } + function setAwaitContext(val) { + setContextFlag(val, 16384); + } + function doOutsideOfContext(context, func) { + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + setContextFlag(false, contextFlagsToClear); + var result = func(); + setContextFlag(true, contextFlagsToClear); + return result; + } + return func(); + } + function doInsideOfContext(context, func) { + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + setContextFlag(true, contextFlagsToSet); + var result = func(); + setContextFlag(false, contextFlagsToSet); + return result; + } + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 | 16384, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096); + } + function inDisallowInContext() { + return inContext(2048); + } + function inDecoratorContext() { + return inContext(8192); + } + function inAwaitContext() { + return inContext(16384); + } + function parseErrorAtCurrentToken(message, arg0) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + parseErrorAtPosition(start, length, message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + parseErrorBeforeNextFinishedNode = true; + } + function scanError(message, length) { + var pos = scanner.getTextPos(); + parseErrorAtPosition(pos, length || 0, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var saveContextFlags = contextFlags; + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, true); + } + function tryParse(callback) { + return speculationHelper(callback, false); + } + function isIdentifier() { + if (token() === 71) { + return true; + } + if (token() === 116 && inYieldContext()) { + return false; + } + if (token() === 121 && inAwaitContext()) { + return false; + } + return token() > 107; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + if (token() === 25) { + return true; + } + return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 25) { + nextToken(); + } + return true; + } + else { + return parseExpected(25); + } + } + function createNode(kind, pos) { + nodeCount++; + if (!(pos >= 0)) { + pos = scanner.getStartPos(); + } + return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : + kind === 71 ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind, scanner.getStartPos()); + if (kind === 71) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(71); + if (token() !== 71) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName() { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 9 || token() === 8) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 21) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseComputedPropertyName() { + var node = createNode(144); + parseExpected(21); + node.expression = allowInAnd(parseExpression); + parseExpected(22); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + if (token() === 76) { + return nextToken() === 83; + } + if (token() === 84) { + nextToken(); + if (token() === 79) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + } + if (token() === 79) { + return nextTokenCanFollowDefaultKeyword(); + } + if (token() === 115) { + nextToken(); + return canFollowModifier(); + } + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 21 + || token() === 17 + || token() === 39 + || token() === 24 + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 75 || token() === 89 || + token() === 109 || + (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0: + case 1: + case 3: + return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); + case 2: + return token() === 73 || token() === 79; + case 4: + return lookAhead(isTypeMemberStart); + case 5: + return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); + case 6: + return token() === 21 || isLiteralPropertyName(); + case 12: + return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); + case 17: + return isLiteralPropertyName(); + case 9: + return token() === 21 || token() === 24 || isLiteralPropertyName(); + case 7: + if (token() === 17) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8: + return isIdentifierOrPattern(); + case 10: + return token() === 26 || token() === 24 || isIdentifierOrPattern(); + case 18: + return isIdentifier(); + case 11: + case 15: + return token() === 26 || token() === 24 || isStartOfExpression(); + case 16: + return isStartOfParameter(); + case 19: + case 20: + return token() === 26 || isStartOfType(); + case 21: + return isHeritageClause(); + case 22: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; + case 14: + return true; + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 17); + if (nextToken() === 18) { + var next = nextToken(); + return next === 26 || next === 17 || next === 85 || next === 108; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 108 || + token() === 85) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function isListTerminator(kind) { + if (token() === 1) { + return true; + } + switch (kind) { + case 1: + case 2: + case 4: + case 5: + case 6: + case 12: + case 9: + case 22: + return token() === 18; + case 3: + return token() === 18 || token() === 73 || token() === 79; + case 7: + return token() === 17 || token() === 85 || token() === 108; + case 8: + return isVariableDeclaratorListTerminator(); + case 18: + return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; + case 11: + return token() === 20 || token() === 25; + case 15: + case 20: + case 10: + return token() === 22; + case 16: + case 17: + return token() === 20 || token() === 22; + case 19: + return token() !== 26; + case 21: + return token() === 17 || token() === 18; + case 13: + return token() === 29 || token() === 41; + case 14: + return token() === 27 && lookAhead(nextTokenIsSlash); + } + } + function isVariableDeclaratorListTerminator() { + if (canParseSemicolon()) { + return true; + } + if (isInOrOfKeyword(token())) { + return true; + } + if (token() === 36) { + return true; + } + return false; + } + function isInSomeParsingContext() { + for (var kind = 0; kind < 23; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + while (!isListTerminator(kind)) { + if (isListElement(kind, false)) { + var element = parseListElement(kind, parseElement); + result.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + if (ts.nodeIsMissing(node)) { + return undefined; + } + if (node.intersectsChange) { + return undefined; + } + if (ts.containsParseError(node)) { + return undefined; + } + var nodeContextFlags = node.flags & 96256; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5: + return isReusableClassMember(node); + case 2: + return isReusableSwitchClause(node); + case 0: + case 1: + case 3: + return isReusableStatement(node); + case 6: + return isReusableEnumMember(node); + case 4: + return isReusableTypeMember(node); + case 8: + return isReusableVariableDeclaration(node); + case 16: + return isReusableParameter(node); + case 17: + return false; + case 21: + case 18: + case 20: + case 19: + case 11: + case 12: + case 7: + case 13: + case 14: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 152: + case 157: + case 153: + case 154: + case 149: + case 206: + return true; + case 151: + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 71 && + methodDeclaration.name.originalKeywordKind === 123; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 257: + case 258: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 228: + case 208: + case 207: + case 211: + case 210: + case 223: + case 219: + case 221: + case 218: + case 217: + case 215: + case 216: + case 214: + case 213: + case 220: + case 209: + case 224: + case 222: + case 212: + case 225: + case 238: + case 237: + case 244: + case 243: + case 233: + case 229: + case 230: + case 232: + case 231: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 264; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 156: + case 150: + case 157: + case 148: + case 155: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 226) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.initializer === undefined; + } + function isReusableParameter(node) { + if (node.kind !== 146) { + return false; + } + var parameter = node; + return parameter.initializer === undefined; + } + function abortParsingListOrMoveToNextToken(kind) { + parseErrorAtCurrentToken(parsingContextErrors(kind)); + if (isInSomeParsingContext()) { + return true; + } + nextToken(); + return false; + } + function parsingContextErrors(context) { + switch (context) { + case 0: return ts.Diagnostics.Declaration_or_statement_expected; + case 1: return ts.Diagnostics.Declaration_or_statement_expected; + case 2: return ts.Diagnostics.case_or_default_expected; + case 3: return ts.Diagnostics.Statement_expected; + case 17: + case 4: return ts.Diagnostics.Property_or_signature_expected; + case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 6: return ts.Diagnostics.Enum_member_expected; + case 7: return ts.Diagnostics.Expression_expected; + case 8: return ts.Diagnostics.Variable_declaration_expected; + case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; + case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; + case 11: return ts.Diagnostics.Argument_expression_expected; + case 12: return ts.Diagnostics.Property_assignment_expected; + case 15: return ts.Diagnostics.Expression_or_comma_expected; + case 16: return ts.Diagnostics.Parameter_declaration_expected; + case 18: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_argument_expected; + case 20: return ts.Diagnostics.Type_expected; + case 21: return ts.Diagnostics.Unexpected_token_expected; + case 22: return ts.Diagnostics.Identifier_expected; + case 13: return ts.Diagnostics.Identifier_expected; + case 14: return ts.Diagnostics.Identifier_expected; + } + } + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + var commaStart = -1; + while (true) { + if (isListElement(kind, false)) { + var startPos = scanner.getStartPos(); + result.push(parseListElement(kind, parseElement)); + commaStart = scanner.getTokenPos(); + if (parseOptional(26)) { + continue; + } + commaStart = -1; + if (isListTerminator(kind)) { + break; + } + parseExpected(26); + if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + } + if (startPos === scanner.getStartPos()) { + nextToken(); + } + continue; + } + if (isListTerminator(kind)) { + break; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + if (commaStart >= 0) { + result.hasTrailingComma = true; + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + return createNodeArray(); + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(23)) { + if (token() === 27) { + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(143, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(196); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); + var templateSpans = createNodeArray(); + do { + templateSpans.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); + templateSpans.end = getNodeEnd(); + template.templateSpans = templateSpans; + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(205); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 18) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + var text = scanner.getTokenValue(); + node.text = text; + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + if (node.kind === 8) { + node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + } + nextToken(); + finishNode(node); + return node; + } + function parseTypeReference() { + var node = createNode(159); + node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(158, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(169); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType() { + var result = createNode(268); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + nextToken(); + if (token() === 26 || + token() === 18 || + token() === 20 || + token() === 29 || + token() === 58 || + token() === 49) { + var result = createNode(269, pos); + return finishNode(result); + } + else { + var result = createNode(270, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNode(273); + nextToken(); + fillSignature(56, 4 | 32, result); + return finishNode(result); + } + var node = createNode(159); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(146); + if (token() === 99 || token() === 94) { + parameter.name = parseIdentifierName(); + parseExpected(56); + } + parameter.type = parseType(); + return finishNode(parameter); + } + function parseJSDocNodeWithType(kind) { + var result = createNode(kind); + nextToken(); + result.type = parseType(); + return finishNode(result); + } + function parseTypeQuery() { + var node = createNode(162); + parseExpected(103); + node.exprName = parseEntityName(true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + if (parseOptional(85)) { + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(58)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 27) { + return parseBracketedList(18, parseTypeParameter, 27, 29); + } + } + function parseParameterType() { + if (parseOptional(56)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter() { + return token() === 24 || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 57 || isStartOfType(); + } + function parseParameter() { + var node = createNode(146); + if (token() === 99) { + node.name = createIdentifier(true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + nextToken(); + } + node.questionToken = parseOptionalToken(55); + node.type = parseParameterType(); + node.initializer = parseBindingElementInitializer(true); + return addJSDocComment(finishNode(node)); + } + function parseBindingElementInitializer(inParameter) { + return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); + } + function parseParameterInitializer() { + return parseInitializer(true); + } + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32)) { + signature.typeParameters = parseTypeParameters(); + } + signature.parameters = parseParameterList(flags); + var returnTokenRequired = returnToken === 36; + if (returnTokenRequired) { + parseExpected(returnToken); + signature.type = parseTypeOrTypePredicate(); + } + else if (parseOptional(returnToken)) { + signature.type = parseTypeOrTypePredicate(); + } + else if (flags & 4) { + var start = scanner.getTokenPos(); + var length_1 = scanner.getTextPos() - start; + var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); + if (backwardToken) { + signature.type = parseTypeOrTypePredicate(); + parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); + } + } + } + function parseParameterList(flags) { + if (parseExpected(19)) { + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + if (!parseExpected(20) && (flags & 8)) { + return undefined; + } + return result; + } + return (flags & 8) ? undefined : createMissingList(); + } + function parseTypeMemberSemicolon() { + if (parseOptional(26)) { + return; + } + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNode(kind); + if (kind === 156) { + parseExpected(94); + } + fillSignature(56, 4, node); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(node)); + } + function isIndexSignature() { + if (token() !== 21) { + return false; + } + return lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + nextToken(); + if (token() === 24 || token() === 22) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + nextToken(); + } + if (token() === 56 || token() === 26) { + return true; + } + if (token() !== 55) { + return false; + } + nextToken(); + return token() === 56 || token() === 26 || token() === 22; + } + function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { + var node = createNode(157, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.parameters = parseBracketedList(16, parseParameter, 21, 22); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(fullStart, modifiers) { + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (token() === 19 || token() === 27) { + var method = createNode(150, fullStart); + method.modifiers = modifiers; + method.name = name; + method.questionToken = questionToken; + fillSignature(56, 4, method); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(method)); + } + else { + var property = createNode(148, fullStart); + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + if (token() === 58) { + property.initializer = parseNonParameterInitializer(); + } + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(property)); + } + } + function isTypeMemberStart() { + if (token() === 19 || token() === 27) { + return true; + } + var idToken; + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + if (token() === 21) { + return true; + } + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + if (idToken) { + return token() === 19 || + token() === 27 || + token() === 55 || + token() === 56 || + token() === 26 || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 19 || token() === 27) { + return parseSignatureMember(155); + } + if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(156); + } + var fullStart = getNodePos(); + var modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 19 || token() === 27; + } + function parseTypeLiteral() { + var node = createNode(163); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(17)) { + members = parseList(4, parseTypeMember); + parseExpected(18); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 131) { + nextToken(); + } + return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; + } + function parseMappedTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + parseExpected(92); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(172); + parseExpected(17); + node.readonlyToken = parseOptionalToken(131); + parseExpected(21); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(22); + node.questionToken = parseOptionalToken(55); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(18); + return finishNode(node); + } + function parseTupleType() { + var node = createNode(165); + node.elementTypes = parseBracketedList(20, parseType, 21, 22); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(168); + parseExpected(19); + node.type = parseType(); + parseExpected(20); + return finishNode(node); + } + function parseFunctionOrConstructorType(kind) { + var node = createNode(kind); + if (kind === 161) { + parseExpected(94); + } + fillSignature(36, 4, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 23 ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(173); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8; + } + function parseNonArrayType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 139: + case 130: + case 134: + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 39: + return parseJSDocAllType(); + case 55: + return parseJSDocUnknownOrNullableType(); + case 89: + return parseJSDocFunctionType(); + case 24: + return parseJSDocNodeWithType(274); + case 51: + return parseJSDocNodeWithType(271); + case 9: + case 8: + case 101: + case 86: + return parseLiteralTypeNode(); + case 38: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + case 105: + case 95: + return parseTokenNode(); + case 99: { + var thisKeyword = parseThisTypeNode(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 103: + return parseTypeQuery(); + case 17: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 21: + return parseTupleType(); + case 19: + return parseParenthesizedType(); + default: + return parseTypeReference(); + } + } + function isStartOfType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 105: + case 139: + case 95: + case 99: + case 103: + case 130: + case 17: + case 21: + case 27: + case 49: + case 48: + case 94: + case 9: + case 8: + case 101: + case 86: + case 134: + return true; + case 38: + return lookAhead(nextTokenIsNumericLiteral); + case 19: + return lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 20 || isStartOfParameter() || isStartOfType(); + } + function parseJSDocPostfixTypeOrHigher() { + var type = parseNonArrayType(); + var kind = getKind(token()); + if (!kind) + return type; + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + function getKind(tokenKind) { + switch (tokenKind) { + case 58: + return contextFlags & 1048576 ? 272 : undefined; + case 51: + return 271; + case 55: + return 270; + } + } + } + function parseArrayTypeOrHigher() { + var type = parseJSDocPostfixTypeOrHigher(); + while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { + if (isStartOfType()) { + var node = createNode(171, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22); + type = finishNode(node); + } + else { + var node = createNode(164, type.pos); + node.elementType = type; + parseExpected(22); + type = finishNode(node); + } + } + return type; + } + function parseTypeOperator(operator) { + var node = createNode(170); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 127: + return parseTypeOperator(127); + } + return parseArrayTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = createNodeArray([type], type.pos); + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + types.end = getNodeEnd(); + var node = createNode(kind, type.pos); + node.types = types; + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + } + function isStartOfFunctionType() { + if (token() === 27) { + return true; + } + return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + parseModifiers(); + } + if (isIdentifier() || token() === 99) { + nextToken(); + return true; + } + if (token() === 21 || token() === 17) { + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 20 || token() === 24) { + return true; + } + if (skipParameterStart()) { + if (token() === 56 || token() === 26 || + token() === 55 || token() === 58) { + return true; + } + if (token() === 20) { + nextToken(); + if (token() === 36) { + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(158, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + return doOutsideOfContext(20480, parseTypeWorker); + } + function parseTypeWorker() { + if (isStartOfFunctionType()) { + return parseFunctionOrConstructorType(160); + } + if (token() === 94) { + return parseFunctionOrConstructorType(161); + } + return parseUnionTypeOrHigher(); + } + function parseTypeAnnotation() { + return parseOptional(56) ? parseType() : undefined; + } + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 99: + case 97: + case 95: + case 101: + case 86: + case 8: + case 9: + case 13: + case 14: + case 19: + case 21: + case 17: + case 89: + case 75: + case 94: + case 41: + case 63: + case 71: + return true; + case 91: + return lookAhead(nextTokenIsOpenParenOrLessThan); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 43: + case 44: + case 27: + case 121: + case 116: + return true; + default: + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + return token() !== 17 && + token() !== 89 && + token() !== 75 && + token() !== 57 && + isStartOfExpression(); + } + function parseExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(26))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return expr; + } + function parseInitializer(inParameter) { + if (token() !== 58) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { + return undefined; + } + } + parseExpected(58); + return parseAssignmentExpressionOrHigher(); + } + function parseAssignmentExpressionOrHigher() { + if (isYieldExpression()) { + return parseYieldExpression(); + } + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + var expr = parseBinaryExpressionOrHigher(0); + if (expr.kind === 71 && token() === 36) { + return parseSimpleArrowFunctionExpression(expr); + } + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 116) { + if (inYieldContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(197); + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 39 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(39); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(187, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(187, identifier.pos); + } + var parameter = createNode(146, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos); + node.parameters.end = parameter.end; + node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(!!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0) { + return undefined; + } + var arrowFunction = triState === 1 + ? parseParenthesizedArrowFunctionExpressionHead(true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + return undefined; + } + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 36 || lastToken === 17) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return addJSDocComment(finishNode(arrowFunction)); + } + function isParenthesizedArrowFunctionExpression() { + if (token() === 19 || token() === 27 || token() === 120) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 36) { + return 1; + } + return 0; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0; + } + if (token() !== 19 && token() !== 27) { + return 0; + } + } + var first = token(); + var second = nextToken(); + if (first === 19) { + if (second === 20) { + var third = nextToken(); + switch (third) { + case 36: + case 56: + case 17: + return 1; + default: + return 0; + } + } + if (second === 21 || second === 17) { + return 2; + } + if (second === 24) { + return 1; + } + if (!isIdentifier()) { + return 0; + } + if (nextToken() === 56) { + return 1; + } + return 2; + } + else { + ts.Debug.assert(first === 27); + if (!isIdentifier()) { + return 0; + } + if (sourceFile.languageVariant === 1) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 85) { + var fourth = nextToken(); + switch (fourth) { + case 58: + case 29: + return false; + default: + return true; + } + } + else if (third === 26) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1; + } + return 0; + } + return 2; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + if (token() === 120) { + var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); + if (isUnParenthesizedAsyncArrowFunction === 1) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak() || token() === 36) { + return 0; + } + var expr = parseBinaryExpressionOrHigher(0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { + return 1; + } + } + return 0; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNode(187); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + if (!node.parameters) { + return undefined; + } + if (!allowAmbiguity && token() !== 36 && token() !== 17) { + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 17) { + return parseFunctionBlock(isAsync ? 2 : 0); + } + if (token() !== 25 && + token() !== 89 && + token() !== 75 && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + return parseFunctionBlock(16 | (isAsync ? 2 : 0)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + var questionToken = parseOptionalToken(55); + if (!questionToken) { + return leftOperand; + } + var node = createNode(195, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); + node.whenFalse = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 92 || t === 142; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + reScanGreaterToken(); + var newPrecedence = getBinaryOperatorPrecedence(); + var consumeCurrentOperator = token() === 40 ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 92 && inDisallowInContext()) { + break; + } + if (token() === 118) { + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 92) { + return false; + } + return getBinaryOperatorPrecedence() > 0; + } + function getBinaryOperatorPrecedence() { + switch (token()) { + case 54: + return 1; + case 53: + return 2; + case 49: + return 3; + case 50: + return 4; + case 48: + return 5; + case 32: + case 33: + case 34: + case 35: + return 6; + case 27: + case 29: + case 30: + case 31: + case 93: + case 92: + case 118: + return 7; + case 45: + case 46: + case 47: + return 8; + case 37: + case 38: + return 9; + case 39: + case 41: + case 42: + return 10; + case 40: + return 11; + } + return -1; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(194, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(202, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(188); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(189); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(190); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 121) { + if (inAwaitContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(191); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseUnaryExpressionOrHigher() { + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 40 ? + parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + updateExpression; + } + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 40) { + var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + if (simpleUnaryExpression.kind === 184) { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + function parseSimpleUnaryExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + return parsePrefixUnaryExpression(); + case 80: + return parseDeleteExpression(); + case 103: + return parseTypeOfExpression(); + case 105: + return parseVoidExpression(); + case 27: + return parseTypeAssertion(); + case 121: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + default: + return parseUpdateExpression(); + } + } + function isUpdateExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 121: + return false; + case 27: + if (sourceFile.languageVariant !== 1) { + return false; + } + default: + return true; + } + } + function parseUpdateExpression() { + if (token() === 43 || token() === 44) { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + return parseJsxElementOrSelfClosingElement(true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(193, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + var expression; + if (token() === 91 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + sourceFile.flags |= 524288; + expression = parseTokenNode(); + } + else { + expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 19 || token() === 23 || token() === 21) { + return expression; + } + var node = createNode(179, expression.pos); + node.expression = expression; + parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(true); + return finishNode(node); + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 71) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 99) { + return true; + } + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + function parseJsxElementOrSelfClosingElement(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + var result; + if (opening.kind === 251) { + var node = createNode(249, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement.tagName); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 250); + result = opening; + } + if (inExpressionContext && token() === 27) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(194, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(26, false, undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(10, scanner.getStartPos()); + node.containsOnlyWhiteSpaces = currentToken === 11; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild() { + switch (token()) { + case 10: + case 11: + return parseJsxText(); + case 17: + return parseJsxExpression(false); + case 27: + return parseJsxElementOrSelfClosingElement(false); + } + ts.Debug.fail("Unknown JSX child kind " + token()); + } + function parseJsxChildren(openingTagName) { + var result = createNodeArray(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14; + while (true) { + currentToken = scanner.reScanJsxToken(); + if (token() === 28) { + break; + } + else if (token() === 1) { + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + break; + } + else if (token() === 7) { + break; + } + var child = parseJsxChild(); + if (child) { + result.push(child); + } + } + result.end = scanner.getTokenPos(); + parsingContext = saveParsingContext; + return result; + } + function parseJsxAttributes() { + var jsxAttributes = createNode(254); + jsxAttributes.properties = parseList(13, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(27); + var tagName = parseJsxElementName(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 29) { + node = createNode(251, fullStart); + scanJsxText(); + } + else { + parseExpected(41); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + node = createNode(250, fullStart); + } + node.tagName = tagName; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + var expression = token() === 99 ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(23)) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(256); + parseExpected(17); + if (token() !== 18) { + node.dotDotDotToken = parseOptionalToken(24); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(18); + } + else { + parseExpected(18, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 17) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(253); + node.name = parseIdentifierName(); + if (token() === 58) { + switch (scanJsxAttributeValue()) { + case 9: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(255); + parseExpected(17); + parseExpected(24); + node.expression = parseExpression(); + parseExpected(18); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(252); + parseExpected(28); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(184); + parseExpected(27); + node.type = parseType(); + parseExpected(29); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(23); + if (dotToken) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 51 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(203, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + if (!inDecoratorContext() && parseOptional(21)) { + var indexedAccess = createNode(180, expression.pos); + indexedAccess.expression = expression; + if (token() !== 22) { + indexedAccess.argumentExpression = allowInAnd(parseExpression); + if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { + var literal = indexedAccess.argumentExpression; + literal.text = internIdentifier(literal.text); + } + } + parseExpected(22); + expression = finishNode(indexedAccess); + continue; + } + if (token() === 13 || token() === 14) { + var tagExpression = createNode(183, expression.pos); + tagExpression.tag = expression; + tagExpression.template = token() === 13 + ? parseLiteralNode() + : parseTemplateExpression(); + expression = finishNode(tagExpression); + continue; + } + return expression; + } + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 27) { + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 19) { + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(19); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(20); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(27)) { + return undefined; + } + var typeArguments = parseDelimitedList(19, parseType); + if (!parseExpected(29)) { + return undefined; + } + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 19: + case 23: + case 20: + case 22: + case 56: + case 25: + case 55: + case 32: + case 34: + case 33: + case 35: + case 53: + case 54: + case 50: + case 48: + case 49: + case 18: + case 1: + return true; + case 26: + case 17: + default: + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8: + case 9: + case 13: + return parseLiteralNode(); + case 99: + case 97: + case 95: + case 101: + case 86: + return parseTokenNode(); + case 19: + return parseParenthesizedExpression(); + case 21: + return parseArrayLiteralExpression(); + case 17: + return parseObjectLiteralExpression(); + case 120: + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 75: + return parseClassExpression(); + case 89: + return parseFunctionExpression(); + case 94: + return parseNewExpression(); + case 41: + case 63: + if (reScanSlashToken() === 12) { + return parseLiteralNode(); + } + break; + case 14: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNode(185); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + return addJSDocComment(finishNode(node)); + } + function parseSpreadElement() { + var node = createNode(198); + parseExpected(24); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 24 ? parseSpreadElement() : + token() === 26 ? createNode(200) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(177); + parseExpected(21); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); + parseExpected(22); + return finishNode(node); + } + function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + } + else if (parseContextualModifier(135)) { + return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + } + return undefined; + } + function parseObjectLiteralElement() { + var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(24); + if (dotDotDotToken) { + var spreadElement = createNode(263, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + var asteriskToken = parseOptionalToken(39); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + } + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); + if (isShorthandPropertyAssignment) { + var shorthandDeclaration = createNode(262, fullStart); + shorthandDeclaration.name = propertyName; + shorthandDeclaration.questionToken = questionToken; + var equalsToken = parseOptionalToken(58); + if (equalsToken) { + shorthandDeclaration.equalsToken = equalsToken; + shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return addJSDocComment(finishNode(shorthandDeclaration)); + } + else { + var propertyAssignment = createNode(261, fullStart); + propertyAssignment.modifiers = modifiers; + propertyAssignment.name = propertyName; + propertyAssignment.questionToken = questionToken; + parseExpected(56); + propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + return addJSDocComment(finishNode(propertyAssignment)); + } + } + function parseObjectLiteralExpression() { + var node = createNode(178); + parseExpected(17); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); + parseExpected(18); + return finishNode(node); + } + function parseFunctionExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var node = createNode(186); + node.modifiers = parseModifiers(); + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return addJSDocComment(finishNode(node)); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpression() { + var fullStart = scanner.getStartPos(); + parseExpected(94); + if (parseOptional(23)) { + var node_1 = createNode(204, fullStart); + node_1.keywordToken = 94; + node_1.name = parseIdentifierName(); + return finishNode(node_1); + } + var node = createNode(182, fullStart); + node.expression = parseMemberExpressionOrHigher(); + node.typeArguments = tryParse(parseTypeArgumentsInExpression); + if (node.typeArguments || token() === 19) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(207); + if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2)); + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var block = parseBlock(!!(flags & 16), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(209); + parseExpected(25); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(211); + parseExpected(90); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(82) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(212); + parseExpected(81); + node.statement = parseStatement(); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + parseOptional(25); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(213); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(88); + var awaitToken = parseOptionalToken(121); + parseExpected(19); + var initializer = undefined; + if (token() !== 25) { + if (token() === 104 || token() === 110 || token() === 76) { + initializer = parseVariableDeclarationList(true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(142) : parseOptional(142)) { + var forOfStatement = createNode(216, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(20); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(92)) { + var forInStatement = createNode(215, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(20); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(214, pos); + forStatement.initializer = initializer; + parseExpected(25); + if (token() !== 25 && token() !== 20) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(25); + if (token() !== 20) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(20); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 218 ? 72 : 77); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(219); + parseExpected(96); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(220); + parseExpected(107); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(257); + parseExpected(73); + node.expression = allowInAnd(parseExpression); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(258); + parseExpected(79); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 73 ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(221); + parseExpected(98); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + var caseBlock = createNode(235, scanner.getStartPos()); + parseExpected(17); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(18); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + var node = createNode(223); + parseExpected(100); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + function parseTryStatement() { + var node = createNode(224); + parseExpected(102); + node.tryBlock = parseBlock(false); + node.catchClause = token() === 74 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 87) { + parseExpected(87); + node.finallyBlock = parseBlock(false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(260); + parseExpected(74); + if (parseExpected(19)) { + result.variableDeclaration = parseVariableDeclaration(); + } + parseExpected(20); + result.block = parseBlock(false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(225); + parseExpected(78); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + var fullStart = scanner.getStartPos(); + var expression = allowInAnd(parseExpression); + if (expression.kind === 71 && parseOptional(56)) { + var labeledStatement = createNode(222, fullStart); + labeledStatement.label = expression; + labeledStatement.statement = parseStatement(); + return addJSDocComment(finishNode(labeledStatement)); + } + else { + var expressionStatement = createNode(210, fullStart); + expressionStatement.expression = expression; + parseSemicolon(); + return addJSDocComment(finishNode(expressionStatement)); + } + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 75 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 89 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 104: + case 110: + case 76: + case 89: + case 75: + case 83: + return true; + case 109: + case 138: + return nextTokenIsIdentifierOnSameLine(); + case 128: + case 129: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 117: + case 120: + case 124: + case 112: + case 113: + case 114: + case 131: + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 141: + nextToken(); + return token() === 17 || token() === 71 || token() === 84; + case 91: + nextToken(); + return token() === 9 || token() === 39 || + token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); + case 84: + nextToken(); + if (token() === 58 || token() === 39 || + token() === 17 || token() === 79 || + token() === 118) { + return true; + } + continue; + case 115: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 57: + case 25: + case 17: + case 104: + case 110: + case 89: + case 75: + case 83: + case 90: + case 81: + case 106: + case 88: + case 77: + case 72: + case 96: + case 107: + case 98: + case 100: + case 102: + case 78: + case 74: + case 87: + return true; + case 91: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + case 76: + case 84: + return isStartOfDeclaration(); + case 120: + case 124: + case 109: + case 128: + case 129: + case 138: + case 141: + return true; + case 114: + case 112: + case 113: + case 115: + case 131: + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 17 || token() === 21; + } + function isLetDeclaration() { + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 25: + return parseEmptyStatement(); + case 17: + return parseBlock(false); + case 104: + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 110: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; + case 89: + return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); + case 75: + return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); + case 90: + return parseIfStatement(); + case 81: + return parseDoStatement(); + case 106: + return parseWhileStatement(); + case 88: + return parseForOrForInOrForOfStatement(); + case 77: + return parseBreakOrContinueStatement(217); + case 72: + return parseBreakOrContinueStatement(218); + case 96: + return parseReturnStatement(); + case 107: + return parseWithStatement(); + case 98: + return parseSwitchStatement(); + case 100: + return parseThrowStatement(); + case 102: + case 74: + case 87: + return parseTryStatement(); + case 78: + return parseDebuggerStatement(); + case 57: + return parseDeclaration(); + case 120: + case 109: + case 138: + case 128: + case 129: + case 124: + case 76: + case 83: + case 84: + case 91: + case 112: + case 113: + case 114: + case 117: + case 115: + case 131: + case 141: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function parseDeclaration() { + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + switch (token()) { + case 104: + case 110: + case 76: + return parseVariableStatement(fullStart, decorators, modifiers); + case 89: + return parseFunctionDeclaration(fullStart, decorators, modifiers); + case 75: + return parseClassDeclaration(fullStart, decorators, modifiers); + case 109: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 138: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 83: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 141: + case 128: + case 129: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 91: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 84: + nextToken(); + switch (token()) { + case 79: + case 58: + return parseExportAssignment(fullStart, decorators, modifiers); + case 118: + return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + default: + return parseExportDeclaration(fullStart, decorators, modifiers); + } + default: + if (decorators || modifiers) { + var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + node.modifiers = modifiers; + return finishNode(node); + } + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 17 && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + function parseArrayBindingElement() { + if (token() === 26) { + return createNode(200); + } + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 56) { + node.name = propertyName; + } + else { + parseExpected(56); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(174); + parseExpected(17); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(18); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(175); + parseExpected(21); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(22); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 17 || token() === 21 || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 21) { + return parseArrayBindingPattern(); + } + if (token() === 17) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclaration() { + var node = createNode(226); + node.name = parseIdentifierOrPattern(); + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(false); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(227); + switch (token()) { + case 104: + break; + case 110: + node.flags |= 1; + break; + case 76: + node.flags |= 2; + break; + default: + ts.Debug.fail(); + } + nextToken(); + if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 20; + } + function parseVariableStatement(fullStart, decorators, modifiers) { + var node = createNode(208, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.declarationList = parseVariableDeclarationList(false); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseFunctionDeclaration(fullStart, decorators, modifiers) { + var node = createNode(228, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseConstructorDeclaration(pos, decorators, modifiers) { + var node = createNode(152, pos); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(123); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { + var method = createNode(151, fullStart); + method.decorators = decorators; + method.modifiers = modifiers; + method.asteriskToken = asteriskToken; + method.name = name; + method.questionToken = questionToken; + var isGenerator = asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(method, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, method); + method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return addJSDocComment(finishNode(method)); + } + function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { + var property = createNode(149, fullStart); + property.decorators = decorators; + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + property.initializer = ts.hasModifier(property, 32) + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); + parseSemicolon(); + return addJSDocComment(finishNode(property)); + } + function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + var asteriskToken = parseOptionalToken(39); + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + } + else { + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + } + } + function parseNonParameterInitializer() { + return parseInitializer(false); + } + function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.name = parsePropertyName(); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0); + return addJSDocComment(finishNode(node)); + } + function isClassMemberModifier(idToken) { + switch (idToken) { + case 114: + case 112: + case 113: + case 115: + case 131: + return true; + default: + return false; + } + } + function isClassMemberStart() { + var idToken; + if (token() === 57) { + return true; + } + while (ts.isModifierKind(token())) { + idToken = token(); + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 39) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + if (token() === 21) { + return true; + } + if (idToken !== undefined) { + if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { + return true; + } + switch (token()) { + case 19: + case 27: + case 56: + case 58: + case 55: + return true; + default: + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var decorators; + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(57)) { + break; + } + var decorator = createNode(147, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } + } + if (decorators) { + decorators.end = getNodeEnd(); + } + return decorators; + } + function parseModifiers(permitInvalidConstAsModifier) { + var modifiers; + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 76 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + if (!modifiers) { + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); + } + } + if (modifiers) { + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 120) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseClassElement() { + if (token() === 25) { + var result = createNode(206); + nextToken(); + return finishNode(result); + } + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(true); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + if (token() === 123) { + return parseConstructorDeclaration(fullStart, decorators, modifiers); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + } + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8 || + token() === 39 || + token() === 21) { + return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + } + if (decorators || modifiers) { + var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + } + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + } + function parseClassDeclaration(fullStart, decorators, modifiers) { + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + } + function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(75); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(17)) { + node.members = parseClassMembers(); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseNameOfClassDeclarationOrExpression() { + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + if (isHeritageClause()) { + return parseList(21, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + if (tok === 85 || tok === 108) { + var node = createNode(259); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); + } + return undefined; + } + function parseExpressionWithTypeArguments() { + var node = createNode(201); + node.expression = parseLeftHandSideExpressionOrHigher(); + if (token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function isHeritageClause() { + return token() === 85 || token() === 108; + } + function parseClassMembers() { + return parseList(5, parseClassElement); + } + function parseInterfaceDeclaration(fullStart, decorators, modifiers) { + var node = createNode(230, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(109); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return addJSDocComment(finishNode(node)); + } + function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { + var node = createNode(231, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(138); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(58); + node.type = parseType(); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseEnumMember() { + var node = createNode(264, scanner.getStartPos()); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseNonParameterInitializer); + return addJSDocComment(finishNode(node)); + } + function parseEnumDeclaration(fullStart, decorators, modifiers) { + var node = createNode(232, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(83); + node.name = parseIdentifier(); + if (parseExpected(17)) { + node.members = parseDelimitedList(6, parseEnumMember); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseModuleBlock() { + var node = createNode(234, scanner.getStartPos()); + if (parseExpected(17)) { + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { + var node = createNode(233, fullStart); + var namespaceFlag = flags & 16; + node.decorators = decorators; + node.modifiers = modifiers; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(23) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + : parseModuleBlock(); + return addJSDocComment(finishNode(node)); + } + function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { + var node = createNode(233, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (token() === 141) { + node.name = parseIdentifier(); + node.flags |= 512; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 17) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(fullStart, decorators, modifiers) { + var flags = 0; + if (token() === 141) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(129)) { + flags |= 16; + } + else { + parseExpected(128); + if (token() === 9) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + } + return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + } + function isExternalModuleReference() { + return token() === 132 && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 19; + } + function nextTokenIsSlash() { + return nextToken() === 41; + } + function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { + var exportDeclaration = createNode(236, fullStart); + exportDeclaration.decorators = decorators; + exportDeclaration.modifiers = modifiers; + parseExpected(118); + parseExpected(129); + exportDeclaration.name = parseIdentifier(); + parseSemicolon(); + return finishNode(exportDeclaration); + } + function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + parseExpected(91); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 26 && token() !== 140) { + return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + } + } + var importDeclaration = createNode(238, fullStart); + importDeclaration.decorators = decorators; + importDeclaration.modifiers = modifiers; + if (identifier || + token() === 39 || + token() === 17) { + importDeclaration.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(140); + } + importDeclaration.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(importDeclaration); + } + function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { + var importEqualsDeclaration = createNode(237, fullStart); + importEqualsDeclaration.decorators = decorators; + importEqualsDeclaration.modifiers = modifiers; + importEqualsDeclaration.name = identifier; + parseExpected(58); + importEqualsDeclaration.moduleReference = parseModuleReference(); + parseSemicolon(); + return addJSDocComment(finishNode(importEqualsDeclaration)); + } + function parseImportClause(identifier, fullStart) { + var importClause = createNode(239, fullStart); + if (identifier) { + importClause.name = identifier; + } + if (!importClause.name || + parseOptional(26)) { + importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(false); + } + function parseExternalModuleReference() { + var node = createNode(248); + parseExpected(132); + parseExpected(19); + node.expression = parseModuleSpecifier(); + parseExpected(20); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 9) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + return parseExpression(); + } + } + function parseNamespaceImport() { + var namespaceImport = createNode(240); + parseExpected(39); + parseExpected(118); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(246); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(242); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 118) { + node.propertyName = identifierName; + parseExpected(118); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 242 && checkIdentifierIsKeyword) { + parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(fullStart, decorators, modifiers) { + var node = createNode(244, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(39)) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(245); + if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(fullStart, decorators, modifiers) { + var node = createNode(243, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(58)) { + node.isExportEquals = true; + } + else { + parseExpected(79); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function processReferenceComments(sourceFile) { + var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); + var referencedFiles = []; + var typeReferenceDirectives = []; + var amdDependencies = []; + var amdModuleName; + var checkJsDirective = undefined; + while (true) { + var kind = triviaScanner.scan(); + if (kind !== 2) { + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); + if (referencePathMatchResult) { + var fileReference = referencePathMatchResult.fileReference; + sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + if (fileReference) { + if (referencePathMatchResult.isTypeReferenceDirective) { + typeReferenceDirectives.push(fileReference); + } + else { + referencedFiles.push(fileReference); + } + } + if (diagnosticMessage) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + } + } + else { + var amdModuleNameRegEx = /^\/\/\/\s*= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + var tags; + var comments = []; + var result; + if (!isJsDocStart(content, start)) { + return result; + } + scanner.scanRange(start + 3, length - 5, function () { + var advanceToken = true; + var state = 1; + var margin = undefined; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5) { + nextJSDocToken(); + } + if (token() === 4) { + state = 0; + indent = 0; + nextJSDocToken(); + } + while (token() !== 1) { + switch (token()) { + case 57: + if (state === 0 || state === 1) { + removeTrailingNewlines(comments); + parseTag(indent); + state = 0; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 39: + var asterisk = scanner.getTokenText(); + if (state === 1 || state === 2) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 71: + pushComment(scanner.getTokenText()); + state = 2; + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break; + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { + nextJSDocToken(); + } + else { + advanceToken = true; + } + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42; + } + function createJSDocComment() { + var result = createNode(275, start); + result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function skipWhitespace() { + while (token() === 5 || token() === 4) { + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return; + } + var tag; + if (tagName) { + switch (tagName.escapedText) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + tag = parseParameterOrPropertyTag(atToken, tagName, 1); + break; + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; + } + } + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + } + function parseTagComments(indent) { + var comments = []; + var state = 0; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 57 && token() !== 1) { + switch (token()) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 57: + break; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 39: + if (state === 0) { + state = 1; + indent += scanner.getTokenText().length; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (token() === 57) { + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { + var result = createNode(276, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); + } + else { + tags.push(tag); + } + tags.end = tag.end; + } + function tryParseTypeExpression() { + return tryParse(function () { + skipWhitespace(); + if (token() !== 17) { + return undefined; + } + return parseJSDocTypeExpression(); + }); + } + function parseBracketNameInPropertyAndParamTag() { + var isBracketed = parseOptional(21); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + if (parseOptionalToken(58)) { + parseExpression(); + } + parseExpected(22); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 134: + return true; + case 164: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(atToken, tagName, target) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespace(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 ? + createNode(279, atToken.pos) : + createNode(284, atToken.pos); + var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { + if (!children) { + children = []; + } + children.push(child); + } + if (children) { + jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(280, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(281, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(277, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } + function parseClassTag(atToken, tagName) { + var tag = createNode(278, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var typedefTag = createNode(283, atToken.pos); + typedefTag.atToken = atToken; + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (true) { + if (rightNode.kind === 71 || !rightNode.body) { + typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; + break; + } + rightNode = rightNode.body; + } + } + skipWhitespace(); + typedefTag.typeExpression = typeExpression; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var alreadyHasTypeTag = false; + var start_3 = scanner.getStartPos(); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(285, start_3); + } + if (child.kind === 281) { + if (alreadyHasTypeTag) { + break; + } + else { + jsdocTypeLiteral.jsDocTypeTag = child; + alreadyHasTypeTag = true; + } + } + else { + if (!jsdocTypeLiteral.jsDocPropertyTags) { + jsdocTypeLiteral.jsDocPropertyTags = []; + } + jsdocTypeLiteral.jsDocPropertyTags.push(child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + } + } + return finishNode(typedefTag); + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23)) { + var jsDocNamespaceNode = createNode(233, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && flags & 4) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildParameterOrPropertyTag(target, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + nextJSDocToken(); + switch (token()) { + case 57: + if (canParseTag) { + var child = tryParseChildTag(target); + if (child && child.kind === 279 && + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4: + canParseTag = true; + seenAsterisk = false; + break; + case 39: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 71: + canParseTag = false; + break; + case 1: + return false; + } + } + } + function tryParseChildTag(target) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getStartPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return false; + } + switch (tagName.escapedText) { + case "type": + return target === 0 && parseTypeTag(atToken, tagName); + case "prop": + case "property": + return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + case "arg": + case "argument": + case "param": + return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + } + return false; + } + function parseTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var typeParameters = createNodeArray(); + while (true) { + var name = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(145, name.pos); + typeParameter.name = name; + finishNode(typeParameter); + typeParameters.push(typeParameter); + if (token() === 26) { + nextJSDocToken(); + skipWhitespace(); + } + else { + break; + } + } + var result = createNode(282, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + finishNode(result); + typeParameters.end = result.end; + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + while (parseOptional(23)) { + var name = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(createIfMissing) { + if (createIfMissing === void 0) { createIfMissing = false; } + if (!ts.tokenIsIdentifierOrKeyword(token())) { + if (createIfMissing) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); + return undefined; + } + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(71, pos); + result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); + } + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + forEachChild(jsDocComment, visitNode, visitArray); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 9: + case 8: + case 71: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + element.pos = Math.min(element.pos, changeRangeNewEnd); + if (element.end >= changeRangeOldEnd) { + element.end += delta; + } + else { + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + checkNodePositions(child, aggressiveChecks); + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; + visitNode(node); + } + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + var maxLookahead = 1; + var start = changeRange.span.start; + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } + else { + ts.Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1; + return { + currentNode: function (position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = undefined; + currentArrayIndex = -1; + current = undefined; + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode, visitArray); + return true; + } + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + return false; + } + } + } + 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; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2; + } + else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { + return 0; + } + else if (node.kind === 234) { + var state_1 = 0; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0: + return false; + case 2: + state_1 = 2; + return false; + case 1: + state_1 = 1; + return true; + } + }); + return state_1; + } + else if (node.kind === 233) { + var body = node.body; + return body ? getModuleInstanceState(body) : 1; + } + else if (node.kind === 71 && node.isInJSDocNamespace) { + return 0; + } + else { + return 1; + } + } + 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"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + var emitFlags; + var inStrictMode; + var symbolCount = 0; + var Symbol; + var classifiableNames; + var unreachableFlow = { flags: 1 }; + var reportedUnreachableFlow = { flags: 1 }; + var subtreeTransformFlags = 0; + var skipTransformFlagAggregation; + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0; + subtreeTransformFlags = 0; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & 6240 && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { + symbol.valueDeclaration = node; + } + } + } + function getDeclarationName(node) { + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 144) { + var nameExpression = name.expression; + if (ts.isStringOrNumericLiteral(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + } + return ts.getEscapedTextOfIdentifierOrLiteral(name); + } + switch (node.kind) { + case 152: + return "__constructor"; + case 160: + case 155: + return "__call"; + case 161: + case 156: + return "__new"; + case 157: + return "__index"; + case 244: + return "__export"; + case 243: + return node.isExportEquals ? "export=" : "default"; + case 194: + if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + return "export="; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 228: + case 229: + return (ts.hasModifier(node, 512) ? "default" : undefined); + case 273: + return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); + case 146: + ts.Debug.assert(node.parent.kind === 273); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "arg" + index; + case 283: + var parentNode = node.parent && node.parent.parent; + var nameFromParentNode = void 0; + if (parentNode && parentNode.kind === 208) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (ts.isIdentifier(nameIdentifier)) { + nameFromParentNode = nameIdentifier.escapedText; + } + } + } + return nameFromParentNode; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + } + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512); + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0, "__missing"); + } + else { + symbol = symbolTable.get(name); + if (includes & 788448) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + symbolTable.set(name, symbol = createSymbol(0, name)); + } + else { + if (node.name) { + node.name.parent = node; + } + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; + if (symbolFlags & 2097152) { + if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + if (node.kind === 283) + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var isJSDocTypedefInJSDocNamespace = node.kind === 283 && + node.name && + node.name.kind === 71 && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { + var exportKind = symbolFlags & 107455 ? 1048576 : 0; + var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + } + function bindContainer(node, containerFlags) { + var saveContainer = container; + var savedBlockScopeContainer = blockScopeContainer; + if (containerFlags & 1) { + container = blockScopeContainer = node; + if (containerFlags & 32) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); + if (isIIFE) { + currentReturnTarget = createBranchLabel(); + } + else { + currentFlow = { flags: 2 }; + if (containerFlags & (16 | 128)) { + currentFlow.container = node; + } + currentReturnTarget = undefined; + } + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + node.flags &= ~1408; + if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { + node.flags |= 128; + if (hasExplicitReturn) + node.flags |= 256; + } + if (node.kind === 265) { + node.flags |= emitFlags; + } + if (isIIFE) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + } + else { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; + } + else { + bindChildren(node); + } + container = saveContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (node.jsDoc) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + if (checkUnreachable(node)) { + bindEachChild(node); + return; + } + switch (node.kind) { + case 213: + bindWhileStatement(node); + break; + case 212: + bindDoStatement(node); + break; + case 214: + bindForStatement(node); + break; + case 215: + case 216: + bindForInOrForOfStatement(node); + break; + case 211: + bindIfStatement(node); + break; + case 219: + case 223: + bindReturnOrThrow(node); + break; + case 218: + case 217: + bindBreakOrContinueStatement(node); + break; + case 224: + bindTryStatement(node); + break; + case 221: + bindSwitchStatement(node); + break; + case 235: + bindCaseBlock(node); + break; + case 257: + bindCaseClause(node); + break; + case 222: + bindLabeledStatement(node); + break; + case 192: + bindPrefixUnaryExpressionFlow(node); + break; + case 193: + bindPostfixUnaryExpressionFlow(node); + break; + case 194: + bindBinaryExpressionFlow(node); + break; + case 188: + bindDeleteExpressionFlow(node); + break; + case 195: + bindConditionalExpressionFlow(node); + break; + case 226: + bindVariableDeclarationFlow(node); + break; + case 181: + bindCallExpressionFlow(node); + break; + case 275: + bindJSDocComment(node); + break; + case 283: + bindJSDocTypedefTag(node); + break; + default: + bindEachChild(node); + break; + } + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 71: + case 99: + case 179: + return isNarrowableReference(expr); + case 181: + return hasNarrowableArgument(expr); + case 185: + return isNarrowingExpression(expr.expression); + case 194: + return isNarrowingBinaryExpression(expr); + case 192: + return expr.operator === 51 && isNarrowingExpression(expr.operand); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 71 || + expr.kind === 99 || + expr.kind === 97 || + expr.kind === 179 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 179 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 58: + return isNarrowableReference(expr.left); + case 32: + case 33: + case 34: + case 35: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 93: + return isNarrowableOperand(expr.left); + case 26: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 185: + return isNarrowableOperand(expr.expression); + case 194: + switch (expr.operatorToken.kind) { + case 58: + return isNarrowableOperand(expr.left); + case 26: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + flow.flags |= flow.flags & 512 ? 1024 : 512; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1) { + return antecedent; + } + if (!expression) { + return flags & 32 ? antecedent : unreachableFlow; + } + if (expression.kind === 101 && flags & 64 || + expression.kind === 86 && flags & 32) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: flags, + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent + }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 16, + antecedent: antecedent, + node: node + }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256, + antecedent: antecedent, + node: node + }; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 211: + case 213: + case 212: + return parent.expression === node; + case 214: + case 195: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 185) { + node = node.expression; + } + else if (node.kind === 192 && node.operator === 51) { + node = node.operand; + } + else { + return node.kind === 194 && (node.operatorToken.kind === 53 || + node.operatorToken.kind === 54); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 185 || + node.parent.kind === 192 && + node.parent.operator === 51) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 222 + ? ts.lastOrUndefined(activeLabels) + : undefined; + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 216) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 227) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 219) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 218 ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + if (!(currentFlow.flags & 1)) { + if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1)) { + var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + } + if (!node.statement || node.statement.kind !== 212) { + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 194 && node.operatorToken.kind === 58) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 177) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 198) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 178) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 261) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 262) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 263) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 53) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 51) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 43 || node.operator === 44) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 43 || node.operator === 44) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 53 || operator === 54) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 58 && node.left.kind === 180) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 179) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocComment(node) { + ts.forEachChild(node, function (n) { + if (n.kind !== 283) { + bind(n); + } + }); + } + function bindJSDocTypedefTag(node) { + ts.forEachChild(node, function (n) { + if (node.fullName && n === node.name && node.fullName.kind !== 71) { + return; + } + bind(n); + }); + } + function bindCallExpressionFlow(node) { + var expr = node.expression; + while (expr.kind === 185) { + expr = expr.expression; + } + if (expr.kind === 186 || expr.kind === 187) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 179) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 199: + case 229: + case 232: + case 178: + case 163: + case 285: + case 254: + return 1; + case 230: + return 1 | 64; + case 233: + case 231: + case 172: + return 1 | 32; + case 265: + return 1 | 4 | 32; + case 151: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } + case 152: + case 228: + case 150: + case 153: + case 154: + case 155: + case 273: + case 160: + case 156: + case 157: + case 161: + return 1 | 4 | 32 | 8; + case 186: + case 187: + return 1 | 4 | 32 | 8 | 16; + case 234: + return 4; + case 149: + return node.initializer ? 4 : 0; + case 260: + case 214: + case 215: + case 216: + case 235: + return 2; + case 207: + return ts.isFunctionLike(node.parent) ? 0 : 2; + } + return 0; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + case 233: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 265: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 199: + case 229: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 232: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 163: + case 285: + case 178: + case 230: + case 254: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 160: + case 161: + case 155: + case 156: + case 157: + case 151: + case 150: + case 152: + case 153: + case 154: + case 228: + case 186: + case 187: + case 273: + case 231: + case 172: + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 265 ? node : node.body; + if (body && (body.kind === 265 || body.kind === 234)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 244 || stat.kind === 243) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 32; + } + else { + node.flags &= ~32; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isExternalModuleAugmentation(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 9) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); + if (pattern) { + (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); + } + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0) { + if (node.symbol.flags & (16 | 32 | 256)) { + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2; + if (node.symbol.constEnumOnlyModule === undefined) { + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); + return state; + } + function bindFunctionOrConstructorType(node) { + var symbol = createSymbol(131072, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072); + var typeLiteralSymbol = createSymbol(2048, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, 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.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263 || prop.name.kind !== 71) { + continue; + } + var identifier = prop.name; + var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 + ? 1 + : 2; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 && existingKind === 1) { + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096, "__object"); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 233: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 265: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2, 107455); + } + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 108 && + node.originalKeywordKind <= 116 && + !ts.isIdentifierName(node) && + !ts.isInAmbientContext(node)) { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + if (inStrictMode && node.expression.kind === 71) { + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 71) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2) { + if (blockScopeContainer.kind !== 265 && + blockScopeContainer.kind !== 233 && + !ts.isFunctionLike(blockScopeContainer)) { + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 4) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + if (inStrictMode) { + if (node.operator === 43 || node.operator === 44) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + if (ts.isInJavaScriptFile(node)) + bindJSDocTypedefTagIfAny(node); + bindWorker(node); + if (node.kind > 142) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } + inStrictMode = saveInStrictMode; + } + function bindJSDocTypedefTagIfAny(node) { + if (!node.jsDoc) { + return; + } + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (!jsDoc.tags) { + continue; + } + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.kind === 283) { + var savedParent = parent; + parent = jsDoc; + bind(tag); + parent = savedParent; + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + case 71: + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 283) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288, 793064); + break; + } + case 99: + if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 179: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + break; + case 194: + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 5: + bindStaticPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 260: + return checkStrictModeCatchClause(node); + case 188: + return checkStrictModeDeleteExpression(node); + case 8: + return checkStrictModeNumericLiteral(node); + case 193: + return checkStrictModePostfixUnaryExpression(node); + case 192: + return checkStrictModePrefixUnaryExpression(node); + case 220: + return checkStrictModeWithStatement(node); + case 169: + seenThisKeyword = true; + return; + case 158: + return checkTypePredicate(node); + case 145: + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + case 146: + return bindParameter(node); + case 226: + return bindVariableDeclarationOrBindingElement(node); + case 176: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 149: + case 148: + return bindPropertyWorker(node); + case 261: + case 262: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 264: + return bindPropertyOrMethodOrAccessor(node, 8, 900095); + case 155: + case 156: + case 157: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 151: + case 150: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + case 228: + return bindFunctionDeclaration(node); + case 152: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 153: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 154: + return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + case 160: + case 273: + case 161: + return bindFunctionOrConstructorType(node); + case 163: + case 285: + case 172: + return bindAnonymousTypeWorker(node); + case 178: + return bindObjectLiteralExpression(node); + case 186: + case 187: + return bindFunctionExpression(node); + case 181: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + case 199: + case 229: + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 230: + return bindBlockScopedDeclaration(node, 64, 792968); + case 231: + return bindBlockScopedDeclaration(node, 524288, 793064); + case 232: + return bindEnumDeclaration(node); + case 233: + return bindModuleDeclaration(node); + case 254: + return bindJsxAttributes(node); + case 253: + return bindJsxAttribute(node, 4, 0); + case 237: + case 240: + case 242: + case 246: + return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + case 236: + return bindNamespaceExportDeclaration(node); + case 239: + return bindImportClause(node); + case 244: + return bindExportDeclaration(node); + case 243: + return bindExportAssignment(node); + case 265: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 207: + if (!ts.isFunctionLike(node.parent)) { + return; + } + case 234: + return updateStrictModeStatementList(node.statements); + case 279: + if (node.parent.kind !== 285) { + break; + } + case 284: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? + 4 | 16777216 : + 4; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0); + case 283: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048, "__type"); + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 71) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 169) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); + } + else { + var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) + ? 2097152 + : 4; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 2097152 | 32 | 16); + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + if (node.parent.kind !== 265) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + } + else if (!node.exportClause) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + } + } + function setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } + } + } + function bindExportsPropertyAssignment(node) { + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); + } + function isExportsOrModuleExportsOrAlias(node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + isNameOfExportsOrModuleExportsAliasDeclaration(node); + } + function isNameOfExportsOrModuleExportsAliasDeclaration(node) { + if (ts.isIdentifier(node)) { + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); + } + return false; + } + function isExportsOrModuleExportsOrAliasOrAssignment(node) { + return isExportsOrModuleExportsOrAlias(node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); + } + function bindModuleExportsAssignment(node) { + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + setCommonJsModuleIndicator(node); + return; + } + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node, 4 | 1048576 | 512, 0); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var container = ts.getThisContainer(node, false); + switch (container.kind) { + case 228: + case 186: + container.symbol.members = container.symbol.members || ts.createSymbolTable(); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + break; + case 152: + case 149: + case 151: + case 153: + case 154: + var containingClass = container.parent; + var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); + break; + } + } + function bindPrototypePropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); + } + function bindStaticPropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var target = leftSideOfAssignment.expression; + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); + } + } + function lookupSymbolForName(name) { + return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); + } + function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { + var targetSymbol = lookupSymbolForName(functionName); + if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { + targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + } + if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { + return; + } + var symbolTable = isPrototypeProperty ? + (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : + (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); + declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); + } + function bindCallExpression(node) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 229) { + bindBlockScopedDeclaration(node, 32, 899519); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class"; + bindAnonymousDeclaration(node, 32, bindingName); + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + var prototypeSymbol = createSymbol(4 | 4194304, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isConst(node) + ? bindBlockScopedDeclaration(node, 128, 899967) + : bindBlockScopedDeclaration(node, 256, 899327); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + declareSymbolAndAddToSymbolTable(node, 1, 107455); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 107454); + } + } + } + function bindParameter(node) { + if (inStrictMode && !ts.isInAmbientContext(node)) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 107455); + } + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16, 106927); + } + else { + declareSymbolAndAddToSymbolTable(node, 16, 106927); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function"; + return bindAnonymousDeclaration(node, 16, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || + node.kind === 229 || + (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 208 || + ts.getCombinedNodeFlags(node.declarationList) & 3 || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + } + return true; + } + } + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 181: + return computeCallExpression(node, subtreeFlags); + case 182: + return computeNewExpression(node, subtreeFlags); + case 233: + return computeModuleDeclaration(node, subtreeFlags); + case 185: + return computeParenthesizedExpression(node, subtreeFlags); + case 194: + return computeBinaryExpression(node, subtreeFlags); + case 210: + return computeExpressionStatement(node, subtreeFlags); + case 146: + return computeParameter(node, subtreeFlags); + case 187: + return computeArrowFunction(node, subtreeFlags); + case 186: + return computeFunctionExpression(node, subtreeFlags); + case 228: + return computeFunctionDeclaration(node, subtreeFlags); + case 226: + return computeVariableDeclaration(node, subtreeFlags); + case 227: + return computeVariableDeclarationList(node, subtreeFlags); + case 208: + return computeVariableStatement(node, subtreeFlags); + case 222: + return computeLabeledStatement(node, subtreeFlags); + case 229: + return computeClassDeclaration(node, subtreeFlags); + case 199: + return computeClassExpression(node, subtreeFlags); + case 259: + return computeHeritageClause(node, subtreeFlags); + case 260: + return computeCatchClause(node, subtreeFlags); + case 201: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 152: + return computeConstructor(node, subtreeFlags); + case 149: + return computePropertyDeclaration(node, subtreeFlags); + case 151: + return computeMethod(node, subtreeFlags); + case 153: + case 154: + return computeAccessor(node, subtreeFlags); + case 237: + return computeImportEquals(node, subtreeFlags); + case 179: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288 + || isSuperOrSuperProperty(expression, expressionKind)) { + transformFlags |= 192; + } + if (expression.kind === 91) { + transformFlags |= 67108864; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 97: + return true; + case 179: + case 180: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 97; + } + return false; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 58 && leftKind === 178) { + transformFlags |= 8 | 192 | 3072; + } + else if (operatorTokenKind === 58 && leftKind === 177) { + transformFlags |= 192 | 3072; + } + else if (operatorTokenKind === 40 + || operatorTokenKind === 62) { + transformFlags |= 32; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + if (node.questionToken + || node.type + || subtreeFlags & 4096 + || ts.isThisIdentifier(name)) { + transformFlags |= 3; + } + if (modifierFlags & 92) { + transformFlags |= 3 | 262144; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { + transformFlags |= 192 | 131072; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + if (expressionKind === 202 + || expressionKind === 184) { + transformFlags |= 3; + } + if (expressionTransformFlags & 1024) { + transformFlags |= 1024; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 192; + if ((subtreeFlags & 274432) + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~539358529; + } + function computeClassExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (subtreeFlags & 274432 + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~539358529; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 85: + transformFlags |= 192; + break; + case 108: + transformFlags |= 3; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537920833; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.typeArguments) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computeMethod(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.typeParameters + || node.type + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.type + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computePropertyDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags | 3; + if (node.initializer) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 33554432; + if (modifierFlags & 2270 + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (modifierFlags & 256) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601281857; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601281857; + } + function computeArrowFunction(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 16384) { + transformFlags |= 32768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601249089; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (expressionKind === 97) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 | 8388608; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (node.type) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 8388608) { + transformFlags |= 192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (subtreeFlags & 4194304 + && ts.isIterationStatement(node, true)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.expression.transformFlags & 1024) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~574674241; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 33554432; + if (subtreeFlags & 8388608) { + transformFlags |= 192; + } + if (node.flags & 3) { + transformFlags |= 192 | 4194304; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~546309441; + } + function computeOther(node, kind, subtreeFlags) { + var transformFlags = subtreeFlags; + var excludeFlags = 536872257; + switch (kind) { + case 120: + case 191: + transformFlags |= 8 | 16; + break; + case 114: + case 112: + case 113: + case 117: + case 124: + case 76: + case 232: + case 264: + case 184: + case 202: + case 203: + case 131: + transformFlags |= 3; + break; + case 249: + case 250: + case 251: + case 10: + case 252: + case 253: + case 254: + case 255: + case 256: + transformFlags |= 4; + break; + case 13: + case 14: + case 15: + case 16: + case 196: + case 183: + case 262: + case 115: + case 204: + transformFlags |= 192; + break; + case 9: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192; + } + break; + case 8: + if (node.numericLiteralFlags & 48) { + transformFlags |= 192; + } + break; + case 216: + if (node.awaitModifier) { + transformFlags |= 8; + } + transformFlags |= 192; + break; + case 197: + transformFlags |= 8 | 192 | 16777216; + break; + case 119: + case 133: + case 130: + case 134: + case 136: + case 122: + case 137: + case 105: + case 145: + case 148: + case 150: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 161: + case 162: + case 163: + case 164: + case 165: + case 166: + case 167: + case 168: + case 230: + case 231: + case 169: + case 170: + case 171: + case 172: + case 173: + case 236: + transformFlags = 3; + excludeFlags = -3; + break; + case 144: + transformFlags |= 2097152; + if (subtreeFlags & 16384) { + transformFlags |= 65536; + } + break; + case 198: + transformFlags |= 192 | 524288; + break; + case 263: + transformFlags |= 8 | 1048576; + break; + case 97: + transformFlags |= 192; + break; + case 99: + transformFlags |= 16384; + break; + case 174: + transformFlags |= 192 | 8388608; + if (subtreeFlags & 524288) { + transformFlags |= 8 | 1048576; + } + excludeFlags = 537396545; + break; + case 175: + transformFlags |= 192 | 8388608; + excludeFlags = 537396545; + break; + case 176: + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 524288; + } + break; + case 147: + transformFlags |= 3 | 4096; + break; + case 178: + excludeFlags = 540087617; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + break; + case 177: + case 182: + excludeFlags = 537396545; + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + break; + case 212: + case 213: + case 214: + case 215: + if (subtreeFlags & 4194304) { + transformFlags |= 192; + } + break; + case 265: + if (subtreeFlags & 32768) { + transformFlags |= 192; + } + break; + case 219: + case 217: + case 218: + transformFlags |= 33554432; + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~excludeFlags; + } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 158 && kind <= 173) { + return -3; + } + switch (kind) { + case 181: + case 182: + case 177: + return 537396545; + case 233: + return 574674241; + case 146: + return 536872257; + case 187: + return 601249089; + case 186: + case 228: + return 601281857; + case 227: + return 546309441; + case 229: + case 199: + return 539358529; + case 152: + return 601015617; + case 151: + case 153: + case 154: + return 601015617; + case 119: + case 133: + case 130: + case 136: + case 134: + case 122: + case 137: + case 105: + case 145: + case 148: + case 150: + case 155: + case 156: + case 157: + case 230: + case 231: + return -3; + case 178: + return 540087617; + case 260: + return 537920833; + case 174: + case 175: + return 537396545; + default: + return 536872257; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 || + (preserveConstEnums && moduleState === 2); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var symbolInstantiationDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); + var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; + var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; + var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; + var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4, "arguments"); + var apparentArgumentCount; + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { + parameter = ts.getParseTreeNode(parameter, ts.isParameter); + ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (node) { + node = ts.getParseTreeNode(node, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : unknownType; + }, + getParameterType: getTypeAtPosition, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (node) { + node = ts.getParseTreeNode(node, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : unknownType; + }, + getPropertySymbolOfDestructuringAssignment: function (location) { + location = ts.getParseTreeNode(location, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, + symbolToString: function (symbol, enclosingDeclaration, meaning) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (node) { + node = ts.getParseTreeNode(node, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { + node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + apparentArgumentCount = theArgumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; + apparentArgumentCount = undefined; + return res; + }, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (node, propertyName) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); + return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + }, + getSignatureFromDeclaration: function (declaration) { + declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: function (symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + links.immediateTarget = getTargetOfAliasDeclaration(node, true); + } + return links.immediateTarget; + }, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getAmbientModules: getAmbientModules, + getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { + node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; + }, + getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + isOptionalParameter: function (node) { + node = ts.getParseTreeNode(node, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + return tryFindAmbientModule(moduleName, false); + }, + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + resolveNameAtLocation: function (location, name, meaning) { + location = ts.getParseTreeNode(location); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, ts.escapeLeadingUnderscores(name)); + }, + }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var unknownSymbol = createSymbol(4, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); + var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); + var unknownType = createIntrinsicType(1, "unknown"); + var undefinedType = createIntrinsicType(2048, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); + var nullType = createIntrinsicType(4096, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); + var stringType = createIntrinsicType(2, "string"); + var numberType = createIntrinsicType(4, "number"); + var trueType = createIntrinsicType(128, "true"); + var falseType = createIntrinsicType(128, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512, "symbol"); + var voidType = createIntrinsicType(1024, "void"); + var neverType = createIntrinsicType(8192, "never"); + var silentNeverType = createIntrinsicType(8192, "never"); + var nonPrimitiveType = createIntrinsicType(16777216, "object"); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + anyFunctionType.flags |= 8388608; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var enumNumberIndexInfo = createIndexInfo(stringType, true); + var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); + var globals = ts.createSymbolTable(); + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredJsxElementClassType; + var deferredJsxElementType; + var deferredJsxStatelessElementType; + var deferredNodes; + var deferredUnusedIdentifierNodes; + var flowLoopStart = 0; + var flowLoopCount = 0; + var visitedFlowCount = 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 = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var visitedFlowNodes = []; + var visitedFlowTypes = []; + var potentialThisCollisions = []; + 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, + "boolean": 4, + "symbol": 8, + "undefined": 16384, + "object": 16, + "function": 32 + }); + var typeofNEFacts = ts.createMapFromTemplate({ + "string": 128, + "number": 256, + "boolean": 512, + "symbol": 1024, + "undefined": 131072, + "object": 2048, + "function": 4096 + }); + var typeofTypesByName = ts.createMapFromTemplate({ + "string": stringType, + "number": numberType, + "boolean": booleanType, + "symbol": esSymbolType, + "undefined": undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var _jsxElementPropertiesName; + var _hasComputedJsxElementPropertiesName = false; + var _jsxElementChildrenPropertyName; + var _hasComputedJsxElementChildrenPropertyName = false; + var jsxTypes = ts.createUnderscoreEscapedMap(); + var JsxNames = { + JSX: "JSX", + IntrinsicElements: "IntrinsicElements", + ElementClass: "ElementClass", + ElementAttributesPropertyNameContainer: "ElementAttributesProperty", + ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" + }; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + 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.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + initializeTypeChecker(); + return checker; + function getJsxNamespace() { + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function error(location, message, arg0, arg1, arg2) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + diagnostics.add(diagnostic); + } + function createSymbol(flags, name) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432, name)); + symbol.checkFlags = 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2) + result |= 107455; + if (flags & 1) + result |= 107454; + if (flags & 4) + result |= 0; + if (flags & 8) + result |= 900095; + if (flags & 16) + result |= 106927; + if (flags & 32) + result |= 899519; + if (flags & 64) + result |= 792968; + if (flags & 256) + result |= 899327; + if (flags & 128) + result |= 899967; + if (flags & 512) + result |= 106639; + if (flags & 8192) + result |= 99263; + if (flags & 32768) + result |= 41919; + if (flags & 65536) + result |= 74687; + if (flags & 262144) + result |= 530920; + if (flags & 524288) + result |= 793064; + if (flags & 2097152) + result |= 2097152; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations.slice(0); + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024) { + 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + ts.forEach(target.declarations, function (node) { + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + } + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + } + else { + if (!(targetSymbol.flags & 33554432)) { + targetSymbol = cloneSymbol(targetSymbol); + target.set(id, targetSymbol); + } + mergeSymbol(targetSymbol, sourceSymbol); + } + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); + if (!mainModule) { + return; + } + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920) { + mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function getObjectFlags(type) { + return type.flags & 32768 ? type.objectFlags : 0; + } + function isGlobalSourceFile(node) { + return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + ts.isInAmbientContext(declaration)) { + return true; + } + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + } + if (declaration.pos <= usage.pos) { + if (declaration.kind === 176) { + var errorBindingElement = ts.getAncestor(usage, 176); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); + } + else if (declaration.kind === 226) { + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + return true; + } + if (usage.parent.kind === 246) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 208: + case 214: + case 216: + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 149 && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.getModifierFlags(current.parent) & 32) { + if (declaration.kind === 151) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + }); + } + } + 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; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + 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 !== 275) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 146 || + lastLocation.kind === 145 + : false; + } + if (meaning & 107455 && result.flags & 1) { + useResult = + lastLocation.kind === 146 || + (lastLocation === location.type && + result.valueDeclaration.kind === 146); + } + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 265: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + case 233: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 265 || ts.isAmbientModule(location)) { + if (result = moduleExports.get("default")) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 && + ts.getDeclarationOfKind(moduleExport, 246)) { + break; + } + } + if (result = lookup(moduleExports, name, meaning & 2623475)) { + break loop; + } + break; + case 232: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { + break loop; + } + break; + case 149: + case 148: + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 107455)) { + propertyWithInvalidInitializer = location; + } + } + } + break; + case 229: + case 199: + case 230: + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + result = undefined; + break; + } + if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 199 && meaning & 32) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 144: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 230) { + 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; + } + } + break; + case 151: + case 150: + case 152: + case 153: + case 154: + case 228: + case 187: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 186: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 147: + if (location.parent && location.parent.kind === 146) { + location = location.parent; + } + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (result && nameNotFoundMessage && noUnusedIdentifiers) { + result.isReferenced = true; + } + if (!result) { + result = lookup(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + if (errorLocation && + (meaning & 2 || + ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + if (result && isInExternalModule && (meaning & 107455) === 107455) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 236) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + } + } + } + return result; + } + function diagnosticName(nameArg) { + return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 145 && decl.parent === container) { + return true; + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if ((errorLocation.kind === 71 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + if (location === container && !(ts.getModifierFlags(location) & 32)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64, true)); + if (isError) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + } + return isError; + } + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 71: + case 179: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 201: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + 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, ts.unescapeLeadingUnderscores(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, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (107455 & ~1024 & ~793064)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (793064 & ~1024 & ~107455)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); + 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(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 32) { + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + } + } + function isSameScopeDescendentOf(initial, parent, stopAt) { + return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + if (ts.isAliasSymbolDeclaration(node)) { + if (node.kind === 237) { + return node; + } + return ts.findAncestor(node, ts.isImportDeclaration); + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 248) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + var exportValue = moduleSymbol.exports.get("export="); + exportDefaultSymbol = exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") + : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + } + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (793064 | 1920)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + switch (node.kind) { + case 237: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 239: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 240: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 242: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 246: + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); + case 243: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 236: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + } + } + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 107455 | 793064 | 1920; } + return symbol && (symbol.flags & (2097152 | excludes)) === 2097152; + } + function resolveSymbol(symbol, dontResolveAlias) { + var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); + return shouldResolve ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + if (node.kind === 243) { + checkExpressionCached(node.expression); + } + else if (node.kind === 246) { + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + checkExpressionCached(node.moduleReference); + } + } + } + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (entityName.kind === 71 || entityName.parent.kind === 143) { + return resolveEntityName(entityName, 1920, false, dontResolveAlias); + } + else { + ts.Debug.assert(entityName.parent.kind === 237); + return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol) { + return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + } + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var symbol; + if (name.kind === 71) { + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + if (!symbol) { + return undefined; + } + } + else if (name.kind === 143 || name.kind === 179) { + var left = void 0; + if (name.kind === 143) { + left = name.left; + } + else if (name.kind === 179 && + (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { + left = name.expression; + } + else { + return undefined; + } + var right = name.kind === 143 ? name.right : name.name; + var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else if (name.kind === 185) { + return ts.isEntityNameExpression(name.expression) ? + resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : + undefined; + } + else { + ts.Debug.fail("Unknown entity name kind."); + } + 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) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReferenceExpression.kind !== 9 && moduleReferenceExpression.kind !== 13) { + return; + } + var moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === 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(moduleReference, true); + if (ambientModule) { + return ambientModule; + } + var isRelative = ts.isExternalModuleNameRelative(moduleReference); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (noImplicitAny && moduleNotFoundError) { + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return undefined; + } + if (moduleNotFoundError) { + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + } + function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { + 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)); + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=") !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (!symbol) { + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); + } + } + return symbol; + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + function extendExportSymbols(target, source, lookupTable, exportNode) { + source && source.forEach(function (sourceSymbol, id) { + if (id === "default") + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + function visit(symbol) { + if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + return; + } + visitedSymbols.push(symbol); + var symbols = ts.cloneMap(symbol.exports); + var exportStars = symbol.exports.get("__export"); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent); + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return symbol && (symbol.flags & 1048576) !== 0 + ? getMergedSymbol(symbol.exportSymbol) + : symbol; + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 107455 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 107455); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 152 && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(32768); + type.objectFlags = objectFlags; + type.symbol = symbol; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 && + name.charCodeAt(1) === 95 && + name.charCodeAt(2) !== 95 && + name.charCodeAt(2) !== 64; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + if (symbolIsValue(symbol)) { + result.push(symbol); + } + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 265: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + case 233: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + return rightMeaning === 107455 ? 107455 : 1920; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; + function canQualifySymbol(symbolFromSymbolTable, meaning) { + if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { + return true; + } + var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + return !!accessibleParent; + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + } + function trySymbolTable(symbols) { + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; + } + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + } + }); + } + } + if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + if (!symbolFromSymbolTable) { + return false; + } + if (symbolFromSymbolTable === symbol) { + return true; + } + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 149: + case 151: + case 153: + case 154: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { + var initialSymbol = symbol; + var meaningToLook = meaning; + while (symbol) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); + if (accessibleSymbolChain) { + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (!hasAccessibleDeclarations) { + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, + }; + } + return hasAccessibleDeclarations; + } + meaningToLook = getQualifiedLeftMeaning(meaning); + symbol = getParentOfSymbol(symbol); + } + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + return { + accessibility: 2, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 }; + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + return undefined; + } + return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !(ts.getModifierFlags(anyImportSyntax) & 1) && + isDeclarationVisible(anyImportSyntax.parent)) { + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; + } + } + return true; + } + return false; + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + var meaning; + if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning = 107455 | 1048576; + } + else if (entityName.kind === 143 || entityName.kind === 179 || + entityName.parent.kind === 237) { + meaning = 1920; + } + else { + meaning = 793064; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined); + return (symbol && hasVisibleDeclarations(symbol, true)) || { + accessibility: 1, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function writeKeyword(writer, kind) { + writer.writeKeyword(ts.tokenToString(kind)); + } + function writePunctuation(writer, kind) { + writer.writePunctuation(ts.tokenToString(kind)); + } + function writeSpace(writer) { + writer.writeSpace(" "); + } + function symbolToString(symbol, enclosingDeclaration, meaning) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); + }); + } + function signatureToString(signature, enclosingDeclaration, flags, kind) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); + }); + } + function typeToString(type, enclosingDeclaration, flags) { + 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); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); + var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; + if (maxLength && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 8) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 256) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 4096) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 64) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + 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) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + } + }; + function createNodeBuilderContext(enclosingDeclaration, flags) { + return { + enclosingDeclaration: enclosingDeclaration, + flags: flags, + encounteredError: false, + symbolStack: undefined + }; + } + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + if (!type) { + context.encounteredError = true; + return undefined; + } + if (type.flags & 1) { + return ts.createKeywordTypeNode(119); + } + if (type.flags & 2) { + return ts.createKeywordTypeNode(136); + } + if (type.flags & 4) { + return ts.createKeywordTypeNode(133); + } + if (type.flags & 8) { + return ts.createKeywordTypeNode(122); + } + 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.setEmitFlags(ts.createLiteral(type.value), 16777216)); + } + if (type.flags & (64)) { + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 128) { + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 1024) { + return ts.createKeywordTypeNode(105); + } + if (type.flags & 2048) { + return ts.createKeywordTypeNode(139); + } + if (type.flags & 4096) { + return ts.createKeywordTypeNode(95); + } + if (type.flags & 8192) { + return ts.createKeywordTypeNode(130); + } + if (type.flags & 512) { + return ts.createKeywordTypeNode(137); + } + if (type.flags & 16777216) { + return ts.createKeywordTypeNode(134); + } + if (type.flags & 16384 && type.isThisType) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + context.encounteredError = true; + } + } + return ts.createThis(); + } + var objectFlags = getObjectFlags(type); + if (objectFlags & 4) { + ts.Debug.assert(!!(type.flags & 32768)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); + return ts.createTypeReferenceNode(name, undefined); + } + 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); + } + 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)) { + context.encounteredError = true; + } + return undefined; + } + } + 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, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 524288) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 32768)); + var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; + var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; + 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; + if (symbol) { + if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || + symbol.flags & (384 | 512) || + shouldWriteTypeOfFunctionSymbol()) { + return createTypeQueryNodeFromSymbol(symbol, 107455); + } + else if (ts.contains(context.symbolStack, symbol)) { + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + var entityName = symbolToName(typeAlias, context, 793064, false); + return ts.createTypeReferenceNode(entityName, undefined); + } + else { + return ts.createKeywordTypeNode(119); + } + } + else { + if (!context.symbolStack) { + context.symbolStack = []; + } + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } + } + else { + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 || declaration.parent.kind === 234; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return ts.contains(context.symbolStack, symbol); + } + } + } + function createTypeNodeFromObjectType(type) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + return createMappedTypeNodeFromType(type); + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); + } + 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.escapedName) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var qualifiedName = void 0; + if (outerTypeParameters) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + 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 { + qualifiedName = ts.createQualifiedName(namePart, undefined); + } + } + } + } + var entityName = undefined; + var nameIdentifier = symbolToTypeReferenceName(type.symbol); + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); + entityName = qualifiedName; + } + else { + entityName = nameIdentifier; + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.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, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); + } + if (resolvedType.stringIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + var propertyType = getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 ? 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, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + typeElements.push(methodDeclaration); + } + } + else { + 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 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 ? 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.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, context); + } + 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, context) { + var name = symbolToName(type.symbol, context, 793064, true); + var constraint = getConstraintFromTypeParameter(type); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function symbolToParameterDeclaration(parameterSymbol, context) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { + return ts.createParameter(undefined, undefined, parameterSymbol.isRestParameter ? ts.createToken(24) : undefined, "args", undefined, typeToTypeNodeHelper(anyArrayType, context), undefined); + } + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name) : + ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; + var parameterType = getTypeOfSymbol(parameterSymbol); + 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, context, meaning, expectsIdentifier) { + var chain; + var isTypeParameter = symbol.flags & 262144; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(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 typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { + var parentSymbol = chain[index - 1]; + var typeParameters = void 0; + if (ts.getCheckFlags(symbol) & 1) { + typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); + } + else { + var targetSymbol = getTargetSymbol(parentSymbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + } + } + typeParameterNodes = mapToTypeNodes(typeParameters, context); + } + 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) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var parentSymbol; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); + if (parentChain) { + parentSymbol = parent; + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + return [symbol]; + } + } + } + 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 ts.unescapeLeadingUnderscores(symbol.escapedName); + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + }); + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144)) { + if (t.flags & (128 | 256)) { + 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); + } + } + if (flags & 4096) + result.push(nullType); + if (flags & 2048) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8) { + return "private"; + } + if (flags === 16) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); + if (node.kind === 231) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 234 && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function literalTypeToString(type) { + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + } + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; + } + } + return ts.unescapeLeadingUnderscores(symbol.escapedName); + } + function getSymbolDisplayBuilder() { + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); + } + function appendPropertyOrElementAccessForSymbol(symbol, writer) { + var symbolName = getNameOfSymbol(symbol); + var firstChar = symbolName.charCodeAt(0); + var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); + if (needsElementAccess) { + writePunctuation(writer, 21); + if (ts.isSingleOrDoubleQuote(firstChar)) { + writer.writeStringLiteral(symbolName); + } + else { + writer.writeSymbol(symbolName, symbol); + } + writePunctuation(writer, 22); + } + else { + writePunctuation(writer, 23); + writer.writeSymbol(symbolName, symbol); + } + } + function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { + var parentSymbol; + function appendParentTypeArgumentsAndSymbolName(symbol) { + if (parentSymbol) { + if (flags & 1) { + if (ts.getCheckFlags(symbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); + } + else { + buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); + } + } + appendPropertyOrElementAccessForSymbol(symbol, writer); + } + else { + appendSymbolNameOnly(symbol, writer); + } + parentSymbol = symbol; + } + writer.trackSymbol(symbol, enclosingDeclaration, meaning); + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); + } + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + } + } + else if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + var isTypeParameter = symbol.flags & 262144; + var typeFormatFlag = 256 & typeFlags; + if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { + walkSymbol(symbol, meaning, true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { + var globalFlagsToPass = globalFlags & (32 | 16384); + var inObjectTypeLiteral = false; + return writeType(type, globalFlags); + function writeType(type, flags) { + var nextFlags = flags & ~1024; + if (type.flags & 16793231) { + writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } + else if (type.flags & 16384 && type.isThisType) { + if (inObjectTypeLiteral) { + writer.reportInaccessibleThisError(); + } + writer.writeKeyword("this"); + } + else if (getObjectFlags(type) & 4) { + writeTypeReference(type, nextFlags); + } + 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 & (272 | 16384)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); + } + else if (!(flags & 1024) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); + } + else if (type.flags & 196608) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (getObjectFlags(type) & (16 | 32)) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96) { + writer.writeStringLiteral(literalTypeToString(type)); + } + else if (type.flags & 262144) { + if (flags & 128) { + writePunctuation(writer, 19); + } + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 128); + if (flags & 128) { + writePunctuation(writer, 20); + } + } + else if (type.flags & 524288) { + writeType(type.objectType, 128); + writePunctuation(writer, 21); + writeType(type.indexType, 0); + writePunctuation(writer, 22); + } + else { + writePunctuation(writer, 17); + writeSpace(writer); + writePunctuation(writer, 24); + writeSpace(writer); + writePunctuation(writer, 18); + } + } + function writeTypeList(types, delimiter) { + for (var i = 0; i < types.length; i++) { + if (i > 0) { + if (delimiter !== 26) { + writeSpace(writer); + } + writePunctuation(writer, delimiter); + writeSpace(writer); + } + writeType(types[i], delimiter === 26 ? 0 : 128); + } + } + function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { + if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); + } + if (pos < end) { + writePunctuation(writer, 27); + writeType(typeArguments[pos], 512); + pos++; + while (pos < end) { + writePunctuation(writer, 26); + writeSpace(writer); + writeType(typeArguments[pos], 0); + pos++; + } + writePunctuation(writer, 29); + } + } + function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType && !(flags & 1)) { + writeType(typeArguments[0], 128 | 32768); + writePunctuation(writer, 21); + writePunctuation(writer, 22); + } + else if (type.target.objectFlags & 8) { + writePunctuation(writer, 21); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); + writePunctuation(writer, 22); + } + else if (flags & 16384 && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 199) { + writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_3 = outerTypeParameters.length; + while (i < length_3) { + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + writeSymbolTypeReference(parent, typeArguments, start, i, flags); + writePunctuation(writer, 23); + } + } + } + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); + } + } + function writeUnionOrIntersectionType(type, flags) { + if (flags & 128) { + writePunctuation(writer, 19); + } + if (type.flags & 65536) { + writeTypeList(formatUnionTypes(type.types), 49); + } + else { + writeTypeList(type.types, 48); + } + if (flags & 128) { + writePunctuation(writer, 20); + } + } + function writeAnonymousType(type, flags) { + var symbol = type.symbol; + if (symbol) { + if (symbol.flags & 32 && + !getBaseTypeVariableOfClass(symbol) && + !(symbol.valueDeclaration.kind === 199 && flags & 16384) || + symbol.flags & (384 | 512)) { + writeTypeOfSymbol(type, flags); + } + else if (shouldWriteTypeOfFunctionSymbol()) { + writeTypeOfSymbol(type, flags); + } + else if (ts.contains(symbolStack, symbol)) { + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); + } + else { + writeKeyword(writer, 119); + } + } + else { + if (!symbolStack) { + symbolStack = []; + } + var isConstructorObject = type.flags & 32768 && + getObjectFlags(type) & 16 && + type.symbol && type.symbol.flags & 32; + if (isConstructorObject) { + writeLiteralType(type, flags); + } + else { + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } + } + } + else { + writeLiteralType(type, flags); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 || declaration.parent.kind === 234; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return !!(flags & 4) || + (ts.contains(symbolStack, symbol)); + } + } + } + function writeTypeOfSymbol(type, typeFormatFlags) { + if (typeFormatFlags & 32768) { + writePunctuation(writer, 19); + } + writeKeyword(writer, 103); + writeSpace(writer); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); + if (typeFormatFlags & 32768) { + writePunctuation(writer, 20); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 131); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 16777216) { + writePunctuation(writer, 55); + } + } + function shouldAddParenthesisAroundFunctionType(callSignature, flags) { + if (flags & 128) { + return true; + } + else if (flags & 512) { + var typeParameters = callSignature.target && (flags & 64) ? + callSignature.target.typeParameters : callSignature.typeParameters; + return typeParameters && typeParameters.length !== 0; + } + return false; + } + function writeLiteralType(type, flags) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + writeMappedType(type); + return; + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + writePunctuation(writer, 17); + writePunctuation(writer, 18); + return; + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); + if (parenthesizeSignature) { + writePunctuation(writer, 19); + } + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); + if (parenthesizeSignature) { + writePunctuation(writer, 20); + } + return; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + if (flags & 128) { + writePunctuation(writer, 19); + } + writeKeyword(writer, 94); + writeSpace(writer); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); + if (flags & 128) { + writePunctuation(writer, 20); + } + return; + } + } + var saveInObjectTypeLiteral = inObjectTypeLiteral; + inObjectTypeLiteral = true; + writePunctuation(writer, 17); + writer.writeLine(); + writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 18); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); + buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + if (globalFlags & 16384) { + if (p.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { + writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + } + } + var t = getTypeOfSymbol(p); + if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { + var signatures = getSignaturesOfType(t, 0); + for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { + var signature = signatures_2[_f]; + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + else { + writePropertyWithModifiers(p); + writePunctuation(writer, 56); + writeSpace(writer); + writeType(t, globalFlags & 16384); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + } + function writeMappedType(type) { + writePunctuation(writer, 17); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 131); + writeSpace(writer); + } + writePunctuation(writer, 21); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 92); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0); + writePunctuation(writer, 22); + if (type.declaration.questionToken) { + writePunctuation(writer, 55); + } + writePunctuation(writer, 56); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0); + writePunctuation(writer, 25); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 18); + } + } + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); + } + } + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { + appendSymbolNameOnly(tp.symbol, writer); + var constraint = getConstraintOfTypeParameter(tp); + if (constraint) { + writeSpace(writer); + writeKeyword(writer, 85); + writeSpace(writer); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); + } + var defaultType = getDefaultFromTypeParameter(tp); + if (defaultType) { + writeSpace(writer); + writePunctuation(writer, 58); + writeSpace(writer); + buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { + writePunctuation(writer, 24); + } + if (parameterNode && ts.isBindingPattern(parameterNode.name)) { + buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + appendSymbolNameOnly(p, writer); + } + if (parameterNode && isOptionalParameter(parameterNode)) { + writePunctuation(writer, 55); + } + writePunctuation(writer, 56); + writeSpace(writer); + var type = getTypeOfSymbol(p); + if (parameterNode && isRequiredInitializedParameter(parameterNode)) { + type = getNullableType(type, 2048); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { + if (bindingPattern.kind === 174) { + writePunctuation(writer, 17); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 18); + } + else if (bindingPattern.kind === 175) { + writePunctuation(writer, 21); + var elements = bindingPattern.elements; + buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (elements && elements.hasTrailingComma) { + writePunctuation(writer, 26); + } + writePunctuation(writer, 22); + } + } + function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isOmittedExpression(bindingElement)) { + return; + } + ts.Debug.assert(bindingElement.kind === 176); + if (bindingElement.propertyName) { + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 56); + writeSpace(writer); + } + if (ts.isBindingPattern(bindingElement.name)) { + buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + if (bindingElement.dotDotDotToken) { + writePunctuation(writer, 24); + } + appendSymbolNameOnly(bindingElement.symbol, writer); + } + } + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27); + buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 29); + } + } + function buildDisplayForCommaSeparatedList(list, writer, action) { + for (var i = 0; i < list.length; i++) { + if (i > 0) { + writePunctuation(writer, 26); + writeSpace(writer); + } + action(list[i]); + } + } + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27); + var flags = 512; + for (var i = 0; i < typeParameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 26); + writeSpace(writer); + flags = 0; + } + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); + } + writePunctuation(writer, 29); + } + } + function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { + writePunctuation(writer, 19); + if (thisParameter) { + buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); + } + for (var i = 0; i < parameters.length; i++) { + if (i > 0 || thisParameter) { + writePunctuation(writer, 26); + writeSpace(writer); + } + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); + } + writePunctuation(writer, 20); + } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 99); + } + writeSpace(writer); + writeKeyword(writer, 126); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + var returnType = getReturnTypeOfSignature(signature); + if (flags & 4096 && isTypeAny(returnType)) { + return; + } + if (flags & 16) { + writeSpace(writer); + writePunctuation(writer, 36); + } + else { + writePunctuation(writer, 56); + } + writeSpace(writer); + if (signature.typePredicate) { + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); + } + else { + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1) { + writeKeyword(writer, 94); + writeSpace(writer); + } + if (signature.target && (flags & 64)) { + buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); + } + else { + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); + } + buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); + } + function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 131); + writeSpace(writer); + } + writePunctuation(writer, 21); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 56); + writeSpace(writer); + switch (kind) { + case 1: + writeKeyword(writer, 133); + break; + case 0: + writeKeyword(writer, 136); + break; + } + writePunctuation(writer, 22); + writePunctuation(writer, 56); + writeSpace(writer); + buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + return _displayBuilder || (_displayBuilder = { + buildSymbolDisplay: buildSymbolDisplay, + buildTypeDisplay: buildTypeDisplay, + buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, + buildParameterDisplay: buildParameterDisplay, + buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, + buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, + buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, + buildSignatureDisplay: buildSignatureDisplay, + buildIndexSignatureDisplay: buildIndexSignatureDisplay, + buildReturnTypeDisplay: buildReturnTypeDisplay + }); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 176: + return isDeclarationVisible(node.parent.parent); + case 226: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + return false; + } + case 233: + case 229: + case 230: + case 231: + case 228: + case 232: + case 237: + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + if (!(ts.getCombinedModifierFlags(node) & 1) && + !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { + return isGlobalSourceFile(parent); + } + return isDeclarationVisible(parent); + case 149: + case 148: + case 153: + case 154: + case 151: + case 150: + if (ts.getModifierFlags(node) & (8 | 16)) { + return false; + } + case 152: + case 156: + case 155: + case 157: + case 146: + case 234: + case 160: + case 161: + case 163: + case 159: + case 164: + case 165: + case 166: + case 167: + case 168: + return isDeclarationVisible(node.parent); + case 239: + case 240: + case 242: + return false; + case 145: + case 265: + case 236: + return true; + case 243: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node) { + var exportSymbol; + if (node.parent && node.parent.kind === 243) { + exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node); + } + else if (node.parent.kind === 246) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); + } + var result = []; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + getNodeLinks(declaration).isVisible = true; + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (!ts.contains(result, resultNode)) { + result.push(resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + var length_4 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_4; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + if (propertyName === 0) { + return getSymbolLinks(target).type; + } + if (propertyName === 2) { + return getSymbolLinks(target).declaredType; + } + if (propertyName === 1) { + return target.resolvedBaseConstructorType; + } + if (propertyName === 3) { + return target.resolvedReturnType; + } + ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + } + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 226: + case 227: + case 242: + case 241: + case 240: + case 239: + return false; + default: + return true; + } + }); + return node && node.parent; + } + function getTypeOfPrototypeProperty(prototype) { + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1) !== 0; + } + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); + } + function isComputedNonLiteralName(name) { + return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144); }); + if (source.flags & 8192) { + return emptyObjectType; + } + if (source.flags & 65536) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createSymbolTable(); + var names = ts.createUnderscoreEscapedMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name), true); + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = names.has(prop.escapedName); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + members.set(prop.escapedName, prop); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0); + var numberIndexInfo = getIndexInfoOfType(source, 1); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + if (parentType === unknownType) { + return unknownType; + } + if (!parentType || isTypeAny(parentType)) { + if (declaration.initializer) { + return checkDeclarationInitializer(declaration); + } + return parentType; + } + var type; + if (pattern.kind === 174) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + var name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + var text = ts.getTextOfPropertyName(name); + var declaredType = getTypeOfPropertyOfType(parentType, text); + type = declaredType && getFlowTypeOfReference(declaration, declaredType) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || + getIndexTypeOfType(parentType, 0); + if (!type) { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); + return unknownType; + } + } + } + else { + var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); + if (declaration.dotDotDotToken) { + type = createArrayType(elementType); + } + else { + var propName = "" + ts.indexOf(pattern.elements, declaration); + type = isTupleLikeType(parentType) + ? getTypeOfPropertyOfType(parentType, propName) + : elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + } + return unknownType; + } + } + } + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + type = getTypeWithFacts(type, 131072); + } + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 177 && expr.elements.length === 0; + } + function addOptionality(type, optional) { + return strictNullChecks && optional ? getNullableType(type, 2048) : type; + } + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + if (declaration.parent.parent.kind === 215) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 | 262144) ? indexType : stringType; + } + if (declaration.parent.parent.kind === 216) { + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + var declaredType = getTypeFromTypeNode(typeNode); + return addOptionality(declaredType, declaration.questionToken && includeOptionality); + } + if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 146) { + var func = declaration.parent; + if (func.kind === 154 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + var type = void 0; + if (declaration.symbol.escapedName === "this") { + type = getContextualThisParameterType(func); + } + else { + type = getContextuallyTypedParameterType(declaration); + } + if (type) { + return addOptionality(type, declaration.questionToken && includeOptionality); + } + } + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, declaration.questionToken && includeOptionality); + } + if (ts.isJsxAttribute(declaration)) { + return trueType; + } + if (declaration.kind === 262) { + return checkIdentifier(declaration.name); + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, false, true); + } + return undefined; + } + function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + 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 : + declaration.kind === 179 ? ts.getAncestor(declaration, 194) : + undefined; + if (!expression) { + return unknownType; + } + if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { + if (ts.getThisContainer(expression, false).kind === 152) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + 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)); + } + } + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } + } + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + } + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return checkDeclarationInitializer(element); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAnyError(element, anyType); + } + return anyType; + } + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var hasComputedProperties = false; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + hasComputedProperties = true; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 | (e.initializer ? 16777216 : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + if (includePatternInType) { + result.pattern = pattern; + } + if (hasComputedProperties) { + result.objectFlags |= 512; + } + return result; + } + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + return pattern.kind === 174 + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + var type = getTypeForVariableLikeDeclaration(declaration, true); + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + if (declaration.kind === 261) { + return type; + } + return getWidenedType(type); + } + type = declaration.dotDotDotToken ? anyArrayType : anyType; + if (reportErrors && noImplicitAny) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAnyError(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 146 ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 4194304) { + return links.type = getTypeOfPrototypeProperty(symbol); + } + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return links.type = anyType; + } + if (declaration.kind === 243) { + return links.type = checkExpression(declaration.expression); + } + if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = void 0; + if (declaration.kind === 194 || + declaration.kind === 179 && declaration.parent.kind === 194) { + type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } + else { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function getAnnotatedAccessorType(accessor) { + if (accessor) { + if (accessor.kind === 153) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + } + } + return undefined; + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var getter = ts.getDeclarationOfKind(symbol, 153); + var setter = ts.getDeclarationOfKind(symbol, 154); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return links.type = jsDocType; + } + } + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = void 0; + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + else { + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 153); + error(getter_1, 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, symbolToString(symbol)); + } + } + links.type = type; + } + return links.type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { + links.type = anyType; + } + else { + var type = createObjectType(16, symbol); + if (symbol.flags & 32) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + links.type = strictNullChecks && symbol.flags & 16777216 ? getNullableType(type, 2048) : type; + } + } + } + return links.type; + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getDeclaredTypeOfEnumMember(symbol); + } + return links.type; + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + links.type = targetSymbol.flags & 107455 + ? getTypeOfSymbol(targetSymbol) + : unknownType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbolInstantiationDepth === 100) { + error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); + links.type = unknownType; + } + else { + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + symbolInstantiationDepth++; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + symbolInstantiationDepth--; + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + } + return links.type; + } + function reportCircularityError(symbol) { + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (symbol.flags & (3 | 4)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152) { + return getTypeOfAlias(symbol); + } + return unknownType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (getObjectFlags(type) & 4) !== 0 + && type.target === target; + } + function getTargetType(type) { + return getObjectFlags(type) & 4 ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (getObjectFlags(type) & (3 | 4)) { + var target = getTargetType(type); + return target === checkBase || ts.forEach(getBaseTypes(target), check); + } + else if (type.flags & 131072) { + return ts.forEach(type.types, check); + } + } + } + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + if (!typeParameters) { + typeParameters = [tp]; + } + else if (!ts.contains(typeParameters, tp)) { + typeParameters.push(tp); + } + } + return typeParameters; + } + function appendOuterTypeParameters(typeParameters, node) { + while (true) { + node = node.parent; + if (!node) { + return typeParameters; + } + if (node.kind === 229 || node.kind === 199 || + node.kind === 228 || node.kind === 186 || + node.kind === 151 || node.kind === 187) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); + } + } + } + } + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); + return appendOuterTypeParameters(undefined, declaration); + } + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 230 || node.kind === 229 || + node.kind === 199 || node.kind === 231) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } + return result; + } + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { + return true; + } + if (type.flags & 540672) { + var constraint = getBaseConstraintOfType(type); + return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return false; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavaScript = ts.isInJavaScriptFile(location); + return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + } + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & (32768 | 131072)) { + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = unknownType; + } + if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + return type.resolvedBaseConstructorType = unknownType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 | 64)) { + if (type.symbol.flags & 32) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { + 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, typeArgs); + } + else if (baseConstructorType.flags & 1) { + baseType = baseConstructorType; + } + else { + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } + if (baseType === unknownType) { + return; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + return; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + return; + } + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + function areAllOuterTypeParametersApplied(type) { + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } + function isValidBaseType(type) { + return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || + type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== unknownType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + } + } + else { + error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + } + } + } + } + } + } + function isIndependentInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230) { + if (declaration.flags & 64) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064, true); + if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 ? 1 : 2; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + type.objectFlags |= 4; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + if (!pushTypeResolution(symbol, 2)) { + return unknownType; + } + var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 || d.kind === 231; }); + var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + switch (expr.kind) { + case 9: + case 8: + return true; + case 192: + return expr.operator === 38 && + expr.operand.kind === 8; + case 71: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + default: + return false; + } + } + 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 (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 : 1; + } + 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) { + 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); + } + } + } + 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; + } + } + 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)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(16384); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 | 64)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152) { + return getDeclaredTypeOfAlias(symbol); + } + return unknownType; + } + function isIndependentTypeReference(node) { + if (node.typeArguments) { + for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { + var typeNode = _a[_i]; + if (!isIndependentType(typeNode)) { + return false; + } + } + } + return true; + } + function isIndependentType(node) { + switch (node.kind) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 134: + case 105: + case 139: + case 95: + case 130: + case 173: + return true; + case 164: + return isIndependentType(node.elementType); + case 159: + return isIndependentTypeReference(node); + } + return false; + } + function isIndependentVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isIndependentType(typeNode) : !node.initializer; + } + function isIndependentFunctionLikeDeclaration(node) { + if (node.kind !== 152) { + var typeNode = ts.getEffectiveReturnTypeNode(node); + if (!typeNode || !isIndependentType(typeNode)) { + return false; + } + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (!isIndependentVariableLikeDeclaration(parameter)) { + return false; + } + } + return true; + } + function isIndependentMember(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 149: + case 148: + return isIndependentVariableLikeDeclaration(declaration); + case 151: + case 150: + case 152: + return isIndependentFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); + type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + } + return type; + } + function getTypeWithThisArgument(type, thisArgument) { + if (getObjectFlags(type) & 4) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + } + } + else if (type.flags & 131072) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + } + return type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === source.symbol.members) { + members = ts.createSymbolTable(source.declaredProperties); + } + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, false) : + getIndexInfoOfType(instantiatedBaseType, 0); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { + return undefined; + } + } + return [signature]; + } + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); + if (!match) { + return undefined; + } + if (!ts.contains(result, match)) { + (result || (result = [])).push(match); + } + } + return result; + } + function getUnionSignatures(types, kind) { + var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + if (!result || !findMatchingSignature(result, signature, false, true, true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + if (unionSignatures.length > 1) { + s = cloneSignature(signature); + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s.resolvedReturnType = undefined; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + 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; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + var callSignatures = getUnionSignatures(type.types, 0); + var constructSignatures = getUnionSignatures(type.types, 1); + var stringIndexInfo = getUnionIndexInfo(type.types, 0); + var numberIndexInfo = getUnionIndexInfo(type.types, 1); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_3 = function (i) { + var t = type.types[i]; + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); + }; + for (var i = 0; i < types.length; i++) { + _loop_3(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048) { + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members.get("__call")); + var constructSignatures = getSignaturesOfSymbol(members.get("__new")); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + var members = emptySymbols; + var constructSignatures = ts.emptyArray; + var stringIndexInfo = undefined; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (32768 | 131072 | 540672)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, false); + } + } + var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } + } + } + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 170) { + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var propertySymbol = _a[_i]; + addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); + } + if (getIndexInfoOfType(modifiersType, 0)) { + addMemberForKeyType(stringType); + } + } + else { + var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t, propertySymbol) { + var iterationMapper = createTypeMapper([typeParameter], [t]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + if (t.flags & 32) { + var propName = ts.escapeLeadingUnderscores(t.value); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216); + var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + prop.type = propType; + if (propertySymbol) { + prop.syntheticOrigin = propertySymbol; + prop.declarations = propertySymbol.declarations; + } + members.set(propName, prop); + } + else if (t.flags & 2) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 170) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function isPartialMappedType(type) { + return getObjectFlags(type) & 32 && !!type.declaration.questionToken; + } + function isGenericMappedType(type) { + return getObjectFlags(type) & 32 && + maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 | 262144); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 32768) { + if (type.objectFlags & 4) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 65536) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 131072) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + function getPropertiesOfObjectType(type) { + if (type.flags & 32768) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + function getPropertyOfObjectType(type, name) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + if (type.flags & 65536) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 196608 ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createSymbolTable(); + 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 escapedName = _c[_b].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); + } + } + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } + function getConstraintOfType(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? getConstraintOfIndexedAccess(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var baseObjectType = getBaseConstraintOfType(type.objectType); + var baseIndexType = getBaseConstraintOfType(type.indexType); + return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (540672 | 196608)) { + var constraint = getResolvedBaseConstraint(type); + if (constraint !== noConstraintType && constraint !== circularConstraintType) { + return constraint; + } + } + else if (type.flags & 262144) { + return stringType; + } + return undefined; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + function getResolvedBaseConstraint(type) { + var typeStack; + var circular; + if (!type.resolvedBaseConstraint) { + typeStack = []; + var constraint = getBaseConstraint(type); + type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + } + return type.resolvedBaseConstraint; + function getBaseConstraint(t) { + if (ts.contains(typeStack, t)) { + circular = true; + return undefined; + } + typeStack.push(t); + var result = computeBaseConstraint(t); + typeStack.pop(); + return result; + } + function computeBaseConstraint(t) { + if (t.flags & 16384) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType ? constraint : + constraint ? getBaseConstraint(constraint) : undefined; + } + if (t.flags & 196608) { + var types = t.types; + var baseTypes = []; + 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); + } + } + return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 262144) { + return stringType; + } + if (t.flags & 524288) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + } + function getDefaultFromTypeParameter(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + } + } + return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + } + function getApparentType(type) { + var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : + t.flags & 262178 ? globalStringType : + t.flags & 84 ? globalNumberType : + t.flags & 136 ? globalBooleanType : + t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 16777216 ? emptyObjectType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var types = containingType.types; + var isUnion = containingType.flags & 65536; + var excludeModifiers = isUnion ? 24 : 0; + var commonFlags = isUnion ? 0 : 16777216; + var syntheticFlag = 4; + var checkFlags = 0; + 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + if (!props) { + props = [prop]; + } + else if (!ts.contains(props, prop)) { + props.push(prop); + } + checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | + (!(modifiers & 24) ? 64 : 0) | + (modifiers & 16 ? 128 : 0) | + (modifiers & 8 ? 256 : 0) | + (modifiers & 32 ? 512 : 0); + if (!isMethodLike(prop)) { + syntheticFlag = 2; + } + } + else if (isUnion) { + checkFlags |= 16; + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16)) { + return props[0]; + } + var propTypes = []; + var declarations = []; + var commonType = undefined; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; + if (prop.declarations) { + ts.addRange(declarations, prop.declarations); + } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + checkFlags |= 32; + } + propTypes.push(type); + } + var result = createSymbol(4 | commonFlags, name); + result.checkFlags = syntheticFlag | checkFlags; + result.containingType = containingType; + result.declarations = declarations; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; + } + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 196608) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 229376) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 229376) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, true); + } + } + return undefined; + } + function getTypeParametersFromDeclaration(declaration) { + var result; + ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + var tp = getDeclaredTypeOfTypeParameter(node.symbol); + if (!ts.contains(result, tp)) { + if (!result) { + result = []; + } + result.push(tp); + } + }); + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + if (ts.isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 272) { + return true; + } + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 272; + } + } + } + } + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signatureDeclaration = node.parent; + var signature = getSignatureFromDeclaration(signatureDeclaration); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= signature.minArgumentCount; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } + return false; + } + function createTypePredicateFromTypePredicateNode(node) { + var parameterName = node.parameterName; + if (parameterName.kind === 71) { + return { + kind: 1, + parameterName: parameterName ? parameterName.escapedText : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0, + type: getTypeFromTypeNode(node.type) + }; + } + } + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!getDefaultFromTypeParameter(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + var numTypeParameters = ts.length(typeParameters); + if (numTypeParameters) { + var numTypeArguments = ts.length(typeArguments); + var isJavaScript = ts.isInJavaScriptFile(location); + if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (!typeArguments) { + typeArguments = []; + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, typeArguments); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + } + } + } + return typeArguments; + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = undefined; + var hasThisParameter = void 0; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this") { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (param.type && param.type.kind === 173) { + hasLiteralTypes = true; + } + var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !param.type || + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + if ((declaration.kind === 153 || declaration.kind === 154) && + !ts.hasDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 153 ? 154 : 153; + var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 152 ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 158 ? + createTypePredicateFromTypePredicateNode(declaration.type) : + undefined; + var hasRestLikeParameter = ts.hasRestParameter(declaration); + if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { + hasRestLikeParameter = true; + var syntheticArgsSymbol = createSymbol(3, "args"); + syntheticArgsSymbol.type = anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + parameters.push(syntheticArgsSymbol); + } + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { + if (isJSConstructSignature) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { + return classType; + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 154); + return getAnnotatedAccessorType(setter); + } + if (ts.nodeIsMissing(declaration.body)) { + return anyType; + } + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 71: + return node.escapedText === "arguments" && ts.isPartOfExpression(node); + case 149: + case 151: + case 153: + case 154: + return node.name.kind === 144 + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var node = symbol.declarations[i]; + switch (node.kind) { + case 160: + case 161: + case 228: + case 151: + case 150: + case 152: + case 155: + case 156: + case 157: + case 153: + case 154: + case 186: + case 187: + case 273: + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + break; + } + } + result.push(getSignatureFromDeclaration(node)); + } + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3)) { + return unknownType; + } + var type = void 0; + if (signature.target) { + type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); + } + else if (signature.unionSignatures) { + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + } + else { + type = getReturnTypeFromBody(signature.declaration); + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var declaration = signature.declaration; + 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); + } + } + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + if (getObjectFlags(type) & 4 && type.target === globalArrayType) { + return type.typeArguments[0]; + } + } + return anyType; + } + function getSignatureInstantiation(signature, typeArguments) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + } + function getErasedSignature(signature) { + if (!signature.typeParameters) + return signature; + if (!signature.erasedSignatureCache) { + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + return signature.erasedSignatureCache; + } + function getOrCreateTypeFromSignature(signature) { + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; + var type = createObjectType(16); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index"); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 ? 133 : 136; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = decl; + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 145).constraint; + } + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_5 = types.length; + var i = 0; + while (i < length_5) { + var startId = types[i].id; + var count = 1; + while (i + count < length_5 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 14680064; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : 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(typeArgs, typeParameters, minTypeArgumentCount, node)); + return createTypeReference(type, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + } + return instantiation; + } + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return unknownType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + function getTypeFromNonGenericTypeReference(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 159: + return node.typeName; + case 201: + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); + if (symbol === unknownSymbol) { + return unknownType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + if (symbol.flags & 107455 && isJSDocTypeReference(node)) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; + } + } + resolveTypeReferenceName(getTypeReferenceName(node), 793064); + return valueType; + } + return getTypeFromNonGenericTypeReference(node, symbol); + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 | 64)) { + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function isJSDocTypeReference(node) { + return node.flags & 1048576 && node.kind === 159; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + if (node.typeName.escapedText === "Object") { + if (node.typeArguments && node.typeArguments.length === 2) { + var indexed = getTypeFromTypeNode(node.typeArguments[0]); + var target = getTypeFromTypeNode(node.typeArguments[1]); + var index = createIndexInfo(target, false); + if (indexed === stringType || indexed === numberType) { + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + } + } + return anyType; + } + switch (node.typeName.escapedText) { + case "String": + return stringType; + case "Number": + return numberType; + case "Boolean": + return booleanType; + case "Void": + return voidType; + case "Undefined": + return undefinedType; + case "Null": + return nullType; + case "Function": + case "function": + return globalFunctionType; + case "Array": + case "array": + return !node.typeArguments || !node.typeArguments.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getUnionType([type, nullType]) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 793064; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 107455; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + 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) { + links.resolvedType = getWidenedType(checkExpression(node.exprName)); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + switch (declaration.kind) { + case 229: + case 230: + case 232: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 32768)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName(undefined, name, meaning, diagnostic, name); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 793064, undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getExportedTypeFromNamespace(namespace, name) { + var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); + return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); + } + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384); + typeParameters.push(typeParameter); + var property = createSymbol(4, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(8 | 4); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + return type; + } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + } + return links.resolvedType; + } + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 65536) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144) { + if (flags & 2048) + typeSet.containsUndefined = true; + if (flags & 4096) + typeSet.containsNull = true; + if (!(flags & 2097152)) + typeSet.containsNonWideningType = true; + } + else if (!(flags & 8192)) { + if (flags & 2) + typeSet.containsString = true; + if (flags & 4) + typeSet.containsNumber = true; + if (flags & 96) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } + } + } + function addTypesToUnion(typeSet, types) { + 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_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function isSubtypeOfAny(candidate, types) { + 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; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 && types.containsString || + t.flags & 64 && types.containsNumber || + t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + addTypesToUnion(typeSet, types); + if (typeSet.containsAny) { + return anyType; + } + if (subtypeReduction) { + removeSubtypes(typeSet); + } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } + if (typeSet.length === 0) { + return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : + typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : + neverType; + } + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); + type = createType(65536 | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, type) { + if (type.flags & 131072) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (type.flags & 8192) { + typeSet.containsNever = true; + } + else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { + typeSet.containsEmptyObject = true; + } + else if ((strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + if (type.flags & 32768) { + typeSet.containsObjectType = true; + } + if (type.flags & 65536 && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } + if (!(type.flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } + } + } + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; + addTypeToIntersection(typeSet, type); + } + } + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return emptyObjectType; + } + var typeSet = []; + addTypesToIntersection(typeSet, types); + if (typeSet.containsNever) { + return neverType; + } + if (typeSet.containsAny) { + return anyType; + } + if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { + typeSet.push(emptyObjectType); + } + if (typeSet.length === 1) { + return typeSet[0]; + } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); + type = createType(131072 | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + neverType : + getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; + var propName = indexType.flags & 96 ? + ts.escapeLeadingUnderscores("" + indexType.value) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? + ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || + getIndexInfoOfType(objectType, 0) || + undefined; + if (indexInfo) { + if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + 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.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)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + return unknownType; + } + return anyType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1) { + return objectType; + } + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (node.symbol.members.size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function getSpreadType(left, right) { + if (left.flags & 1 || right.flags & 1) { + return anyType; + } + if (left.flags & 8192) { + return right; + } + if (right.flags & 8192) { + return left; + } + if (left.flags & 65536) { + return mapType(left, function (t) { return getSpreadType(t, right); }); + } + if (right.flags & 65536) { + return mapType(right, function (t) { return getSpreadType(left, t); }); + } + if (right.flags & 16777216) { + return emptyObjectType; + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + stringIndexInfo = getIndexInfoOfType(right, 0); + numberIndexInfo = getIndexInfoOfType(right, 1); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 && !(leftProp.flags & 32768) + || skippedPrivateMembers.has(leftProp.escapedName) + || isClassMethod(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 | (leftProp.flags & 16777216); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + } + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getNonReadonlySymbol(prop) { + if (!isReadonlySymbol(prop)) { + return prop; + } + var flags = 4 | (prop.flags & 16777216); + var result = createSymbol(flags, prop.escapedName); + result.type = getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.syntheticOrigin = prop; + return result; + } + function isClassMethod(prop) { + return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + 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.value, type.symbol); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; + } + 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) { + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { + if (!(ts.getModifierFlags(container) & 32) && + (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return unknownType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 119: + case 268: + case 269: + return anyType; + case 136: + return stringType; + case 133: + return numberType; + case 122: + return booleanType; + case 137: + return esSymbolType; + case 105: + return voidType; + case 139: + return undefinedType; + case 95: + return nullType; + case 130: + return neverType; + case 134: + return node.flags & 65536 ? anyType : nonPrimitiveType; + case 169: + case 99: + return getTypeFromThisTypeNode(node); + case 173: + return getTypeFromLiteralTypeNode(node); + case 159: + return getTypeFromTypeReference(node); + case 158: + return booleanType; + case 201: + return getTypeFromTypeReference(node); + case 162: + return getTypeFromTypeQueryNode(node); + case 164: + return getTypeFromArrayTypeNode(node); + case 165: + return getTypeFromTupleTypeNode(node); + case 166: + return getTypeFromUnionTypeNode(node); + case 167: + return getTypeFromIntersectionTypeNode(node); + case 270: + return getTypeFromJSDocNullableTypeNode(node); + case 168: + case 271: + case 272: + case 267: + return getTypeFromTypeNode(node.type); + case 160: + case 161: + case 163: + case 285: + case 273: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 170: + return getTypeFromTypeOperatorNode(node); + case 171: + return getTypeFromIndexedAccessTypeNode(node); + case 172: + return getTypeFromMappedTypeNode(node); + case 71: + case 143: + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + case 274: + return getTypeFromJSDocVariadicType(node); + default: + return unknownType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + var result = []; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; + result.push(instantiator(v, mapper)); + } + return result; + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + mapper.mappedTypes = sources; + return mapper; + } + function createTypeEraser(sources) { + return createTypeMapper(sources, undefined); + } + function createBackreferenceMapper(typeParameters, index) { + var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + mapper.mappedTypes = typeParameters; + return mapper; + } + function isInferenceContext(mapper) { + return !!mapper.signature; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.signature, mapper.flags | 2, mapper.inferences) : + mapper; + } + function identityMapper(type) { + return type; + } + function combineTypeMappers(mapper1, mapper2) { + var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; + mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); + return mapper; + } + function createReplacementMapper(source, target, baseMapper) { + var mapper = function (t) { return t === source ? target : baseMapper(t); }; + mapper.mappedTypes = baseMapper.mappedTypes; + return mapper; + } + function cloneTypeParameter(typeParameter) { + var result = createType(16384); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + var freshTypePredicate; + if (signature.typeParameters && !eraseTypeParameters) { + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + if (signature.typePredicate) { + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); + } + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + if (ts.getCheckFlags(symbol) & 1) { + var links = getSymbolLinks(symbol); + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + var result = createSymbol(symbol.flags, symbol.escapedName); + result.checkFlags = 1; + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + return result; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(16 | 64, type.symbol); + result.target = type.objectFlags & 64 ? type.target : type; + result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144) { + var typeVariable_1 = constraintType.type; + if (typeVariable_1.flags & 16384) { + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + } + return t; + }); + } + } + } + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 | 32768 | 131072 | 524288); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 | 64, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } + var mappedTypes = mapper.mappedTypes; + return !!ts.findAncestor(symbol.declarations[0], function (node) { + if (node.kind === 233 || node.kind === 265) { + return "quit"; + } + switch (node.kind) { + case 160: + case 161: + case 228: + case 151: + case 150: + case 152: + case 155: + case 156: + case 157: + case 153: + case 154: + case 186: + case 187: + case 229: + case 199: + case 230: + case 231: + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var d = typeParameters_1[_i]; + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { + return true; + } + } + } + if (ts.isClassLike(node) || node.kind === 230) { + var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + if (thisType && ts.contains(mappedTypes, thisType)) { + return true; + } + } + break; + case 172: + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { + return true; + } + break; + case 273: + var func = node; + for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { + var p = _b[_a]; + if (ts.contains(mappedTypes, getTypeOfNode(p))) { + return true; + } + } + break; + } + }); + } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 265 || parentKind === 234; + } + return false; + } + function instantiateType(type, mapper) { + if (type && mapper !== identityMapper) { + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; + } + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { + return type.symbol && + type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && + (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; + } + if (type.objectFlags & 32) { + return instantiateCached(type, mapper, instantiateMappedType); + } + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + } + } + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + return type; + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 186: + case 187: + return isContextSensitiveFunctionLikeDeclaration(node); + case 178: + return ts.forEach(node.properties, isContextSensitive); + case 177: + return ts.forEach(node.elements, isContextSensitive); + case 195: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 194: + return node.operatorToken.kind === 54 && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 261: + return isContextSensitive(node.initializer); + case 151: + case 150: + return isContextSensitiveFunctionLikeDeclaration(node); + case 185: + return isContextSensitive(node.expression); + case 254: + return ts.forEach(node.properties, isContextSensitive); + case 253: + return node.initializer && isContextSensitive(node.initializer); + case 256: + return node.expression && isContextSensitive(node.expression); + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + if (node.typeParameters) { + return false; + } + if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind === 187) { + return false; + } + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length) { + var result = createObjectType(16, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 131072) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeInstanceOf(source, target) { + return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + } + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + } + function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + if (source === target) { + return -1; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0; + } + if (source.typeParameters) { + source = instantiateSignatureInContextOf(source, target); + } + var result = -1; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType, false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0; + } + result &= related; + } + } + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); + var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); + var related = callbacks ? + compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : + !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + } + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0; + } + } + else { + result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + if (source.kind === 1) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 16777216 ? true : + type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + false; + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined) { + return relation; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { + enumRelation.set(id, false); + return false; + } + 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.escapedName); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + } + enumRelation.set(id, false); + return false; + } + } + } + enumRelation.set(id, true); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 8192) + return false; + if (t & 1 || s & 8192) + return true; + if (s & 262178 && t & 2) + return true; + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) + return true; + if (s & 84 && t & 4) + return true; + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) + return true; + if (s & 136 && t & 8) + return true; + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + 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 (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (s & 1) + return true; + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 && source.flags & 1048576) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 1048576) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 32768 && target.flags & 32768) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + return related === 1; + } + } + if (source.flags & 1032192 || target.flags & 1032192) { + return checkTypeRelatedTo(source, target, relation, undefined); + } + return false; + } + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + var errorInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0; + var overflow = false; + var isIntersectionConstituent = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return result !== 0; + function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, undefined, 256); + targetType = typeToString(target, undefined, 256); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + function isRelatedTo(source, target, reportErrors, headMessage) { + if (source.flags & 96 && source.flags & 1048576) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 1048576) { + target = target.regularType; + } + if (source === target) + return -1; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1; + if (getObjectFlags(source) & 128 && source.flags & 1048576) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0; + } + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && + !(source.flags & 196608) && + !(target.flags & 65536) && + !isIntersectionConstituent && + source !== globalObjectType && + getPropertiesOfType(source).length > 0 && + isWeakType(target) && + !hasCommonProperties(source, target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + return 0; + } + var result = 0; + var saveErrorInfo = errorInfo; + var saveIsIntersectionConstituent = isIntersectionConstituent; + isIntersectionConstituent = false; + if (source.flags & 65536) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + } + else { + if (target.flags & 65536) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190)); + } + else if (target.flags & 131072) { + isIntersectionConstituent = true; + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 131072) { + result = someTypeRelatedToType(source, target, false); + } + if (!result && (source.flags & 1032192 || target.flags & 1032192)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + } + } + } + isIntersectionConstituent = saveIsIntersectionConstituent; + if (!result && reportErrors) { + if (source.flags & 32768 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 32768 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + if (source.flags & 32768 && target.flags & 32768) { + return recursiveTypeRelatedTo(source, target, false); + } + if (source.flags & 65536 && target.flags & 65536 || + source.flags & 131072 && target.flags & 131072) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0; + } + function hasExcessProperties(source, target, reportErrors) { + if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { + var isComparingJsxAttributes = !!(source.flags & 33554432); + if ((relation === assignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + var _loop_4 = function (prop) { + if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + ts.Debug.assert(!!errorNode); + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + errorNode = prop.valueDeclaration; + } + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, false); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 65536 && containsType(targetTypes, source)) { + return -1; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, false); + if (related) { + return related; + } + } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); + } + return 0; + } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 65536 && containsType(sourceTypes, target)) { + return -1; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(source, target, reportErrors) { + var sources = source.typeArguments || ts.emptyArray; + var targets = target.typeArguments || ts.emptyArray; + if (sources.length !== targets.length && relation === identityRelation) { + return 0; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1; + for (var i = 0; i < length; i++) { + var related = isRelatedTo(sources[i], targets[i], reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function recursiveTypeRelatedTo(source, target, reportErrors) { + if (overflow) { + return 0; + } + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2) { + relation.set(id, 3); + } + else { + return related === 1 ? -1 : 0; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + if (id === maybeKeys[i]) { + return 1; + } + } + if (depth === 100) { + overflow = true; + return 0; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2; + var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 || depth === 0) { + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1); + } + maybeCount = maybeStart; + } + } + else { + relation.set(id, reportErrors ? 3 : 2); + maybeCount = maybeStart; + } + return result; + } + function structuredTypeRelatedTo(source, target, reportErrors) { + var result; + var saveErrorInfo = errorInfo; + if (target.flags & 16384) { + if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144) { + if (source.flags & 262144) { + if (result = isRelatedTo(target.type, source.type, false)) { + return result; + } + } + var constraint = getConstraintOfType(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + else if (target.flags & 524288) { + var constraint = getConstraintOfType(target); + if (constraint) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + if (source.flags & 16384) { + if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + var constraint = getConstraintOfTypeParameter(source); + if (constraint || !(target.flags & 16777216)) { + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + constraint = getTypeWithThisArgument(constraint, source); + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else if (source.flags & 524288) { + var constraint = getConstraintOfType(source); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (target.flags & 524288 && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + } + else { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + return result; + } + } + var sourceIsPrimitive = !!(source.flags & 8190); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (source.flags & (32768 | 131072) && target.flags & 32768) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + result = -1; + } + else if (isGenericMappedType(target)) { + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; + } + else { + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + return 0; + } + function mappedTypeRelatedTo(source, target, reportErrors) { + var sourceReadonly = !!source.declaration.readonlyToken; + var sourceOptional = !!source.declaration.questionToken; + var targetReadonly = !!target.declaration.readonlyToken; + var targetOptional = !!target.declaration.questionToken; + var modifiersRelated = relation === identityRelation ? + sourceReadonly === targetReadonly && sourceOptional === targetOptional : + relation === comparableRelation || !sourceOptional || targetOptional; + if (modifiersRelated) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var result = -1; + var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp !== targetProp) { + if (!sourceProp) { + if (!(targetProp.flags & 16777216) || requireOptionalProperties) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); + } + return 0; + } + } + else if (!(targetProp.flags & 4194304)) { + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 || targetPropFlags & 8) { + 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)); + } + return 0; + } + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (reportErrors) { + if (sourcePropFlags & 8 && targetPropFlags & 8) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); + } + } + return 0; + } + } + else if (targetPropFlags & 16) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0; + } + } + else if (sourcePropFlags & 16) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0; + } + result &= related; + if (relation !== comparableRelation && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + } + } + } + return result; + } + function isWeakType(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 131072) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(source.flags & 33554432); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 32768 && target.flags & 32768)) { + return 0; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0; + } + var result = -1; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1; + } + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0; + } + } + var result = -1; + var saveErrorInfo = errorInfo; + 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], true, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + 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, true, 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 result; + } + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0; + } + var result = -1; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 1 && !sourceIsPrimitive) { + return -1; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 && getIndexInfoOfType(source, 0); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1; + if (kind === 0) { + var sourceNumberInfo = getIndexInfoOfType(source, 1); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; + if (targetAccessibility === 8) { + return true; + } + if (targetAccessibility === 16 && sourceAccessibility !== 8) { + return true; + } + if (targetAccessibility !== 16 && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function forEachProperty(prop, callback) { + 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.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + 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 ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + function isAbstractConstructorType(type) { + if (getObjectFlags(type) & 16) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && ts.getModifierFlags(declaration) & 128) { + return true; + } + } + } + return false; + } + function isDeeplyNestedType(type, stack, depth) { + if (depth >= 5 && type.flags & 32768) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 32768 && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + if (sourceProp === targetProp) { + return -1; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0; + } + } + else { + if ((sourceProp.flags & 16777216) !== (targetProp.flags & 16777216)) { + return 0; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + if (source === target) { + return -1; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0; + } + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0; + } + result &= related; + } + } + } + var targetLen = target.parameters.length; + for (var i = 0; i < targetLen; i++) { + var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); + var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var related = compareTypes(s, t); + if (!related) { + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function isRestParameterIndex(signature, parameterIndex) { + return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getUnionType(types, true); + } + function isArrayType(type) { + return getObjectFlags(type) & 4 && type.target === globalArrayType; + } + function isArrayLikeType(type) { + return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isTupleLikeType(type) { + return !!getPropertyOfType(type, "0"); + } + function isUnitType(type) { + return (type.flags & (224 | 2048 | 4096)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 ? true : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + 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 & 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) { + return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + result |= getFalsyFlags(t); + } + return result; + } + function getFalsyFlags(type) { + return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : + 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 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; + } + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && + getSignaturesOfType(type, 0).length === 0 && + getSignaturesOfType(type, 1).length === 0; + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + function getRegularTypeOfObjectLiteral(type) { + if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576; + regularNew.objectFlags |= 128; + type.regularType = regularNew; + return regularNew; + } + function getWidenedProperty(prop) { + var original = getTypeOfSymbol(prop); + var widened = getWidenedType(original); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getWidenedTypeOfObjectLiteral(type) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop) : prop); + } + var stringIndexInfo = getIndexInfoOfType(type, 0); + var numberIndexInfo = getIndexInfoOfType(type, 1); + return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + } + function getWidenedConstituentType(type) { + return type.flags & 6144 ? type : getWidenedType(type); + } + function getWidenedType(type) { + if (type.flags & 6291456) { + if (type.flags & 6144) { + return anyType; + } + if (getObjectFlags(type) & 128) { + return getWidenedTypeOfObjectLiteral(type); + } + if (type.flags & 65536) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 65536) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (getObjectFlags(type) & 128) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 2097152) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + return errorReported; + } + function reportImplicitAnyError(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + var diagnostic; + switch (declaration.kind) { + case 149: + case 148: + diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + break; + case 146: + diagnostic = declaration.dotDotDotToken ? + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + break; + case 176: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 228: + case 151: + case 150: + case 153: + case 154: + case 186: + case 187: + if (!declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + break; + default: + diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + } + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { + if (!reportWideningErrorsInType(type)) { + reportImplicitAnyError(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var count; + if (source.hasRestParameter && target.hasRestParameter) { + count = Math.max(sourceMax, targetMax); + } + else if (source.hasRestParameter) { + count = targetMax; + } + else if (target.hasRestParameter) { + count = sourceMax; + } + else { + count = Math.min(sourceMax, targetMax); + } + for (var i = 0; i < count; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + } + function createInferenceContext(signature, flags, baseInferences) { + var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + var context = mapper; + context.mappedTypes = signature.typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 || + objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || + objectFlags & 32 || + type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var inference = createInferenceInfo(typeParameter); + var inferences = [inference]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 16777216; + var members = ts.createSymbolTable(); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + members.set(prop.escapedName, inferredProp); + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + inference.candidates = undefined; + inferTypes(inferences, sourceType, templateType); + return inference.candidates && getUnionType(inference.candidates, true); + } + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + 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++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (64 | 32)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 540672) { + if (source.flags & 8388608 || source === silentNeverType) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (!inference.candidates || priority < inference.priority) { + inference.candidates = [source]; + inference.priority = priority; + } + else if (priority === inference.priority) { + inference.candidates.push(source); + } + if (!(priority & 4) && target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + } + else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + for (var i = 0; i < count; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 196608) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 196608) { + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + source = getApparentType(source); + if (source.flags & 32768) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (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); + } + } + } + } + function getInferenceInfoForType(type) { + if (type.flags & 540672) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144) { + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + var savePriority = priority; + priority |= 2; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return; + } + if (constraintType.flags & 16384) { + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } + function inferFromProperties(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + for (var i = 0; i < len; i++) { + inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + } + } + function inferFromSignature(source, target) { + forEachMatchingParameterType(source, target, inferFromTypes); + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 0); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1) || + getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 1); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190 | 262144); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + if (inference.candidates) { + var signature = context.signature; + var widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; + var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? + getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2) { + inferredType = silentNeverType; + } + else { + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + } + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; + } + function isInTypeQuery(node) { + return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); + } + function getFlowCacheKey(node) { + if (node.kind === 71) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 99) { + return "0"; + } + if (node.kind === 179) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + } + if (node.kind === 176) { + var container = node.parent.parent; + var key = container.kind === 176 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getLeftmostIdentifierOrThis(node) { + switch (node.kind) { + case 71: + case 99: + return node; + case 179: + return getLeftmostIdentifierOrThis(node.expression); + } + return undefined; + } + function getBindingElementNameText(element) { + if (element.parent.kind === 174) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 71: + return ts.unescapeLeadingUnderscores(name.escapedText); + case 144: + return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + case 9: + case 8: + return name.text; + default: + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + element.parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 71: + return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 226 || target.kind === 176) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 99: + return target.kind === 99; + case 97: + return target.kind === 97; + case 179: + return target.kind === 179 && + source.name.escapedText === target.name.escapedText && + isMatchingReference(source.expression, target.expression); + case 176: + if (target.kind !== 179) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 176 && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 226) { + var maybeId = source.parent.parent.initializer; + return maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function containsMatchingReference(source, target) { + while (source.kind === 179) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 179 && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 71) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 179) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 65536) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 179 && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 65536)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 8192) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 2) { + return strictNullChecks ? 4079361 : 4194049; + } + if (flags & 32) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { + return strictNullChecks ? 4079234 : 4193922; + } + if (flags & 64) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 3030658 : 1982082 : + isZero ? 3145346 : 4193922; + } + if (flags & 8) { + return strictNullChecks ? 4078980 : 4193668; + } + if (flags & 136) { + return strictNullChecks ? + type === falseType ? 3030404 : 1981828 : + type === falseType ? 3145092 : 4193668; + } + if (flags & 32768) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 : 8376288 : + strictNullChecks ? 6166480 : 8378320; + } + if (flags & (1024 | 2048)) { + return 2457472; + } + if (flags & 4096) { + return 2340752; + } + if (flags & 512) { + return strictNullChecks ? 1981320 : 4193160; + } + if (flags & 16777216) { + return strictNullChecks ? 6166480 : 8378320; + } + if (flags & 540672) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 196608) { + return getTypeFactsOfTypes(type.types); + } + return 8388607; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 131072), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getTypeOfPropertyOfType(type, text) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || + getIndexTypeOfType(type, 0) || + unknownType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + checkIteratedTypeOrElementType(type, undefined, false, false) || + unknownType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 194 && parent.parent.left === parent || + parent.parent.kind === 216 && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 215: + return stringType; + case 216: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; + case 194: + return getAssignedTypeOfBinaryExpression(parent); + case 188: + return undefinedType; + case 177: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 198: + return getAssignedTypeOfSpreadExpression(parent); + case 261: + return getAssignedTypeOfPropertyAssignment(parent); + case 262: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return unknownType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 174 ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 215) { + return stringType; + } + if (node.parent.parent.kind === 216) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; + } + return unknownType; + } + function getInitialType(node) { + return node.kind === 226 ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node) { + return node.kind === 226 || node.kind === 176 ? + getInitialType(node) : + getAssignedType(node); + } + function isEmptyArrayAssignment(node) { + return node.kind === 226 && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 176 && node.parent.kind === 194 && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 185: + return getReferenceCandidate(node.expression); + case 194: + switch (node.operatorToken.kind) { + case 58: + return getReferenceCandidate(node.left); + case 26: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 185 || + parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || + parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 257) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + var type = getTypeOfSwitchClause(clause); + if (type === undefined) { + return links.switchTypes = ts.emptyArray; + } + links.switchTypes.push(type); + } + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 65536) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 65536) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper) { + if (!(type.flags & 65536)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function createEvolvingArrayType(elementType) { + var result = createObjectType(256); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 ? + autoArrayType : + createArrayType(elementType.flags & 65536 ? + getUnionType(elementType.types, true) : + elementType); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; + if (!(t.flags & 8192)) { + if (!(getObjectFlags(t) & 256)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.escapedText === "length" || + parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 180 && + parent.expression === root && + parent.parent.kind === 194 && + parent.parent.operatorToken.kind === 58 && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 97) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { + return declaredType; + } + var visitedFlowStart = visitedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + visitedFlowCount = visitedFlowStart; + var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + while (true) { + if (flow.flags & 1024) { + for (var i = visitedFlowStart; i < visitedFlowCount; i++) { + if (visitedFlowNodes[i] === flow) { + return visitedFlowTypes[i]; + } + } + } + var type = void 0; + if (flow.flags & 4096) { + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048) { + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 96) { + type = getTypeAtFlowCondition(flow); + } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } + else if (flow.flags & 12) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flow.flags & 4 ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flow.flags & 256) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 2) { + var container = flow.container; + if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { + flow = container.flowNode; + continue; + } + type = initialType; + } + else { + type = convertAutoToAny(declaredType); + } + if (flow.flags & 1024) { + visitedFlowNodes[visitedFlowCount] = flow; + visitedFlowTypes[visitedFlowCount] = type; + visitedFlowCount++; + } + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; + } + if (containsMatchingReference(reference, node)) { + return declaredType; + } + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 181 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 181) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 8192) { + return flowType; + } + var assumeTrue = (flow.flags & 32) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 && antecedent.lock.locked) { + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + if (type === declaredType && declaredType === initialType) { + return type; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); + } + } + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (type === declaredType) { + break; + } + } + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + return expr.kind === 179 && + computedType.flags & 65536 && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(computedType, expr.name.escapedText); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.escapedText; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 58: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 32: + case 33: + case 34: + case 35: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 189 && right_1.kind === 9) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 189 && left_1.kind === 9) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 93: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 26: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1) { + return type; + } + if (operator === 33 || operator === 35) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 6144) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 32 || operator === 33; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + value.kind === 95 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); + } + if (type.flags & 16810497) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { + return declaredType; + } + return type; + } + if (operator === 33 || operator === 35) { + assumeTrue = !assumeTrue; + } + if (assumeTrue && !(type.flags & 65536)) { + var targetType = typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 540672) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 : + typeofNEFacts.get(literal.text) || 8192; + return getTypeWithFacts(type, facts); + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + if (containsMatchingReference(reference, left)) { + return declaredType; + } + return type; + } + var rightType = getTypeOfExpression(expr.right); + if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = void 0; + if (getObjectFlags(rightType) & 2) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; + } + else if (getObjectFlags(rightType) & 16) { + constructSignatures = getSignaturesOfType(rightType, 1); + } + if (constructSignatures && constructSignatures.length) { + targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + } + } + if (targetType) { + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + } + return type; + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + if (type.flags & 65536) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 8192)) { + return assignableType; + } + } + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 71: + case 99: + case 97: + case 179: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 181: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 185: + return narrowType(type, expr.expression, assumeTrue); + case 194: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 192: + if (expr.operator === 51) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + if (location.kind === 71) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 234 || + node.kind === 265 || + node.kind === 149; + }); + } + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304)) { + links.flags |= 4194304; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); + } + function markParameterAssignments(node) { + if (node.kind === 71) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 146 && + declaration.initializer && + getFalsyFlags(declaredType) & 2048 && + !(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) { + return unknownType; + } + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2) { + if (container.kind === 187) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192; + return getTypeOfSymbol(symbol); + } + if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32) { + if (declaration.kind === 229 + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 199) { + var container = ts.getThisContainer(node, false); + while (container !== undefined) { + if (container.parent === declaration) { + if (container.kind === 149 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + } + break; + } + container = ts.getThisContainer(container, false); + } + } + } + checkCollisionWithCapturedSuperVariable(node, node); + checkCollisionWithCapturedThisVariable(node, node); + checkCollisionWithCapturedNewTargetVariable(node, node); + checkNestedBlockScopedBinding(node, symbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152; + if (localOrExportSymbol.flags & 3) { + if (assignmentKind === 1) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + var isParameter = ts.getRootDeclaration(declaration).kind === 146; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || + flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + var assumeInitialized = isParameter || isAlias || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || + node.parent.kind === 203 || + ts.isInAmbientContext(declaration); + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getNullableType(type, 2048); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + 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); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 || + (symbol.flags & (2 | 32)) === 0 || + symbol.valueDeclaration.parent.kind === 260) { + return; + } + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + getNodeLinks(current).flags |= 65536; + } + if (container.kind === 214 && + ts.getAncestor(symbol.valueDeclaration, 227).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + } + getNodeLinks(symbol.valueDeclaration).flags |= 262144; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + while (current.parent.kind === 185) { + current = current.parent; + } + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 192 || current.parent.kind === 193)) { + var expr = current.parent; + isAssigned = expr.operator === 43 || expr.operator === 44; + } + if (!isAssigned) { + return false; + } + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2; + if (container.kind === 149 || container.kind === 152) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4; + } + else { + getNodeLinks(container).flags |= 4; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + var container = ts.getThisContainer(node, true); + var needToCaptureLexicalThis = false; + if (container.kind === 152) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + if (container.kind === 187) { + container = ts.getThisContainer(container, false); + needToCaptureLexicalThis = (languageVersion < 2); + } + switch (container.kind) { + case 233: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + break; + case 232: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + break; + case 152: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + } + break; + case 149: + case 148: + if (ts.getModifierFlags(container) & 32) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + } + break; + case 144: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node, container); + } + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + if (container.kind === 186 && + container.parent.kind === 194 && + ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { + var className = container.parent + .left + .expression + .expression; + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + return getInferredClassType(classSymbol); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return thisType; + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + } + if (noImplicitThis) { + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return anyType; + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 273) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this") { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; + var container = ts.getSuperContainer(node, true); + var needToCaptureLexicalThis = false; + if (!isCallExpression) { + while (container && container.kind === 187) { + container = ts.getSuperContainer(container, true); + needToCaptureLexicalThis = languageVersion < 2; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); + if (current && current.kind === 144) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return unknownType; + } + if (!isCallExpression && container.kind === 152) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if ((ts.getModifierFlags(container) & 32) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (container.kind === 151 && ts.getModifierFlags(container) & 256) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096; + } + else { + getNodeLinks(container).flags |= 2048; + } + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 178) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return unknownType; + } + return nodeCheckFlag === 512 + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + return container.kind === 152; + } + else { + if (ts.isClassLike(container.parent) || container.parent.kind === 178) { + if (ts.getModifierFlags(container) & 32) { + return container.kind === 151 || + container.kind === 150 || + container.kind === 153 || + container.kind === 154; + } + else { + return container.kind === 151 || + container.kind === 150 || + container.kind === 153 || + container.kind === 154 || + container.kind === 149 || + container.kind === 148 || + container.kind === 152; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 151 || + func.kind === 153 || + func.kind === 154) && func.parent.kind === 178 ? func.parent : + func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 187) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 261) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { + var target = func.parent.left; + if (target.kind === 179 || target.kind === 180) { + return checkExpressionCached(target.expression); + } + } + } + return undefined; + } + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); + } + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + } + } + } + return undefined; + } + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 146) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, true, false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 176) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + return functionFlags & 2 + ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) + : contextualReturnType; + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (node.parent.kind === 146 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + if (functionDecl.kind === 152 || + ts.getEffectiveReturnTypeNode(functionDecl) || + isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + } + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); + if (argIndex >= 0) { + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + return getTypeAtPosition(signature, argIndex); + } + return undefined; + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 183) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var operator = binaryExpression.operatorToken.kind; + if (ts.isAssignmentOperator(operator)) { + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + return undefined; + } + if (node === binaryExpression.right) { + return getTypeOfExpression(binaryExpression.left); + } + } + else if (operator === 54) { + var type = getContextualType(binaryExpression); + if (!type && node === binaryExpression.right) { + type = getTypeOfExpression(binaryExpression.left); + } + return type; + } + else if (operator === 53 || operator === 26) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } + return undefined; + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; + return prop ? getTypeOfSymbol(prop) : undefined; + }); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + } + function contextualTypeIsTupleLikeType(type) { + return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + } + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (isInsideWithStatementBody(node)) { + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!ts.hasDynamicName(element)) { + var symbolName = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || + getIndexTypeOfContextualType(type, 0); + } + return undefined; + } + function getContextualTypeForElementExpression(node) { + var arrayLiteral = node.parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + if (type) { + var index = ts.indexOf(arrayLiteral.elements, node); + return getTypeOfPropertyOfContextualType(type, "" + index) + || getIndexTypeOfContextualType(type, 1) + || getIteratedTypeOrElementType(type, undefined, false, false, false); + } + return undefined; + } + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? + node.parent.parent : + node.parent.openingElement.attributes; + var attributesType = getContextualType(jsxAttributes); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + if (ts.isJsxAttribute(node.parent)) { + return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + } + else if (node.parent.kind === 249) { + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + } + else { + return attributesType; + } + } + function getContextualTypeForJsxAttribute(attribute) { + var attributesType = getContextualType(attribute.parent); + if (ts.isJsxAttribute(attribute)) { + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + } + else { + return attributesType; + } + } + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); + return type && getApparentType(type); + } + function getContextualType(node) { + if (isInsideWithStatementBody(node)) { + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 176: + return getContextualTypeForInitializerExpression(node); + case 187: + case 219: + return getContextualTypeForReturnExpression(node); + case 197: + return getContextualTypeForYieldOperand(parent); + case 181: + case 182: + return getContextualTypeForArgument(parent, node); + case 184: + case 202: + return getTypeFromTypeNode(parent.type); + case 194: + return getContextualTypeForBinaryOperand(node); + case 261: + case 262: + return getContextualTypeForObjectLiteralElement(parent); + case 263: + return getApparentTypeOfContextualType(parent.parent); + case 177: + return getContextualTypeForElementExpression(node); + case 195: + return getContextualTypeForConditionalOperand(node); + case 205: + ts.Debug.assert(parent.parent.kind === 196); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 185: + return getContextualType(parent); + case 256: + return getContextualTypeForJsxExpression(parent); + case 253: + case 255: + return getContextualTypeForJsxAttribute(parent); + case 251: + case 250: + return getAttributesTypeFromJsxOpeningLikeElement(parent); + } + return undefined; + } + function getContextualMapper(node) { + node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return node ? node.contextualMapper : identityMapper; + } + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfStructuredType(type, 0); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 186 || node.kind === 187; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 65536)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { + return undefined; + } + else { + signatureList.push(signature); + } + } + } + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.resolvedReturnType = undefined; + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); + } + function hasDefaultValue(node) { + return (node.kind === 176 && !!node.initializer) || + (node.kind === 194 && node.operatorToken.kind === 58); + } + function checkArrayLiteral(node, checkMode) { + var elements = node.elements; + var hasSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; + if (inDestructuringPattern && e.kind === 198) { + var restArrayType = checkExpression(e.expression, checkMode); + var restElementType = getIndexTypeOfType(restArrayType, 1) || + getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var type = checkExpressionForMutableLocation(e, checkMode); + elementTypes.push(type); + } + hasSpreadElement = hasSpreadElement || e.kind === 198; + } + if (!hasSpreadElement) { + if (inDestructuringPattern && elementTypes.length) { + var type = cloneTypeReference(createTupleType(elementTypes)); + type.pattern = node; + return type; + } + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { + var patternElements = pattern.elements; + for (var i = elementTypes.length; i < patternElements.length; i++) { + var patternElement = patternElements[i]; + if (hasDefaultValue(patternElement)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else { + if (patternElement.kind !== 200) { + error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(unknownType); + } + } + } + if (elementTypes.length) { + return createTupleType(elementTypes); + } + } + } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, true) : + strictNullChecks ? neverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 144: + return isNumericComputedName(name); + case 71: + return isNumericLiteralName(name.escapedText); + case 8: + case 9: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || isTypeOfKind(type, kind); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + 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 { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + return createIndexInfo(unionType, false); + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable = ts.createSymbolTable(); + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); + var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + var isInJSFile = ts.isInJavaScriptFile(node); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 261 || + memberDecl.kind === 262 || + ts.isObjectLiteralMethod(memberDecl)) { + var jsdocType = void 0; + if (isInJSFile) { + jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); + } + var type = void 0; + if (memberDecl.kind === 261) { + type = checkPropertyAssignment(memberDecl, checkMode); + } + else if (memberDecl.kind === 151) { + type = checkObjectLiteralMethod(memberDecl, checkMode); + } + else { + ts.Debug.assert(memberDecl.kind === 262); + type = checkExpressionForMutableLocation(memberDecl.name, checkMode); + } + if (jsdocType) { + checkTypeAssignableTo(type, jsdocType, memberDecl); + type = jsdocType; + } + typeFlags |= type.flags; + var prop = createSymbol(4 | member.flags, member.escapedName); + if (inDestructuringPattern) { + var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216; + } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } + } + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 263) { + if (languageVersion < 2) { + checkExternalEmitHelpers(memberDecl, 2); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type); + offset = i + 1; + continue; + } + else { + ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); + checkNodeDeferred(memberDecl); + } + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName)) { + if (!(prop.flags & 16777216)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + } + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; + spread.symbol = node.symbol; + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.objectFlags |= 128; + if (patternWithComputedProperties) { + result.objectFlags |= 512; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144)) { + propagatedFlags |= (result.flags & 14680064); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 | 4096 | 2048 | 16777216) || + type.flags & 32768 && !isGenericMappedType(type) || + type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + } + function checkJsxSelfClosingElement(node) { + checkJsxOpeningLikeElement(node); + return getJsxGlobalElementType() || anyType; + } + function checkJsxElement(node) { + checkJsxOpeningLikeElement(node.openingElement); + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + return getJsxGlobalElementType() || anyType; + } + function isUnhyphenatedJsxName(name) { + return name.indexOf("-") < 0; + } + function isJsxIntrinsicIdentifier(tagName) { + switch (tagName.kind) { + case 179: + case 99: + return false; + case 71: + return ts.isIntrinsicJsxName(tagName.escapedText); + default: + ts.Debug.fail(); + } + } + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + 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; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = attributeDecl.initializer ? + checkExpression(attributeDecl.initializer, checkMode) : + trueType; + var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + attributesArray.push(attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 255); + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpression(attributeDecl.expression); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createSymbolTable(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; + if (!filter || filter(attr)) { + attributesTable.set(attr.escapedName, attr); + } + } + } + var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = []; + 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); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + createArrayType(getUnionType(childrenTypes, false)); + attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + } + } + 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, ts.emptyArray, ts.emptyArray, undefined, undefined); + result.flags |= 33554432 | 4194304; + result.objectFlags |= 128; + return result; + } + } + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); + } + function getJsxType(name) { + var jsxType = jsxTypes.get(name); + if (jsxType === undefined) { + jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); + } + return jsxType; + } + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + if (!ts.isIdentifier(node.tagName)) + throw ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1; + return links.resolvedSymbol = intrinsicProp; + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + links.jsxFlags |= 2; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxElementInstanceType(node, valueType) { + ts.Debug.assert(!(valueType.flags & 65536)); + if (isTypeAny(valueType)) { + return anyType; + } + var signatures = getSignaturesOfType(valueType, 1); + if (signatures.length === 0) { + signatures = getSignaturesOfType(valueType, 0); + if (signatures.length === 0) { + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return unknownType; + } + } + 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); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxElementPropertiesName() { + if (!_hasComputedJsxElementPropertiesName) { + _hasComputedJsxElementPropertiesName = true; + _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); + } + return _jsxElementPropertiesName; + } + function getJsxElementChildrenPropertyname() { + if (!_hasComputedJsxElementChildrenPropertyName) { + _hasComputedJsxElementChildrenPropertyName = true; + _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); + } + 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)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); + 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) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + } + } + } + return undefined; + } + function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { + ts.Debug.assert(!(elementType.flags & 65536)); + if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + var candidatesOutArray = []; + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + var result = void 0; + var allMatchingAttributesType = void 0; + for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { + 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++) { + var attribute = _b[_a]; + if (ts.isJsxAttribute(attribute) && + isUnhyphenatedJsxName(attribute.name.escapedText) && + !getPropertyOfType(paramType, attribute.name.escapedText)) { + shouldBeCandidate = false; + break; + } + } + if (shouldBeCandidate) { + result = intersectTypes(result, paramType); + } + allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); + } + } + if (!result) { + result = allMatchingAttributesType; + } + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + result = intersectTypes(intrinsicAttributes, result); + } + return result; + } + } + return undefined; + } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { + if (!elementType) { + elementType = checkExpression(openingLikeElement.tagName); + } + if (elementType.flags & 65536) { + var types = elementType.types; + return getUnionType(types.map(function (type) { + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); + }), true); + } + if (elementType.flags & 2) { + return anyType; + } + else if (elementType.flags & 32) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + return indexSignatureType; + } + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + } + return anyType; + } + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? + tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : + defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); + if (statelessAttributesType) { + return statelessAttributesType; + } + if (elementClassType) { + checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + if (isTypeAny(elemInstanceType)) { + return elemInstanceType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + return anyType; + } + else if (propsName === "") { + return elemInstanceType; + } + else { + var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + if (!attributesType) { + return emptyObjectType; + } + else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + return attributesType; + } + else { + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; + } + else { + return links.resolvedJsxElementAttributesType = unknownType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var elemClassType = getJsxGlobalElementClassType(); + return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + } + return links.resolvedJsxElementAttributesType; + } + function getAllAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, true); + } + } + function getAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, false); + } + } + function getJsxAttributePropertySymbol(attrib) { + var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); + var prop = getPropertyOfType(attributesType, attrib.name.escapedText); + return prop || unknownSymbol; + } + function getJsxGlobalElementClassType() { + if (!deferredJsxElementClassType) { + deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); + } + return deferredJsxElementClassType; + } + function getJsxGlobalElementType() { + if (!deferredJsxElementType) { + deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); + } + return deferredJsxElementType; + } + function getJsxGlobalStatelessElementType() { + if (!deferredJsxStatelessElementType) { + var jsxElementType = getJsxGlobalElementType(); + if (jsxElementType) { + deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); + } + } + return deferredJsxStatelessElementType; + } + function getJsxIntrinsicTagNames() { + var intrinsics = getJsxType(JsxNames.IntrinsicElements); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + if ((compilerOptions.jsx || 0) === 0) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxGlobalElementType() === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElement(node) { + checkGrammarJsxElement(node); + checkJsxPreconditions(node); + var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(); + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + if (reactSym) { + reactSym.isReferenced = true; + if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + checkJsxAttributesAssignableToTagNameAttributes(node); + } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(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) : + getCustomJsxElementAttributesType(openingLikeElement, false); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { + return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); + }); + if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + } + else { + 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.escapedText, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + break; + } + } + } + } + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + } + return type; + } + else { + return unknownType; + } + } + function getDeclarationKindFromSymbol(s) { + return s.valueDeclaration ? s.valueDeclaration.kind : 149; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + function isMethodLike(symbol) { + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); + } + function checkPropertyAccessibility(node, left, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 179 || node.kind === 226 ? + node.name : + node.right; + 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; + } + if (left.kind === 97) { + if (languageVersion < 2) { + var hasNonMethodDeclaration = forEachProperty(prop, function (p) { + var propKind = getDeclarationKindFromSymbol(p); + return propKind !== 151 && propKind !== 150; + }); + if (hasNonMethodDeclaration) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + if (!(flags & 24)) { + return true; + } + if (flags & 8) { + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + if (left.kind === 97) { + return true; + } + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + if (!enclosingClass) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + if (flags & 32) { + return true; + } + if (type.flags & 16384 && type.isThisType) { + type = getConstraintOfTypeParameter(type); + } + if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); + } + function checkNonNullType(type, errorNode) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; + if (kind) { + error(errorNode, kind & 2048 ? kind & 4096 ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + var t = getNonNullableType(type); + return t.flags & (6144 | 8192) ? unknownType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.escapedText); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0); + if (stringIndexType) { + return stringIndexType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + if (prop.valueDeclaration.kind === 229 && + node.parent && node.parent.kind !== 159 && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); + return unknownType; + } + } + if (node.kind !== 179 || assignmentKind === 1 || + !(prop.flags & (3 | 4 | 98304)) && + !(prop.flags & 8192 && propType.flags & 65536)) { + return propType; + } + 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.escapedText)) { + 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(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455); + return suggestion && suggestion.escapedName; + } + 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(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.escapedName; + } + } + 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; + var justCheckExactMatches = false; + 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]; + var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); + if (candidate.flags & meaning && + candidateName && + Math.abs(candidateName.length - name.length) < maximumLengthDifference) { + candidateName = candidateName.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + 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) { + justCheckExactMatches = true; + bestCandidate = 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 + : node.left; + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { + if (type !== unknownType && !isTypeAny(type)) { + var prop = getPropertyOfType(type, propertyName); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); + } + if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; + } + return true; + } + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 227) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 71) { + return getResolvedSymbol(initializer); + } + return undefined; + } + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); + } + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 71) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 215 && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 182 && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return unknownType; + } + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === unknownType) { + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + if ((expressionType.flags & 512) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); + if (!globalESSymbol) { + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + 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); + } + else if (node.kind !== 147) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + 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) { + if (lastParent && parent === lastParent) { + index++; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function getSpreadArgumentIndex(args) { + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (arg && arg.kind === 198) { + return i; + } + } + return -1; + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var typeArguments; + var callIsIncomplete; + var isDecorator; + var spreadArgIndex = -1; + if (ts.isJsxOpeningLikeElement(node)) { + return true; + } + if (node.kind === 183) { + var tagExpression = node; + argCount = args.length; + typeArguments = undefined; + if (tagExpression.template.kind === 196) { + var templateExpression = tagExpression.template; + var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); + ts.Debug.assert(lastSpan !== undefined); + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + var templateLiteral = tagExpression.template; + ts.Debug.assert(templateLiteral.kind === 13); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 147) { + isDecorator = true; + typeArguments = undefined; + argCount = getEffectiveArgumentCount(node, undefined, signature); + } + else { + var callExpression = node; + if (!callExpression.arguments) { + ts.Debug.assert(callExpression.kind === 182); + return signature.minArgumentCount === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + callIsIncomplete = callExpression.arguments.end === callExpression.end; + typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); + } + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + var hasRightNumberOfTypeArgs = !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + if (!hasRightNumberOfTypeArgs) { + return false; + } + if (spreadArgIndex >= 0) { + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + } + if (!signature.hasRestParameter && argCount > signature.parameters.length) { + return false; + } + var hasEnoughArguments = argCount >= signature.minArgumentCount; + return callIsIncomplete || hasEnoughArguments; + } + function getSingleCallSignature(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { + var context = createInferenceContext(signature, 1); + forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); + } + return getSignatureInstantiation(signature, getInferredTypes(context)); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isExpression(node)) { + var contextualType = getContextualType(node); + if (contextualType) { + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 200) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i); + if (argType === undefined) { + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + argType = checkExpressionWithContextualType(arg, paramType, mapper); + } + inferTypes(context.inferences, argType, paramType); + } + } + if (excludeArgument) { + for (var i = 0; i < argCount; i++) { + if (excludeArgument[i] === false) { + var arg = args[i]; + var paramType = getTypeAtPosition(signature, i); + inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); + } + } + } + return getInferredTypes(context); + } + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + var typeParameters = signature.typeParameters; + var typeArgumentsAreAssignable = true; + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + if (typeArgumentsAreAssignable) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); + } + } + } + return typeArgumentsAreAssignable; + } + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { + var callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var paramType = getTypeAtPosition(signature, 0); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); + var argProperties = getPropertiesOfType(attributesType); + for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { + var arg = argProperties_1[_i]; + if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { + return false; + } + } + return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 182) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 200) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } + } + } + return true; + } + function getThisArgumentOfCall(node) { + if (node.kind === 181) { + var callee = node.expression; + if (callee.kind === 179) { + return callee.expression; + } + else if (callee.kind === 180) { + return callee.expression; + } + } + } + function getEffectiveCallArguments(node) { + if (node.kind === 183) { + var template = node.template; + var args_4 = [undefined]; + if (template.kind === 196) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + else if (node.kind === 147) { + return undefined; + } + else if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + } + else { + return node.arguments || ts.emptyArray; + } + } + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 147) { + switch (node.parent.kind) { + case 229: + case 199: + return 1; + case 149: + return 2; + case 151: + case 153: + case 154: + if (languageVersion === 0) { + return 2; + } + return signature.parameters.length >= 3 ? 3 : 2; + case 146: + return 3; + } + } + else { + return args.length; + } + } + function getEffectiveDecoratorFirstArgumentType(node) { + if (node.kind === 229) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + if (node.kind === 146) { + node = node.parent; + if (node.kind === 152) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + } + if (node.kind === 149 || + node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + return getParentTypeOfClassElement(node); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorSecondArgumentType(node) { + if (node.kind === 229) { + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + } + if (node.kind === 146) { + node = node.parent; + if (node.kind === 152) { + return anyType; + } + } + if (node.kind === 149 || + node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + var element = node; + switch (element.name.kind) { + case 71: + return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + case 8: + case 9: + return getLiteralType(element.name.text); + case 144: + var nameType = checkComputedPropertyName(element.name); + if (isTypeOfKind(nameType, 512)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorThirdArgumentType(node) { + if (node.kind === 229) { + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 146) { + return numberType; + } + if (node.kind === 149) { + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + function getEffectiveArgumentType(node, argIndex) { + if (node.kind === 147) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 183) { + return getGlobalTemplateStringsArrayType(); + } + return undefined; + } + function getEffectiveArgument(node, args, argIndex) { + if (node.kind === 147 || + (argIndex === 0 && node.kind === 183)) { + return undefined; + } + return args[argIndex]; + } + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 147) { + return node.expression; + } + else if (argIndex === 0 && node.kind === 183) { + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + var isTaggedTemplate = node.kind === 183; + var isDecorator = node.kind === 147; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var typeArguments; + if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { + typeArguments = node.typeArguments; + if (node.expression.kind !== 97) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + reorderCandidates(signatures, candidates); + if (!candidates.length) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + var excludeArgument; + var excludeCount = 0; + if (!isDecorator) { + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + excludeCount++; + } + } + } + var candidateForArgumentError; + var candidateForTypeArgumentError; + var result; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + if (candidateForArgumentError) { + if (isJsxOpeningOrSelfClosingElement) { + return candidateForArgumentError; + } + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); + } + else if (candidateForTypeArgumentError) { + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + } + 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) { + ts.Debug.assert(candidates.length > 0); + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { + var typeArguments_2 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_2.length > typeParameters.length) { + typeArguments_2.pop(); + } + while (typeArguments_2.length < typeParameters.length) { + typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + candidates[bestIndex] = instantiated; + return instantiated; + } + return candidate; + } + return resolveErrorCall(node); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var originalCandidate = candidates[candidateIndex]; + if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + continue; + } + var candidate = void 0; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + undefined; + while (true) { + candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } + } + else { + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; + break; + } + if (excludeCount === 0) { + candidates[candidateIndex] = candidate; + return candidate; + } + excludeCount--; + if (excludeCount > 0) { + excludeArgument[ts.indexOf(excludeArgument, true)] = false; + } + else { + excludeArgument = undefined; + } + } + } + return undefined; + } + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + return i; + } + if (candidate.parameters.length > maxParams) { + maxParams = candidate.parameters.length; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray) { + if (node.expression.kind === 97) { + var superType = checkSuperExpression(node.expression); + if (superType !== unknownType) { + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType !== unknownType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + if (constructSignatures.length) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + } + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + if (funcType.flags & 65536) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } + function resolveNewExpression(node, candidatesOutArray) { + if (node.arguments && languageVersion < 1) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + return resolveErrorCall(node); + } + 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(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + var constructSignatures = getSignaturesOfType(expressionType, 1); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray); + } + var callSignatures = getSignaturesOfType(expressionType, 0); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray); + if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + return signature; + } + error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + return resolveErrorCall(node); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getModifierFlags(declaration); + if (!(modifiers & 24)) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + while (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + baseTypes = getBaseTypes(baseType); + } + } + if (modifiers & 8) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function resolveTaggedTemplateExpression(node, candidatesOutArray) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 229: + case 199: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 146: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 149: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 151: + case 153: + case 154: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = void 0; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + ts.Debug.assert(!(elementType.flags & 65536)); + var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); + return callSignature; + } + function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { + if (elementType.flags & 65536) { + var types = elementType.types; + var result = void 0; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; + result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); + } + return result; + } + var callSignatures = elementType && getSignaturesOfType(elementType, 0); + if (callSignatures && callSignatures.length > 0) { + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + } + return undefined; + } + function resolveSignature(node, candidatesOutArray) { + switch (node.kind) { + case 181: + return resolveCallExpression(node, candidatesOutArray); + case 182: + return resolveNewExpression(node, candidatesOutArray); + case 183: + return resolveTaggedTemplateExpression(node, candidatesOutArray); + case 147: + return resolveDecorator(node, candidatesOutArray); + case 251: + case 250: + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + } + ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + } + function getResolvedSignature(node, candidatesOutArray) { + var links = getNodeLinks(node); + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray); + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + function isJavaScriptConstructor(node) { + if (ts.isInJavaScriptFile(node)) { + if (ts.getJSDocClassTag(node)) + return true; + var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : + ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + undefined; + return symbol && symbol.members !== undefined; + } + return false; + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && getObjectFlags(type) & 16 + && getSymbolLinks(type.symbol).inferredClassType === type; + } + function checkCallExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 97) { + return voidType; + } + if (node.kind === 182) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 152 && + declaration.kind !== 156 && + declaration.kind !== 161 && + !ts.isJSDocConstructSignature(declaration)) { + var funcSymbol = node.expression.kind === 71 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { + funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); + } + if (funcSymbol && funcSymbol.flags & 16 && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { + return getInferredClassType(funcSymbol); + } + else if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + return getReturnTypeOfSignature(signature); + } + function checkImportCallExpression(node) { + checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 2048 || specifierType.flags & 4096 || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, true)) { + return false; + } + if (!ts.isIdentifier(node.expression)) + throw ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined); + if (!resolvedRequire) { + return true; + } + if (resolvedRequire.flags & 2097152) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 + ? 228 + : resolvedRequire.flags & 3 + ? 226 + : 0; + if (targetDeclarationKind !== 0) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return ts.isInAmbientContext(decl); + } + return false; + } + function checkTaggedTemplateExpression(node) { + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== unknownType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return unknownType; + } + else if (container.kind === 152) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && declaration.initializer) { + return getNullableType(type, 2048); + } + } + return type; + } + function getTypeAtPosition(signature, pos) { + return signature.hasRestParameter ? + pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : + pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + } + function getTypeOfFirstParameterOfSignature(signature) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + var parameter = ts.lastOrUndefined(signature.parameters); + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + function assignBindingElementTypes(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + assignBindingElementTypes(element); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); + if (links.type === emptyObjectType && + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); + } + assignBindingElementTypes(parameter.valueDeclaration); + } + } + function createPromiseType(promisedType) { + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return unknownType; + } + else if (!getGlobalPromiseConstructorSymbol(true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!func.body) { + return unknownType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 207) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = void 0; + if (functionFlags & 1) { + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 + ? createAsyncIterableIteratorType(anyType) + : createIterableIteratorType(anyType); + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (!types) { + return functionFlags & 2 + ? createPromiseReturnType(func, neverType) + : neverType; + } + if (types.length === 0) { + return functionFlags & 2 + ? createPromiseReturnType(func, voidType) + : voidType; + } + } + type = getUnionType(types, true); + if (functionFlags & 1) { + type = functionFlags & 2 + ? createAsyncIterableIteratorType(type) + : createIterableIteratorType(type); + } + } + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } + var widenedType = getWidenedType(type); + return (functionFlags & 3) === 2 + ? createPromiseReturnType(func, widenedType) + : widenedType; + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var functionFlags = ts.getFunctionFlags(func); + ts.forEachYieldExpression(func.body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (yieldExpression.asteriskToken) { + type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); + } + if (functionFlags & 2) { + type = checkAwaitedType(type, expr, yieldExpression.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 8192) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 186 || func.kind === 187)) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (!ts.contains(aggregatedTypes, undefinedType)) { + aggregatedTypes.push(undefinedType); + } + } + return aggregatedTypes; + } + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + return; + } + if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256; + if (returnType && returnType.flags & 8192) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186) { + checkGrammarForGenerator(node); + } + if (checkMode === 1 && isContextSensitive(node)) { + checkNodeDeferred(node); + return anyFunctionType; + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(node.symbol); + if (!(links.flags & 1024)) { + var contextualSignature = getContextualSignature(node); + if (!(links.flags & 1024)) { + links.flags |= 1024; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + checkNodeDeferred(node); + } + } + if (produceDiagnostics && node.kind !== 151) { + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + } + return type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnOrPromisedType = returnTypeNode && + ((functionFlags & 3) === 2 ? + checkAsyncFunctionReturnType(node) : + getTypeFromTypeNode(returnTypeNode)); + if ((functionFlags & 1) === 0) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!returnTypeNode) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 207) { + checkSourceElement(node.body); + } + else { + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3) === 2) { + 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); + } + else { + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + } + } + } + registerForUnusedIdentifiersCheck(node); + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlySymbol(symbol) { + 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); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + if (symbol.flags & 4 && + (expr.kind === 179 || expr.kind === 180) && + expr.expression.kind === 99) { + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 152)) { + return true; + } + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 179 || expr.kind === 180) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 71) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 240; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + var node = ts.skipOuterExpressions(expr, 2 | 1); + if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 179 && expr.kind !== 180) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 16384)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 38 && node.operand.kind === 8) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + switch (node.operator) { + case 37: + case 38: + case 52: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 512)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + return numberType; + case 51: + var facts = getTypeFacts(operandType) & (1048576 | 2097152); + return facts === 1048576 ? falseType : + facts === 2097152 ? trueType : + booleanType; + case 43: + case 44: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + return unknownType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + function maybeTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 196608) { + var types = type.types; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 65536) { + var types = type.types; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; + if (!isTypeOfKind(t, kind)) { + return false; + } + } + return true; + } + if (type.flags & 131072) { + var types = type.types; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isConstEnumObjectType(type) { + return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (isTypeOfKind(leftType, 8190)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + if (!(isTypeAny(rightType) || + getSignaturesOfType(rightType, 0).length || + getSignaturesOfType(rightType, 1).length || + isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + 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)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType) { + var properties = node.properties; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + } + return sourceType; + } + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 261 || property.kind === 262) { + var name = property.name; + if (name.kind === 144) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var text = ts.getTextOfPropertyName(name); + var type = isTypeAny(objectLiteralType) + ? objectLiteralType + : getTypeOfPropertyOfType(objectLiteralType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || + getIndexTypeOfType(objectLiteralType, 0); + if (type) { + if (property.kind === 262) { + return checkDestructuringAssignment(property, type); + } + else { + return checkDestructuringAssignment(property.initializer, type); + } + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 263) { + if (languageVersion < 5) { + checkExternalEmitHelpers(property, 4); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || unknownType; + var elements = node.elements; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 200) { + if (element.kind !== 198) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) + ? getTypeOfPropertyOfType(sourceType, propName) + : elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + else { + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + var target; + if (exprOrAssignment.kind === 262) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + sourceType = getTypeWithFacts(sourceType, 131072); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 194 && target.operatorToken.kind === 58) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 178) { + return checkObjectLiteralAssignment(target, sourceType); + } + if (target.kind === 177) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 263 ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableTo(sourceType, targetType, target, undefined); + } + return sourceType; + } + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 71: + case 9: + case 12: + case 183: + case 196: + case 13: + case 8: + case 101: + case 86: + case 95: + case 139: + case 186: + case 199: + case 187: + case 177: + case 178: + case 189: + case 203: + case 250: + case 249: + return true; + case 195: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 194: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 192: + case 193: + switch (node.operator) { + case 51: + case 37: + case 38: + case 52: + return true; + } + return false; + case 190: + case 184: + case 202: + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], true); + } + function checkBinaryExpression(node, checkMode) { + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 58 && (left.kind === 178 || left.kind === 177)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + } + var leftType = checkExpression(left, checkMode); + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 39: + case 40: + case 61: + case 62: + case 41: + case 63: + case 42: + case 64: + case 38: + case 60: + case 45: + case 65: + case 46: + case 66: + case 47: + case 67: + case 49: + case 69: + case 50: + case 70: + case 48: + case 68: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + if ((leftType.flags & 136) && + (rightType.flags & 136) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + } + else { + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + if (leftOk && rightOk) { + checkAssignmentOperator(numberType); + } + } + return numberType; + case 37: + case 59: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { + resultType = numberType; + } + else { + if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 59) { + checkAssignmentOperator(resultType); + } + return resultType; + case 27: + case 29: + case 30: + case 31: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + reportOperatorError(); + } + } + return booleanType; + case 32: + case 33: + case 34: + case 35: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 93: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 92: + return checkInExpression(left, right, leftType, rightType); + case 53: + return getTypeFacts(leftType) & 1048576 ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 54: + return getTypeFacts(leftType) & 2097152 ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; + case 58: + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + case 26: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + } + function isEvalNode(node) { + return node.kind === 71 && node.escapedText === "eval"; + } + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : + maybeTypeOfKind(rightType, 512) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 49: + case 69: + return 54; + case 50: + case 70: + return 35; + case 48: + case 68: + return 53; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { + checkTypeAssignableTo(valueType, leftType, left, undefined); + } + } + } + function reportOperatorError() { + error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + if (node.expression) { + var func = ts.getContainingFunction(node); + var functionFlags = func && ts.getFunctionFlags(func); + if (node.asteriskToken) { + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); + } + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256); + } + } + if (functionFlags & 1) { + var expressionType = checkExpressionCached(node.expression); + var expressionElementType = void 0; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); + } + var returnType = ts.getEffectiveReturnTypeNode(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2) !== 0) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(functionFlags & 2 + ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionElementType, signatureElementType, node.expression, undefined); + } + else { + checkTypeAssignableTo(functionFlags & 2 + ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionType, signatureElementType, node.expression, undefined); + } + } + } + } + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getBestChoiceType(type1, type2); + } + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8: + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 101: + return trueType; + case 86: + return falseType; + } + } + function checkTemplateExpression(node) { + ts.forEach(node.templateSpans, function (templateSpan) { + checkExpression(templateSpan.expression); + }); + return stringType; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var saveContextualType = node.contextualType; + var saveContextualMapper = node.contextualMapper; + node.contextualType = contextualType; + node.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 : + contextualMapper ? 2 : 0; + var result = checkExpression(node, checkMode); + node.contextualType = saveContextualType; + node.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 184 || node.kind === 202; + } + function checkDeclarationInitializer(declaration) { + var type = getTypeOfExpression(declaration.initializer, true); + return ts.getCombinedNodeFlags(declaration) & 2 || + ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 540672) { + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + if (constraint.flags & (2 | 4 | 8 | 16)) { + return true; + } + contextualType = constraint; + } + return maybeTypeOfKind(contextualType, (224 | 262144)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode) { + var type = checkExpression(node, checkMode); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } + function checkPropertyAssignment(node, checkMode) { + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + checkGrammarMethod(node); + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + function getTypeOfExpression(node, cache) { + if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + return cache ? checkExpressionCached(node) : checkExpression(node); + } + function getContextFreeTypeOfExpression(node) { + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = getTypeOfExpression(node); + node.contextualType = saveContextualType; + return type; + } + function checkExpression(node, checkMode) { + var type; + if (node.kind === 143) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + var ok = (node.parent.kind === 179 && node.parent.expression === node) || + (node.parent.kind === 180 && node.parent.expression === node) || + ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281; }); }); + if (typecasts && typecasts.length) { + var cast_1 = typecasts[0]; + return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); + } + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode) { + switch (node.kind) { + case 71: + return checkIdentifier(node); + case 99: + return checkThisExpression(node); + case 97: + return checkSuperExpression(node); + case 95: + return nullWideningType; + case 9: + case 8: + case 101: + case 86: + return checkLiteralExpression(node); + case 196: + return checkTemplateExpression(node); + case 13: + return stringType; + case 12: + return globalRegExpType; + case 177: + return checkArrayLiteral(node, checkMode); + case 178: + return checkObjectLiteral(node, checkMode); + case 179: + return checkPropertyAccessExpression(node); + case 180: + return checkIndexedAccess(node); + case 181: + if (node.expression.kind === 91) { + return checkImportCallExpression(node); + } + case 182: + return checkCallExpression(node); + case 183: + return checkTaggedTemplateExpression(node); + case 185: + return checkParenthesizedExpression(node, checkMode); + case 199: + return checkClassExpression(node); + case 186: + case 187: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 189: + return checkTypeOfExpression(node); + case 184: + case 202: + return checkAssertion(node); + case 203: + return checkNonNullAssertion(node); + case 204: + return checkMetaProperty(node); + case 188: + return checkDeleteExpression(node); + case 190: + return checkVoidExpression(node); + case 191: + return checkAwaitExpression(node); + case 192: + return checkPrefixUnaryExpression(node); + case 193: + return checkPostfixUnaryExpression(node); + case 194: + return checkBinaryExpression(node, checkMode); + case 195: + return checkConditionalExpression(node, checkMode); + case 198: + return checkSpreadExpression(node, checkMode); + case 200: + return undefinedWideningType; + case 197: + return checkYieldExpression(node); + case 256: + return checkJsxExpression(node, checkMode); + case 249: + return checkJsxElement(node); + case 250: + return checkJsxSelfClosingElement(node); + case 254: + return checkJsxAttributes(node, checkMode); + case 251: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return unknownType; + } + function checkTypeParameter(node) { + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.getModifierFlags(node) & 92) { + func = ts.getContainingFunction(node); + if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (ts.indexOf(func.parameters, node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 152 || func.kind === 156 || func.kind === 161) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + } + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 && param.name.escapedText === parameter.escapedText) { + return i; + } + } + } + return -1; + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 187: + case 155: + case 228: + case 186: + case 160: + case 151: + case 150: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 71 && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 175 || name.kind === 174) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + if (node.kind === 157) { + checkGrammarIndexSignature(node); + } + else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || + node.kind === 155 || node.kind === 152 || + node.kind === 156) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); + } + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); + } + if ((functionFlags & 3) !== 0 && languageVersion < 2) { + checkExternalEmitHelpers(node, 128); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 156: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 155: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 | 1)) === 1) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 + ? createAsyncIterableIteratorType(generatorElementType) + : createIterableIteratorType(generatorElementType); + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3) === 2) { + checkAsyncFunctionReturnType(node); + } + } + if (noUnusedIdentifiers && !node.body) { + checkUnusedTypeParameters(node); + } + } + } + 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.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 152) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3); + } + } + } + else { + var isStatic = ts.getModifierFlags(member) & 32; + var names = isStatic ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 153: + addName(names, member.name, memberName, 1); + break; + case 154: + addName(names, member.name, memberName, 2); + break; + case 149: + addName(names, member.name, memberName, 3); + break; + case 151: + addName(names, member.name, memberName, 4); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4) { + if (meaning !== 4) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.getModifierFlags(member) & 32; + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbol(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + var memberName = void 0; + switch (member.name.kind) { + case 9: + case 8: + memberName = member.name.text; + break; + case 71: + memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 230) { + var nodeSymbol = getSymbolOfNode(node); + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 136: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 133: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + checkFunctionOrMethodDeclaration(node); + if (ts.getModifierFlags(node) & 128 && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + checkSignatureDeclaration(node); + checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function containsSuperCallAsComputedPropertyName(n) { + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); + } + function containsSuperCall(n) { + if (ts.isSuperCall(n)) { + return true; + } + else if (ts.isFunctionLike(n)) { + return false; + } + else if (ts.isClassLike(n)) { + return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); + } + return ts.forEachChild(n, containsSuperCall); + } + function markThisReferencesAsErrors(n) { + if (n.kind === 99) { + error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + } + else if (n.kind !== 186 && n.kind !== 228) { + ts.forEachChild(n, markThisReferencesAsErrors); + } + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 149 && + !(ts.getModifierFlags(n) & 32) && + !!n.initializer; + } + var containingClassDecl = node.parent; + if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 153) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (!(node.flags & 256)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + var otherKind = node.kind === 153 ? 154 : 153; + var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (otherAccessor) { + if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 153) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + mapper = createTypeMapper(typeParameters, typeArguments); + } + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== unknownType) { + if (node.typeArguments) { + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var symbol = getNodeLinks(node).resolvedSymbol; + var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); + } + } + 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)); + } + } + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { + grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + } + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 524288)) { + return type; + } + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + return type; + } + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { + var constraint = getBaseConstraintOfType(objectType); + if (constraint && getIndexInfoOfType(constraint, 1)) { + return type; + } + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); + } + function isPrivateWithinAmbient(node) { + return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + if (n.parent.kind !== 230 && + n.parent.kind !== 229 && + n.parent.kind !== 199 && + ts.isInAmbientContext(n)) { + if (!(flags & 2)) { + flags |= 1; + } + flags |= 2; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 | 16)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 | 2 | 8 | 16 | 128; + var someNodeFlags = 0; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 151 || node.kind === 150) && + (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); + if (reportError) { + var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + if (ts.getModifierFlags(node) & 128) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var current = declarations_5[_i]; + var node = current; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = undefined; + } + if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + 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; + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + var symbol = node.localSymbol; + if (!symbol) { + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + return; + } + } + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0; + var nonExportedDeclarationSpaces = 0; + var defaultExportedDeclarationSpaces = 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); + if (effectiveDeclarationFlags & 1) { + if (effectiveDeclarationFlags & 512) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function getDeclarationSpaces(d) { + switch (d.kind) { + case 230: + case 231: + return 2; + case 233: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 + ? 4 | 1 + : 4; + case 229: + case 232: + return 2 | 1; + case 237: + var result_3 = 0; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 226: + case 176: + case 228: + case 242: + return 1; + default: + ts.Debug.fail(ts.SyntaxKind[d.kind]); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + function getPromisedTypeOfPromise(promise, errorNode) { + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + } + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 65536) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { + if (errorNode) { + ts.Debug.assert(!!diagnosticMessage); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + function checkAsyncFunctionReturnType(node) { + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } + } + else { + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + } + return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 229: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 146: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 149: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 151: + case 153: + case 154: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + } + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 ? 793064 : 1920) | 2097152, undefined, undefined); + if (rootSymbol + && rootSymbol.flags & 2097152 + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + 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.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + function checkDecorators(node) { + if (!node.decorators) { + return; + } + if (!ts.nodeCanBeDecorated(node)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8); + if (node.kind === 146) { + checkExternalEmitHelpers(firstDecorator, 32); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16); + switch (node.kind) { + case 229: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 151: + case 153: + case 154: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 149: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 146: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDoc(node) { + if (!ts.isInJavaScriptFile(node)) { + return; + } + ts.forEach(node.jsDoc, checkSourceElement); + } + function checkJSDocComment(node) { + if (node.tags) { + for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + checkSourceElement(tag); + } + } + } + function checkFunctionOrMethodDeclaration(node) { + checkJSDoc(node); + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + if (node.name && node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + checkFunctionOrConstructorSymbol(symbol); + } + } + } + checkSourceElement(node.body); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if ((functionFlags & 1) === 0) { + var returnOrPromisedType = returnTypeNode && (functionFlags & 2 + ? checkAsyncFunctionReturnType(node) + : getTypeFromTypeNode(returnTypeNode)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !returnTypeNode) { + if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (functionFlags & 1 && ts.nodeIsPresent(node.body)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + registerForUnusedIdentifiersCheck(node); + } + function registerForUnusedIdentifiersCheck(node) { + if (deferredUnusedIdentifierNodes) { + deferredUnusedIdentifierNodes.push(node); + } + } + function checkUnusedIdentifiers() { + if (deferredUnusedIdentifierNodes) { + for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { + var node = deferredUnusedIdentifierNodes_1[_i]; + switch (node.kind) { + case 265: + case 233: + checkUnusedModuleMembers(node); + break; + case 229: + case 199: + checkUnusedClassMembers(node); + checkUnusedTypeParameters(node); + break; + case 230: + checkUnusedTypeParameters(node); + break; + case 207: + case 235: + case 214: + case 215: + case 216: + checkUnusedLocalsAndParameters(node); + break; + case 152: + case 186: + case 228: + case 187: + case 151: + case 153: + case 154: + if (node.body) { + checkUnusedLocalsAndParameters(node); + } + checkUnusedTypeParameters(node); + break; + case 150: + case 155: + case 156: + case 157: + case 160: + case 161: + checkUnusedTypeParameters(node); + break; + case 231: + checkUnusedTypeParameters(node); + break; + } + } + } + } + function checkUnusedLocalsAndParameters(node) { + if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + 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(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + } + } + }); + } + } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 226 && ts.isForInOrOfStatement(declaration.parent.parent)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 71 && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95; + } + function checkUnusedClassMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.members) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 151 || member.kind === 149) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { + error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + } + } + else if (member.kind === 152) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + } + } + } + } + } + } + } + function checkUnusedTypeParameters(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.typeParameters) { + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var typeParameter = _a[_i]; + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + } + } + } + } + } + function checkUnusedModuleMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + } + }); + } + } + function checkBlock(node) { + if (node.kind === 207) { + checkGrammarStatementInAmbientContext(node); + } + ts.forEach(node.statements, checkSourceElement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 149 || + node.kind === 148 || + node.kind === 151 || + node.kind === 150 || + node.kind === 153 || + node.kind === 154) { + return false; + } + if (ts.isInAmbientContext(node)) { + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { + return false; + } + return true; + } + function checkCollisionWithCapturedThisVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_this")) { + potentialThisCollisions.push(node); + } + } + function checkCollisionWithCapturedNewTargetVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + potentialNewTargetCollisions.push(node); + } + } + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4) { + var isDeclaration_1 = node.kind !== 71; + if (isDeclaration_1) { + 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); + } + return true; + } + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8) { + var isDeclaration_2 = node.kind !== 71; + if (isDeclaration_2) { + 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); + } + return true; + } + }); + } + function checkCollisionWithCapturedSuperVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_super")) { + return; + } + var enclosingClass = ts.getContainingClass(node); + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + return; + } + if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { + var isDeclaration_3 = node.kind !== 71; + if (isDeclaration_3) { + error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); + } + } + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + if (node.kind === 226 && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1) { + if (!ts.isIdentifier(node.name)) + throw ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); + var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + var namesShareScope = container && + (container.kind === 207 && ts.isFunctionLike(container.parent) || + container.kind === 234 || + container.kind === 233 || + container.kind === 265); + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 146) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + return; + } + if (n.kind === 179) { + return visit(n.expression); + } + else if (n.kind === 71) { + var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 146 || + symbol.valueDeclaration.kind === 176) { + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + (current.parent.kind === 149 && + !(ts.hasModifier(current.parent, 32)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + checkSourceElement(node.type); + if (!node.name) { + return; + } + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 176) { + if (node.parent.kind === 174 && languageVersion < 5) { + checkExternalEmitHelpers(node, 4); + } + if (node.propertyName && node.propertyName.kind === 144) { + checkComputedPropertyName(node.propertyName); + } + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + markPropertyAsReferenced(property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); + } + } + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + ts.forEach(node.name.elements, checkSourceElement); + } + if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + if (ts.isBindingPattern(node.name)) { + if (node.initializer && node.parent.parent.kind !== 215) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + if (node === symbol.valueDeclaration) { + if (node.initializer && node.parent.parent.kind !== 215) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); + checkParameterInitializer(node); + } + } + else { + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { + error(node.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(node.name), typeToString(type), typeToString(declarationType)); + } + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + 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)); + } + } + if (node.kind !== 149 && node.kind !== 148) { + checkExportsOnMergedDeclarations(node); + if (node.kind === 226 || node.kind === 176) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 146 && right.kind === 226) || + (left.kind === 226 && right.kind === 146)) { + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 | + 16 | + 256 | + 128 | + 64 | + 32; + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { + if (node.modifiers && node.parent.kind === 178) { + if (ts.getFunctionFlags(node) & 2) { + if (node.modifiers.length > 1) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function checkExpressionStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 209) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkExpression(node.expression); + } + function checkWhileStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.statement); + } + function checkForStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 227) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 227) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.kind === 216) { + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2) { + checkExternalEmitHelpers(node, 256); + } + } + if (node.initializer.kind === 227) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + if (varExpr.kind === 177 || varExpr.kind === 178) { + checkDestructuringAssignment(varExpr, iteratedType || unknownType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + if (iteratedType) { + checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + checkGrammarForInOrForOfStatement(node); + var rightType = checkNonNullExpression(node.expression); + if (node.initializer.kind === 227) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 177 || varExpr.kind === 178) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, true) || anyType; + } + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + var uplevelIteration = languageVersion >= 2; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + if (allowStringInput) { + if (arrayType.flags & 65536) { + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, true); + } + } + else if (arrayType.flags & 262178) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + if (arrayType.flags & 8192) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1); + if (hasStringConstituent && arrayElementType) { + if (arrayElementType.flags & 262178) { + return stringType; + } + return getUnionType([arrayElementType, stringType], true); + } + return arrayElementType; + } + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return typeAsIterable.iteratedTypeOfIterable; + } + if (isReferenceToType(type, getGlobalIterableType(false)) || + isReferenceToType(type, getGlobalIterableIteratorType(false))) { + return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType && getSignaturesOfType(methodType, 0); + if (!ts.some(signatures)) { + if (errorNode) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + return asyncMethodType + ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); + if (isTypeAny(nextResult)) { + return undefined; + } + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, !isAsyncGenerator, false) + || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + } + function isGetAccessorWithAnnotatedSetAccessor(node) { + return node.kind === 153 + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154)) !== undefined; + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 + ? getPromisedTypeOfPromise(returnType) + : returnType; + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + } + function checkReturnStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + var functionBlock = ts.getContainingFunction(node); + if (!functionBlock) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + } + } + var func = ts.getContainingFunction(node); + if (func) { + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + if (strictNullChecks || node.expression || returnType.flags & 8192) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return; + } + if (func.kind === 154) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 152) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableTo(exprType, returnType, node); + } + } + } + else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + } + function checkWithStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + if (clause.kind === 258 && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 257) { + var caseClause = clause; + var caseType = checkExpression(caseClause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 222 && current.label.escapedText === node.label.escapedText) { + var sourceFile = ts.getSourceFileOfNode(node); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); + return true; + } + }); + } + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); + var stringIndexType = getIndexTypeOfType(type, 0); + var numberIndexType = getIndexTypeOfType(type, 1); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); + }); + if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { + var classDeclaration = type.symbol.valueDeclaration; + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + if (!errorNode && (getObjectFlags(type) & 2)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + var propDeclaration = prop.valueDeclaration; + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + return; + } + var errorNode; + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (getObjectFlags(containingType) & 2) { + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + switch (name.escapedText) { + case "any": + case "number": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, typeParameters) { + var maxTypeArgumentCount = ts.length(typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var numTypeParameters = ts.length(declaration.typeParameters); + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = declaration.typeParameters[i]; + var target = typeParameters[i]; + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); + var targetConstraint = getConstraintFromTypeParameter(target); + if ((sourceConstraint || targetConstraint) && + (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { + return false; + } + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !(ts.getModifierFlags(node) & 512)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkTypeParameters(node.typeParameters); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + if (!ts.isInAmbientContext(node)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + if (languageVersion < 2) { + checkExternalEmitHelpers(baseTypeNode.parent, 1); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== unknownType) { + if (isValidBaseType(t)) { + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + } + else { + error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.getModifierFlags(declaration) & 8) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(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; }); + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 229 || d.kind === 230; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + 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) { + var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { + if (derivedClassDecl.kind === 199) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { + continue; + } + if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { + continue; + } + var errorMessage = void 0; + if (isMethodLike(base)) { + if (derived.flags & 98304) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 4) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkInterfaceDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384)) { + nodeLinks.flags |= 16384; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + 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); + } + } + 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; + } + } + 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; + case 47: return left >>> right; + case 45: return left << right; + case 50: return left ^ right; + case 39: return left * right; + case 41: return left / right; + case 37: return left + right; + case 38: return left - right; + case 42: return left % right; + } + } + 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.escapedText); + case 180: + case 179: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = void 0; + if (ex.kind === 179) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + 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; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isConst(node); + if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + if (declaration.kind !== 232) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 229 || + (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && + !ts.isInAmbientContext(declaration)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!inAmbientContext && node.name.kind === 9) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + if (symbol.flags & 512 + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + var mergedClass = ts.getDeclarationOfKind(symbol, 229); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 208: + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 243: + case 244: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 237: + case 238: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 176: + case 226: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + case 229: + case 232: + case 228: + case 230: + case 233: + case 231: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + var reportError = !(symbol.flags & 33554432); + if (!reportError) { + reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 71: + return node; + case 143: + do { + node = node.left; + } while (node.kind !== 71); + return node; + case 179: + do { + node = node.expression; + } while (node.kind !== 71); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 265 && !inAmbientExternalModule) { + error(moduleName, node.kind === 244 ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (!isTopLevelInExternalModuleAugmentation(node)) { + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | + (symbol.flags & 793064 ? 793064 : 0) | + (symbol.flags & 1920 ? 1920 : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 246 ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + if (compilerOptions.isolatedModules + && node.kind === 246 + && !(target.flags & 107455) + && !ts.isInAmbientContext(node)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 240) { + checkImportBinding(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.getModifierFlags(node) & 1) { + markExportAsReferenced(node); + } + if (ts.isInternalModuleImportEqualsDeclaration(node)) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 107455) { + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 793064) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + grammarErrorOnNode(node, ts.Diagnostics.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); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && + !node.moduleSpecifier && ts.isInAmbientContext(node); + if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + checkExternalEmitHelpers(node, 32768); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + return; + } + var container = node.parent.kind === 265 ? node.parent : node.parent.parent; + if (container.kind === 233 && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 71) { + markExportAsReferenced(node); + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (modulekind === ts.ModuleKind.System) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + var exports_1 = getExportsOfModule(moduleSymbol); + exports_1 && exports_1.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + if (flags & (1920 | 64 | 384)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + links.exportsChecked = true; + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 && declaration.kind !== 151) || + !!declaration.body; + } + } + function checkSourceElement(node) { + if (!node) { + return; + } + var kind = node.kind; + if (cancellationToken) { + switch (kind) { + case 233: + case 229: + case 230: + case 228: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 145: + return checkTypeParameter(node); + case 146: + return checkParameter(node); + case 149: + case 148: + return checkPropertyDeclaration(node); + case 160: + case 161: + case 155: + case 156: + return checkSignatureDeclaration(node); + case 157: + return checkSignatureDeclaration(node); + case 151: + case 150: + return checkMethodDeclaration(node); + case 152: + return checkConstructorDeclaration(node); + case 153: + case 154: + return checkAccessorDeclaration(node); + case 159: + return checkTypeReferenceNode(node); + case 158: + return checkTypePredicate(node); + case 162: + return checkTypeQuery(node); + case 163: + return checkTypeLiteral(node); + case 164: + return checkArrayType(node); + case 165: + return checkTupleType(node); + case 166: + case 167: + return checkUnionOrIntersectionType(node); + case 168: + case 170: + return checkSourceElement(node.type); + case 275: + return checkJSDocComment(node); + case 279: + return checkSourceElement(node.typeExpression); + case 273: + checkSignatureDeclaration(node); + case 274: + case 271: + case 270: + case 268: + case 269: + if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + return; + case 267: + return checkSourceElement(node.type); + case 171: + return checkIndexedAccessType(node); + case 172: + return checkMappedType(node); + case 228: + return checkFunctionDeclaration(node); + case 207: + case 234: + return checkBlock(node); + case 208: + return checkVariableStatement(node); + case 210: + return checkExpressionStatement(node); + case 211: + return checkIfStatement(node); + case 212: + return checkDoStatement(node); + case 213: + return checkWhileStatement(node); + case 214: + return checkForStatement(node); + case 215: + return checkForInStatement(node); + case 216: + return checkForOfStatement(node); + case 217: + case 218: + return checkBreakOrContinueStatement(node); + case 219: + return checkReturnStatement(node); + case 220: + return checkWithStatement(node); + case 221: + return checkSwitchStatement(node); + case 222: + return checkLabeledStatement(node); + case 223: + return checkThrowStatement(node); + case 224: + return checkTryStatement(node); + case 226: + return checkVariableDeclaration(node); + case 176: + return checkBindingElement(node); + case 229: + return checkClassDeclaration(node); + case 230: + return checkInterfaceDeclaration(node); + case 231: + return checkTypeAliasDeclaration(node); + case 232: + return checkEnumDeclaration(node); + case 233: + return checkModuleDeclaration(node); + case 238: + return checkImportDeclaration(node); + case 237: + return checkImportEqualsDeclaration(node); + case 244: + return checkExportDeclaration(node); + case 243: + return checkExportAssignment(node); + case 209: + checkGrammarStatementInAmbientContext(node); + return; + case 225: + checkGrammarStatementInAmbientContext(node); + return; + case 247: + return checkMissingDeclaration(node); + } + } + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 186: + case 187: + case 151: + case 150: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 153: + case 154: + checkAccessorDeclaration(node); + break; + case 199: + checkClassExpressionDeferred(node); + break; + } + } + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1)) { + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; + } + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + deferredNodes = []; + deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + ts.forEach(node.statements, checkSourceElement); + checkDeferredNodes(); + if (ts.isExternalModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile) { + checkUnusedIdentifiers(); + } + deferredNodes = undefined; + deferredUnusedIdentifierNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1; + } + } + function getDiagnostics(sourceFile, ct) { + try { + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + function isInsideWithStatementBody(node) { + if (node) { + while (node.parent) { + if (node.parent.kind === 220 && node.parent.statement === node) { + return true; + } + node = node.parent; + } + } + return false; + } + function getSymbolsInScope(location, meaning) { + if (isInsideWithStatementBody(location)) { + return []; + } + var symbols = ts.createSymbolTable(); + var memberFlags = 0; + populateSymbols(); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 233: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); + break; + case 232: + copySymbols(getSymbolOfNode(location).exports, meaning & 8); + break; + case 199: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + case 229: + case 230: + if (!(memberFlags & 32)) { + copySymbols(getSymbolOfNode(location).members, meaning & 793064); + } + break; + case 186: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + memberFlags = ts.getModifierFlags(location); + location = location.parent; + } + copySymbols(globals, meaning); + } + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 71 && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 145: + case 229: + case 230: + case 231: + case 232: + return true; + } + } + function isTypeReferenceIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 143) { + node = node.parent; + } + return node.parent && node.parent.kind === 159; + } + function isHeritageClauseElementIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 179) { + node = node.parent; + } + return node.parent && node.parent.kind === 201; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 143) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 237) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 243) { + return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1: + case 3: + return getSymbolOfNode(entityName.parent); + case 4: + case 2: + case 5: + return getSymbolOfNode(entityName.parent.parent); + } + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJavaScriptFile(entityName) && + entityName.parent.kind === 179 && + entityName.parent === entityName.parent.parent.left) { + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); + } + if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 237); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); + } + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0; + if (entityName.parent.kind === 201) { + meaning = 793064; + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 107455; + } + } + else { + meaning = 1920; + } + meaning |= 2097152; + var entityNameSymbol = resolveEntityName(entityName, meaning); + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 279) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 145 && entityName.parent.parent.kind === 282) { + ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isPartOfExpression(entityName)) { + if (ts.nodeIsMissing(entityName)) { + return undefined; + } + if (entityName.kind === 71) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + return getIntrinsicTagSymbol(entityName.parent); + } + return resolveEntityName(entityName, 107455, false, true); + } + else if (entityName.kind === 179 || entityName.kind === 143) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 179) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 159 ? 793064 : 1920; + return resolveEntityName(entityName, meaning, false, true); + } + else if (entityName.parent.kind === 253) { + return getJsxAttributePropertySymbol(entityName.parent); + } + if (entityName.parent.kind === 158) { + return resolveEntityName(entityName, 1); + } + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 265) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + if (isInsideWithStatementBody(node)) { + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + return getSymbolOfNode(node.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(node.parent.parent); + } + if (node.kind === 71) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (node.parent.kind === 176 && + node.parent.parent.kind === 174 && + node === node.parent.propertyName) { + var typeOfPattern = getTypeOfNode(node.parent.parent); + var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 71: + case 179: + case 143: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 99: + var container = ts.getThisContainer(node, false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + case 97: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); + return type.symbol; + case 169: + return getTypeFromTypeNode(node).symbol; + case 123: + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 152) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 9: + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { + return resolveExternalModuleName(node, node); + } + case 8: + if (node.parent.kind === 180 && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); + if (objectType === unknownType) + return undefined; + var apparentType = getApparentType(objectType); + if (apparentType === unknownType) + return undefined; + return getPropertyOfType(apparentType, node.text); + } + break; + } + return undefined; + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 262) { + return resolveEntityName(location.name, 107455 | 2097152); + } + return undefined; + } + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 2097152); + } + function getTypeOfNode(node) { + if (isInsideWithStatementBody(node)) { + return unknownType; + } + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + var containingClass = ts.getContainingClass(node); + var classType = getTypeOfNode(containingClass); + typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + } + return typeFromTypeNode; + } + if (ts.isPartOfExpression(node)) { + return getRegularTypeOfExpression(node); + } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + var classNode = ts.getContainingClass(node); + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var baseType = getBaseTypes(classType)[0]; + return baseType && getTypeWithThisArgument(baseType, classType.thisType); + } + if (isTypeDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + } + if (ts.isDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getTypeOfSymbol(symbol); + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, true); + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + } + return unknownType; + } + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 178 || expr.kind === 177); + if (expr.parent.kind === 216) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + if (expr.parent.kind === 194) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + if (expr.parent.kind === 261) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + } + ts.Debug.assert(expr.parent.kind === 177); + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + } + function getPropertySymbolOfDestructuringAssignment(location) { + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.getModifierFlags(node) & 32 + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function getRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; + var name_2 = symbol.escapedName; + ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { + var symbol = getPropertyOfType(t, name_2); + if (symbol) { + symbols_4.push(symbol); + } + }); + return symbols_4; + } + else if (symbol.flags & 33554432) { + var transient = symbol; + if (transient.leftSpread) { + return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); + } + if (transient.syntheticOrigin) { + return getRootSymbols(transient.syntheticOrigin); + } + var target = void 0; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + if (target) { + return [target]; + } + } + return [symbol]; + } + function isArgumentsLocalBinding(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + function getReferencedImportDeclaration(node) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (isNonLocalAlias(symbol, 107455)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined)) { + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072) { + var isDeclaredInLoop = nodeLinks_1.flags & 262144; + var inLoopInitializer = ts.isIterationStatement(container, false); + var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + function getReferencedDeclarationWithCollidingName(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + function isDeclarationWithCollidingName(node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 237: + case 239: + case 240: + case 242: + case 246: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 244: + var exportClause = node.exportClause; + return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + case 243: + return node.expression + && node.expression.kind === 71 + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(node) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + return target.flags & 107455 && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + } + if (checkChildren) { + return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + return signaturesOfSymbol.length > 1 || + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92); + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 264: + case 179: + case 180: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 264) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8)) { + if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { + return getEnumMemberValue(symbol.valueDeclaration); + } + } + return undefined; + } + function isFunctionType(type) { + return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; + } + function getTypeReferenceSerializationKind(typeName, location) { + var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); + var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === unknownType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 1) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeOfKind(type, 136)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeOfKind(type, 84)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeOfKind(type, 262178)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeOfKind(type, 512)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 | 131072)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : unknownType; + if (flags & 8192) { + type = getNullableType(type, 2048); + } + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + var signature = getSignatureFromDeclaration(signatureDeclaration); + getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + } + function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + var type = getWidenedType(getRegularTypeOfExpression(expr)); + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined); + } + function getReferencedValueDeclaration(reference) { + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 && type.flags & 1048576); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); + } + function createResolver() { + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : undefined; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + writeTypeOfDeclaration: writeTypeOfDeclaration, + writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, + writeTypeOfExpression: writeTypeOfExpression, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + }; + function getTypeReferenceDirectivesForEntityName(node) { + if (!fileToDirective) { + return undefined; + } + var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) + ? 107455 | 1048576 + : 793064 | 1920; + var symbol = resolveEntityName(node, meaning, true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + if (!symbol.declarations) { + return false; + } + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { + return false; + } + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 265); + } + function initializeTypeChecker() { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + if (augmentations) { + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + mergeModuleAugmentation(augmentation); + } + } + } + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); + getSymbolLinks(unknownSymbol).type = unknownType; + globalArrayType = getGlobalType("Array", 1, true); + globalObjectType = getGlobalType("Object", 0, true); + globalFunctionType = getGlobalType("Function", 0, true); + globalStringType = getGlobalType("String", 0, true); + globalNumberType = getGlobalType("Number", 0, true); + globalBooleanType = getGlobalType("Boolean", 0, true); + globalRegExpType = getGlobalType("RegExp", 0, true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", 1); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1; helper <= 32768; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1: return "__extends"; + case 2: return "__assign"; + case 4: return "__rest"; + case 8: return "__decorate"; + case 16: return "__metadata"; + case 32: return "__param"; + case 64: return "__awaiter"; + case 128: return "__generator"; + case 256: return "__values"; + case 512: return "__read"; + case 1024: return "__spread"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; + case 32768: return "__exportStar"; + default: ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node)) { + if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 153 || node.kind === 154) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var flags = 0; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 131) { + if (node.kind === 148 || node.kind === 150) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 157) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 76: + if (node.kind !== 232 && node.parent.kind === 229) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); + } + break; + case 114: + case 113: + case 112: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 113) { + lastProtected = modifier; + } + else if (modifier.kind === 112) { + lastPrivate = modifier; + } + if (flags & 28) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 234 || node.parent.kind === 265) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128) { + if (modifier.kind === 112) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 115: + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 234 || node.parent.kind === 265) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32; + lastStatic = modifier; + break; + case 131: + if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64; + lastReadonly = modifier; + break; + case 84: + if (flags & 1) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 229) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1; + break; + case 79: + var container = node.parent.kind === 265 ? node.parent : node.parent.parent; + if (container.kind === 233 && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512; + break; + case 124: + if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 229) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2; + lastDeclare = modifier; + break; + case 117: + if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 229) { + if (node.kind !== 151 && + node.kind !== 149 && + node.kind !== 153 && + node.kind !== 154) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128; + break; + case 120: + if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256; + lastAsync = modifier; + break; + } + } + if (node.kind === 152) { + if (flags & 32) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return; + } + else if ((node.kind === 238 || node.kind === 237) && flags & 2) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256) { + return checkGrammarAsyncModifier(node, lastAsync); + } + } + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 153: + case 154: + case 152: + case 149: + case 148: + case 151: + case 150: + case 157: + case 233: + case 238: + case 237: + case 244: + case 243: + case 186: + case 187: + case 146: + return false; + default: + if (node.parent.kind === 234 || node.parent.kind === 265) { + return false; + } + switch (node.kind) { + case 228: + return nodeHasAnyModifiersExcept(node, 120); + case 229: + return nodeHasAnyModifiersExcept(node, 117); + case 230: + case 208: + case 231: + return true; + case 232: + return nodeHasAnyModifiersExcept(node, 76); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 151: + case 228: + case 186: + case 187: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list) { + if (list && list.hasTrailingComma) { + var start = list.end - ",".length; + var end = list.end; + var sourceFile = ts.getSourceFileOfNode(list[0]); + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (checkGrammarForDisallowedTrailingComma(typeParameters)) { + return true; + } + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function checkGrammarFunctionLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (node.kind === 187) { + var arrowFunction = node; + var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + if (startLine !== endLine) { + return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + } + return false; + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.getModifierFlags(parameter) !== 0) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + } + function checkGrammarIndexSignature(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(node, args) { + if (args) { + var sourceFile = ts.getSourceFileOfNode(node); + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 200) { + return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + } + function checkGrammarArguments(node, args) { + return checkGrammarForOmittedArgument(node, args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + var sourceFile = ts.getSourceFileOfNode(node); + return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + if (node.kind !== 144) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 228 || + node.kind === 186 || + node.kind === 151); + if (ts.isInAmbientContext(node)) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + if (questionToken) { + return grammarErrorOnNode(questionToken, message); + } + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var seen = ts.createUnderscoreEscapedMap(); + var Property = 1; + var GetAccessor = 2; + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263) { + continue; + } + var name = prop.name; + if (name.kind === 144) { + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 120 || prop.kind !== 151) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + var currentKind = void 0; + if (prop.kind === 261 || prop.kind === 262) { + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8) { + checkGrammarNumericLiteral(name); + } + currentKind = Property; + } + else if (prop.kind === 151) { + currentKind = Property; + } + else if (prop.kind === 153) { + currentKind = GetAccessor; + } + else if (prop.kind === 154) { + currentKind = SetAccessor; + } + else { + ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === Property && existingKind === Property) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { + if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 255) { + continue; + } + var jsxAttr = attr; + var name = jsxAttr.name; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + var initializer = jsxAttr.initializer; + if (initializer && initializer.kind === 256 && !initializer.expression) { + return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384) === 0) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 227) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (ts.isInAmbientContext(accessor)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { + return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 153 ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 154) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + } + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarForNonSymbolComputedProperty(node, message) { + if (ts.isDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || + checkGrammarFunctionLikeDeclaration(node) || + checkGrammarForGenerator(node)) { + return true; + } + if (node.parent.kind === 178) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (ts.isClassLike(node.parent)) { + if (ts.isInAmbientContext(node)) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + } + else if (!node.body) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + } + } + else if (node.parent.kind === 230) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + } + else if (node.parent.kind === 163) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 222: + if (node.label && current.label.escapedText === node.label.escapedText) { + var isMisplacedContinueLabel = node.kind === 217 + && !ts.isIterationStatement(current.statement, true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 221: + if (node.kind === 218 && !node.label) { + return false; + } + break; + default: + if (ts.isIterationStatement(current, false) && !node.label) { + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 218 + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 218 + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.lastOrUndefined(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + if (node.name.kind === 175 || node.name.kind === 174) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (node.initializer) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 || expr.kind === 8 || + expr.kind === 192 && expr.operator === 38 && + expr.operand.kind === 8; + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { + if (ts.isInAmbientContext(node)) { + if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 71) { + if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 71) { + if (name.originalKeywordKind === 110) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 211: + case 212: + case 213: + case 220: + case 214: + case 215: + case 216: + return false; + case 222: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + if (node.keywordToken === 94) { + if (node.name.escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + } + function checkGrammarConstructorTypeParameters(node) { + if (node.typeParameters) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + if (node.type) { + return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + else if (node.parent.kind === 230) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 163) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (ts.isInAmbientContext(node) && node.initializer) { + return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + if (node.kind === 230 || + node.kind === 231 || + node.kind === 238 || + node.kind === 237 || + node.kind === 244 || + node.kind === 243 || + node.kind === 236 || + ts.getModifierFlags(node) & (2 | 1 | 512)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 208) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + } + function checkGrammarSourceFile(node) { + return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (ts.isInAmbientContext(node)) { + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { + var links_1 = getNodeLinks(node.parent); + if (!links_1.hasReportedStatementInAmbientContext) { + return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + } + } + } + function checkGrammarNumericLiteral(node) { + if (node.numericLiteralFlags & 4) { + var diagnosticMessage = void 0; + if (languageVersion >= 1) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 173)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 264)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); + return true; + } + } + function getAmbientModules() { + var result = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { + result.push(global); + } + }); + return result; + } + function checkGrammarImportCallExpression(node) { + if (modulekind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + } + } + ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + return true; + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 239: + case 237: + case 240: + case 242: + return true; + case 71: + return decl.parent.kind === 242; + default: + return false; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { function createSynthesizedNode(kind) { var node = ts.createNode(kind, -1, -1); @@ -10708,13 +38819,13 @@ var ts; return node; } function createLiteralFromNode(sourceNode) { - var node = createStringLiteral(sourceNode.text); + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; return node; } function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); - node.text = ts.escapeIdentifier(text); + node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; @@ -10726,7 +38837,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(node.text, typeArguments), node) + ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -10900,13 +39011,14 @@ var ts; return node; } ts.createProperty = createProperty; - function updateProperty(node, decorators, modifiers, name, type, initializer) { + function updateProperty(node, decorators, modifiers, name, questionToken, type, initializer) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name + || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer), node) + ? updateNode(createProperty(decorators, modifiers, name, questionToken, type, initializer), node) : node; } ts.updateProperty = updateProperty; @@ -10946,6 +39058,7 @@ var ts; || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name + || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type @@ -11141,7 +39254,7 @@ var ts; ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { var node = createSynthesizedNode(164); - node.elementType = ts.parenthesizeElementTypeMember(elementType); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } ts.createArrayTypeNode = createArrayTypeNode; @@ -11342,7 +39455,7 @@ var ts; function updatePropertyAccess(node, expression, name) { return node.expression !== expression || node.name !== name - ? updateNode(setEmitFlags(createPropertyAccess(expression, name), getEmitFlags(node)), node) + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) : node; } ts.updatePropertyAccess = updatePropertyAccess; @@ -12612,28 +40725,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295); + var node = createSynthesizedNode(287); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299); + var node = createSynthesizedNode(291); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(290); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296); + var node = createSynthesizedNode(288); node.expression = expression; node.original = original; setTextRange(node, original); @@ -12649,7 +40762,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297) { + if (node.kind === 289) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -12659,7 +40772,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(289); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -12683,6 +40796,10 @@ var ts; return node; } ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; function createComma(left, right) { return createBinary(left, 26, right); } @@ -12785,11 +40902,6 @@ var ts; return range; } ts.setTextRange = setTextRange; - function getEmitFlags(node) { - var emitNode = node.emitNode; - return emitNode && emitNode.flags; - } - ts.getEmitFlags = getEmitFlags; function setEmitFlags(node, emitFlags) { getOrCreateEmitNode(node).flags = emitFlags; return node; @@ -12805,6 +40917,11 @@ var ts; return node; } ts.setSourceMapRange = setSourceMapRange; + var SourceMapSource; + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; function getTokenSourceMapRange(node, token) { var emitNode = node.emitNode; var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; @@ -13056,12 +41173,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(jsxFactory.right.text); - right.text = jsxFactory.right.text; + var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(jsxFactory.text, parent); + return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -13284,27 +41401,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_1 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_1.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_1.push(setter); + properties_8.push(setter); } - properties_1.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_1.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_1, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -13386,8 +41503,20 @@ var ts; return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); } ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + ts.Debug.assert(!!node.body); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (node.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; } function addPrologue(target, source, ensureUseStrict, visitor) { var offset = addStandardPrologue(target, source, ensureUseStrict); @@ -13442,8 +41571,8 @@ var ts; ts.startsWithUseStrict = startsWithUseStrict; function ensureUseStrict(statements) { var foundUseStrict = false; - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; if (ts.isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { foundUseStrict = true; @@ -13463,7 +41592,7 @@ var ts; } ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var skipped = skipPartiallyEmittedExpressions(operand); + var skipped = ts.skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { return operand; } @@ -13475,7 +41604,7 @@ var ts; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var binaryOperatorPrecedence = ts.getOperatorPrecedence(194, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(194, binaryOperator); - var emittedOperand = skipPartiallyEmittedExpressions(operand); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: @@ -13516,7 +41645,7 @@ var ts; || binaryOperator === 50; } function getLiteralKindOfBinaryPlusOperand(node) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } @@ -13536,7 +41665,7 @@ var ts; } function parenthesizeForConditionalHead(condition) { var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { return ts.createParen(condition); @@ -13551,7 +41680,7 @@ var ts; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; function parenthesizeForNew(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { case 181: return ts.createParen(expression); @@ -13564,7 +41693,7 @@ var ts; } ts.parenthesizeForNew = parenthesizeForNew; function parenthesizeForAccess(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 182 || emittedExpression.arguments)) { return expression; @@ -13602,7 +41731,7 @@ var ts; } ts.parenthesizeListElements = parenthesizeListElements; function parenthesizeExpressionForList(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); var commaPrecedence = ts.getOperatorPrecedence(194, 26); return expressionPrecedence > commaPrecedence @@ -13611,14 +41740,14 @@ var ts; } ts.parenthesizeExpressionForList = parenthesizeExpressionForList; function parenthesizeExpressionForExpressionStatement(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; - var kind = skipPartiallyEmittedExpressions(callee).kind; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; if (kind === 186 || kind === 187) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); - return recreatePartiallyEmittedExpressions(expression, mutableCall); + return recreateOuterExpressions(expression, mutableCall, 4); } } else { @@ -13641,31 +41770,32 @@ var ts; return member; } ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 162: + case 170: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; function parenthesizeElementTypeMembers(members) { return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); } ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; function parenthesizeTypeParameters(typeParameters) { if (ts.some(typeParameters)) { - var nodeArray = ts.createNodeArray(); + var params = []; for (var i = 0; i < typeParameters.length; ++i) { var entry = typeParameters[i]; - nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? ts.createParenthesizedType(entry) : entry); } - return nodeArray; + return ts.createNodeArray(params); } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { - if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { - var clone_1 = ts.getMutableClone(originalOuterExpression); - clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); - return clone_1; - } - return newInnerExpression; - } function getLeftmostExpression(node) { while (true) { switch (node.kind) { @@ -13683,7 +41813,7 @@ var ts; case 179: node = node.expression; continue; - case 296: + case 288: node = node.expression; continue; } @@ -13704,6 +41834,21 @@ var ts; OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7; } + switch (node.kind) { + case 185: + return (kinds & 1) !== 0; + case 184: + case 202: + case 203: + return (kinds & 2) !== 0; + case 288: + return (kinds & 4) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7; } var previousNode; @@ -13716,7 +41861,7 @@ var ts; node = skipAssertions(node); } if (kinds & 4) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); } } while (previousNode !== node); return node; @@ -13730,19 +41875,29 @@ var ts; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node)) { + while (ts.isAssertionExpression(node) || node.kind === 203) { node = node.expression; } return node; } ts.skipAssertions = skipAssertions; - function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296) { - node = node.expression; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 185: return ts.updateParen(outerExpression, expression); + case 184: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 202: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 203: return ts.updateNonNullExpression(outerExpression, expression); + case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } - return node; } - ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7; } + if (outerExpression && isOuterExpression(outerExpression, kinds)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { node.startsOnNewLine = true; return node; @@ -13754,23 +41909,33 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { - if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } - var helpers = ts.getEmitHelpers(node); - if (helpers) { - for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { - var helper = helpers_2[_i]; - if (!helper.scoped) { - var parseNode = ts.getOriginalNode(node, ts.isSourceFile); - var emitNode = ts.getOrCreateEmitNode(parseNode); - return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = hasExportStarsToExportValues + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } } } } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } } } ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; @@ -13834,7 +41999,7 @@ var ts; if (ts.isAssignmentExpression(bindingElement, true)) { return bindingElement.right; } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); } } @@ -13857,7 +42022,7 @@ var ts; if (ts.isAssignmentExpression(bindingElement, true)) { return getTargetOfBindingOrAssignmentElement(bindingElement.left); } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return bindingElement; @@ -13983,27237 +42148,6 @@ var ts; return node; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; - function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { - var externalImports = []; - var exportSpecifiers = ts.createMultiMap(); - var exportedBindings = []; - var uniqueExports = ts.createMap(); - var exportedNames; - var hasExportDefault = false; - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); - var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - if (externalHelpersImportDeclaration) { - externalImports.push(externalHelpersImportDeclaration); - } - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 238: - externalImports.push(node); - break; - case 237: - if (node.moduleReference.kind === 248) { - externalImports.push(node); - } - break; - case 244: - if (node.moduleSpecifier) { - if (!node.exportClause) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - else { - externalImports.push(node); - } - } - else { - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - if (!uniqueExports.get(specifier.name.text)) { - var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(name.text, specifier); - var decl = resolver.getReferencedImportDeclaration(name) - || resolver.getReferencedValueDeclaration(name); - if (decl) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); - } - uniqueExports.set(specifier.name.text, true); - exportedNames = ts.append(exportedNames, specifier.name); - } - } - } - break; - case 243: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; - case 208: - if (ts.hasModifier(node, 1)) { - for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { - var decl = _e[_d]; - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); - } - } - break; - case 228: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - case 229: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - } - } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; - } - ts.collectExternalModuleInfo = collectExternalModuleInfo; - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { - if (ts.isBindingPattern(decl.name)) { - for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); - } - } - } - else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(decl.name.text)) { - uniqueExports.set(decl.name.text, true); - exportedNames = ts.append(exportedNames, decl.name); - } - } - return exportedNames; - } - function multiMapSparseArrayAdd(map, key, value) { - var values = map[key]; - if (values) { - values.push(value); - } - else { - map[key] = values = [value]; - } - return values; - } -})(ts || (ts = {})); -var ts; -(function (ts) { - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - function createNode(kind, pos, end) { - if (kind === 265) { - return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); - } - else if (kind === 71) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 143) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } - else { - return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); - } - } - ts.createNode = createNode; - function visitNode(cbNode, node) { - if (node) { - return cbNode(node); - } - } - function visitNodeArray(cbNodes, nodes) { - if (nodes) { - return cbNodes(nodes); - } - } - function visitEachNode(cbNode, nodes) { - if (nodes) { - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; - var result = cbNode(node); - if (result) { - return result; - } - } - } - } - function forEachChild(node, cbNode, cbNodeArray) { - if (!node) { - return; - } - var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; - var cbNodes = cbNodeArray || cbNode; - switch (node.kind) { - case 143: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); - case 145: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.constraint) || - visitNode(cbNode, node.default) || - visitNode(cbNode, node.expression); - case 262: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.equalsToken) || - visitNode(cbNode, node.objectAssignmentInitializer); - case 263: - return visitNode(cbNode, node.expression); - case 146: - case 149: - case 148: - case 261: - case 226: - case 176: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 160: - case 161: - case 155: - case 156: - case 157: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 151: - case 150: - case 152: - case 153: - case 154: - case 186: - case 228: - case 187: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.equalsGreaterThanToken) || - visitNode(cbNode, node.body); - case 159: - return visitNode(cbNode, node.typeName) || - visitNodes(cbNodes, node.typeArguments); - case 158: - return visitNode(cbNode, node.parameterName) || - visitNode(cbNode, node.type); - case 162: - return visitNode(cbNode, node.exprName); - case 163: - return visitNodes(cbNodes, node.members); - case 164: - return visitNode(cbNode, node.elementType); - case 165: - return visitNodes(cbNodes, node.elementTypes); - case 166: - case 167: - return visitNodes(cbNodes, node.types); - case 168: - case 170: - return visitNode(cbNode, node.type); - case 171: - return visitNode(cbNode, node.objectType) || - visitNode(cbNode, node.indexType); - case 172: - return visitNode(cbNode, node.readonlyToken) || - visitNode(cbNode, node.typeParameter) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); - case 173: - return visitNode(cbNode, node.literal); - case 174: - case 175: - return visitNodes(cbNodes, node.elements); - case 177: - return visitNodes(cbNodes, node.elements); - case 178: - return visitNodes(cbNodes, node.properties); - case 179: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.name); - case 180: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.argumentExpression); - case 181: - case 182: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments) || - visitNodes(cbNodes, node.arguments); - case 183: - return visitNode(cbNode, node.tag) || - visitNode(cbNode, node.template); - case 184: - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.expression); - case 188: - return visitNode(cbNode, node.expression); - case 189: - return visitNode(cbNode, node.expression); - case 190: - return visitNode(cbNode, node.expression); - case 192: - return visitNode(cbNode, node.operand); - case 197: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 191: - return visitNode(cbNode, node.expression); - case 193: - return visitNode(cbNode, node.operand); - case 194: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.operatorToken) || - visitNode(cbNode, node.right); - case 202: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.type); - case 203: - return visitNode(cbNode, node.expression); - case 204: - return visitNode(cbNode, node.name); - case 195: - return visitNode(cbNode, node.condition) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.whenTrue) || - visitNode(cbNode, node.colonToken) || - visitNode(cbNode, node.whenFalse); - case 198: - return visitNode(cbNode, node.expression); - case 207: - case 234: - return visitNodes(cbNodes, node.statements); - case 265: - return visitNodes(cbNodes, node.statements) || - visitNode(cbNode, node.endOfFileToken); - case 208: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.declarationList); - case 227: - return visitNodes(cbNodes, node.declarations); - case 210: - return visitNode(cbNode, node.expression); - case 211: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.thenStatement) || - visitNode(cbNode, node.elseStatement); - case 212: - return visitNode(cbNode, node.statement) || - visitNode(cbNode, node.expression); - case 213: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 214: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.condition) || - visitNode(cbNode, node.incrementor) || - visitNode(cbNode, node.statement); - case 215: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 216: - return visitNode(cbNode, node.awaitModifier) || - visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 217: - case 218: - return visitNode(cbNode, node.label); - case 219: - return visitNode(cbNode, node.expression); - case 220: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 221: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 235: - return visitNodes(cbNodes, node.clauses); - case 257: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 258: - return visitNodes(cbNodes, node.statements); - case 222: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); - case 223: - return visitNode(cbNode, node.expression); - case 224: - return visitNode(cbNode, node.tryBlock) || - visitNode(cbNode, node.catchClause) || - visitNode(cbNode, node.finallyBlock); - case 260: - return visitNode(cbNode, node.variableDeclaration) || - visitNode(cbNode, node.block); - case 147: - return visitNode(cbNode, node.expression); - case 229: - case 199: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 230: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 231: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); - case 232: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 264: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 233: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); - case 237: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); - case 238: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.importClause) || - visitNode(cbNode, node.moduleSpecifier); - case 239: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.namedBindings); - case 236: - return visitNode(cbNode, node.name); - case 240: - return visitNode(cbNode, node.name); - case 241: - case 245: - return visitNodes(cbNodes, node.elements); - case 244: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.exportClause) || - visitNode(cbNode, node.moduleSpecifier); - case 242: - case 246: - return visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name); - case 243: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.expression); - case 196: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 205: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144: - return visitNode(cbNode, node.expression); - case 259: - return visitNodes(cbNodes, node.types); - case 201: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments); - case 248: - 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) || - visitNode(cbNode, node.closingElement); - case 250: - case 251: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.attributes); - case 254: - return visitNodes(cbNodes, node.properties); - case 253: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 255: - return visitNode(cbNode, node.expression); - case 256: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.expression); - case 252: - return visitNode(cbNode, node.tagName); - case 267: - return visitNode(cbNode, node.type); - case 271: - return visitNodes(cbNodes, node.types); - case 272: - return visitNodes(cbNodes, node.types); - case 270: - return visitNode(cbNode, node.elementType); - case 274: - return visitNode(cbNode, node.type); - case 273: - return visitNode(cbNode, node.type); - case 275: - return visitNode(cbNode, node.literal); - case 277: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 278: - return visitNode(cbNode, node.type); - case 279: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 280: - return visitNode(cbNode, node.type); - case 281: - return visitNode(cbNode, node.type); - case 282: - return visitNode(cbNode, node.type); - case 276: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.type); - case 283: - return visitNodes(cbNodes, node.tags); - case 286: - return visitNode(cbNode, node.preParameterName) || - visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.postParameterName); - case 287: - return visitNode(cbNode, node.typeExpression); - case 288: - return visitNode(cbNode, node.typeExpression); - case 285: - return visitNode(cbNode, node.typeExpression); - case 289: - return visitNodes(cbNodes, node.typeParameters); - case 290: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.jsDocTypeLiteral); - case 292: - return visitNodes(cbNodes, node.jsDocPropertyTags); - case 291: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - case 296: - return visitNode(cbNode, node.expression); - case 293: - return visitNode(cbNode, node.literal); - } - } - ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { - if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); - return result; - } - ts.createSourceFile = createSourceFile; - function parseIsolatedEntityName(text, languageVersion) { - return Parser.parseIsolatedEntityName(text, languageVersion); - } - ts.parseIsolatedEntityName = parseIsolatedEntityName; - function isExternalModule(file) { - return file.externalModuleIndicator !== undefined; - } - ts.isExternalModule = isExternalModule; - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - } - ts.updateSourceFile = updateSourceFile; - function parseIsolatedJSDocComment(content, start, length) { - var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDoc) { - Parser.fixupParentReferences(result.jsDoc); - } - return result; - } - ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocTypeExpressionForTests(content, start, length) { - return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); - } - ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - var Parser; - (function (Parser) { - var scanner = ts.createScanner(5, true); - var disallowInAndDecoratorContext = 2048 | 8192; - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - var sourceFile; - var parseDiagnostics; - var syntaxCursor; - var currentToken; - var sourceText; - var nodeCount; - var identifiers; - var identifierCount; - var parsingContext; - var contextFlags; - var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { - scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); - clearState(); - return result; - } - Parser.parseSourceFile = parseSourceFile; - function parseIsolatedEntityName(content, languageVersion) { - initializeState(content, languageVersion, undefined, 1); - nextToken(); - var entityName = parseEntityName(true); - var isInvalid = token() === 1 && !parseDiagnostics.length; - clearState(); - return isInvalid ? entityName : undefined; - } - Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function getLanguageVariant(scriptKind) { - return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; - } - function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { - NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); - SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); - sourceText = _sourceText; - syntaxCursor = _syntaxCursor; - parseDiagnostics = []; - parsingContext = 0; - identifiers = ts.createMap(); - identifierCount = 0; - nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 65536 : 0; - parseErrorBeforeNextFinishedNode = false; - scanner.setText(sourceText); - scanner.setOnError(scanError); - scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(getLanguageVariant(scriptKind)); - } - function clearState() { - scanner.setText(""); - scanner.setOnError(undefined); - parseDiagnostics = undefined; - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); - sourceFile.flags = contextFlags; - nextToken(); - processReferenceComments(sourceFile); - sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token() === 1); - sourceFile.endOfFileToken = parseTokenNode(); - setExternalModuleIndicator(sourceFile); - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.identifiers = identifiers; - sourceFile.parseDiagnostics = parseDiagnostics; - if (setParentNodes) { - fixupParentReferences(sourceFile); - } - return sourceFile; - } - function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; - } - node.jsDoc.push(jsDoc); - } - } - return node; - } - function fixupParentReferences(rootNode) { - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDoc) { - for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - jsDoc.parent = n; - parent = jsDoc; - forEachChild(jsDoc, visitNode); - } - } - parent = saveParent; - } - } - } - Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); - nodeCount++; - sourceFile.text = sourceText; - sourceFile.bindDiagnostics = []; - sourceFile.languageVersion = languageVersion; - sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); - sourceFile.scriptKind = scriptKind; - return sourceFile; - } - function setContextFlag(val, flag) { - if (val) { - contextFlags |= flag; - } - else { - contextFlags &= ~flag; - } - } - function setDisallowInContext(val) { - setContextFlag(val, 2048); - } - function setYieldContext(val) { - setContextFlag(val, 4096); - } - function setDecoratorContext(val) { - setContextFlag(val, 8192); - } - function setAwaitContext(val) { - setContextFlag(val, 16384); - } - function doOutsideOfContext(context, func) { - var contextFlagsToClear = context & contextFlags; - if (contextFlagsToClear) { - setContextFlag(false, contextFlagsToClear); - var result = func(); - setContextFlag(true, contextFlagsToClear); - return result; - } - return func(); - } - function doInsideOfContext(context, func) { - var contextFlagsToSet = context & ~contextFlags; - if (contextFlagsToSet) { - setContextFlag(true, contextFlagsToSet); - var result = func(); - setContextFlag(false, contextFlagsToSet); - return result; - } - return func(); - } - function allowInAnd(func) { - return doOutsideOfContext(2048, func); - } - function disallowInAnd(func) { - return doInsideOfContext(2048, func); - } - function doInYieldContext(func) { - return doInsideOfContext(4096, func); - } - function doInDecoratorContext(func) { - return doInsideOfContext(8192, func); - } - function doInAwaitContext(func) { - return doInsideOfContext(16384, func); - } - function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(16384, func); - } - function doInYieldAndAwaitContext(func) { - return doInsideOfContext(4096 | 16384, func); - } - function inContext(flags) { - return (contextFlags & flags) !== 0; - } - function inYieldContext() { - return inContext(4096); - } - function inDisallowInContext() { - return inContext(2048); - } - function inDecoratorContext() { - return inContext(8192); - } - function inAwaitContext() { - return inContext(16384); - } - function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); - } - function parseErrorAtPosition(start, length, message, arg0) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (!lastError || start !== lastError.start) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); - } - parseErrorBeforeNextFinishedNode = true; - } - function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); - } - function getNodePos() { - return scanner.getStartPos(); - } - function getNodeEnd() { - return scanner.getStartPos(); - } - function token() { - return currentToken; - } - function nextToken() { - return currentToken = scanner.scan(); - } - function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); - } - function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); - } - function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); - } - function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); - } - function scanJsxText() { - return currentToken = scanner.scanJsxToken(); - } - function scanJsxAttributeValue() { - return currentToken = scanner.scanJsxAttributeValue(); - } - function speculationHelper(callback, isLookAhead) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var saveContextFlags = contextFlags; - var result = isLookAhead - ? scanner.lookAhead(callback) - : scanner.tryScan(callback); - ts.Debug.assert(saveContextFlags === contextFlags); - if (!result || isLookAhead) { - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - } - return result; - } - function lookAhead(callback) { - return speculationHelper(callback, true); - } - function tryParse(callback) { - return speculationHelper(callback, false); - } - function isIdentifier() { - if (token() === 71) { - return true; - } - if (token() === 116 && inYieldContext()) { - return false; - } - if (token() === 121 && inAwaitContext()) { - return false; - } - return token() > 107; - } - function parseExpected(kind, diagnosticMessage, shouldAdvance) { - if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { - if (shouldAdvance) { - nextToken(); - } - return true; - } - if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage); - } - else { - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); - } - return false; - } - function parseOptional(t) { - if (token() === t) { - nextToken(); - return true; - } - return false; - } - function parseOptionalToken(t) { - if (token() === t) { - return parseTokenNode(); - } - return undefined; - } - function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { - return parseOptionalToken(t) || - createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); - } - function parseTokenNode() { - var node = createNode(token()); - nextToken(); - return finishNode(node); - } - function canParseSemicolon() { - if (token() === 25) { - return true; - } - return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); - } - function parseSemicolon() { - if (canParseSemicolon()) { - if (token() === 25) { - nextToken(); - } - return true; - } - else { - return parseExpected(25); - } - } - function createNode(kind, pos) { - nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); - } - return kind >= 143 ? new NodeConstructor(kind, pos, pos) : - kind === 71 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); - } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } - array.pos = pos; - array.end = pos; - return array; - } - function finishNode(node, end) { - node.end = end === undefined ? scanner.getStartPos() : end; - if (contextFlags) { - node.flags |= contextFlags; - } - if (parseErrorBeforeNextFinishedNode) { - parseErrorBeforeNextFinishedNode = false; - node.flags |= 32768; - } - return node; - } - function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { - if (reportAtCurrentPosition) { - parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); - } - else { - parseErrorAtCurrentToken(diagnosticMessage, arg0); - } - var result = createNode(kind, scanner.getStartPos()); - result.text = ""; - return finishNode(result); - } - function internIdentifier(text) { - text = ts.escapeIdentifier(text); - var identifier = identifiers.get(text); - if (identifier === undefined) { - identifiers.set(text, identifier = text); - } - return identifier; - } - function createIdentifier(isIdentifier, diagnosticMessage) { - identifierCount++; - if (isIdentifier) { - var node = createNode(71); - if (token() !== 71) { - node.originalKeywordKind = token(); - } - node.text = internIdentifier(scanner.getTokenValue()); - nextToken(); - return finishNode(node); - } - return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); - } - function parseIdentifier(diagnosticMessage) { - return createIdentifier(isIdentifier(), diagnosticMessage); - } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8; - } - function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { - return parseLiteralNode(true); - } - if (allowComputedPropertyNames && token() === 21) { - return parseComputedPropertyName(); - } - return parseIdentifierName(); - } - function parsePropertyName() { - return parsePropertyNameWorker(true); - } - function parseSimplePropertyName() { - return parsePropertyNameWorker(false); - } - function isSimplePropertyName() { - return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); - } - function parseComputedPropertyName() { - var node = createNode(144); - parseExpected(21); - node.expression = allowInAnd(parseExpression); - parseExpected(22); - return finishNode(node); - } - function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); - } - function nextTokenIsOnSameLineAndCanFollowModifier() { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); - } - function nextTokenCanFollowModifier() { - if (token() === 76) { - return nextToken() === 83; - } - if (token() === 84) { - nextToken(); - if (token() === 79) { - return lookAhead(nextTokenIsClassOrFunctionOrAsync); - } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); - } - if (token() === 79) { - return nextTokenIsClassOrFunctionOrAsync(); - } - if (token() === 115) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); - } - function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); - } - function canFollowModifier() { - return token() === 21 - || token() === 17 - || token() === 39 - || token() === 24 - || isLiteralPropertyName(); - } - function nextTokenIsClassOrFunctionOrAsync() { - nextToken(); - return token() === 75 || token() === 89 || - (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); - } - function isListElement(parsingContext, inErrorRecovery) { - var node = currentNode(parsingContext); - if (node) { - return true; - } - switch (parsingContext) { - case 0: - case 1: - case 3: - return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); - case 2: - return token() === 73 || token() === 79; - case 4: - return lookAhead(isTypeMemberStart); - case 5: - return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); - case 6: - return token() === 21 || isLiteralPropertyName(); - case 12: - return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); - case 17: - return isLiteralPropertyName(); - case 9: - return token() === 21 || token() === 24 || isLiteralPropertyName(); - case 7: - if (token() === 17) { - return lookAhead(isValidHeritageClauseObjectLiteral); - } - if (!inErrorRecovery) { - return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - else { - return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - case 8: - return isIdentifierOrPattern(); - case 10: - return token() === 26 || token() === 24 || isIdentifierOrPattern(); - case 18: - return isIdentifier(); - case 11: - case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); - case 16: - return isStartOfParameter(); - case 19: - case 20: - return token() === 26 || isStartOfType(); - case 21: - return isHeritageClause(); - case 22: - return ts.tokenIsIdentifierOrKeyword(token()); - case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; - case 14: - return true; - case 23: - case 24: - case 26: - return JSDocParser.isJSDocType(); - case 25: - return isSimplePropertyName(); - } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); - } - function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17); - if (nextToken() === 18) { - var next = nextToken(); - return next === 26 || next === 17 || next === 85 || next === 108; - } - return true; - } - function nextTokenIsIdentifier() { - nextToken(); - return isIdentifier(); - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); - } - function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 || - token() === 85) { - return lookAhead(nextTokenIsStartOfExpression); - } - return false; - } - function nextTokenIsStartOfExpression() { - nextToken(); - return isStartOfExpression(); - } - function isListTerminator(kind) { - if (token() === 1) { - return true; - } - switch (kind) { - case 1: - case 2: - case 4: - case 5: - case 6: - case 12: - case 9: - case 22: - return token() === 18; - case 3: - return token() === 18 || token() === 73 || token() === 79; - case 7: - return token() === 17 || token() === 85 || token() === 108; - case 8: - return isVariableDeclaratorListTerminator(); - case 18: - return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; - case 11: - return token() === 20 || token() === 25; - case 15: - case 20: - case 10: - return token() === 22; - case 16: - case 17: - return token() === 20 || token() === 22; - case 19: - return token() !== 26; - case 21: - return token() === 17 || token() === 18; - case 13: - return token() === 29 || token() === 41; - case 14: - return token() === 27 && lookAhead(nextTokenIsSlash); - case 23: - return token() === 20 || token() === 56 || token() === 18; - case 24: - return token() === 29 || token() === 18; - case 26: - return token() === 22 || token() === 18; - case 25: - return token() === 18; - } - } - function isVariableDeclaratorListTerminator() { - if (canParseSemicolon()) { - return true; - } - if (isInOrOfKeyword(token())) { - return true; - } - if (token() === 36) { - return true; - } - return false; - } - function isInSomeParsingContext() { - for (var kind = 0; kind < 27; kind++) { - if (parsingContext & (1 << kind)) { - if (isListElement(kind, true) || isListTerminator(kind)) { - return true; - } - } - } - return false; - } - function parseList(kind, parseElement) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - while (!isListTerminator(kind)) { - if (isListElement(kind, false)) { - var element = parseListElement(kind, parseElement); - result.push(element); - continue; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function parseListElement(parsingContext, parseElement) { - var node = currentNode(parsingContext); - if (node) { - return consumeNode(node); - } - return parseElement(); - } - function currentNode(parsingContext) { - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - return undefined; - } - var node = syntaxCursor.currentNode(scanner.getStartPos()); - if (ts.nodeIsMissing(node)) { - return undefined; - } - if (node.intersectsChange) { - return undefined; - } - if (ts.containsParseError(node)) { - return undefined; - } - var nodeContextFlags = node.flags & 96256; - if (nodeContextFlags !== contextFlags) { - return undefined; - } - if (!canReuseNode(node, parsingContext)) { - return undefined; - } - return node; - } - function consumeNode(node) { - scanner.setTextPos(node.end); - nextToken(); - return node; - } - function canReuseNode(node, parsingContext) { - switch (parsingContext) { - case 5: - return isReusableClassMember(node); - case 2: - return isReusableSwitchClause(node); - case 0: - case 1: - case 3: - return isReusableStatement(node); - case 6: - return isReusableEnumMember(node); - case 4: - return isReusableTypeMember(node); - case 8: - return isReusableVariableDeclaration(node); - case 16: - return isReusableParameter(node); - case 17: - return false; - case 21: - case 18: - case 20: - case 19: - case 11: - case 12: - case 7: - case 13: - case 14: - } - return false; - } - function isReusableClassMember(node) { - if (node) { - switch (node.kind) { - case 152: - case 157: - case 153: - case 154: - case 149: - case 206: - return true; - case 151: - var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 && - methodDeclaration.name.originalKeywordKind === 123; - return !nameIsConstructor; - } - } - return false; - } - function isReusableSwitchClause(node) { - if (node) { - switch (node.kind) { - case 257: - case 258: - return true; - } - } - return false; - } - function isReusableStatement(node) { - if (node) { - switch (node.kind) { - case 228: - case 208: - case 207: - case 211: - case 210: - case 223: - case 219: - case 221: - case 218: - case 217: - case 215: - case 216: - case 214: - case 213: - case 220: - case 209: - case 224: - case 222: - case 212: - case 225: - case 238: - case 237: - case 244: - case 243: - case 233: - case 229: - case 230: - case 232: - case 231: - return true; - } - } - return false; - } - function isReusableEnumMember(node) { - return node.kind === 264; - } - function isReusableTypeMember(node) { - if (node) { - switch (node.kind) { - case 156: - case 150: - case 157: - case 148: - case 155: - return true; - } - } - return false; - } - function isReusableVariableDeclaration(node) { - if (node.kind !== 226) { - return false; - } - var variableDeclarator = node; - return variableDeclarator.initializer === undefined; - } - function isReusableParameter(node) { - if (node.kind !== 146) { - return false; - } - var parameter = node; - return parameter.initializer === undefined; - } - function abortParsingListOrMoveToNextToken(kind) { - parseErrorAtCurrentToken(parsingContextErrors(kind)); - if (isInSomeParsingContext()) { - return true; - } - nextToken(); - return false; - } - function parsingContextErrors(context) { - switch (context) { - case 0: return ts.Diagnostics.Declaration_or_statement_expected; - case 1: return ts.Diagnostics.Declaration_or_statement_expected; - case 2: return ts.Diagnostics.case_or_default_expected; - case 3: return ts.Diagnostics.Statement_expected; - case 17: - case 4: return ts.Diagnostics.Property_or_signature_expected; - case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; - case 6: return ts.Diagnostics.Enum_member_expected; - case 7: return ts.Diagnostics.Expression_expected; - case 8: return ts.Diagnostics.Variable_declaration_expected; - case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; - case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; - case 11: return ts.Diagnostics.Argument_expression_expected; - case 12: return ts.Diagnostics.Property_assignment_expected; - case 15: return ts.Diagnostics.Expression_or_comma_expected; - case 16: return ts.Diagnostics.Parameter_declaration_expected; - case 18: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19: return ts.Diagnostics.Type_argument_expected; - case 20: return ts.Diagnostics.Type_expected; - case 21: return ts.Diagnostics.Unexpected_token_expected; - case 22: return ts.Diagnostics.Identifier_expected; - case 13: return ts.Diagnostics.Identifier_expected; - case 14: return ts.Diagnostics.Identifier_expected; - case 23: return ts.Diagnostics.Parameter_declaration_expected; - case 24: return ts.Diagnostics.Type_argument_expected; - case 26: return ts.Diagnostics.Type_expected; - case 25: return ts.Diagnostics.Property_assignment_expected; - } - } - function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - var commaStart = -1; - while (true) { - if (isListElement(kind, false)) { - result.push(parseListElement(kind, parseElement)); - commaStart = scanner.getTokenPos(); - if (parseOptional(26)) { - continue; - } - commaStart = -1; - if (isListTerminator(kind)) { - break; - } - parseExpected(26); - if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - } - continue; - } - if (isListTerminator(kind)) { - break; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - if (commaStart >= 0) { - result.hasTrailingComma = true; - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function createMissingList() { - return createNodeArray(); - } - function parseBracketedList(kind, parseElement, open, close) { - if (parseExpected(open)) { - var result = parseDelimitedList(kind, parseElement); - parseExpected(close); - return result; - } - return createMissingList(); - } - function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(23)) { - var node = createNode(143, entity.pos); - node.left = entity; - node.right = parseRightSideOfDot(allowReservedWords); - entity = finishNode(node); - } - return entity; - } - function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { - var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - if (matchesPattern) { - return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); - } - } - return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); - } - function parseTemplateExpression() { - var template = createNode(196); - template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); - do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; - return finishNode(template); - } - function parseTemplateSpan() { - var span = createNode(205); - span.expression = allowInAnd(parseExpression); - var literal; - if (token() === 18) { - reScanTemplateToken(); - literal = parseTemplateMiddleOrTemplateTail(); - } - else { - literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); - } - span.literal = literal; - return finishNode(span); - } - function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); - } - function parseTemplateHead() { - var fragment = parseLiteralLikeNode(token(), false); - ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); - return fragment; - } - function parseTemplateMiddleOrTemplateTail() { - var fragment = parseLiteralLikeNode(token(), false); - ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); - return fragment; - } - function parseLiteralLikeNode(kind, internName) { - var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = internName ? internIdentifier(text) : text; - if (scanner.hasExtendedUnicodeEscape()) { - node.hasExtendedUnicodeEscape = true; - } - if (scanner.isUnterminated()) { - node.isUnterminated = true; - } - if (node.kind === 8) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); - } - nextToken(); - finishNode(node); - return node; - } - function parseTypeReference() { - var node = createNode(159); - node.typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } - return finishNode(node); - } - function parseThisTypePredicate(lhs) { - nextToken(); - var node = createNode(158, lhs.pos); - node.parameterName = lhs; - node.type = parseType(); - return finishNode(node); - } - function parseThisTypeNode() { - var node = createNode(169); - nextToken(); - return finishNode(node); - } - function parseTypeQuery() { - var node = createNode(162); - parseExpected(103); - node.exprName = parseEntityName(true); - return finishNode(node); - } - function parseTypeParameter() { - var node = createNode(145); - node.name = parseIdentifier(); - if (parseOptional(85)) { - if (isStartOfType() || !isStartOfExpression()) { - node.constraint = parseType(); - } - else { - node.expression = parseUnaryExpressionOrHigher(); - } - } - if (parseOptional(58)) { - node.default = parseType(); - } - return finishNode(node); - } - function parseTypeParameters() { - if (token() === 27) { - return parseBracketedList(18, parseTypeParameter, 27, 29); - } - } - function parseParameterType() { - if (parseOptional(56)) { - return parseType(); - } - return undefined; - } - function isStartOfParameter() { - return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 || token() === 99; - } - function parseParameter() { - var node = createNode(146); - if (token() === 99) { - node.name = createIdentifier(true); - node.type = parseParameterType(); - return finishNode(node); - } - node.decorators = parseDecorators(); - node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24); - node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { - nextToken(); - } - node.questionToken = parseOptionalToken(55); - node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(true); - return addJSDocComment(finishNode(node)); - } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(true); - } - function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 36; - signature.typeParameters = parseTypeParameters(); - signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); - if (returnTokenRequired) { - parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); - } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); - } - } - function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - if (parseExpected(19)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(yieldContext); - setAwaitContext(awaitContext); - var result = parseDelimitedList(16, parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20) && requireCompleteParameterList) { - return undefined; - } - return result; - } - return requireCompleteParameterList ? undefined : createMissingList(); - } - function parseTypeMemberSemicolon() { - if (parseOptional(26)) { - return; - } - parseSemicolon(); - } - function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156) { - parseExpected(94); - } - fillSignature(56, false, false, false, node); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); - } - function isIndexSignature() { - if (token() !== 21) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); - } - function isUnambiguouslyIndexSignature() { - nextToken(); - if (token() === 24 || token() === 22) { - return true; - } - if (ts.isModifierKind(token())) { - nextToken(); - if (isIdentifier()) { - return true; - } - } - else if (!isIdentifier()) { - return false; - } - else { - nextToken(); - } - if (token() === 56 || token() === 26) { - return true; - } - if (token() !== 55) { - return false; - } - nextToken(); - return token() === 56 || token() === 26 || token() === 22; - } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.parameters = parseBracketedList(16, parseParameter, 21, 22); - node.type = parseTypeAnnotation(); - parseTypeMemberSemicolon(); - return finishNode(node); - } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (token() === 19 || token() === 27) { - var method = createNode(150, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - fillSignature(56, false, false, false, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); - } - else { - var property = createNode(148, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - if (token() === 58) { - property.initializer = parseNonParameterInitializer(); - } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); - } - } - function isTypeMemberStart() { - if (token() === 19 || token() === 27) { - return true; - } - var idToken; - while (ts.isModifierKind(token())) { - idToken = true; - nextToken(); - } - if (token() === 21) { - return true; - } - if (isLiteralPropertyName()) { - idToken = true; - nextToken(); - } - if (idToken) { - return token() === 19 || - token() === 27 || - token() === 55 || - token() === 56 || - token() === 26 || - canParseSemicolon(); - } - return false; - } - function parseTypeMember() { - if (token() === 19 || token() === 27) { - return parseSignatureMember(155); - } - if (token() === 94 && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(156); - } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); - } - return parsePropertyOrMethodSignature(fullStart, modifiers); - } - function isStartOfConstructSignature() { - nextToken(); - return token() === 19 || token() === 27; - } - function parseTypeLiteral() { - var node = createNode(163); - node.members = parseObjectTypeMembers(); - return finishNode(node); - } - function parseObjectTypeMembers() { - var members; - if (parseExpected(17)) { - members = parseList(4, parseTypeMember); - parseExpected(18); - } - else { - members = createMissingList(); - } - return members; - } - function isStartOfMappedType() { - nextToken(); - if (token() === 131) { - nextToken(); - } - return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; - } - function parseMappedTypeParameter() { - var node = createNode(145); - node.name = parseIdentifier(); - parseExpected(92); - node.constraint = parseType(); - return finishNode(node); - } - function parseMappedType() { - var node = createNode(172); - parseExpected(17); - node.readonlyToken = parseOptionalToken(131); - parseExpected(21); - node.typeParameter = parseMappedTypeParameter(); - parseExpected(22); - node.questionToken = parseOptionalToken(55); - node.type = parseTypeAnnotation(); - parseSemicolon(); - parseExpected(18); - return finishNode(node); - } - function parseTupleType() { - var node = createNode(165); - node.elementTypes = parseBracketedList(20, parseType, 21, 22); - return finishNode(node); - } - function parseParenthesizedType() { - var node = createNode(168); - parseExpected(19); - node.type = parseType(); - parseExpected(20); - return finishNode(node); - } - function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161) { - parseExpected(94); - } - fillSignature(36, false, false, false, node); - return finishNode(node); - } - function parseKeywordAndNoDot() { - var node = parseTokenNode(); - return token() === 23 ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(173); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8; - } - function parseNonArrayType() { - switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 139: - case 130: - case 134: - var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); - case 9: - case 8: - case 101: - case 86: - return parseLiteralTypeNode(); - case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 105: - case 95: - return parseTokenNode(); - case 99: { - var thisKeyword = parseThisTypeNode(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { - return parseThisTypePredicate(thisKeyword); - } - else { - return thisKeyword; - } - } - case 103: - return parseTypeQuery(); - case 17: - return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21: - return parseTupleType(); - case 19: - return parseParenthesizedType(); - default: - return parseTypeReference(); - } - } - function isStartOfType() { - switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 105: - case 139: - case 95: - case 99: - case 103: - case 130: - case 17: - case 21: - case 27: - case 49: - case 48: - case 94: - case 9: - case 8: - case 101: - case 86: - case 134: - return true; - case 38: - return lookAhead(nextTokenIsNumericLiteral); - case 19: - return lookAhead(isStartOfParenthesizedOrFunctionType); - default: - return isIdentifier(); - } - } - function isStartOfParenthesizedOrFunctionType() { - nextToken(); - return token() === 20 || isStartOfParameter() || isStartOfType(); - } - function parseArrayTypeOrHigher() { - var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { - if (isStartOfType()) { - var node = createNode(171, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22); - type = finishNode(node); - } - else { - var node = createNode(164, type.pos); - node.elementType = type; - parseExpected(22); - type = finishNode(node); - } - } - return type; - } - function parseTypeOperator(operator) { - var node = createNode(170); - parseExpected(operator); - node.operator = operator; - node.type = parseTypeOperatorOrHigher(); - return finishNode(node); - } - function parseTypeOperatorOrHigher() { - switch (token()) { - case 127: - return parseTypeOperator(127); - } - return parseArrayTypeOrHigher(); - } - function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { - parseOptional(operator); - var type = parseConstituentType(); - if (token() === operator) { - var types = createNodeArray([type], type.pos); - while (parseOptional(operator)) { - types.push(parseConstituentType()); - } - types.end = getNodeEnd(); - var node = createNode(kind, type.pos); - node.types = types; - type = finishNode(node); - } - return type; - } - function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); - } - function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); - } - function isStartOfFunctionType() { - if (token() === 27) { - return true; - } - return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); - } - function skipParameterStart() { - if (ts.isModifierKind(token())) { - parseModifiers(); - } - if (isIdentifier() || token() === 99) { - nextToken(); - return true; - } - if (token() === 21 || token() === 17) { - var previousErrorCount = parseDiagnostics.length; - parseIdentifierOrPattern(); - return previousErrorCount === parseDiagnostics.length; - } - return false; - } - function isUnambiguouslyStartOfFunctionType() { - nextToken(); - if (token() === 20 || token() === 24) { - return true; - } - if (skipParameterStart()) { - if (token() === 56 || token() === 26 || - token() === 55 || token() === 58) { - return true; - } - if (token() === 20) { - nextToken(); - if (token() === 36) { - return true; - } - } - } - return false; - } - function parseTypeOrTypePredicate() { - var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); - var type = parseType(); - if (typePredicateVariable) { - var node = createNode(158, typePredicateVariable.pos); - node.parameterName = typePredicateVariable; - node.type = type; - return finishNode(node); - } - else { - return type; - } - } - function parseTypePredicatePrefix() { - var id = parseIdentifier(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - return id; - } - } - function parseType() { - return doOutsideOfContext(20480, parseTypeWorker); - } - function parseTypeWorker() { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160); - } - if (token() === 94) { - return parseFunctionOrConstructorType(161); - } - return parseUnionTypeOrHigher(); - } - function parseTypeAnnotation() { - return parseOptional(56) ? parseType() : undefined; - } - function isStartOfLeftHandSideExpression() { - switch (token()) { - case 99: - case 97: - case 95: - case 101: - case 86: - case 8: - case 9: - case 13: - case 14: - case 19: - case 21: - case 17: - case 89: - case 75: - case 94: - case 41: - case 63: - case 71: - return true; - default: - return isIdentifier(); - } - } - function isStartOfExpression() { - if (isStartOfLeftHandSideExpression()) { - return true; - } - switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 43: - case 44: - case 27: - case 121: - case 116: - return true; - default: - if (isBinaryOperator()) { - return true; - } - return isIdentifier(); - } - } - function isStartOfExpressionStatement() { - return token() !== 17 && - token() !== 89 && - token() !== 75 && - token() !== 57 && - isStartOfExpression(); - } - function parseExpression() { - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var expr = parseAssignmentExpressionOrHigher(); - var operatorToken; - while ((operatorToken = parseOptionalToken(26))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); - } - if (saveDecoratorContext) { - setDecoratorContext(true); - } - return expr; - } - function parseInitializer(inParameter) { - if (token() !== 58) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { - return undefined; - } - } - parseExpected(58); - return parseAssignmentExpressionOrHigher(); - } - function parseAssignmentExpressionOrHigher() { - if (isYieldExpression()) { - return parseYieldExpression(); - } - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); - if (arrowExpression) { - return arrowExpression; - } - var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 71 && token() === 36) { - return parseSimpleArrowFunctionExpression(expr); - } - if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); - } - return parseConditionalExpressionRest(expr); - } - function isYieldExpression() { - if (token() === 116) { - if (inYieldContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); - } - return false; - } - function nextTokenIsIdentifierOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && isIdentifier(); - } - function parseYieldExpression() { - var node = createNode(197); - nextToken(); - if (!scanner.hasPrecedingLineBreak() && - (token() === 39 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - else { - return finishNode(node); - } - } - function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node; - if (asyncModifier) { - node = createNode(187, asyncModifier.pos); - node.modifiers = asyncModifier; - } - else { - node = createNode(187, identifier.pos); - } - var parameter = createNode(146, identifier.pos); - parameter.name = identifier; - finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - node.body = parseArrowFunctionExpressionBody(!!asyncModifier); - return addJSDocComment(finishNode(node)); - } - function tryParseParenthesizedArrowFunctionExpression() { - var triState = isParenthesizedArrowFunctionExpression(); - if (triState === 0) { - return undefined; - } - var arrowFunction = triState === 1 - ? parseParenthesizedArrowFunctionExpressionHead(true) - : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); - if (!arrowFunction) { - return undefined; - } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); - var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 36 || lastToken === 17) - ? parseArrowFunctionExpressionBody(isAsync) - : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); - } - function isParenthesizedArrowFunctionExpression() { - if (token() === 19 || token() === 27 || token() === 120) { - return lookAhead(isParenthesizedArrowFunctionExpressionWorker); - } - if (token() === 36) { - return 1; - } - return 0; - } - function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120) { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return 0; - } - if (token() !== 19 && token() !== 27) { - return 0; - } - } - var first = token(); - var second = nextToken(); - if (first === 19) { - if (second === 20) { - var third = nextToken(); - switch (third) { - case 36: - case 56: - case 17: - return 1; - default: - return 0; - } - } - if (second === 21 || second === 17) { - return 2; - } - if (second === 24) { - return 1; - } - if (!isIdentifier()) { - return 0; - } - if (nextToken() === 56) { - return 1; - } - return 2; - } - else { - ts.Debug.assert(first === 27); - if (!isIdentifier()) { - return 0; - } - if (sourceFile.languageVariant === 1) { - var isArrowFunctionInJsx = lookAhead(function () { - var third = nextToken(); - if (third === 85) { - var fourth = nextToken(); - switch (fourth) { - case 58: - case 29: - return false; - default: - return true; - } - } - else if (third === 26) { - return true; - } - return false; - }); - if (isArrowFunctionInJsx) { - return 1; - } - return 0; - } - return 2; - } - } - function parsePossibleParenthesizedArrowFunctionExpressionHead() { - return parseParenthesizedArrowFunctionExpressionHead(false); - } - function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 120) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1) { - var asyncModifier = parseModifiersForArrowFunction(); - var expr = parseBinaryExpressionOrHigher(0); - return parseSimpleArrowFunctionExpression(expr, asyncModifier); - } - } - return undefined; - } - function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 120) { - nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 36) { - return 0; - } - var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { - return 1; - } - } - return 0; - } - function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187); - node.modifiers = parseModifiersForArrowFunction(); - var isAsync = !!(ts.getModifierFlags(node) & 256); - fillSignature(56, false, isAsync, !allowAmbiguity, node); - if (!node.parameters) { - return undefined; - } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { - return undefined; - } - return node; - } - function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17) { - return parseFunctionBlock(false, isAsync, false); - } - if (token() !== 25 && - token() !== 89 && - token() !== 75 && - isStartOfStatement() && - !isStartOfExpressionStatement()) { - return parseFunctionBlock(false, isAsync, true); - } - return isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); - } - function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(55); - if (!questionToken) { - return leftOperand; - } - var node = createNode(195, leftOperand.pos); - node.condition = leftOperand; - node.questionToken = questionToken; - node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseBinaryExpressionOrHigher(precedence) { - var leftOperand = parseUnaryExpressionOrHigher(); - return parseBinaryExpressionRest(precedence, leftOperand); - } - function isInOrOfKeyword(t) { - return t === 92 || t === 142; - } - function parseBinaryExpressionRest(precedence, leftOperand) { - while (true) { - reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 40 ? - newPrecedence >= precedence : - newPrecedence > precedence; - if (!consumeCurrentOperator) { - break; - } - if (token() === 92 && inDisallowInContext()) { - break; - } - if (token() === 118) { - if (scanner.hasPrecedingLineBreak()) { - break; - } - else { - nextToken(); - leftOperand = makeAsExpression(leftOperand, parseType()); - } - } - else { - leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); - } - } - return leftOperand; - } - function isBinaryOperator() { - if (inDisallowInContext() && token() === 92) { - return false; - } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54: - return 1; - case 53: - return 2; - case 49: - return 3; - case 50: - return 4; - case 48: - return 5; - case 32: - case 33: - case 34: - case 35: - return 6; - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - return 7; - case 45: - case 46: - case 47: - return 8; - case 37: - case 38: - return 9; - case 39: - case 41: - case 42: - return 10; - case 40: - return 11; - } - return -1; - } - function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194, left.pos); - node.left = left; - node.operatorToken = operatorToken; - node.right = right; - return finishNode(node); - } - function makeAsExpression(left, right) { - var node = createNode(202, left.pos); - node.expression = left; - node.type = right; - return finishNode(node); - } - function parsePrefixUnaryExpression() { - var node = createNode(192); - node.operator = token(); - nextToken(); - node.operand = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseDeleteExpression() { - var node = createNode(188); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseTypeOfExpression() { - var node = createNode(189); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseVoidExpression() { - var node = createNode(190); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function isAwaitExpression() { - if (token() === 121) { - if (inAwaitContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOnSameLine); - } - return false; - } - function parseAwaitExpression() { - var node = createNode(191); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseUnaryExpressionOrHigher() { - if (isUpdateExpression()) { - var incrementExpression = parseIncrementExpression(); - return token() === 40 ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : - incrementExpression; - } - var unaryOperator = token(); - var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184) { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); - } - else { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); - } - } - return simpleUnaryExpression; - } - function parseSimpleUnaryExpression() { - switch (token()) { - case 37: - case 38: - case 52: - case 51: - return parsePrefixUnaryExpression(); - case 80: - return parseDeleteExpression(); - case 103: - return parseTypeOfExpression(); - case 105: - return parseVoidExpression(); - case 27: - return parseTypeAssertion(); - case 121: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - default: - return parseIncrementExpression(); - } - } - function isUpdateExpression() { - switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 121: - return false; - case 27: - if (sourceFile.languageVariant !== 1) { - return false; - } - default: - return true; - } - } - function parseIncrementExpression() { - if (token() === 43 || token() === 44) { - var node = createNode(192); - node.operator = token(); - nextToken(); - node.operand = parseLeftHandSideExpressionOrHigher(); - return finishNode(node); - } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { - return parseJsxElementOrSelfClosingElement(true); - } - var expression = parseLeftHandSideExpressionOrHigher(); - ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193, expression.pos); - node.operand = expression; - node.operator = token(); - nextToken(); - return finishNode(node); - } - return expression; - } - function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 97 - ? parseSuperExpression() - : parseMemberExpressionOrHigher(); - return parseCallExpressionRest(expression); - } - function parseMemberExpressionOrHigher() { - var expression = parsePrimaryExpression(); - return parseMemberExpressionRest(expression); - } - function parseSuperExpression() { - var expression = parseTokenNode(); - if (token() === 19 || token() === 23 || token() === 21) { - return expression; - } - var node = createNode(179, expression.pos); - node.expression = expression; - parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - node.name = parseRightSideOfDot(true); - return finishNode(node); - } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 71) { - return lhs.text === rhs.text; - } - if (lhs.kind === 99) { - return true; - } - return lhs.name.text === rhs.name.text && - tagNamesAreEquivalent(lhs.expression, rhs.expression); - } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); - var result; - if (opening.kind === 251) { - var node = createNode(249, opening.pos); - node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); - node.closingElement = parseJsxClosingElement(inExpressionContext); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); - } - result = finishNode(node); - } - else { - ts.Debug.assert(opening.kind === 250); - result = opening; - } - if (inExpressionContext && token() === 27) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); - if (invalidElement) { - parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194, result.pos); - badNode.end = invalidElement.end; - badNode.left = result; - badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26, false, undefined); - badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; - return badNode; - } - } - return result; - } - function parseJsxText() { - var node = createNode(10, scanner.getStartPos()); - node.containsOnlyWhiteSpaces = currentToken === 11; - currentToken = scanner.scanJsxToken(); - return finishNode(node); - } - function parseJsxChild() { - switch (token()) { - case 10: - case 11: - return parseJsxText(); - case 17: - return parseJsxExpression(false); - case 27: - return parseJsxElementOrSelfClosingElement(false); - } - ts.Debug.fail("Unknown JSX child kind " + token()); - } - function parseJsxChildren(openingTagName) { - var result = createNodeArray(); - var saveParsingContext = parsingContext; - parsingContext |= 1 << 14; - while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28) { - break; - } - else if (token() === 1) { - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); - break; - } - else if (token() === 7) { - break; - } - var child = parseJsxChild(); - if (child) { - result.push(child); - } - } - result.end = scanner.getTokenPos(); - parsingContext = saveParsingContext; - return result; - } - function parseJsxAttributes() { - var jsxAttributes = createNode(254); - jsxAttributes.properties = parseList(13, parseJsxAttribute); - return finishNode(jsxAttributes); - } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { - var fullStart = scanner.getStartPos(); - parseExpected(27); - var tagName = parseJsxElementName(); - var attributes = parseJsxAttributes(); - var node; - if (token() === 29) { - node = createNode(251, fullStart); - scanJsxText(); - } - else { - parseExpected(41); - if (inExpressionContext) { - parseExpected(29); - } - else { - parseExpected(29, undefined, false); - scanJsxText(); - } - node = createNode(250, fullStart); - } - node.tagName = tagName; - node.attributes = attributes; - return finishNode(node); - } - function parseJsxElementName() { - scanJsxIdentifier(); - var expression = token() === 99 ? - parseTokenNode() : parseIdentifierName(); - while (parseOptional(23)) { - var propertyAccess = createNode(179, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); - expression = finishNode(propertyAccess); - } - return expression; - } - function parseJsxExpression(inExpressionContext) { - var node = createNode(256); - parseExpected(17); - if (token() !== 18) { - node.dotDotDotToken = parseOptionalToken(24); - node.expression = parseAssignmentExpressionOrHigher(); - } - if (inExpressionContext) { - parseExpected(18); - } - else { - parseExpected(18, undefined, false); - scanJsxText(); - } - return finishNode(node); - } - function parseJsxAttribute() { - if (token() === 17) { - return parseJsxSpreadAttribute(); - } - scanJsxIdentifier(); - var node = createNode(253); - node.name = parseIdentifierName(); - if (token() === 58) { - switch (scanJsxAttributeValue()) { - case 9: - node.initializer = parseLiteralNode(); - break; - default: - node.initializer = parseJsxExpression(true); - break; - } - } - return finishNode(node); - } - function parseJsxSpreadAttribute() { - var node = createNode(255); - parseExpected(17); - parseExpected(24); - node.expression = parseExpression(); - parseExpected(18); - return finishNode(node); - } - function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252); - parseExpected(28); - node.tagName = parseJsxElementName(); - if (inExpressionContext) { - parseExpected(29); - } - else { - parseExpected(29, undefined, false); - scanJsxText(); - } - return finishNode(node); - } - function parseTypeAssertion() { - var node = createNode(184); - parseExpected(27); - node.type = parseType(); - parseExpected(29); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseMemberExpressionRest(expression) { - while (true) { - var dotToken = parseOptionalToken(23); - if (dotToken) { - var propertyAccess = createNode(179, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); - expression = finishNode(propertyAccess); - continue; - } - if (token() === 51 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var nonNullExpression = createNode(203, expression.pos); - nonNullExpression.expression = expression; - expression = finishNode(nonNullExpression); - continue; - } - if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(180, expression.pos); - indexedAccess.expression = expression; - if (token() !== 22) { - indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { - var literal = indexedAccess.argumentExpression; - literal.text = internIdentifier(literal.text); - } - } - parseExpected(22); - expression = finishNode(indexedAccess); - continue; - } - if (token() === 13 || token() === 14) { - var tagExpression = createNode(183, expression.pos); - tagExpression.tag = expression; - tagExpression.template = token() === 13 - ? parseLiteralNode() - : parseTemplateExpression(); - expression = finishNode(tagExpression); - continue; - } - return expression; - } - } - function parseCallExpressionRest(expression) { - while (true) { - expression = parseMemberExpressionRest(expression); - if (token() === 27) { - var typeArguments = tryParse(parseTypeArgumentsInExpression); - if (!typeArguments) { - return expression; - } - var callExpr = createNode(181, expression.pos); - callExpr.expression = expression; - callExpr.typeArguments = typeArguments; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - else if (token() === 19) { - var callExpr = createNode(181, expression.pos); - callExpr.expression = expression; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - return expression; - } - } - function parseArgumentList() { - parseExpected(19); - var result = parseDelimitedList(11, parseArgumentExpression); - parseExpected(20); - return result; - } - function parseTypeArgumentsInExpression() { - if (!parseOptional(27)) { - return undefined; - } - var typeArguments = parseDelimitedList(19, parseType); - if (!parseExpected(29)) { - return undefined; - } - return typeArguments && canFollowTypeArgumentsInExpression() - ? typeArguments - : undefined; - } - function canFollowTypeArgumentsInExpression() { - switch (token()) { - case 19: - case 23: - case 20: - case 22: - case 56: - case 25: - case 55: - case 32: - case 34: - case 33: - case 35: - case 53: - case 54: - case 50: - case 48: - case 49: - case 18: - case 1: - return true; - case 26: - case 17: - default: - return false; - } - } - function parsePrimaryExpression() { - switch (token()) { - case 8: - case 9: - case 13: - return parseLiteralNode(); - case 99: - case 97: - case 95: - case 101: - case 86: - return parseTokenNode(); - case 19: - return parseParenthesizedExpression(); - case 21: - return parseArrayLiteralExpression(); - case 17: - return parseObjectLiteralExpression(); - case 120: - if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { - break; - } - return parseFunctionExpression(); - case 75: - return parseClassExpression(); - case 89: - return parseFunctionExpression(); - case 94: - return parseNewExpression(); - case 41: - case 63: - if (reScanSlashToken() === 12) { - return parseLiteralNode(); - } - break; - case 14: - return parseTemplateExpression(); - } - return parseIdentifier(ts.Diagnostics.Expression_expected); - } - function parseParenthesizedExpression() { - var node = createNode(185); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - return finishNode(node); - } - function parseSpreadElement() { - var node = createNode(198); - parseExpected(24); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseArgumentOrArrayLiteralElement() { - return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(200) : - parseAssignmentExpressionOrHigher(); - } - function parseArgumentExpression() { - return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); - } - function parseArrayLiteralExpression() { - var node = createNode(177); - parseExpected(21); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(22); - return finishNode(node); - } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(153, fullStart, decorators, modifiers); - } - else if (parseContextualModifier(135)) { - return parseAccessorDeclaration(154, fullStart, decorators, modifiers); - } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24); - if (dotDotDotToken) { - var spreadElement = createNode(263, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - var asteriskToken = parseOptionalToken(39); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); - } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); - if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(58); - if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); - } - return addJSDocComment(finishNode(shorthandDeclaration)); - } - else { - var propertyAssignment = createNode(261, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; - parseExpected(56); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); - } - } - function parseObjectLiteralExpression() { - var node = createNode(178); - parseExpected(17); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(18); - return finishNode(node); - } - function parseFunctionExpression() { - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var node = createNode(186); - node.modifiers = parseModifiers(); - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - var isGenerator = !!node.asteriskToken; - var isAsync = !!(ts.getModifierFlags(node) & 256); - node.name = - isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : - isGenerator ? doInYieldContext(parseOptionalIdentifier) : - isAsync ? doInAwaitContext(parseOptionalIdentifier) : - parseOptionalIdentifier(); - fillSignature(56, isGenerator, isAsync, false, node); - node.body = parseFunctionBlock(isGenerator, isAsync, false); - if (saveDecoratorContext) { - setDecoratorContext(true); - } - return addJSDocComment(finishNode(node)); - } - function parseOptionalIdentifier() { - return isIdentifier() ? parseIdentifier() : undefined; - } - function parseNewExpression() { - var fullStart = scanner.getStartPos(); - parseExpected(94); - if (parseOptional(23)) { - var node_1 = createNode(204, fullStart); - node_1.keywordToken = 94; - node_1.name = parseIdentifierName(); - return finishNode(node_1); - } - var node = createNode(182, fullStart); - node.expression = parseMemberExpressionOrHigher(); - node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 19) { - node.arguments = parseArgumentList(); - } - return finishNode(node); - } - function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207); - if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.statements = parseList(1, parseStatement); - parseExpected(18); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseFunctionBlock(allowYield, allowAwait, ignoreMissingOpenBrace, diagnosticMessage) { - var savedYieldContext = inYieldContext(); - setYieldContext(allowYield); - var savedAwaitContext = inAwaitContext(); - setAwaitContext(allowAwait); - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); - if (saveDecoratorContext) { - setDecoratorContext(true); - } - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - return block; - } - function parseEmptyStatement() { - var node = createNode(209); - parseExpected(25); - return finishNode(node); - } - function parseIfStatement() { - var node = createNode(211); - parseExpected(90); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82) ? parseStatement() : undefined; - return finishNode(node); - } - function parseDoStatement() { - var node = createNode(212); - parseExpected(81); - node.statement = parseStatement(); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - parseOptional(25); - return finishNode(node); - } - function parseWhileStatement() { - var node = createNode(213); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.statement = parseStatement(); - return finishNode(node); - } - function parseForOrForInOrForOfStatement() { - var pos = getNodePos(); - parseExpected(88); - var awaitToken = parseOptionalToken(121); - parseExpected(19); - var initializer = undefined; - if (token() !== 25) { - if (token() === 104 || token() === 110 || token() === 76) { - initializer = parseVariableDeclarationList(true); - } - else { - initializer = disallowInAnd(parseExpression); - } - } - var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142) : parseOptional(142)) { - var forOfStatement = createNode(216, pos); - forOfStatement.awaitModifier = awaitToken; - forOfStatement.initializer = initializer; - forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20); - forOrForInOrForOfStatement = forOfStatement; - } - else if (parseOptional(92)) { - var forInStatement = createNode(215, pos); - forInStatement.initializer = initializer; - forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20); - forOrForInOrForOfStatement = forInStatement; - } - else { - var forStatement = createNode(214, pos); - forStatement.initializer = initializer; - parseExpected(25); - if (token() !== 25 && token() !== 20) { - forStatement.condition = allowInAnd(parseExpression); - } - parseExpected(25); - if (token() !== 20) { - forStatement.incrementor = allowInAnd(parseExpression); - } - parseExpected(20); - forOrForInOrForOfStatement = forStatement; - } - forOrForInOrForOfStatement.statement = parseStatement(); - return finishNode(forOrForInOrForOfStatement); - } - function parseBreakOrContinueStatement(kind) { - var node = createNode(kind); - parseExpected(kind === 218 ? 72 : 77); - if (!canParseSemicolon()) { - node.label = parseIdentifier(); - } - parseSemicolon(); - return finishNode(node); - } - function parseReturnStatement() { - var node = createNode(219); - parseExpected(96); - if (!canParseSemicolon()) { - node.expression = allowInAnd(parseExpression); - } - parseSemicolon(); - return finishNode(node); - } - function parseWithStatement() { - var node = createNode(220); - parseExpected(107); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.statement = parseStatement(); - return finishNode(node); - } - function parseCaseClause() { - var node = createNode(257); - parseExpected(73); - node.expression = allowInAnd(parseExpression); - parseExpected(56); - node.statements = parseList(3, parseStatement); - return finishNode(node); - } - function parseDefaultClause() { - var node = createNode(258); - parseExpected(79); - parseExpected(56); - node.statements = parseList(3, parseStatement); - return finishNode(node); - } - function parseCaseOrDefaultClause() { - return token() === 73 ? parseCaseClause() : parseDefaultClause(); - } - function parseSwitchStatement() { - var node = createNode(221); - parseExpected(98); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - var caseBlock = createNode(235, scanner.getStartPos()); - parseExpected(17); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); - parseExpected(18); - node.caseBlock = finishNode(caseBlock); - return finishNode(node); - } - function parseThrowStatement() { - var node = createNode(223); - parseExpected(100); - node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); - parseSemicolon(); - return finishNode(node); - } - function parseTryStatement() { - var node = createNode(224); - parseExpected(102); - node.tryBlock = parseBlock(false); - node.catchClause = token() === 74 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 87) { - parseExpected(87); - node.finallyBlock = parseBlock(false); - } - return finishNode(node); - } - function parseCatchClause() { - var result = createNode(260); - parseExpected(74); - if (parseExpected(19)) { - result.variableDeclaration = parseVariableDeclaration(); - } - parseExpected(20); - result.block = parseBlock(false); - return finishNode(result); - } - function parseDebuggerStatement() { - var node = createNode(225); - parseExpected(78); - parseSemicolon(); - return finishNode(node); - } - function parseExpressionOrLabeledStatement() { - var fullStart = scanner.getStartPos(); - var expression = allowInAnd(parseExpression); - if (expression.kind === 71 && parseOptional(56)) { - var labeledStatement = createNode(222, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); - } - else { - var expressionStatement = createNode(210, fullStart); - expressionStatement.expression = expression; - parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); - } - } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsClassKeywordOnSameLine() { - nextToken(); - return token() === 75 && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsFunctionKeywordOnSameLine() { - nextToken(); - return token() === 89 && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { - nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); - } - function isDeclaration() { - while (true) { - switch (token()) { - case 104: - case 110: - case 76: - case 89: - case 75: - case 83: - return true; - case 109: - case 138: - return nextTokenIsIdentifierOnSameLine(); - case 128: - case 129: - return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117: - case 120: - case 124: - case 112: - case 113: - case 114: - case 131: - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - continue; - case 141: - nextToken(); - return token() === 17 || token() === 71 || token() === 84; - case 91: - nextToken(); - return token() === 9 || token() === 39 || - token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); - case 84: - nextToken(); - if (token() === 58 || token() === 39 || - token() === 17 || token() === 79 || - token() === 118) { - return true; - } - continue; - case 115: - nextToken(); - continue; - default: - return false; - } - } - } - function isStartOfDeclaration() { - return lookAhead(isDeclaration); - } - function isStartOfStatement() { - switch (token()) { - case 57: - case 25: - case 17: - case 104: - case 110: - case 89: - case 75: - case 83: - case 90: - case 81: - case 106: - case 88: - case 77: - case 72: - case 96: - case 107: - case 98: - case 100: - case 102: - case 78: - case 74: - case 87: - return true; - case 76: - case 84: - case 91: - return isStartOfDeclaration(); - case 120: - case 124: - case 109: - case 128: - case 129: - case 138: - case 141: - return true; - case 114: - case 112: - case 113: - case 115: - case 131: - return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - default: - return isStartOfExpression(); - } - } - function nextTokenIsIdentifierOrStartOfDestructuring() { - nextToken(); - return isIdentifier() || token() === 17 || token() === 21; - } - function isLetDeclaration() { - return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); - } - function parseStatement() { - switch (token()) { - case 25: - return parseEmptyStatement(); - case 17: - return parseBlock(false); - case 104: - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - case 110: - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - } - break; - case 89: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); - case 75: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 90: - return parseIfStatement(); - case 81: - return parseDoStatement(); - case 106: - return parseWhileStatement(); - case 88: - return parseForOrForInOrForOfStatement(); - case 77: - return parseBreakOrContinueStatement(217); - case 72: - return parseBreakOrContinueStatement(218); - case 96: - return parseReturnStatement(); - case 107: - return parseWithStatement(); - case 98: - return parseSwitchStatement(); - case 100: - return parseThrowStatement(); - case 102: - case 74: - case 87: - return parseTryStatement(); - case 78: - return parseDebuggerStatement(); - case 57: - return parseDeclaration(); - case 120: - case 109: - case 138: - case 128: - case 129: - case 124: - case 76: - case 83: - case 84: - case 91: - case 112: - case 113: - case 114: - case 117: - case 115: - case 131: - case 141: - if (isStartOfDeclaration()) { - return parseDeclaration(); - } - break; - } - return parseExpressionOrLabeledStatement(); - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - switch (token()) { - case 104: - case 110: - case 76: - return parseVariableStatement(fullStart, decorators, modifiers); - case 89: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 75: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 109: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 138: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 83: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141: - case 128: - case 129: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 91: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 84: - nextToken(); - switch (token()) { - case 79: - case 58: - return parseExportAssignment(fullStart, decorators, modifiers); - case 118: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); - default: - return parseExportDeclaration(fullStart, decorators, modifiers); - } - default: - if (decorators || modifiers) { - var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); - } - } - } - function nextTokenIsIdentifierOrStringLiteralOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); - } - function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 17 && canParseSemicolon()) { - parseSemicolon(); - return; - } - return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); - } - function parseArrayBindingElement() { - if (token() === 26) { - return createNode(200); - } - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); - node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(false); - return finishNode(node); - } - function parseObjectBindingElement() { - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56) { - node.name = propertyName; - } - else { - parseExpected(56); - node.propertyName = propertyName; - node.name = parseIdentifierOrPattern(); - } - node.initializer = parseBindingElementInitializer(false); - return finishNode(node); - } - function parseObjectBindingPattern() { - var node = createNode(174); - parseExpected(17); - node.elements = parseDelimitedList(9, parseObjectBindingElement); - parseExpected(18); - return finishNode(node); - } - function parseArrayBindingPattern() { - var node = createNode(175); - parseExpected(21); - node.elements = parseDelimitedList(10, parseArrayBindingElement); - parseExpected(22); - return finishNode(node); - } - function isIdentifierOrPattern() { - return token() === 17 || token() === 21 || isIdentifier(); - } - function parseIdentifierOrPattern() { - if (token() === 21) { - return parseArrayBindingPattern(); - } - if (token() === 17) { - return parseObjectBindingPattern(); - } - return parseIdentifier(); - } - function parseVariableDeclaration() { - var node = createNode(226); - node.name = parseIdentifierOrPattern(); - node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(false); - } - return finishNode(node); - } - function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227); - switch (token()) { - case 104: - break; - case 110: - node.flags |= 1; - break; - case 76: - node.flags |= 2; - break; - default: - ts.Debug.fail(); - } - nextToken(); - if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { - node.declarations = createMissingList(); - } - else { - var savedDisallowIn = inDisallowInContext(); - setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8, parseVariableDeclaration); - setDisallowInContext(savedDisallowIn); - } - return finishNode(node); - } - function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20; - } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.declarationList = parseVariableDeclarationList(false); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); - var isGenerator = !!node.asteriskToken; - var isAsync = ts.hasModifier(node, 256); - fillSignature(56, isGenerator, isAsync, false, node); - node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152, pos); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(123); - fillSignature(56, false, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; - var isGenerator = !!asteriskToken; - var isAsync = ts.hasModifier(method, 256); - fillSignature(56, isGenerator, isAsync, false, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - property.initializer = ts.hasModifier(property, 32) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); - parseSemicolon(); - return addJSDocComment(finishNode(property)); - } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(39); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); - } - } - function parseNonParameterInitializer() { - return parseInitializer(false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.name = parsePropertyName(); - fillSignature(56, false, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false, false); - return addJSDocComment(finishNode(node)); - } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114: - case 112: - case 113: - case 115: - case 131: - return true; - default: - return false; - } - } - function isClassMemberStart() { - var idToken; - if (token() === 57) { - return true; - } - while (ts.isModifierKind(token())) { - idToken = token(); - if (isClassMemberModifier(idToken)) { - return true; - } - nextToken(); - } - if (token() === 39) { - return true; - } - if (isLiteralPropertyName()) { - idToken = token(); - nextToken(); - } - if (token() === 21) { - return true; - } - if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { - return true; - } - switch (token()) { - case 19: - case 27: - case 56: - case 58: - case 55: - return true; - default: - return canParseSemicolon(); - } - } - return false; - } - function parseDecorators() { - var decorators; - while (true) { - var decoratorStart = getNodePos(); - if (!parseOptional(57)) { - break; - } - var decorator = createNode(147, decoratorStart); - decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); - } - return decorators; - } - function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; - while (true) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 76 && permitInvalidConstAsModifier) { - if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { - break; - } - } - else { - if (!parseAnyContextualModifier()) { - break; - } - } - var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseModifiersForArrowFunction() { - var modifiers; - if (token() === 120) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - nextToken(); - var modifier = finishNode(createNode(modifierKind, modifierStart)); - modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseClassElement() { - if (token() === 25) { - var result = createNode(206); - nextToken(); - return finishNode(result); - } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - if (token() === 123) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); - } - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); - } - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8 || - token() === 39 || - token() === 21) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); - } - if (decorators || modifiers) { - var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); - } - ts.Debug.fail("Should not have attempted to parse class member declaration."); - } - function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); - } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); - } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(75); - node.name = parseNameOfClassDeclarationOrExpression(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17)) { - node.members = parseClassMembers(); - parseExpected(18); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseNameOfClassDeclarationOrExpression() { - return isIdentifier() && !isImplementsClause() - ? parseIdentifier() - : undefined; - } - function isImplementsClause() { - return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); - } - function parseHeritageClauses() { - if (isHeritageClause()) { - return parseList(21, parseHeritageClause); - } - return undefined; - } - function parseHeritageClause() { - var tok = token(); - if (tok === 85 || tok === 108) { - var node = createNode(259); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; - } - function parseExpressionWithTypeArguments() { - var node = createNode(201); - node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } - return finishNode(node); - } - function isHeritageClause() { - return token() === 85 || token() === 108; - } - function parseClassMembers() { - return parseList(5, parseClassElement); - } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(109); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); - } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(138); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - parseExpected(58); - node.type = parseType(); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseEnumMember() { - var node = createNode(264, scanner.getStartPos()); - node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); - } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(83); - node.name = parseIdentifier(); - if (parseExpected(17)) { - node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(18); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseModuleBlock() { - var node = createNode(234, scanner.getStartPos()); - if (parseExpected(17)) { - node.statements = parseList(1, parseStatement); - parseExpected(18); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233, fullStart); - var namespaceFlag = flags & 16; - node.decorators = decorators; - node.modifiers = modifiers; - node.flags |= flags; - node.name = parseIdentifier(); - node.body = parseOptional(23) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) - : parseModuleBlock(); - return addJSDocComment(finishNode(node)); - } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141) { - node.name = parseIdentifier(); - node.flags |= 512; - } - else { - node.name = parseLiteralNode(true); - } - if (token() === 17) { - node.body = parseModuleBlock(); - } - else { - parseSemicolon(); - } - return finishNode(node); - } - function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = 0; - if (token() === 141) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - else if (parseOptional(129)) { - flags |= 16; - } - else { - parseExpected(128); - if (token() === 9) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); - } - function isExternalModuleReference() { - return token() === 132 && - lookAhead(nextTokenIsOpenParen); - } - function nextTokenIsOpenParen() { - return nextToken() === 19; - } - function nextTokenIsSlash() { - return nextToken() === 41; - } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; - parseExpected(118); - parseExpected(129); - exportDeclaration.name = parseIdentifier(); - parseSemicolon(); - return finishNode(exportDeclaration); - } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(91); - var afterImportPos = scanner.getStartPos(); - var identifier; - if (isIdentifier()) { - identifier = parseIdentifier(); - if (token() !== 26 && token() !== 140) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); - } - } - var importDeclaration = createNode(238, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; - if (identifier || - token() === 39 || - token() === 17) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140); - } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); - parseSemicolon(); - return finishNode(importDeclaration); - } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; - parseExpected(58); - importEqualsDeclaration.moduleReference = parseModuleReference(); - parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); - } - function parseImportClause(identifier, fullStart) { - var importClause = createNode(239, fullStart); - if (identifier) { - importClause.name = identifier; - } - if (!importClause.name || - parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); - } - return finishNode(importClause); - } - function parseModuleReference() { - return isExternalModuleReference() - ? parseExternalModuleReference() - : parseEntityName(false); - } - function parseExternalModuleReference() { - var node = createNode(248); - parseExpected(132); - parseExpected(19); - node.expression = parseModuleSpecifier(); - parseExpected(20); - return finishNode(node); - } - function parseModuleSpecifier() { - if (token() === 9) { - var result = parseLiteralNode(); - internIdentifier(result.text); - return result; - } - else { - return parseExpression(); - } - } - function parseNamespaceImport() { - var namespaceImport = createNode(240); - parseExpected(39); - parseExpected(118); - namespaceImport.name = parseIdentifier(); - return finishNode(namespaceImport); - } - function parseNamedImportsOrExports(kind) { - var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); - return finishNode(node); - } - function parseExportSpecifier() { - return parseImportOrExportSpecifier(246); - } - function parseImportSpecifier() { - return parseImportOrExportSpecifier(242); - } - function parseImportOrExportSpecifier(kind) { - var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - var checkIdentifierStart = scanner.getTokenPos(); - var checkIdentifierEnd = scanner.getTextPos(); - var identifierName = parseIdentifierName(); - if (token() === 118) { - node.propertyName = identifierName; - parseExpected(118); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - checkIdentifierStart = scanner.getTokenPos(); - checkIdentifierEnd = scanner.getTextPos(); - node.name = parseIdentifierName(); - } - else { - node.name = identifierName; - } - if (kind === 242 && checkIdentifierIsKeyword) { - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); - } - return finishNode(node); - } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(39)) { - parseExpected(140); - node.moduleSpecifier = parseModuleSpecifier(); - } - else { - node.exportClause = parseNamedImportsOrExports(245); - if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(140); - node.moduleSpecifier = parseModuleSpecifier(); - } - } - parseSemicolon(); - return finishNode(node); - } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(58)) { - node.isExportEquals = true; - } - else { - parseExpected(79); - } - node.expression = parseAssignmentExpressionOrHigher(); - parseSemicolon(); - return finishNode(node); - } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*".length; - return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function parseQualifiedName(left) { - var result = createNode(143, left.pos); - result.left = left; - result.right = parseIdentifierName(); - return finishNode(result); - } - function parseJSDocRecordType() { - var result = createNode(275); - result.literal = parseTypeLiteral(); - return finishNode(result); - } - function parseJSDocNonNullableType() { - var result = createNode(274); - nextToken(); - result.type = parseJSDocType(); - return finishNode(result); - } - function parseJSDocTupleType() { - var result = createNode(272); - nextToken(); - result.types = parseDelimitedList(26, parseJSDocType); - checkForTrailingComma(result.types); - parseExpected(22); - return finishNode(result); - } - function checkForTrailingComma(list) { - if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - var start = list.end - ",".length; - parseErrorAtPosition(start, ",".length, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function parseJSDocUnionType() { - var result = createNode(271); - nextToken(); - result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(20); - return finishNode(result); - } - function parseJSDocTypeList(firstType) { - ts.Debug.assert(!!firstType); - var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(49)) { - types.push(parseJSDocType()); - } - types.end = scanner.getStartPos(); - return types; - } - function parseJSDocAllType() { - var result = createNode(268); - nextToken(); - return finishNode(result); - } - function parseJSDocLiteralType() { - var result = createNode(293); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } - function parseJSDocUnknownOrNullableType() { - var pos = scanner.getStartPos(); - nextToken(); - if (token() === 26 || - token() === 18 || - token() === 20 || - token() === 29 || - token() === 58 || - token() === 49) { - var result = createNode(269, pos); - return finishNode(result); - } - else { - var result = createNode(273, pos); - result.type = parseJSDocType(); - return finishNode(result); - } - } - function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = { languageVariant: 0, text: content }; - var jsDoc = parseJSDocCommentWorker(start, length); - var diagnostics = parseDiagnostics; - clearState(); - return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; - } - JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var comment = parseJSDocCommentWorker(start, length); - if (comment) { - comment.parent = parent; - } - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - 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; - var end = length === undefined ? content.length : start + length; - length = end - start; - ts.Debug.assert(start >= 0); - ts.Debug.assert(start <= end); - ts.Debug.assert(end <= content.length); - var tags; - var comments = []; - var result; - if (!isJsDocStart(content, start)) { - return result; - } - scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; - var state = 1; - var margin = undefined; - var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); - } - if (token() === 4) { - state = 0; - indent = 0; - nextJSDocToken(); - } - while (token() !== 1) { - switch (token()) { - case 57: - if (state === 0 || state === 1) { - removeTrailingNewlines(comments); - parseTag(indent); - state = 0; - advanceToken = false; - margin = undefined; - indent++; - } - else { - pushComment(scanner.getTokenText()); - } - break; - case 4: - comments.push(scanner.getTokenText()); - state = 0; - indent = 0; - break; - case 39: - var asterisk = scanner.getTokenText(); - if (state === 1 || state === 2) { - state = 2; - pushComment(asterisk); - } - else { - state = 1; - indent += asterisk.length; - } - break; - case 71: - pushComment(scanner.getTokenText()); - state = 2; - break; - case 5: - var whitespace = scanner.getTokenText(); - if (state === 2) { - comments.push(whitespace); - } - else if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - break; - case 1: - break; - default: - state = 2; - pushComment(scanner.getTokenText()); - break; - } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - result = createJSDocComment(); - }); - return result; - function removeLeadingNewlines(comments) { - while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { - comments.shift(); - } - } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { - comments.pop(); - } - } - function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 && - content.charCodeAt(start + 1) === 42 && - content.charCodeAt(start + 2) === 42 && - content.charCodeAt(start + 3) !== 42; - } - function createJSDocComment() { - var result = createNode(283, start); - result.tags = tags; - result.comment = comments.length ? comments.join("") : undefined; - return finishNode(result, end); - } - function skipWhitespace() { - while (token() === 5 || token() === 4) { - nextJSDocToken(); - } - } - function parseTag(indent) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return; - } - var tag; - if (tagName) { - switch (tagName.text) { - case "augments": - tag = parseAugmentsTag(atToken, tagName); - break; - case "arg": - case "argument": - case "param": - tag = parseParamTag(atToken, tagName); - break; - case "return": - case "returns": - tag = parseReturnTag(atToken, tagName); - break; - case "template": - tag = parseTemplateTag(atToken, tagName); - break; - case "type": - tag = parseTypeTag(atToken, tagName); - break; - case "typedef": - tag = parseTypedefTag(atToken, tagName); - break; - default: - tag = parseUnknownTag(atToken, tagName); - break; - } - } - else { - tag = parseUnknownTag(atToken, tagName); - } - if (!tag) { - return; - } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); - } - function parseTagComments(indent) { - var comments = []; - var state = 0; - var margin; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - while (token() !== 57 && token() !== 1) { - switch (token()) { - case 4: - if (state >= 1) { - state = 0; - comments.push(scanner.getTokenText()); - } - indent = 0; - break; - case 57: - break; - case 5: - if (state === 2) { - pushComment(scanner.getTokenText()); - } - else { - var whitespace = scanner.getTokenText(); - if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - } - break; - case 39: - if (state === 0) { - state = 1; - indent += scanner.getTokenText().length; - break; - } - default: - state = 2; - pushComment(scanner.getTokenText()); - break; - } - if (token() === 57) { - break; - } - nextJSDocToken(); - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - return comments; - } - function parseUnknownTag(atToken, tagName) { - var result = createNode(284, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - return finishNode(result); - } - function addTag(tag, comments) { - tag.comment = comments.join(""); - if (!tags) { - tags = createNodeArray([tag], tag.pos); - } - else { - tags.push(tag); - } - tags.end = tag.end; - } - function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17) { - return undefined; - } - return parseJSDocTypeExpression(); - }); - } - function parseParamTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name; - var isBracketed; - if (parseOptionalToken(21)) { - name = parseJSDocIdentifierName(); - skipWhitespace(); - isBracketed = true; - if (parseOptionalToken(58)) { - parseExpression(); - } - parseExpected(22); - } - else if (ts.tokenIsIdentifierOrKeyword(token())) { - name = parseJSDocIdentifierName(); - } - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var preName, postName; - if (typeExpression) { - postName = name; - } - else { - preName = name; - } - if (!typeExpression) { - typeExpression = tryParseTypeExpression(); - } - var result = createNode(286, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.preParameterName = preName; - result.typeExpression = typeExpression; - result.postParameterName = postName; - result.parameterName = postName || preName; - result.isBracketed = isBracketed; - return finishNode(result); - } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(287, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 288; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(288, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parsePropertyTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var result = createNode(291, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.name = name; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - var result = createNode(285, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseTypedefTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(290, atToken.pos); - typedefTag.atToken = atToken; - typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 || !rightNode.body) { - typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } - typedefTag.typeExpression = typeExpression; - skipWhitespace(); - if (typeExpression) { - if (typeExpression.type.kind === 277) { - var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 71) { - var name = jsDocTypeReference.name; - if (name.text === "Object") { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - } - } - if (!typedefTag.jsDocTypeLiteral) { - typedefTag.jsDocTypeLiteral = typeExpression.type; - } - } - else { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - return finishNode(typedefTag); - function scanChildTags() { - var jsDocTypeLiteral = createNode(292, scanner.getStartPos()); - var resumePos = scanner.getStartPos(); - var canParseTag = true; - var seenAsterisk = false; - var parentTagTerminated = false; - while (token() !== 1 && !parentTagTerminated) { - nextJSDocToken(); - switch (token()) { - case 57: - if (canParseTag) { - parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } - } - seenAsterisk = false; - break; - case 4: - resumePos = scanner.getStartPos() - 1; - canParseTag = true; - seenAsterisk = false; - break; - case 39: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 71: - canParseTag = false; - break; - case 1: - break; - } - } - scanner.setTextPos(resumePos); - return finishNode(jsDocTypeLiteral); - } - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(233, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); - return jsDocNamespaceNode; - } - if (typeNameOrNamespaceName && flags & 4) { - typeNameOrNamespaceName.isInJSDocNamespace = true; - } - return typeNameOrNamespaceName; - } - } - function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getStartPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return false; - } - switch (tagName.text) { - case "type": - if (parentTag.jsDocTypeTag) { - return false; - } - parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); - return true; - case "prop": - case "property": - var propertyTag = parsePropertyTag(atToken, tagName); - if (propertyTag) { - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } - parentTag.jsDocPropertyTags.push(propertyTag); - return true; - } - return false; - } - return false; - } - function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var typeParameters = createNodeArray(); - while (true) { - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var typeParameter = createNode(145, name.pos); - typeParameter.name = name; - finishNode(typeParameter); - typeParameters.push(typeParameter); - if (token() === 26) { - nextJSDocToken(); - skipWhitespace(); - } - else { - break; - } - } - var result = createNode(289, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeParameters = typeParameters; - finishNode(result); - typeParameters.end = result.end; - return result; - } - function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); - } - function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function createJSDocIdentifier(isIdentifier) { - if (!isIdentifier) { - parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - return undefined; - } - var pos = scanner.getTokenPos(); - var end = scanner.getTextPos(); - var result = createNode(71, pos); - result.text = content.substring(pos, end); - finishNode(result, end); - nextJSDocToken(); - return result; - } - } - JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; - })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); - })(Parser || (Parser = {})); - var IncrementalParser; - (function (IncrementalParser) { - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); - checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); - if (ts.textChangeRangeIsUnchanged(textChangeRange)) { - return sourceFile; - } - if (sourceFile.statements.length === 0) { - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); - } - var incrementalSourceFile = sourceFile; - ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); - incrementalSourceFile.hasBeenIncrementallyParsed = true; - var oldText = sourceFile.text; - var syntaxCursor = createSyntaxCursor(sourceFile); - var changeRange = extendToAffectedRange(sourceFile, textChangeRange); - checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); - ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); - ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); - ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); - var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; - updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); - return result; - } - IncrementalParser.updateSourceFile = updateSourceFile; - function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { - if (isArray) { - visitArray(element); - } - else { - visitNode(element); - } - return; - function visitNode(node) { - var text = ""; - if (aggressiveChecks && shouldCheckNode(node)) { - text = oldText.substring(node.pos, node.end); - } - if (node._children) { - node._children = undefined; - } - node.pos += delta; - node.end += delta; - if (aggressiveChecks && shouldCheckNode(node)) { - ts.Debug.assert(text === newText.substring(node.pos, node.end)); - } - forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - forEachChild(jsDocComment, visitNode, visitArray); - } - } - checkNodePositions(node, aggressiveChecks); - } - function visitArray(array) { - array._children = undefined; - array.pos += delta; - array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; - visitNode(node); - } - } - } - function shouldCheckNode(node) { - switch (node.kind) { - case 9: - case 8: - case 71: - return true; - } - return false; - } - function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { - ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); - ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); - ts.Debug.assert(element.pos <= element.end); - element.pos = Math.min(element.pos, changeRangeNewEnd); - if (element.end >= changeRangeOldEnd) { - element.end += delta; - } - else { - element.end = Math.min(element.end, changeRangeNewEnd); - } - ts.Debug.assert(element.pos <= element.end); - if (element.parent) { - ts.Debug.assert(element.pos >= element.parent.pos); - ts.Debug.assert(element.end <= element.parent.end); - } - } - function checkNodePositions(node, aggressiveChecks) { - if (aggressiveChecks) { - var pos_2 = node.pos; - forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; - }); - ts.Debug.assert(pos_2 <= node.end); - } - } - function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { - visitNode(sourceFile); - return; - function visitNode(child) { - ts.Debug.assert(child.pos <= child.end); - if (child.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); - return; - } - var fullEnd = child.end; - if (fullEnd >= changeStart) { - child.intersectsChange = true; - child._children = undefined; - adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - forEachChild(child, visitNode, visitArray); - checkNodePositions(child, aggressiveChecks); - return; - } - ts.Debug.assert(fullEnd < changeStart); - } - function visitArray(array) { - ts.Debug.assert(array.pos <= array.end); - if (array.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); - return; - } - var fullEnd = array.end; - if (fullEnd >= changeStart) { - array.intersectsChange = true; - array._children = undefined; - adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; - visitNode(node); - } - return; - } - ts.Debug.assert(fullEnd < changeStart); - } - } - function extendToAffectedRange(sourceFile, changeRange) { - var maxLookahead = 1; - var start = changeRange.span.start; - for (var i = 0; start > 0 && i <= maxLookahead; i++) { - var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); - ts.Debug.assert(nearestNode.pos <= start); - var position = nearestNode.pos; - start = Math.max(0, position - 1); - } - var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); - var finalLength = changeRange.newLength + (changeRange.span.start - start); - return ts.createTextChangeRange(finalSpan, finalLength); - } - function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { - var bestResult = sourceFile; - var lastNodeEntirelyBeforePosition; - forEachChild(sourceFile, visit); - if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); - if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { - bestResult = lastChildOfLastEntireNodeBeforePosition; - } - } - return bestResult; - function getLastChild(node) { - while (true) { - var lastChild = getLastChildWorker(node); - if (lastChild) { - node = lastChild; - } - else { - return node; - } - } - } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } - function visit(child) { - if (ts.nodeIsMissing(child)) { - return; - } - if (child.pos <= position) { - if (child.pos >= bestResult.pos) { - bestResult = child; - } - if (position < child.end) { - forEachChild(child, visit); - return true; - } - else { - ts.Debug.assert(child.end <= position); - lastNodeEntirelyBeforePosition = child; - } - } - else { - ts.Debug.assert(child.pos > position); - return true; - } - } - } - function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { - var oldText = sourceFile.text; - if (textChangeRange) { - ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); - if (aggressiveChecks || ts.Debug.shouldAssert(3)) { - var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - var newTextPrefix = newText.substr(0, textChangeRange.span.start); - ts.Debug.assert(oldTextPrefix === newTextPrefix); - var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); - var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); - ts.Debug.assert(oldTextSuffix === newTextSuffix); - } - } - } - function createSyntaxCursor(sourceFile) { - var currentArray = sourceFile.statements; - var currentArrayIndex = 0; - ts.Debug.assert(currentArrayIndex < currentArray.length); - var current = currentArray[currentArrayIndex]; - var lastQueriedPosition = -1; - return { - currentNode: function (position) { - if (position !== lastQueriedPosition) { - if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { - currentArrayIndex++; - current = currentArray[currentArrayIndex]; - } - if (!current || current.pos !== position) { - findHighestListElementThatStartsAtPosition(position); - } - } - lastQueriedPosition = position; - ts.Debug.assert(!current || current.pos === position); - return current; - } - }; - function findHighestListElementThatStartsAtPosition(position) { - currentArray = undefined; - currentArrayIndex = -1; - current = undefined; - forEachChild(sourceFile, visitNode, visitArray); - return; - function visitNode(node) { - if (position >= node.pos && position < node.end) { - forEachChild(node, visitNode, visitArray); - return true; - } - return false; - } - function visitArray(array) { - if (position >= array.pos && position < array.end) { - for (var i = 0; i < array.length; i++) { - var child = array[i]; - if (child) { - if (child.pos === position) { - currentArray = array; - currentArrayIndex = i; - current = child; - return true; - } - else { - if (child.pos < position && position < child.end) { - forEachChild(child, visitNode, visitArray); - return true; - } - } - } - } - } - return false; - } - } - } - 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; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2; - } - else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { - return 0; - } - else if (node.kind === 234) { - var state_1 = 0; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0: - return false; - case 2: - state_1 = 2; - return false; - case 1: - state_1 = 1; - return true; - } - }); - return state_1; - } - else if (node.kind === 233) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1; - } - else if (node.kind === 71 && node.isInJSDocNamespace) { - return 0; - } - else { - return 1; - } - } - 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"); - binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var languageVersion; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - var currentFlow; - var currentBreakTarget; - var currentContinueTarget; - var currentReturnTarget; - var currentTrueTarget; - var currentFalseTarget; - var preSwitchCaseFlow; - var activeLabels; - var hasExplicitReturn; - var emitFlags; - var inStrictMode; - var symbolCount = 0; - var Symbol; - var classifiableNames; - var unreachableFlow = { flags: 1 }; - var reportedUnreachableFlow = { flags: 1 }; - var subtreeTransformFlags = 0; - var skipTransformFlagAggregation; - function bindSourceFile(f, opts) { - file = f; - options = opts; - languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = ts.createMap(); - symbolCount = 0; - skipTransformFlagAggregation = file.isDeclarationFile; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = 0; - subtreeTransformFlags = 0; - } - return bindSourceFile; - function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = ts.createMap(); - } - if (symbolFlags & 6240 && !symbol.members) { - symbol.members = ts.createMap(); - } - if (symbolFlags & 107455) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { - symbol.valueDeclaration = node; - } - } - } - function getDeclarationName(node) { - var name = ts.getNameOfDeclaration(node); - if (name) { - if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; - } - 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 name.text; - } - switch (node.kind) { - case 152: - return "__constructor"; - case 160: - case 155: - return "__call"; - case 161: - case 156: - return "__new"; - case 157: - return "__index"; - case 244: - return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; - case 194: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2: - return "export="; - case 1: - case 4: - case 5: - return node.left.name.text; - case 3: - return node.left.expression.name.text; - } - ts.Debug.fail("Unknown binary declaration kind"); - break; - case 228: - case 229: - return ts.hasModifier(node, 512) ? "default" : undefined; - case 279: - return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 146: - ts.Debug.assert(node.parent.kind === 279); - var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); - return "arg" + index; - case 290: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71) { - nameFromParentNode = nameIdentifier.text; - } - } - } - return nameFromParentNode; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512); - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name === undefined) { - symbol = createSymbol(0, "__missing"); - } - else { - symbol = symbolTable.get(name); - if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0, name)); - } - if (name && (includes & 788448)) { - classifiableNames.set(name, name); - } - if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - symbolTable.set(name, symbol = createSymbol(0, name)); - } - else { - if (node.name) { - node.name.parent = node; - } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - if (symbol.declarations && symbol.declarations.length) { - if (isDefaultExport) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); - } - } - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; - if (symbolFlags & 8388608) { - if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - else { - var isJSDocTypedefInJSDocNamespace = node.kind === 290 && - node.name && - node.name.kind === 71 && - node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793064 ? 2097152 : 0) | - (symbolFlags & 1920 ? 4194304 : 0); - var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - } - function bindContainer(node, containerFlags) { - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - if (containerFlags & 1) { - container = blockScopeContainer = node; - if (containerFlags & 32) { - container.locals = ts.createMap(); - } - addToContainerChain(container); - } - else if (containerFlags & 2) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & 4) { - var saveCurrentFlow = currentFlow; - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - var saveReturnTarget = currentReturnTarget; - var saveActiveLabels = activeLabels; - var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { - currentFlow = { flags: 2 }; - if (containerFlags & (16 | 128)) { - currentFlow.container = node; - } - currentReturnTarget = undefined; - } - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - node.flags &= ~1408; - if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { - node.flags |= 128; - if (hasExplicitReturn) - node.flags |= 256; - } - if (node.kind === 265) { - node.flags |= emitFlags; - } - if (isIIFE) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - } - else { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & 64) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - function bindChildren(node) { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & 536870912) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - function bindEach(nodes) { - if (nodes === undefined) { - return; - } - if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var nodeArrayFlags = 0; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; - bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912; - } - nodes.transformFlags = nodeArrayFlags | 536870912; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - } - function bindEachChild(node) { - ts.forEachChild(node, bind, bindEach); - } - function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } - if (checkUnreachable(node)) { - bindEachChild(node); - return; - } - switch (node.kind) { - case 213: - bindWhileStatement(node); - break; - case 212: - bindDoStatement(node); - break; - case 214: - bindForStatement(node); - break; - case 215: - case 216: - bindForInOrForOfStatement(node); - break; - case 211: - bindIfStatement(node); - break; - case 219: - case 223: - bindReturnOrThrow(node); - break; - case 218: - case 217: - bindBreakOrContinueStatement(node); - break; - case 224: - bindTryStatement(node); - break; - case 221: - bindSwitchStatement(node); - break; - case 235: - bindCaseBlock(node); - break; - case 257: - bindCaseClause(node); - break; - case 222: - bindLabeledStatement(node); - break; - case 192: - bindPrefixUnaryExpressionFlow(node); - break; - case 193: - bindPostfixUnaryExpressionFlow(node); - break; - case 194: - bindBinaryExpressionFlow(node); - break; - case 188: - bindDeleteExpressionFlow(node); - break; - case 195: - bindConditionalExpressionFlow(node); - break; - case 226: - bindVariableDeclarationFlow(node); - break; - case 181: - bindCallExpressionFlow(node); - break; - case 283: - bindJSDocComment(node); - break; - case 290: - bindJSDocTypedefTag(node); - break; - default: - bindEachChild(node); - break; - } - } - function isNarrowingExpression(expr) { - switch (expr.kind) { - case 71: - case 99: - case 179: - return isNarrowableReference(expr); - case 181: - return hasNarrowableArgument(expr); - case 185: - return isNarrowingExpression(expr.expression); - case 194: - return isNarrowingBinaryExpression(expr); - case 192: - return expr.operator === 51 && isNarrowingExpression(expr.operand); - } - return false; - } - function isNarrowableReference(expr) { - return expr.kind === 71 || - expr.kind === 99 || - expr.kind === 97 || - expr.kind === 179 && isNarrowableReference(expr.expression); - } - function hasNarrowableArgument(expr) { - if (expr.arguments) { - for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === 179 && - isNarrowableReference(expr.expression.expression)) { - return true; - } - return false; - } - function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; - } - function isNarrowingBinaryExpression(expr) { - switch (expr.operatorToken.kind) { - case 58: - return isNarrowableReference(expr.left); - case 32: - case 33: - case 34: - case 35: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93: - return isNarrowableOperand(expr.left); - case 26: - return isNarrowingExpression(expr.right); - } - return false; - } - function isNarrowableOperand(expr) { - switch (expr.kind) { - case 185: - return isNarrowableOperand(expr.expression); - case 194: - switch (expr.operatorToken.kind) { - case 58: - return isNarrowableOperand(expr.left); - case 26: - return isNarrowableOperand(expr.right); - } - } - return isNarrowableReference(expr); - } - function createBranchLabel() { - return { - flags: 4, - antecedents: undefined - }; - } - function createLoopLabel() { - return { - flags: 8, - antecedents: undefined - }; - } - function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 512 ? 1024 : 512; - } - function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1) { - return antecedent; - } - if (!expression) { - return flags & 32 ? antecedent : unreachableFlow; - } - if (expression.kind === 101 && flags & 64 || - expression.kind === 86 && flags & 32) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; - } - function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: 128, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; - } - function createFlowAssignment(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 16, - antecedent: antecedent, - node: node - }; - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 256, - antecedent: antecedent, - node: node - }; - } - function finishFlowLabel(flow) { - var antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - function isStatementCondition(node) { - var parent = node.parent; - switch (parent.kind) { - case 211: - case 213: - case 212: - return parent.expression === node; - case 214: - case 195: - return parent.condition === node; - } - return false; - } - function isLogicalExpression(node) { - while (true) { - if (node.kind === 185) { - node = node.expression; - } - else if (node.kind === 192 && node.operator === 51) { - node = node.operand; - } - else { - return node.kind === 194 && (node.operatorToken.kind === 53 || - node.operatorToken.kind === 54); - } - } - } - function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 || - node.parent.kind === 192 && - node.parent.operator === 51) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - function bindCondition(node, trueTarget, falseTarget) { - var saveTrueTarget = currentTrueTarget; - var saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); - } - } - function bindIterativeStatement(node, breakTarget, continueTarget) { - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - function bindWhileStatement(node) { - var preWhileLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - function bindDoStatement(node) { - var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 - ? ts.lastOrUndefined(activeLabels) - : undefined; - var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); - var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - function bindForStatement(node) { - var preLoopLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindForInOrForOfStatement(node) { - var preLoopLabel = createLoopLabel(); - var postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - if (node.kind === 216) { - bind(node.awaitModifier); - } - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== 227) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindIfStatement(node) { - var thenLabel = createBranchLabel(); - var elseLabel = createBranchLabel(); - var postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - function bindReturnOrThrow(node) { - bind(node.expression); - if (node.kind === 219) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - function findActiveLabel(name) { - if (activeLabels) { - for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { - var label = activeLabels_1[_i]; - if (label.name === name) { - return label; - } - } - } - return undefined; - } - function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - function bindBreakOrContinueStatement(node) { - bind(node.label); - if (node.label) { - var activeLabel = findActiveLabel(node.label.text); - if (activeLabel) { - activeLabel.referenced = true; - bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; - } - if (node.finallyBlock) { - var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); - bind(node.finallyBlock); - if (!(currentFlow.flags & 1)) { - if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } - } - if (!(currentFlow.flags & 1)) { - var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; - } - } - else { - currentFlow = finishFlowLabel(preFinallyLabel); - } - } - function bindSwitchStatement(node) { - var postSwitchLabel = createBranchLabel(); - bind(node.expression); - var saveBreakTarget = currentBreakTarget; - var savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - function bindCaseBlock(node) { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var clauses = node.clauses; - var fallthroughFlow = unreachableFlow; - for (var i = 0; i < clauses.length; i++) { - var clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - var clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - clauses.transformFlags = subtreeTransformFlags | 536870912; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - function bindCaseClause(node) { - var saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - bindEach(node.statements); - } - function pushActiveLabel(name, breakTarget, continueTarget) { - var activeLabel = { - name: name, - breakTarget: breakTarget, - continueTarget: continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - function popActiveLabel() { - activeLabels.pop(); - } - function bindLabeledStatement(node) { - var preStatementLabel = createLoopLabel(); - var postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - var activeLabel = pushActiveLabel(node.label.text, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); - } - if (!node.statement || node.statement.kind !== 212) { - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - } - function bindDestructuringTargetFlow(node) { - if (node.kind === 194 && node.operatorToken.kind === 58) { - bindAssignmentTargetFlow(node.left); - } - else { - bindAssignmentTargetFlow(node); - } - } - function bindAssignmentTargetFlow(node) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === 177) { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var e = _a[_i]; - if (e.kind === 198) { - bindAssignmentTargetFlow(e.expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === 178) { - for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { - var p = _c[_b]; - if (p.kind === 261) { - bindDestructuringTargetFlow(p.initializer); - } - else if (p.kind === 262) { - bindAssignmentTargetFlow(p.name); - } - else if (p.kind === 263) { - bindAssignmentTargetFlow(p.expression); - } - } - } - } - function bindLogicalExpression(node, trueTarget, falseTarget) { - var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51) { - var saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - bindEachChild(node); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { - bindAssignmentTargetFlow(node.operand); - } - } - } - function bindPostfixUnaryExpressionFlow(node) { - bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { - bindAssignmentTargetFlow(node.operand); - } - } - function bindBinaryExpressionFlow(node) { - var operator = node.operatorToken.kind; - if (operator === 53 || operator === 54) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - bindEachChild(node); - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 58 && node.left.kind === 180) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - function bindDeleteExpressionFlow(node) { - bindEachChild(node); - if (node.expression.kind === 179) { - bindAssignmentTargetFlow(node.expression); - } - } - function bindConditionalExpressionFlow(node) { - var trueLabel = createBranchLabel(); - var falseLabel = createBranchLabel(); - var postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.questionToken); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.colonToken); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - function bindInitializedVariableFlow(node) { - var name = !ts.isOmittedExpression(node) ? node.name : undefined; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var child = _a[_i]; - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - function bindVariableDeclarationFlow(node) { - bindEachChild(node); - if (node.initializer || node.parent.parent.kind === 215 || node.parent.parent.kind === 216) { - bindInitializedVariableFlow(node); - } - } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 290) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - if (node.fullName && n === node.name && node.fullName.kind !== 71) { - return; - } - bind(n); - }); - } - function bindCallExpressionFlow(node) { - var expr = node.expression; - while (expr.kind === 185) { - expr = expr.expression; - } - if (expr.kind === 186 || expr.kind === 187) { - bindEach(node.typeArguments); - bindEach(node.arguments); - bind(node.expression); - } - else { - bindEachChild(node); - } - if (node.expression.kind === 179) { - var propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 199: - case 229: - case 232: - case 178: - case 163: - case 292: - case 275: - case 254: - return 1; - case 230: - return 1 | 64; - case 279: - case 233: - case 231: - case 172: - return 1 | 32; - case 265: - return 1 | 4 | 32; - case 151: - if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 | 4 | 32 | 8 | 128; - } - case 152: - case 228: - case 150: - case 153: - case 154: - case 155: - case 156: - case 157: - case 160: - case 161: - return 1 | 4 | 32 | 8; - case 186: - case 187: - return 1 | 4 | 32 | 8 | 16; - case 234: - return 4; - case 149: - return node.initializer ? 4 : 0; - case 260: - case 214: - case 215: - case 216: - case 235: - return 2; - case 207: - return ts.isFunctionLike(node.parent) ? 0 : 2; - } - return 0; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { - switch (container.kind) { - case 233: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199: - case 229: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 232: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163: - case 178: - case 230: - case 275: - case 292: - case 254: - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160: - case 161: - case 155: - case 156: - case 157: - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 186: - case 187: - case 279: - case 231: - case 172: - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 265 ? node : node.body; - if (body && (body.kind === 265 || body.kind === 234)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 244 || stat.kind === 243) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 32; - } - else { - node.flags &= ~32; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1)) { - errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (ts.isExternalModuleAugmentation(node)) { - declareModuleSymbol(node); - } - else { - var pattern = void 0; - if (node.name.kind === 9) { - var text = node.name.text; - if (ts.hasZeroOrOneAsteriskCharacter(text)) { - pattern = ts.tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } - } - } - else { - var state = declareModuleSymbol(node); - if (state !== 0) { - if (node.symbol.flags & (16 | 32 | 256)) { - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2; - if (node.symbol.constEnumOnlyModule === undefined) { - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function declareModuleSymbol(node) { - var state = getModuleInstanceState(node); - var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); - return state; - } - function bindFunctionOrConstructorType(node) { - var symbol = createSymbol(131072, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072); - var typeLiteralSymbol = createSymbol(2048, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = ts.createMap(); - 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++) { - var prop = _a[_i]; - if (prop.kind === 263 || prop.name.kind !== 71) { - continue; - } - var identifier = prop.name; - var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 - ? 1 - : 2; - var existingKind = seen.get(identifier.text); - if (!existingKind) { - seen.set(identifier.text, currentKind); - continue; - } - if (currentKind === 1 && existingKind === 1) { - var span_1 = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - return bindAnonymousDeclaration(node, 4096, "__object"); - } - function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); - } - function bindJsxAttribute(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 233: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 265: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 107455); - } - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 108 && - node.originalKeywordKind <= 116 && - !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 71) { - var span_2 = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 71 && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71) { - var identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); - } - } - } - function getStrictModeEvalOrArgumentsMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - } - function getStrictModeBlockScopeFunctionDeclarationMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2) { - if (blockScopeContainer.kind !== 265 && - blockScopeContainer.kind !== 233 && - !ts.isFunctionLike(blockScopeContainer)) { - var errorSpan = ts.getErrorSpanForNode(file, node); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - function checkStrictModePostfixUnaryExpression(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - function checkStrictModePrefixUnaryExpression(node) { - if (inStrictMode) { - if (node.operator === 43 || node.operator === 44) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } - bindWorker(node); - if (node.kind > 142) { - var saveParent = parent; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags === 0) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; - } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 290) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; - } - } - } - } - function updateStrictModeStatementList(statements) { - if (!inStrictMode) { - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - case 71: - if (node.isInJSDocNamespace) { - var parentNode = node.parent; - while (parentNode && parentNode.kind !== 290) { - parentNode = parentNode.parent; - } - bindBlockScopedDeclaration(parentNode, 524288, 793064); - break; - } - case 99: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case 179: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - break; - case 194: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case 1: - bindExportsPropertyAssignment(node); - break; - case 2: - bindModuleExportsAssignment(node); - break; - case 3: - bindPrototypePropertyAssignment(node); - break; - case 4: - bindThisPropertyAssignment(node); - break; - case 5: - bindStaticPropertyAssignment(node); - break; - case 0: - break; - default: - ts.Debug.fail("Unknown special property assignment kind"); - } - return checkStrictModeBinaryExpression(node); - case 260: - return checkStrictModeCatchClause(node); - case 188: - return checkStrictModeDeleteExpression(node); - case 8: - return checkStrictModeNumericLiteral(node); - case 193: - return checkStrictModePostfixUnaryExpression(node); - case 192: - return checkStrictModePrefixUnaryExpression(node); - case 220: - return checkStrictModeWithStatement(node); - case 169: - seenThisKeyword = true; - return; - case 158: - return checkTypePredicate(node); - case 145: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); - case 146: - return bindParameter(node); - case 226: - case 176: - return bindVariableDeclarationOrBindingElement(node); - case 149: - case 148: - case 276: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); - case 291: - return bindJSDocProperty(node); - case 261: - case 262: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 264: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 263: - case 255: - var root = container; - var hasRest = false; - while (root.parent) { - if (root.kind === 178 && - root.parent.kind === 194 && - root.parent.operatorToken.kind === 58 && - root.parent.left === root) { - hasRest = true; - break; - } - root = root.parent; - } - return; - case 155: - case 156: - case 157: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); - case 151: - case 150: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 67108864 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 228: - return bindFunctionDeclaration(node); - case 152: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); - case 153: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); - case 154: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 160: - case 161: - case 279: - return bindFunctionOrConstructorType(node); - case 163: - case 172: - case 292: - case 275: - return bindAnonymousDeclaration(node, 2048, "__type"); - case 178: - return bindObjectLiteralExpression(node); - case 186: - case 187: - return bindFunctionExpression(node); - case 181: - if (ts.isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - case 199: - case 229: - inStrictMode = true; - return bindClassLikeDeclaration(node); - case 230: - return bindBlockScopedDeclaration(node, 64, 792968); - case 290: - if (!node.fullName || node.fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); - } - break; - case 231: - return bindBlockScopedDeclaration(node, 524288, 793064); - case 232: - return bindEnumDeclaration(node); - case 233: - return bindModuleDeclaration(node); - case 254: - return bindJsxAttributes(node); - case 253: - return bindJsxAttribute(node, 4, 0); - case 237: - case 240: - case 242: - case 246: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - case 236: - return bindNamespaceExportDeclaration(node); - case 239: - return bindImportClause(node); - case 244: - return bindExportDeclaration(node); - case 243: - return bindExportAssignment(node); - case 265: - updateStrictModeStatementList(node.statements); - return bindSourceFileIfExternalModule(); - case 207: - if (!ts.isFunctionLike(node.parent)) { - return; - } - case 234: - return updateStrictModeStatementList(node.statements); - } - } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 169) { - seenThisKeyword = true; - } - bind(type); - } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } - function bindExportAssignment(node) { - if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); - } - else { - var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) - ? 8388608 - : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); - } - } - function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); - } - if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); - } - function bindExportDeclaration(node) { - if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 33554432, getDeclarationName(node)); - } - else if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 33554432, 0); - } - } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - } - } - function setCommonJsModuleIndicator(node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } - } - } - function bindExportsPropertyAssignment(node) { - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 7340032, 0); - } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (node.kind === 71) { - var symbol = lookupSymbolForName(node.text); - if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === 226) { - var declaration = symbol.valueDeclaration; - if (declaration.initializer) { - return isExportsOrModuleExportsOrAliasOrAssignemnt(declaration.initializer); - } - } - } - return false; - } - function isExportsOrModuleExportsOrAliasOrAssignemnt(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignemnt(node.left) || isExportsOrModuleExportsOrAliasOrAssignemnt(node.right))); - } - function bindModuleExportsAssignment(node) { - var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { - setCommonJsModuleIndicator(node); - return; - } - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); - } - function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, false); - switch (container.kind) { - case 228: - case 186: - container.symbol.members = container.symbol.members || ts.createMap(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); - break; - case 152: - case 149: - case 151: - case 153: - case 154: - var containingClass = container.parent; - var symbol = declareSymbol(ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members, containingClass.symbol, node, 4, 0); - if (symbol) { - symbol.isReplaceableByMethod = true; - } - break; - } - } - function bindPrototypePropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var classPrototype = leftSideOfAssignment.expression; - var constructorFunction = classPrototype.expression; - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.text, leftSideOfAssignment, true); - } - function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.text, leftSideOfAssignment, false); - } - } - function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; - } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { - return; - } - var symbolTable = isPrototypeProperty ? - (targetSymbol.members || (targetSymbol.members = ts.createMap())) : - (targetSymbol.exports || (targetSymbol.exports = ts.createMap())); - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); - } - function bindCallExpression(node) { - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { - setCommonJsModuleIndicator(node); - } - } - function bindClassLikeDeclaration(node) { - if (node.kind === 229) { - bindBlockScopedDeclaration(node, 32, 899519); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32, bindingName); - if (node.name) { - classifiableNames.set(node.name.text, node.name.text); - } - } - var symbol = node.symbol; - var prototypeSymbol = createSymbol(4 | 16777216, "prototype"); - var symbolExport = symbol.exports.get(prototypeSymbol.name); - if (symbolExport) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports.set(prototypeSymbol.name, prototypeSymbol); - prototypeSymbol.parent = symbol; - } - function bindEnumDeclaration(node) { - return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128, 899967) - : bindBlockScopedDeclaration(node, 256, 899327); - } - function bindVariableDeclarationOrBindingElement(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (!ts.isBindingPattern(node.name)) { - if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 107455); - } - else { - declareSymbolAndAddToSymbolTable(node, 1, 107454); - } - } - } - function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1, 107455); - } - if (ts.isParameterPropertyDeclaration(node)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 67108864 : 0), 0); - } - } - function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 106927); - } - else { - declareSymbolAndAddToSymbolTable(node, 16, 106927); - } - } - function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16, bindingName); - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4, 0); - } - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); - } - function checkUnreachable(node) { - if (!(currentFlow.flags & 1)) { - return false; - } - if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || - node.kind === 229 || - (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentFlow = reportedUnreachableFlow; - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - } - return true; - } - } - function computeTransformFlagsForNode(node, subtreeFlags) { - var kind = node.kind; - switch (kind) { - case 181: - return computeCallExpression(node, subtreeFlags); - case 182: - return computeNewExpression(node, subtreeFlags); - case 233: - return computeModuleDeclaration(node, subtreeFlags); - case 185: - return computeParenthesizedExpression(node, subtreeFlags); - case 194: - return computeBinaryExpression(node, subtreeFlags); - case 210: - return computeExpressionStatement(node, subtreeFlags); - case 146: - return computeParameter(node, subtreeFlags); - case 187: - return computeArrowFunction(node, subtreeFlags); - case 186: - return computeFunctionExpression(node, subtreeFlags); - case 228: - return computeFunctionDeclaration(node, subtreeFlags); - case 226: - return computeVariableDeclaration(node, subtreeFlags); - case 227: - return computeVariableDeclarationList(node, subtreeFlags); - case 208: - return computeVariableStatement(node, subtreeFlags); - case 222: - return computeLabeledStatement(node, subtreeFlags); - case 229: - return computeClassDeclaration(node, subtreeFlags); - case 199: - return computeClassExpression(node, subtreeFlags); - case 259: - return computeHeritageClause(node, subtreeFlags); - case 260: - return computeCatchClause(node, subtreeFlags); - case 201: - return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152: - return computeConstructor(node, subtreeFlags); - case 149: - return computePropertyDeclaration(node, subtreeFlags); - case 151: - return computeMethod(node, subtreeFlags); - case 153: - case 154: - return computeAccessor(node, subtreeFlags); - case 237: - return computeImportEquals(node, subtreeFlags); - case 179: - return computePropertyAccess(node, subtreeFlags); - default: - return computeOther(node, kind, subtreeFlags); - } - } - ts.computeTransformFlagsForNode = computeTransformFlagsForNode; - function computeCallExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (node.typeArguments) { - transformFlags |= 3; - } - if (subtreeFlags & 524288 - || isSuperOrSuperProperty(expression, expressionKind)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97: - return true; - case 179: - case 180: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97; - } - return false; - } - function computeNewExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= 3; - } - if (subtreeFlags & 524288) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function computeBinaryExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var operatorTokenKind = node.operatorToken.kind; - var leftKind = node.left.kind; - if (operatorTokenKind === 58 && leftKind === 178) { - transformFlags |= 8 | 192 | 3072; - } - else if (operatorTokenKind === 58 && leftKind === 177) { - transformFlags |= 192 | 3072; - } - else if (operatorTokenKind === 40 - || operatorTokenKind === 62) { - transformFlags |= 32; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeParameter(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var name = node.name; - var initializer = node.initializer; - var dotDotDotToken = node.dotDotDotToken; - if (node.questionToken - || node.type - || subtreeFlags & 4096 - || ts.isThisIdentifier(name)) { - transformFlags |= 3; - } - if (modifierFlags & 92) { - transformFlags |= 3 | 262144; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { - transformFlags |= 192 | 131072; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeParenthesizedExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 202 - || expressionKind === 184) { - transformFlags |= 3; - } - if (expressionTransformFlags & 1024) { - transformFlags |= 1024; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeClassDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 274432) - || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; - } - function computeClassExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 274432 - || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; - } - function computeHeritageClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - switch (node.token) { - case 85: - transformFlags |= 192; - break; - case 108: - transformFlags |= 3; - break; - default: - ts.Debug.fail("Unexpected token for heritage clause"); - break; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeCatchClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; - } - function computeExpressionWithTypeArguments(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (node.typeArguments) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeConstructor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computeMethod(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (node.decorators - || ts.hasModifier(node, 2270) - || node.typeParameters - || node.type - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computeAccessor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.decorators - || ts.hasModifier(node, 2270) - || node.type - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computePropertyDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags | 3; - if (node.initializer) { - transformFlags |= 8192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeFunctionDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body || (modifierFlags & 2)) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags | 33554432; - if (modifierFlags & 2270 - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (modifierFlags & 256) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 163840) { - transformFlags |= 192; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; - } - function computeFunctionExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 163840) { - transformFlags |= 192; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; - } - function computeArrowFunction(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (ts.hasModifier(node, 2270) - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 16384) { - transformFlags |= 32768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; - } - function computePropertyAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeVariableDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags; - transformFlags |= 192 | 8388608; - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (node.type) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeVariableStatement(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var declarationListTransformFlags = node.declarationList.transformFlags; - if (modifierFlags & 2) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608) { - transformFlags |= 192; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeLabeledStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (subtreeFlags & 4194304 - && ts.isIterationStatement(node, true)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeImportEquals(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeExpressionStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 1024) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3; - var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2) === 0) { - transformFlags |= subtreeFlags; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; - } - function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432; - if (subtreeFlags & 8388608) { - transformFlags |= 192; - } - if (node.flags & 3) { - transformFlags |= 192 | 4194304; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; - } - function computeOther(node, kind, subtreeFlags) { - var transformFlags = subtreeFlags; - var excludeFlags = 536872257; - switch (kind) { - case 120: - case 191: - transformFlags |= 8 | 16; - break; - case 114: - case 112: - case 113: - case 117: - case 124: - case 76: - case 232: - case 264: - case 184: - case 202: - case 203: - case 131: - transformFlags |= 3; - break; - case 249: - case 250: - case 251: - case 10: - case 252: - case 253: - case 254: - case 255: - case 256: - transformFlags |= 4; - break; - case 13: - case 14: - case 15: - case 16: - case 196: - case 183: - case 262: - case 115: - case 204: - transformFlags |= 192; - break; - case 9: - if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192; - } - break; - case 8: - if (node.numericLiteralFlags & 48) { - transformFlags |= 192; - } - break; - case 216: - if (node.awaitModifier) { - transformFlags |= 8; - } - transformFlags |= 192; - break; - case 197: - transformFlags |= 8 | 192 | 16777216; - break; - case 119: - case 133: - case 130: - case 134: - case 136: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 158: - case 159: - case 160: - case 161: - case 162: - case 163: - case 164: - case 165: - case 166: - case 167: - case 168: - case 230: - case 231: - case 169: - case 170: - case 171: - case 172: - case 173: - transformFlags = 3; - excludeFlags = -3; - break; - case 144: - transformFlags |= 2097152; - if (subtreeFlags & 16384) { - transformFlags |= 65536; - } - break; - case 198: - transformFlags |= 192 | 524288; - break; - case 263: - transformFlags |= 8 | 1048576; - break; - case 97: - transformFlags |= 192; - break; - case 99: - transformFlags |= 16384; - break; - case 174: - transformFlags |= 192 | 8388608; - if (subtreeFlags & 524288) { - transformFlags |= 8 | 1048576; - } - excludeFlags = 537396545; - break; - case 175: - transformFlags |= 192 | 8388608; - excludeFlags = 537396545; - break; - case 176: - transformFlags |= 192; - if (node.dotDotDotToken) { - transformFlags |= 524288; - } - break; - case 147: - transformFlags |= 3 | 4096; - break; - case 178: - excludeFlags = 540087617; - if (subtreeFlags & 2097152) { - transformFlags |= 192; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - break; - case 177: - case 182: - excludeFlags = 537396545; - if (subtreeFlags & 524288) { - transformFlags |= 192; - } - break; - case 212: - case 213: - case 214: - case 215: - if (subtreeFlags & 4194304) { - transformFlags |= 192; - } - break; - case 265: - if (subtreeFlags & 32768) { - transformFlags |= 192; - } - break; - case 219: - case 217: - case 218: - transformFlags |= 33554432; - break; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~excludeFlags; - } - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 && kind <= 173) { - return -3; - } - switch (kind) { - case 181: - case 182: - case 177: - return 537396545; - case 233: - return 574674241; - case 146: - return 536872257; - case 187: - return 601249089; - case 186: - case 228: - return 601281857; - case 227: - return 546309441; - case 229: - case 199: - return 539358529; - case 152: - return 601015617; - case 151: - case 153: - case 154: - return 601015617; - case 119: - case 133: - case 130: - case 136: - case 134: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 230: - case 231: - return -3; - case 178: - return 540087617; - case 260: - return 537920833; - case 174: - case 175: - return 537396545; - default: - return 536872257; - } - } - ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; -})(ts || (ts = {})); -var ts; -(function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; - var nextSymbolId = 1; - var nextNodeId = 1; - var nextMergeId = 1; - var nextFlowId = 1; - function getNodeId(node) { - if (!node.id) { - node.id = nextNodeId; - nextNodeId++; - } - return node.id; - } - ts.getNodeId = getNodeId; - function getSymbolId(symbol) { - if (!symbol.id) { - symbol.id = nextSymbolId; - nextSymbolId++; - } - return symbol.id; - } - ts.getSymbolId = getSymbolId; - function createTypeChecker(host, produceDiagnostics) { - var cancellationToken; - var requestedExternalEmitHelpers; - var externalHelpersModule; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var Type = ts.objectAllocator.getTypeConstructor(); - var Signature = ts.objectAllocator.getSignatureConstructor(); - var typeCount = 0; - var symbolCount = 0; - var enumCount = 0; - var symbolInstantiationDepth = 0; - var emptyArray = []; - var emptySymbols = ts.createMap(); - var compilerOptions = host.getCompilerOptions(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); - var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; - var emitResolver = createResolver(); - var nodeBuilder = createNodeBuilder(); - var undefinedSymbol = createSymbol(4, "undefined"); - undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4, "arguments"); - var checker = { - getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCount: function () { return typeCount; }, - isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, - isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, - isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, - getMergedSymbol: getMergedSymbol, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeOfSymbolAtLocation: function (symbol, location) { - location = ts.getParseTreeNode(location); - return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; - }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); - return getSymbolsOfParameterPropertyDeclaration(parameter, parameterName); - }, - getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, - getPropertiesOfType: getPropertiesOfType, - getPropertyOfType: getPropertyOfType, - getIndexInfoOfType: getIndexInfoOfType, - getSignaturesOfType: getSignaturesOfType, - getIndexTypeOfType: getIndexTypeOfType, - getBaseTypes: getBaseTypes, - getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, - getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); - return node ? getTypeFromTypeNode(node) : unknownType; - }, - getParameterType: getTypeAtPosition, - getReturnTypeOfSignature: getReturnTypeOfSignature, - getNonNullableType: getNonNullableType, - typeToTypeNode: nodeBuilder.typeToTypeNode, - indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, - signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, - getSymbolsInScope: function (location, meaning) { - location = ts.getParseTreeNode(location); - return location ? getSymbolsInScope(location, meaning) : []; - }, - getSymbolAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getSymbolAtLocation(node) : undefined; - }, - getShorthandAssignmentValueSymbol: function (node) { - node = ts.getParseTreeNode(node); - return node ? getShorthandAssignmentValueSymbol(node) : undefined; - }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); - return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; - }, - getTypeAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getTypeOfNode(node) : unknownType; - }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); - return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; - }, - signatureToString: function (signature, enclosingDeclaration, flags, kind) { - return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); - }, - typeToString: function (type, enclosingDeclaration, flags) { - return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); - }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); - }, - getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, - getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); - return node ? getContextualType(node) : undefined; - }, - getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); - return node ? getResolvedSignature(node, candidatesOutArray) : undefined; - }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, propertyName) : false; - }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); - return declaration ? getSignatureFromDeclaration(declaration) : undefined; - }, - isImplementationOfOverload: function (node) { - node = ts.getParseTreeNode(node, ts.isFunctionLike); - return node ? isImplementationOfOverload(node) : undefined; - }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - links.immediateTarget = getTargetOfAliasDeclaration(node, true); - } - return links.immediateTarget; - }, - getAliasedSymbol: resolveAlias, - getEmitResolver: getEmitResolver, - getExportsOfModule: getExportsOfModuleAsArray, - getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); - return node ? isOptionalParameter(node) : false; - }, - tryGetMemberInModuleExports: tryGetMemberInModuleExports, - tryFindAmbientModuleWithoutAugmentations: function (moduleName) { - return tryFindAmbientModule(moduleName, false); - }, - getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, - getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, - getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, - getBaseConstraintOfType: getBaseConstraintOfType, - }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var literalTypes = ts.createMap(); - var indexedAccessTypes = ts.createMap(); - var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4, "unknown"); - var resolvingSymbol = createSymbol(0, "__resolving__"); - var anyType = createIntrinsicType(1, "any"); - var autoType = createIntrinsicType(1, "any"); - var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); - var stringType = createIntrinsicType(2, "string"); - var numberType = createIntrinsicType(4, "number"); - var trueType = createIntrinsicType(128, "true"); - var falseType = createIntrinsicType(128, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); - var silentNeverType = createIntrinsicType(8192, "never"); - var nonPrimitiveType = createIntrinsicType(16777216, "object"); - var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); - emptyTypeLiteralSymbol.members = ts.createMap(); - var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); - var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; - var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, undefined, 0, false, false); - var enumNumberIndexInfo = createIndexInfo(stringType, true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); - var globals = ts.createMap(); - var patternAmbientModules; - var globalObjectType; - var globalFunctionType; - var globalArrayType; - var globalReadonlyArrayType; - var globalStringType; - var globalNumberType; - var globalBooleanType; - var globalRegExpType; - var globalThisType; - var anyArrayType; - var autoArrayType; - var anyReadonlyArrayType; - var deferredGlobalESSymbolConstructorSymbol; - var deferredGlobalESSymbolType; - var deferredGlobalTypedPropertyDescriptorType; - var deferredGlobalPromiseType; - var deferredGlobalPromiseConstructorSymbol; - var deferredGlobalPromiseConstructorLikeType; - var deferredGlobalIterableType; - var deferredGlobalIteratorType; - var deferredGlobalIterableIteratorType; - var deferredGlobalAsyncIterableType; - var deferredGlobalAsyncIteratorType; - var deferredGlobalAsyncIterableIteratorType; - var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; - var deferredNodes; - var deferredUnusedIdentifierNodes; - var flowLoopStart = 0; - var flowLoopCount = 0; - var visitedFlowCount = 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 = []; - var flowLoopCaches = []; - var flowLoopNodes = []; - var flowLoopKeys = []; - var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; - var potentialThisCollisions = []; - 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, - "boolean": 4, - "symbol": 8, - "undefined": 16384, - "object": 16, - "function": 32 - }); - var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128, - "number": 256, - "boolean": 512, - "symbol": 1024, - "undefined": 131072, - "object": 2048, - "function": 4096 - }); - var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType - }); - var typeofType = createTypeofType(); - var _jsxNamespace; - var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - var jsxTypes = ts.createMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - 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(); - return checker; - function getJsxNamespace() { - if (!_jsxNamespace) { - _jsxNamespace = "React"; - if (compilerOptions.jsxFactory) { - _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); - if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; - } - } - else if (compilerOptions.reactNamespace) { - _jsxNamespace = compilerOptions.reactNamespace; - } - } - return _jsxNamespace; - } - function getEmitResolver(sourceFile, cancellationToken) { - getDiagnostics(sourceFile, cancellationToken); - return emitResolver; - } - function error(location, message, arg0, arg1, arg2) { - var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); - diagnostics.add(diagnostic); - } - function createSymbol(flags, name) { - symbolCount++; - var symbol = (new Symbol(flags | 134217728, name)); - symbol.checkFlags = 0; - return symbol; - } - function isTransientSymbol(symbol) { - return (symbol.flags & 134217728) !== 0; - } - function getExcludedSymbolFlags(flags) { - var result = 0; - if (flags & 2) - result |= 107455; - if (flags & 1) - result |= 107454; - if (flags & 4) - result |= 0; - if (flags & 8) - result |= 900095; - if (flags & 16) - result |= 106927; - if (flags & 32) - result |= 899519; - if (flags & 64) - result |= 792968; - if (flags & 256) - result |= 899327; - if (flags & 128) - result |= 899967; - if (flags & 512) - result |= 106639; - if (flags & 8192) - result |= 99263; - if (flags & 32768) - result |= 41919; - if (flags & 65536) - result |= 74687; - if (flags & 262144) - result |= 530920; - if (flags & 524288) - result |= 793064; - if (flags & 8388608) - result |= 8388608; - return result; - } - function recordMergedSymbol(target, source) { - if (!source.mergeId) { - source.mergeId = nextMergeId; - nextMergeId++; - } - mergedSymbols[source.mergeId] = target; - } - function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags, symbol.name); - result.declarations = symbol.declarations.slice(0); - result.parent = symbol.parent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = ts.cloneMap(symbol.members); - if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); - recordMergedSymbol(result, symbol); - return result; - } - function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { - if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { - target.constEnumOnlyModule = false; - } - target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { - target.valueDeclaration = source.valueDeclaration; - } - ts.addRange(target.declarations, source.declarations); - if (source.members) { - if (!target.members) - target.members = ts.createMap(); - mergeSymbolTable(target.members, source.members); - } - if (source.exports) { - if (!target.exports) - target.exports = ts.createMap(); - mergeSymbolTable(target.exports, source.exports); - } - recordMergedSymbol(target, source); - } - else if (target.flags & 1024) { - 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - } - } - function mergeSymbolTable(target, source) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - } - else { - if (!(targetSymbol.flags & 134217728)) { - targetSymbol = cloneSymbol(targetSymbol); - target.set(id, targetSymbol); - } - mergeSymbol(targetSymbol, sourceSymbol); - } - }); - } - function mergeModuleAugmentation(moduleName) { - var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { - ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); - return; - } - if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports); - } - else { - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) - ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found - : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); - if (!mainModule) { - return; - } - mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920) { - mainModule = mainModule.flags & 134217728 ? mainModule : cloneSymbol(mainModule); - mergeSymbol(mainModule, moduleAugmentation.symbol); - } - else { - error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); - } - } - } - function addToSymbolTable(target, source, message) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (targetSymbol) { - ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(id, message)); - } - else { - target.set(id, sourceSymbol); - } - }); - function addDeclarationDiagnostic(id, message) { - return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; - } - } - function getSymbolLinks(symbol) { - if (symbol.flags & 134217728) - return symbol; - var id = getSymbolId(symbol); - return symbolLinks[id] || (symbolLinks[id] = {}); - } - function getNodeLinks(node) { - var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); - } - function getObjectFlags(type) { - return type.flags & 32768 ? type.objectFlags : 0; - } - function isGlobalSourceFile(node) { - return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); - } - function getSymbol(symbols, name, meaning) { - if (meaning) { - var symbol = symbols.get(name); - if (symbol) { - ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } - } - } - } - function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { - var constructorDeclaration = parameter.parent; - var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); - if (parameterSymbol && propertySymbol) { - return [parameterSymbol, propertySymbol]; - } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); - } - function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { - var declarationFile = ts.getSourceFileOfNode(declaration); - var useFile = ts.getSourceFileOfNode(usage); - if (declarationFile !== useFile) { - if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out) || - ts.isInAmbientContext(declaration)) { - return true; - } - if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - return true; - } - var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); - } - if (declaration.pos <= usage.pos) { - if (declaration.kind === 176) { - var errorBindingElement = ts.getAncestor(usage, 176); - if (errorBindingElement) { - return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || - declaration.pos < errorBindingElement.pos; - } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); - } - else if (declaration.kind === 226) { - return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); - } - return true; - } - if (usage.parent.kind === 246) { - return true; - } - var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); - function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); - switch (declaration.parent.parent.kind) { - case 208: - case 214: - case 216: - if (isSameScopeDescendentOf(usage, declaration, container)) { - return true; - } - break; - } - switch (declaration.parent.parent.kind) { - case 215: - case 216: - if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { - return true; - } - } - return false; - } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { - return !!ts.findAncestor(usage, function (current) { - if (current === container) { - return "quit"; - } - if (ts.isFunctionLike(current)) { - return true; - } - var initializerOfProperty = current.parent && - current.parent.kind === 149 && - current.parent.initializer === current; - if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32) { - if (declaration.kind === 151) { - return true; - } - } - else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); - if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { - return true; - } - } - } - }); - } - } - 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; - var errorLocation = location; - var grandparent; - var isInExternalModule = false; - loop: while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - 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) { - useResult = result.flags & 262144 - ? lastLocation === location.type || - lastLocation.kind === 146 || - lastLocation.kind === 145 - : false; - } - if (meaning & 107455 && result.flags & 1) { - useResult = - lastLocation.kind === 146 || - (lastLocation === location.type && - result.valueDeclaration.kind === 146); - } - } - if (useResult) { - break loop; - } - else { - result = undefined; - } - } - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) - break; - isInExternalModule = true; - case 233: - var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 || ts.isAmbientModule(location)) { - if (result = moduleExports.get("default")) { - var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { - break loop; - } - result = undefined; - } - var moduleExport = moduleExports.get(name); - if (moduleExport && - moduleExport.flags === 8388608 && - ts.getDeclarationOfKind(moduleExport, 246)) { - break; - } - } - if (result = lookup(moduleExports, name, meaning & 8914931)) { - break loop; - } - break; - case 232: - if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { - break loop; - } - break; - case 149: - case 148: - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { - var ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455)) { - propertyWithInvalidInitializer = location; - } - } - } - break; - case 229: - case 199: - case 230: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { - if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { - result = undefined; - break; - } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); - return undefined; - } - break loop; - } - if (location.kind === 199 && meaning & 32) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; - case 144: - grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - 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; - } - } - break; - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 187: - if (meaning & 3 && name === "arguments") { - result = argumentsSymbol; - break loop; - } - break; - case 186: - if (meaning & 3 && name === "arguments") { - result = argumentsSymbol; - break loop; - } - if (meaning & 16) { - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; - } - } - break; - case 147: - if (location.parent && location.parent.kind === 146) { - location = location.parent; - } - if (location.parent && ts.isClassElement(location.parent)) { - location = location.parent; - } - break; - } - lastLocation = location; - location = location.parent; - } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { - result.isReferenced = true; - } - if (!result) { - result = lookup(globals, name, meaning); - } - if (!result) { - if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation) && - !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && - !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - 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; - } - if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer) { - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return undefined; - } - if (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455)) { - var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); - if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { - checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); - } - } - if (result && isInExternalModule && (meaning & 107455) === 107455) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); - } - } - } - return result; - } - function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 145 && decl.parent === container) { - return true; - } - } - return false; - } - function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 71 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { - return false; - } - var container = ts.getThisContainer(errorLocation, true); - var location = container; - while (location) { - if (ts.isClassLike(location.parent)) { - var classSymbol = getSymbolOfNode(location.parent); - if (!classSymbol) { - break; - } - var constructorType = getTypeOfSymbol(classSymbol); - if (getPropertyOfType(constructorType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); - return true; - } - if (location === container && !(ts.getModifierFlags(location) & 32)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; - if (getPropertyOfType(instanceType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return true; - } - } - } - location = location.parent; - } - return false; - } - function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { - error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - } - return isError; - } - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 71: - case 179: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } - } - function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); - return true; - } - } - return false; - } - 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); - return true; - } - } - return false; - } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (107455 & ~1024 & ~793064)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, name); - return true; - } - } - else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, name); - return true; - } - } - return false; - } - function checkResolvedBlockScopedVariable(result, errorLocation) { - ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); - 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(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 256) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - } - } - function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); - } - function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237) { - return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); - } - } - function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); - } - function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248) { - return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); - } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); - } - function getTargetOfImportClause(node, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); - if (moduleSymbol) { - var exportDefaultSymbol = void 0; - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - exportDefaultSymbol = moduleSymbol; - } - else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); - } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { - return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - return exportDefaultSymbol; - } - } - function getTargetOfNamespaceImport(node, dontResolveAlias) { - var moduleSpecifier = node.parent.parent.moduleSpecifier; - return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); - } - function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 | 1920)) { - return valueSymbol; - } - var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); - result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); - result.parent = valueSymbol.parent || typeSymbol.parent; - if (valueSymbol.valueDeclaration) - result.valueDeclaration = valueSymbol.valueDeclaration; - if (typeSymbol.members) - result.members = typeSymbol.members; - if (valueSymbol.exports) - result.exports = valueSymbol.exports; - return result; - } - function getExportOfModule(symbol, name, dontResolveAlias) { - if (symbol.flags & 1536) { - return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); - } - } - function getPropertyOfVariable(symbol, name) { - if (symbol.flags & 3) { - var typeAnnotation = symbol.valueDeclaration.type; - if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); - } - } - } - function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); - if (targetSymbol) { - var name = specifier.propertyName || specifier.name; - if (name.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return moduleSymbol; - } - var symbolFromVariable = void 0; - if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text); - } - else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); - } - symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name.text, dontResolveAlias); - if (!symbolFromModule && allowSyntheticDefaultImports && name.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - var symbol = symbolFromModule && symbolFromVariable ? - combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : - symbolFromModule || symbolFromVariable; - if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); - } - return symbol; - } - } - } - function getTargetOfImportSpecifier(node, dontResolveAlias) { - return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); - } - function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { - return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); - } - function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); - } - function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); - } - function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { - switch (node.kind) { - case 237: - return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239: - return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240: - return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242: - return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246: - return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); - case 243: - return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236: - return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - } - } - function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)); - return shouldResolve ? resolveAlias(symbol) : symbol; - } - function resolveAlias(symbol) { - ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.target) { - links.target = resolvingSymbol; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - var target = getTargetOfAliasDeclaration(node); - if (links.target === resolvingSymbol) { - links.target = target || unknownSymbol; - } - else { - error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); - } - } - else if (links.target === resolvingSymbol) { - links.target = unknownSymbol; - } - return links.target; - } - function markExportAsReferenced(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target) { - var markAlias = target === unknownSymbol || - ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); - if (markAlias) { - markAliasSymbolAsReferenced(symbol); - } - } - } - function markAliasSymbolAsReferenced(symbol) { - var links = getSymbolLinks(symbol); - if (!links.referenced) { - links.referenced = true; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - if (node.kind === 243) { - checkExpressionCached(node.expression); - } - else if (node.kind === 246) { - checkExpressionCached(node.propertyName || node.name); - } - else if (ts.isInternalModuleImportEqualsDeclaration(node)) { - checkExpressionCached(node.moduleReference); - } - } - } - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (entityName.kind === 71 || entityName.parent.kind === 143) { - return resolveEntityName(entityName, 1920, false, dontResolveAlias); - } - else { - ts.Debug.assert(entityName.parent.kind === 237); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); - } - } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); - } - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { - if (ts.nodeIsMissing(name)) { - return undefined; - } - var symbol; - if (name.kind === 71) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); - if (!symbol) { - return undefined; - } - } - else if (name.kind === 143 || name.kind === 179) { - var left = void 0; - if (name.kind === 143) { - left = name.left; - } - else if (name.kind === 179 && - (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { - left = name.expression; - } - else { - return undefined; - } - var right = name.kind === 143 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); - if (!namespace || ts.nodeIsMissing(right)) { - return undefined; - } - else if (namespace === unknownSymbol) { - return namespace; - } - symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); - if (!symbol) { - if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); - } - return undefined; - } - } - else if (name.kind === 185) { - return ts.isEntityNameExpression(name.expression) ? - resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : - undefined; - } - else { - ts.Debug.fail("Unknown entity name kind."); - } - 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) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); - } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - if (moduleReferenceExpression.kind !== 9 && moduleReferenceExpression.kind !== 13) { - return; - } - var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); - } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - var moduleName = ts.escapeIdentifier(moduleReference); - 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; - } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); - var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); - if (sourceFile) { - if (sourceFile.symbol) { - return getMergedSymbol(sourceFile.symbol); - } - if (moduleNotFoundError) { - error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - } - return undefined; - } - if (patternAmbientModules) { - var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleName); - if (pattern) { - return getMergedSymbol(pattern.symbol); - } - } - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { - if (isForAugmentation) { - var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); - } - else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return undefined; - } - if (moduleNotFoundError) { - if (resolutionDiagnostic) { - error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); - } - else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(errorNode, moduleNotFoundError, moduleName); - } - } - } - return undefined; - } - function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; - } - function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { - 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)); - } - return symbol; - } - function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; - } - function getExportsOfModuleAsArray(moduleSymbol) { - return symbolsToArray(getExportsOfModule(moduleSymbol)); - } - function getExportsAndPropertiesOfModule(moduleSymbol) { - var exports = getExportsOfModuleAsArray(moduleSymbol); - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); - } - return exports; - } - function tryGetMemberInModuleExports(memberName, moduleSymbol) { - var symbolTable = getExportsOfModule(moduleSymbol); - if (symbolTable) { - return symbolTable.get(memberName); - } - } - function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; - } - function getExportsOfModule(moduleSymbol) { - var links = getSymbolLinks(moduleSymbol); - return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); - } - function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { - if (id === "default") - return; - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - if (lookupTable && exportNode) { - lookupTable.set(id, { - specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) - }); - } - } - else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { - var collisionTracker = lookupTable.get(id); - if (!collisionTracker.exportsWithDuplicate) { - collisionTracker.exportsWithDuplicate = [exportNode]; - } - else { - collisionTracker.exportsWithDuplicate.push(exportNode); - } - } - }); - } - function getExportsForModule(moduleSymbol) { - var visitedSymbols = []; - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - return visit(moduleSymbol) || moduleSymbol.exports; - function visit(symbol) { - if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { - return; - } - visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); - var exportStars = symbol.exports.get("__export"); - if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable_1 = ts.createMap(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); - } - lookupTable_1.forEach(function (_a, id) { - var exportsWithDuplicate = _a.exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { - return; - } - for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { - var node = exportsWithDuplicate_1[_i]; - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, id)); - } - }); - extendExportSymbols(symbols, nestedSymbols); - } - return symbols; - } - } - function getMergedSymbol(symbol) { - var merged; - return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; - } - function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); - } - function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); - } - function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; - } - function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 || symbol.flags & 8388608 && resolveAlias(symbol).flags & 107455); - } - function findConstructorDeclaration(node) { - var members = node.members; - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var member = members_1[_i]; - if (member.kind === 152 && ts.nodeIsPresent(member.body)) { - return member; - } - } - } - function createType(flags) { - var result = new Type(checker, flags); - typeCount++; - result.id = typeCount; - return result; - } - function createIntrinsicType(kind, intrinsicName) { - var type = createType(kind); - type.intrinsicName = intrinsicName; - return type; - } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8; - type.intrinsicName = "boolean"; - return type; - } - function createObjectType(objectFlags, symbol) { - var type = createType(32768); - type.objectFlags = objectFlags; - type.symbol = symbol; - return type; - } - function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); - } - function isReservedMemberName(name) { - return name.charCodeAt(0) === 95 && - name.charCodeAt(1) === 95 && - name.charCodeAt(2) !== 95 && - name.charCodeAt(2) !== 64; - } - function getNamedMembers(members) { - var result; - members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } - } - }); - return result || emptyArray; - } - function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; - return type; - } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function forEachSymbolTableInScope(enclosingDeclaration, callback) { - var result; - for (var location = enclosingDeclaration; location; location = location.parent) { - if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { - return result; - } - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - case 233: - if (result = callback(getSymbolOfNode(location).exports)) { - return result; - } - break; - } - } - return callback(globals); - } - function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; - } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); - } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { - return undefined; - } - visitedSymbolTables.push(symbols); - var result = trySymbolTable(symbols); - visitedSymbolTables.pop(); - return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } - } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.name))) { - return [symbol]; - } - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } - } - }); - } - } - if (symbol) { - if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - } - } - } - function needsQualification(symbol, enclosingDeclaration, meaning) { - var qualify = false; - forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable.get(symbol.name); - if (!symbolFromSymbolTable) { - return false; - } - if (symbolFromSymbolTable === symbol) { - return true; - } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { - qualify = true; - return true; - } - return false; - }); - return qualify; - } - function isPropertyOrMethodDeclarationSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - switch (declaration.kind) { - case 149: - case 151: - case 153: - case 154: - continue; - default: - return false; - } - } - return true; - } - return false; - } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, - }; - } - return hasAccessibleDeclarations; - } - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); - } - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); - if (symbolExternalModule) { - var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); - if (symbolExternalModule !== enclosingExternalModule) { - return { - accessibility: 2, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) - }; - } - } - return { - accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - }; - } - return { accessibility: 0 }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } - } - function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); - } - function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { - var aliasesToMakeVisible; - if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { - return undefined; - } - return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; - function getIsDeclarationVisible(declaration) { - if (!isDeclarationVisible(declaration)) { - var anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1) && - isDeclarationVisible(anyImportSyntax.parent)) { - if (shouldComputeAliasToMakeVisible) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } - } - return true; - } - return false; - } - return true; - } - } - function isEntityNameVisible(entityName, enclosingDeclaration) { - var meaning; - if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning = 107455 | 1048576; - } - else if (entityName.kind === 143 || entityName.kind === 179 || - entityName.parent.kind === 237) { - meaning = 1920; - } - else { - meaning = 793064; - } - var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol, true)) || { - accessibility: 1, - errorSymbolName: ts.getTextOfNode(firstIdentifier), - errorNode: firstIdentifier - }; - } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function typeToString(type, enclosingDeclaration, flags) { - 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) { - 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() { - return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - 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) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - } - }; - function createNodeBuilderContext(enclosingDeclaration, flags) { - return { - enclosingDeclaration: enclosingDeclaration, - flags: flags, - encounteredError: false, - symbolStack: undefined - }; - } - function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; - if (!type) { - context.encounteredError = true; - return undefined; - } - if (type.flags & 1) { - return ts.createKeywordTypeNode(119); - } - if (type.flags & 2) { - return ts.createKeywordTypeNode(136); - } - if (type.flags & 4) { - return ts.createKeywordTypeNode(133); - } - if (type.flags & 8) { - return ts.createKeywordTypeNode(122); - } - 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.setEmitFlags(ts.createLiteral(type.value), 16777216)); - } - if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.value))); - } - if (type.flags & 128) { - return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); - } - if (type.flags & 1024) { - return ts.createKeywordTypeNode(105); - } - if (type.flags & 2048) { - return ts.createKeywordTypeNode(139); - } - if (type.flags & 4096) { - return ts.createKeywordTypeNode(95); - } - if (type.flags & 8192) { - return ts.createKeywordTypeNode(130); - } - if (type.flags & 512) { - return ts.createKeywordTypeNode(137); - } - if (type.flags & 16777216) { - return ts.createKeywordTypeNode(134); - } - if (type.flags & 16384 && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { - context.encounteredError = true; - } - } - return ts.createThis(); - } - var objectFlags = getObjectFlags(type); - if (objectFlags & 4) { - ts.Debug.assert(!!(type.flags & 32768)); - return typeReferenceToTypeNode(type); - } - if (type.flags & 16384 || objectFlags & 3) { - var name = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name, undefined); - } - 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); - } - 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)) { - context.encounteredError = true; - } - return undefined; - } - } - 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, context); - return ts.createTypeOperatorNode(indexTypeNode); - } - if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); - var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); - return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); - } - ts.Debug.fail("Should be unreachable."); - function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768)); - var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; - var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - 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; - if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 | 512) || - shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455); - } - else if (ts.contains(context.symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - var entityName = symbolToName(typeAlias, context, 793064, false); - return ts.createTypeReferenceNode(entityName, undefined); - } - else { - return ts.createKeywordTypeNode(119); - } - } - else { - if (!context.symbolStack) { - context.symbolStack = []; - } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; - } - } - else { - return createTypeNodeFromObjectType(type); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); - } - } - } - function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - return createMappedTypeNodeFromType(type); - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); - return signatureNode; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); - return signatureNode; - } - } - var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; - var members = createTypeNodesFromResolvedType(resolved); - context.flags = savedFlags; - var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); - } - 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) { - 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - return ts.createTupleTypeNode(tupleConstituentNodes); - } - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { - context.encounteredError = true; - } - return undefined; - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - var qualifiedName = void 0; - if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - 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 { - qualifiedName = ts.createQualifiedName(namePart, undefined); - } - } - } - } - var entityName = undefined; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } - 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, context)); - } - for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); - } - if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); - } - if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); - } - var properties = resolvedType.properties; - if (!properties) { - return typeElements; - } - for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { - var propertySymbol = properties_2[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); - 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, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - typeElements.push(methodDeclaration); - } - } - else { - 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 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 ? 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.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, context); - } - 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, context) { - var name = symbolToName(type.symbol, context, 793064, true); - var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); - var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); - } - 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); - 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, context, meaning, expectsIdentifier) { - var chain; - var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { - chain = getSymbolChain(symbol, meaning, true); - ts.Debug.assert(chain && chain.length > 0); - } - else { - chain = [symbol]; - } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(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 typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - 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) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); - var parentSymbol; - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); - } - } - } - if (accessibleSymbolChain) { - return accessibleSymbolChain; - } - if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - return [symbol]; - } - } - } - 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; - } - } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144)) { - if (t.flags & (128 | 256)) { - 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); - } - } - if (flags & 4096) - result.push(nullType); - if (flags & 2048) - result.push(undefinedType); - return result || types; - } - function visibilityToString(flags) { - if (flags === 8) { - return "private"; - } - if (flags === 16) { - return "protected"; - } - return "public"; - } - function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); - if (node.kind === 231) { - return getSymbolOfNode(node); - } - } - return undefined; - } - function isTopLevelInExternalModuleAugmentation(node) { - return node && node.parent && - node.parent.kind === 234 && - ts.isExternalModuleAugmentation(node.parent.parent); - } - function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; - } - function getNameOfSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } - } - return symbol.name; - } - function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); - } - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - writePunctuation(writer, 21); - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 23); - writer.writeSymbol(symbolName, symbol); - } - } - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 128 & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & 16; - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~512; - if (type.flags & 16793231) { - writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 16384 && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (getObjectFlags(type) & 4) { - writeTypeReference(type, nextFlags); - } - 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 & (272 | 16384)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 512) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 196608) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (getObjectFlags(type) & (16 | 32)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 96) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 262144) { - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 64); - } - else if (type.flags & 524288) { - writeType(type.objectType, 64); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 17); - writeSpace(writer); - writePunctuation(writer, 24); - writeSpace(writer); - writePunctuation(writer, 18); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 ? 0 : 64); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); - } - if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 256); - pos++; - while (pos < end) { - writePunctuation(writer, 26); - writeSpace(writer); - writeType(typeArguments[pos], 0); - pos++; - } - writePunctuation(writer, 29); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 64); - writePunctuation(writer, 21); - writePunctuation(writer, 22); - } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23); - } - } - } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 64) { - writePunctuation(writer, 19); - } - if (type.flags & 65536) { - writeTypeList(formatUnionTypes(type.types), 49); - } - else { - writeTypeList(type.types, 48); - } - if (flags & 64) { - writePunctuation(writer, 20); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); - } - else if (ts.contains(symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); - } - else { - writeKeyword(writer, 119); - } - } - else { - if (!symbolStack) { - symbolStack = []; - } - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - else { - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 2) || - (ts.contains(symbolStack, symbol)); - } - } - } - function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 103); - writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); - writeSpace(writer); - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 67108864) { - writePunctuation(writer, 55); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 64) { - return true; - } - else if (flags & 256) { - var typeParameters = callSignature.target && (flags & 32) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - writeMappedType(type); - return; - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 64) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 94); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); - if (flags & 64) { - writePunctuation(writer, 20); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56); - writeSpace(writer); - writeType(t, 0); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); - if (type.declaration.questionToken) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 174) { - writePunctuation(writer, 17); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); - } - else if (bindingPattern.kind === 175) { - writePunctuation(writer, 21); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); - } - writePunctuation(writer, 22); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 176); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 256; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - flags = 0; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99); - } - writeSpace(writer); - writeKeyword(writer, 126); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 2048 && isTypeAny(returnType)) { - return; - } - if (flags & 8) { - writeSpace(writer); - writePunctuation(writer, 36); - } - else { - writePunctuation(writer, 56); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); - writeSpace(writer); - } - if (signature.target && (flags & 32)) { - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); - writeSpace(writer); - switch (kind) { - case 1: - writeKeyword(writer, 133); - break; - case 0: - writeKeyword(writer, 136); - break; - } - writePunctuation(writer, 22); - writePunctuation(writer, 56); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } - function isDeclarationVisible(node) { - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } - return false; - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 176: - return isDeclarationVisible(node.parent.parent); - case 226: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - return false; - } - case 233: - case 229: - case 230: - case 231: - case 228: - case 232: - case 237: - if (ts.isExternalModuleAugmentation(node)) { - return true; - } - var parent = getDeclarationContainer(node); - if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { - return isGlobalSourceFile(parent); - } - return isDeclarationVisible(parent); - case 149: - case 148: - case 153: - case 154: - case 151: - case 150: - if (ts.getModifierFlags(node) & (8 | 16)) { - return false; - } - case 152: - case 156: - case 155: - case 157: - case 146: - case 234: - case 160: - case 161: - case 163: - case 159: - case 164: - case 165: - case 166: - case 167: - case 168: - return isDeclarationVisible(node.parent); - case 239: - case 240: - case 242: - return false; - case 145: - case 265: - case 236: - return true; - case 243: - return false; - default: - return false; - } - } - } - function collectLinkedAliases(node) { - var exportSymbol; - if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); - } - else if (node.parent.kind === 246) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); - } - var result = []; - if (exportSymbol) { - buildVisibleNodeList(exportSymbol.declarations); - } - return result; - function buildVisibleNodeList(declarations) { - ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; - var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } - if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { - var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); - if (importSymbol) { - buildVisibleNodeList(importSymbol.declarations); - } - } - }); - } - } - function pushTypeResolution(target, propertyName) { - var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); - if (resolutionCycleStartIndex >= 0) { - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { - resolutionResults[i] = false; - } - return false; - } - resolutionTargets.push(target); - resolutionResults.push(true); - resolutionPropertyNames.push(propertyName); - return true; - } - function findResolutionCycleStartIndex(target, propertyName) { - for (var i = resolutionTargets.length - 1; i >= 0; i--) { - if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { - return -1; - } - if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { - return i; - } - } - return -1; - } - function hasType(target, propertyName) { - if (propertyName === 0) { - return getSymbolLinks(target).type; - } - if (propertyName === 2) { - return getSymbolLinks(target).declaredType; - } - if (propertyName === 1) { - return target.resolvedBaseConstructorType; - } - if (propertyName === 3) { - return target.resolvedReturnType; - } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); - } - function popTypeResolution() { - resolutionTargets.pop(); - resolutionPropertyNames.pop(); - return resolutionResults.pop(); - } - function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { - switch (node.kind) { - case 226: - case 227: - case 242: - case 241: - case 240: - case 239: - return false; - default: - return true; - } - }); - return node && node.parent; - } - function getTypeOfPrototypeProperty(prototype) { - var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); - return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; - } - function getTypeOfPropertyOfType(type, name) { - var prop = getPropertyOfType(type, name); - return prop ? getTypeOfSymbol(prop) : undefined; - } - function isTypeAny(type) { - return type && (type.flags & 1) !== 0; - } - function getTypeForBindingElementParent(node) { - var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); - } - function isComputedNonLiteralName(name) { - return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); - } - function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144); }); - if (source.flags & 8192) { - return emptyObjectType; - } - if (source.flags & 65536) { - return mapType(source, function (t) { return getRestType(t, properties, symbol); }); - } - var members = ts.createMap(); - var names = ts.createMap(); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var name = properties_3[_i]; - names.set(ts.getTextOfPropertyName(name), true); - } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - var inNamesToRemove = names.has(prop.name); - 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); - } - } - var stringIndexInfo = getIndexInfoOfType(source, 0); - var numberIndexInfo = getIndexInfoOfType(source, 1); - return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getTypeForBindingElement(declaration) { - var pattern = declaration.parent; - var parentType = getTypeForBindingElementParent(pattern.parent); - if (parentType === unknownType) { - return unknownType; - } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } - return parentType; - } - var type; - if (pattern.kind === 174) { - if (declaration.dotDotDotToken) { - if (!isValidSpreadType(parentType)) { - error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); - return unknownType; - } - var literalMembers = []; - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!element.dotDotDotToken) { - literalMembers.push(element.propertyName || element.name); - } - } - type = getRestType(parentType, literalMembers, declaration.symbol); - } - else { - var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - return anyType; - } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - var text = ts.getTextOfPropertyName(name); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return unknownType; - } - } - } - else { - var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); - if (declaration.dotDotDotToken) { - type = createArrayType(elementType); - } - else { - var propName = "" + ts.indexOf(pattern.elements, declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); - } - return unknownType; - } - } - } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { - type = getTypeWithFacts(type, 131072); - } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : - type; - } - function getTypeForDeclarationFromJSDocComment(declaration) { - var jsdocType = ts.getJSDocType(declaration); - if (jsdocType) { - return getTypeFromTypeNode(jsdocType); - } - return undefined; - } - function isNullOrUndefined(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; - } - function isEmptyArrayLiteral(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 177 && expr.elements.length === 0; - } - function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048) : type; - } - function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - if (declaration.parent.parent.kind === 215) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 | 262144) ? indexType : stringType; - } - if (declaration.parent.parent.kind === 216) { - var forOfStatement = declaration.parent.parent; - return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; - } - if (ts.isBindingPattern(declaration.parent)) { - return getTypeForBindingElement(declaration); - } - if (declaration.type) { - var declaredType = getTypeFromTypeNode(declaration.type); - return addOptionality(declaredType, declaration.questionToken && includeOptionality); - } - if ((noImplicitAny || declaration.flags & 65536) && - declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { - if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { - return autoType; - } - if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { - return autoArrayType; - } - } - if (declaration.kind === 146) { - var func = declaration.parent; - if (func.kind === 154 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); - if (getter) { - var getterSignature = getSignatureFromDeclaration(getter); - var thisParameter = getAccessorThisParameter(func); - if (thisParameter && declaration === thisParameter) { - ts.Debug.assert(!thisParameter.type); - return getTypeOfSymbol(getterSignature.thisParameter); - } - return getReturnTypeOfSignature(getterSignature); - } - } - var type = void 0; - if (declaration.symbol.name === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } - if (type) { - return addOptionality(type, declaration.questionToken && includeOptionality); - } - } - if (declaration.initializer) { - var type = checkDeclarationInitializer(declaration); - return addOptionality(type, declaration.questionToken && includeOptionality); - } - if (ts.isJsxAttribute(declaration)) { - return trueType; - } - if (declaration.kind === 262) { - return checkIdentifier(declaration.name); - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false, true); - } - return undefined; - } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { - 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 : - declaration.kind === 179 ? ts.getAncestor(declaration, 194) : - undefined; - if (!expression) { - return unknownType; - } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 152) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - 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)); - } - } - else if (!jsDocType) { - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); - } - } - var type = jsDocType || getUnionType(types, true); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - } - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { - if (element.initializer) { - return checkDeclarationInitializer(element); - } - if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); - } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); - } - return anyType; - } - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); - var stringIndexInfo; - var hasComputedProperties = false; - ts.forEach(pattern.elements, function (e) { - var name = e.propertyName || e.name; - if (isComputedNonLiteralName(name)) { - hasComputedProperties = true; - return; - } - if (e.dotDotDotToken) { - stringIndexInfo = createIndexInfo(anyType, false); - return; - } - var text = ts.getTextOfPropertyName(name); - var flags = 4 | (e.initializer ? 67108864 : 0); - var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); - symbol.bindingElement = e; - members.set(symbol.name, symbol); - }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); - if (includePatternInType) { - result.pattern = pattern; - } - if (hasComputedProperties) { - result.objectFlags |= 512; - } - return result; - } - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { - var elements = pattern.elements; - var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; - } - var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); - if (includePatternInType) { - result = cloneTypeReference(result); - result.pattern = pattern; - } - return result; - } - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); - } - function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, true); - if (type) { - if (reportErrors) { - reportErrorsFromWidening(declaration, type); - } - if (declaration.kind === 261) { - return type; - } - return getWidenedType(type); - } - type = declaration.dotDotDotToken ? anyArrayType : anyType; - if (reportErrors && noImplicitAny) { - if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); - } - } - return type; - } - function declarationBelongsToPrivateAmbientMember(declaration) { - var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 ? root.parent : root; - return isPrivateWithinAmbient(memberDeclaration); - } - function getTypeOfVariableOrParameterOrProperty(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 16777216) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - if (declaration.kind === 243) { - return links.type = checkExpression(declaration.expression); - } - if (declaration.flags & 65536 && declaration.kind === 291 && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - var type = void 0; - if (declaration.kind === 194 || - declaration.kind === 179 && declaration.parent.kind === 194) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; - } - function getAnnotatedAccessorType(accessor) { - if (accessor) { - if (accessor.kind === 153) { - return accessor.type && getTypeFromTypeNode(accessor.type); - } - else { - var setterTypeAnnotation = ts.getSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); - } - } - return undefined; - } - function getAnnotatedAccessorThisParameter(accessor) { - var parameter = getAccessorThisParameter(accessor); - return parameter && parameter.symbol; - } - function getThisTypeOfDeclaration(declaration) { - return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); - } - function getTypeOfAccessors(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153); - var setter = ts.getDeclarationOfKind(symbol, 154); - if (getter && getter.flags & 65536) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - var type = void 0; - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; - } - else { - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; - } - else { - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - type = anyType; - } - } - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153); - error(getter_1, 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, symbolToString(symbol)); - } - } - links.type = type; - } - return links.type; - } - function getBaseTypeVariableOfClass(symbol) { - var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; - } - function getTypeOfFuncClassEnumModule(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else { - var type = createObjectType(16, symbol); - if (symbol.flags & 32) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; - } - else { - links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; - } - } - } - return links.type; - } - function getTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; - } - function getTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 107455 - ? getTypeOfSymbol(targetSymbol) - : unknownType; - } - return links.type; - } - function getTypeOfInstantiatedSymbol(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = unknownType; - } - else { - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - } - return links.type; - } - function reportCircularityError(symbol) { - if (symbol.valueDeclaration.type) { - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - return unknownType; - } - if (noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - return anyType; - } - function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 1) { - return getTypeOfInstantiatedSymbol(symbol); - } - if (symbol.flags & (3 | 4)) { - return getTypeOfVariableOrParameterOrProperty(symbol); - } - if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { - return getTypeOfFuncClassEnumModule(symbol); - } - if (symbol.flags & 8) { - return getTypeOfEnumMember(symbol); - } - if (symbol.flags & 98304) { - return getTypeOfAccessors(symbol); - } - if (symbol.flags & 8388608) { - return getTypeOfAlias(symbol); - } - return unknownType; - } - function isReferenceToType(type, target) { - return type !== undefined - && target !== undefined - && (getObjectFlags(type) & 4) !== 0 - && type.target === target; - } - function getTargetType(type) { - return getObjectFlags(type) & 4 ? type.target : type; - } - function hasBaseType(type, checkBase) { - return check(type); - function check(type) { - if (getObjectFlags(type) & (3 | 4)) { - var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); - } - else if (type.flags & 131072) { - return ts.forEach(type.types, check); - } - } - } - function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } - } - return typeParameters; - } - function appendOuterTypeParameters(typeParameters, node) { - while (true) { - node = node.parent; - if (!node) { - return typeParameters; - } - if (node.kind === 229 || node.kind === 199 || - node.kind === 228 || node.kind === 186 || - node.kind === 151 || node.kind === 187) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } - } - } - } - function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); - return appendOuterTypeParameters(undefined, declaration); - } - function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { - var result; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - if (node.kind === 230 || node.kind === 229 || - node.kind === 199 || node.kind === 231) { - var declaration = node; - if (declaration.typeParameters) { - result = appendTypeParameters(result, declaration.typeParameters); - } - } - } - return result; - } - function getTypeParametersOfClassOrInterface(symbol) { - return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); - } - function isMixinConstructorType(type) { - var signatures = getSignaturesOfType(type, 1); - if (signatures.length === 1) { - var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; - } - return false; - } - function isConstructorType(type) { - if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { - return true; - } - if (type.flags & 540672) { - var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); - } - return false; - } - function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); - } - function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); - } - function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; - } - function getBaseConstructorTypeOfClass(type) { - if (!type.resolvedBaseConstructorType) { - var baseTypeNode = getBaseTypeNodeOfClass(type); - if (!baseTypeNode) { - return type.resolvedBaseConstructorType = undefinedType; - } - if (!pushTypeResolution(type, 1)) { - return unknownType; - } - var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 | 131072)) { - resolveStructuredTypeMembers(baseConstructorType); - } - if (!popTypeResolution()) { - error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = unknownType; - } - if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); - return type.resolvedBaseConstructorType = unknownType; - } - type.resolvedBaseConstructorType = baseConstructorType; - } - return type.resolvedBaseConstructorType; - } - function getBaseTypes(type) { - if (!type.resolvedBaseTypes) { - if (type.objectFlags & 8) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 | 64)) { - if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(type); - } - } - else { - ts.Debug.fail("type must be class or interface"); - } - } - return type.resolvedBaseTypes; - } - function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { - 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, typeArgs); - } - else if (baseConstructorType.flags & 1) { - baseType = baseConstructorType; - } - else { - var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); - if (!constructors.length) { - error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; - } - baseType = getReturnTypeOfSignature(constructors[0]); - } - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } - if (baseType === unknownType) { - return; - } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; - } - if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - return; - } - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - function areAllOuterTypeParametersApplied(type) { - var outerTypeParameters = type.outerTypeParameters; - if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; - var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; - } - return true; - } - function isValidBaseType(type) { - return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || - type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); - } - function resolveBaseTypesOfInterface(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - } - } - else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); - } - } - } - } - } - } - function isIndependentInterface(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230) { - if (declaration.flags & 64) { - return false; - } - var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); - if (baseTypeNodes) { - for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { - var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064, true); - if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { - return false; - } - } - } - } - } - } - return true; - } - function getDeclaredTypeOfClassOrInterface(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var kind = symbol.flags & 32 ? 1 : 2; - var type = links.declaredType = createObjectType(kind, symbol); - var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); - var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { - type.objectFlags |= 4; - type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); - type.outerTypeParameters = outerTypeParameters; - type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384); - type.thisType.isThisType = true; - type.thisType.symbol = symbol; - type.thisType.constraint = type; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - if (!pushTypeResolution(symbol, 2)) { - return unknownType; - } - var declaration = ts.getDeclarationOfKind(symbol, 290); - var type = void 0; - if (declaration) { - if (declaration.jsDocTypeLiteral) { - type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); - } - else { - type = getTypeFromTypeNode(declaration.typeExpression.type); - } - } - else { - declaration = ts.getDeclarationOfKind(symbol, 231); - type = getTypeFromTypeNode(declaration.type); - } - if (popTypeResolution()) { - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (typeParameters) { - links.typeParameters = typeParameters; - links.instantiations = ts.createMap(); - links.instantiations.set(getTypeListId(typeParameters), type); - } - } - else { - type = unknownType; - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); - } - links.declaredType = type; - } - return links.declaredType; - } - function isLiteralEnumMember(member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && - expr.operand.kind === 8 || - expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); - } - 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 (member.initializer && member.initializer.kind === 9) { - return links.enumKind = 1; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; - } - } - } - } - return links.enumKind = hasNonLiteralMember ? 0 : 1; - } - 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) { - 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); - } - } - } - 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; - } - } - 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)); - if (!links.declaredType) { - links.declaredType = enumType; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeParameter(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(16384); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; - } - function getDeclaredTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; - } - function getDeclaredTypeOfSymbol(symbol) { - if (symbol.flags & (32 | 64)) { - return getDeclaredTypeOfClassOrInterface(symbol); - } - if (symbol.flags & 524288) { - return getDeclaredTypeOfTypeAlias(symbol); - } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); - } - if (symbol.flags & 384) { - return getDeclaredTypeOfEnum(symbol); - } - if (symbol.flags & 8) { - return getDeclaredTypeOfEnumMember(symbol); - } - if (symbol.flags & 8388608) { - return getDeclaredTypeOfAlias(symbol); - } - return unknownType; - } - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; - } - function isIndependentType(node) { - switch (node.kind) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 134: - case 105: - case 139: - case 95: - case 130: - case 173: - return true; - case 164: - return isIndependentType(node.elementType); - case 159: - return isIndependentTypeReference(node); - } - return false; - } - function isIndependentVariableLikeDeclaration(node) { - return node.type && isIndependentType(node.type) || !node.type && !node.initializer; - } - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152 && (!node.type || !isIndependentType(node.type))) { - return false; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; - } - function isIndependentMember(symbol) { - if (symbol.declarations && symbol.declarations.length === 1) { - var declaration = symbol.declarations[0]; - if (declaration) { - switch (declaration.kind) { - case 149: - case 148: - return isIndependentVariableLikeDeclaration(declaration); - case 151: - case 150: - case 152: - return isIndependentFunctionLikeDeclaration(declaration); - } - } - } - return false; - } - function createSymbolTable(symbols) { - var result = ts.createMap(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - result.set(symbol.name, symbol); - } - return result; - } - function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; - result.set(symbol.name, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); - } - return result; - } - function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { - var s = baseSymbols_1[_i]; - if (!symbols.has(s.name)) { - symbols.set(s.name, s); - } - } - } - function resolveDeclaredMembers(type) { - if (!type.declaredProperties) { - var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); - type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - } - return type; - } - function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4) { - var target = type.target; - var typeArguments = type.typeArguments; - if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); - } - } - else if (type.flags & 131072) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); - } - return type; - } - function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { - mapper = createTypeMapper(typeParameters, typeArguments); - members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); - callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); - constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); - stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); - numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); - } - var baseTypes = getBaseTypes(source); - if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { - members = createSymbolTable(source.declaredProperties); - } - var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { - var baseType = baseTypes_1[_i]; - var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; - addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); - constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); - if (!stringIndexInfo) { - stringIndexInfo = instantiatedBaseType === anyType ? - createIndexInfo(anyType, false) : - getIndexInfoOfType(instantiatedBaseType, 0); - } - numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); - } - } - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveClassOrInterfaceMembers(type) { - resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); - } - function resolveTypeReferenceMembers(type) { - var source = resolveDeclaredMembers(type.target); - var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); - var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? - type.typeArguments : ts.concatenate(type.typeArguments, [type]); - resolveObjectTypeMembers(type, source, typeParameters, typeArguments); - } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); - sig.declaration = declaration; - sig.typeParameters = typeParameters; - sig.parameters = parameters; - sig.thisParameter = thisParameter; - sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; - sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; - return sig; - } - function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); - } - function getDefaultConstructSignatures(classType) { - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - var baseSignatures = getSignaturesOfType(baseConstructorType, 1); - if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; - } - var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); - var typeArgCount = ts.length(typeArguments); - var result = []; - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var baseSig = baseSignatures_1[_i]; - var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); - var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); - sig.typeParameters = classType.localTypeParameters; - sig.resolvedReturnType = classType; - result.push(sig); - } - } - return result; - } - function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { - for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { - var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { - return s; - } - } - } - function findMatchingSignatures(signatureLists, signature, listIndex) { - if (signature.typeParameters) { - if (listIndex > 0) { - return undefined; - } - for (var i = 1; i < signatureLists.length; i++) { - if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { - return undefined; - } - } - return [signature]; - } - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); - if (!match) { - return undefined; - } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } - } - return result; - } - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { - var signature = _a[_i]; - if (!result || !findMatchingSignature(result, signature, false, true, true)) { - var unionSignatures = findMatchingSignatures(signatureLists, signature, i); - if (unionSignatures) { - var s = signature; - if (unionSignatures.length > 1) { - s = cloneSignature(signature); - if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); - } - s.resolvedReturnType = undefined; - s.unionSignatures = unionSignatures; - } - (result || (result = [])).push(s); - } - } - } - } - return result || emptyArray; - } - function getUnionIndexInfo(types, kind) { - var indexTypes = []; - var isAnyReadonly = false; - 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; - } - indexTypes.push(indexInfo.type); - isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; - } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); - } - function resolveUnionTypeMembers(type) { - var callSignatures = getUnionSignatures(type.types, 0); - var constructSignatures = getUnionSignatures(type.types, 1); - var stringIndexInfo = getUnionIndexInfo(type.types, 0); - var numberIndexInfo = getUnionIndexInfo(type.types, 1); - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function intersectTypes(type1, type2) { - return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); - } - function intersectIndexInfos(info1, info2) { - return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); - } - function unionSpreadIndexInfos(info1, info2) { - return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); - } - function includeMixinType(type, types, index) { - var mixedTypes = []; - for (var i = 0; i < types.length; i++) { - if (i === index) { - mixedTypes.push(type); - } - else if (isMixinConstructorType(types[i])) { - mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); - } - } - return getIntersectionType(mixedTypes); - } - function resolveIntersectionTypeMembers(type) { - var callSignatures = emptyArray; - var constructSignatures = emptyArray; - var stringIndexInfo; - var numberIndexInfo; - var types = type.types; - var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_3 = function (i) { - var t = type.types[i]; - if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { - var signatures = getSignaturesOfType(t, 1); - if (signatures.length && mixinCount > 0) { - signatures = ts.map(signatures, function (s) { - var clone = cloneSignature(s); - clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); - return clone; - }); - } - constructSignatures = ts.concatenate(constructSignatures, signatures); - } - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); - stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); - numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); - }; - for (var i = 0; i < types.length; i++) { - _loop_3(i); - } - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveAnonymousTypeMembers(type) { - var symbol = type.symbol; - if (type.target) { - var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); - var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); - var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); - var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else if (symbol.flags & 2048) { - var members = symbol.members; - var callSignatures = getSignaturesOfSymbol(members.get("__call")); - var constructSignatures = getSignaturesOfSymbol(members.get("__new")); - var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else { - var members = emptySymbols; - var constructSignatures = emptyArray; - var stringIndexInfo = undefined; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - } - if (symbol.flags & 32) { - var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 | 131072 | 540672)) { - members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); - } - else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, false); - } - } - var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); - if (symbol.flags & (16 | 8192)) { - type.callSignatures = getSignaturesOfSymbol(symbol); - } - } - } - function resolveMappedTypeMembers(type) { - var members = ts.createMap(); - var stringIndexInfo; - setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var typeParameter = getTypeParameterFromMappedType(type); - var constraintType = getConstraintTypeFromMappedType(type); - var templateType = getTemplateTypeFromMappedType(type); - var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); - var templateReadonly = !!type.declaration.readonlyToken; - var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170) { - for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { - var propertySymbol = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); - } - if (getIndexInfoOfType(modifiersType, 0)) { - addMemberForKeyType(stringType); - } - } - else { - var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; - forEachType(iterationType, addMemberForKeyType); - } - setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { - var iterationMapper = createTypeMapper([typeParameter], [t]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; - var propType = instantiateType(templateType, templateMapper); - if (t.flags & 32) { - var propName = t.value; - var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); - var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; - prop.type = propType; - if (propertySymbol) { - prop.syntheticOrigin = propertySymbol; - } - members.set(propName, prop); - } - else if (t.flags & 2) { - stringIndexInfo = createIndexInfo(propType, templateReadonly); - } - } - } - function getTypeParameterFromMappedType(type) { - return type.typeParameter || - (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); - } - function getConstraintTypeFromMappedType(type) { - return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); - } - function getTemplateTypeFromMappedType(type) { - return type.templateType || - (type.templateType = type.declaration.type ? - instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : - unknownType); - } - function getModifiersTypeFromMappedType(type) { - if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170) { - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); - } - else { - var declaredType = getTypeFromMappedTypeNode(type.declaration); - var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; - } - } - return type.modifiersType; - } - function isGenericMappedType(type) { - if (getObjectFlags(type) & 32) { - var constraintType = getConstraintTypeFromMappedType(type); - return maybeTypeOfKind(constraintType, 540672 | 262144); - } - return false; - } - function resolveStructuredTypeMembers(type) { - if (!type.members) { - if (type.flags & 32768) { - if (type.objectFlags & 4) { - resolveTypeReferenceMembers(type); - } - else if (type.objectFlags & 3) { - resolveClassOrInterfaceMembers(type); - } - else if (type.objectFlags & 16) { - resolveAnonymousTypeMembers(type); - } - else if (type.objectFlags & 32) { - resolveMappedTypeMembers(type); - } - } - else if (type.flags & 65536) { - resolveUnionTypeMembers(type); - } - else if (type.flags & 131072) { - resolveIntersectionTypeMembers(type); - } - } - return type; - } - function getPropertiesOfObjectType(type) { - if (type.flags & 32768) { - return resolveStructuredTypeMembers(type).properties; - } - return emptyArray; - } - function getPropertyOfObjectType(type, name) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - } - } - function getPropertiesOfUnionOrIntersectionType(type) { - if (!type.resolvedProperties) { - var members = ts.createMap(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var current = _a[_i]; - for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { - var prop = _c[_b]; - if (!members.has(prop.name)) { - var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.name); - if (combinedProp) { - members.set(prop.name, combinedProp); - } - } - } - if (type.flags & 65536) { - break; - } - } - type.resolvedProperties = getNamedMembers(members); - } - return type.resolvedProperties; - } - function getPropertiesOfType(type) { - type = getApparentType(type); - return type.flags & 196608 ? - 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) : - getBaseConstraintOfType(type); - } - function getConstraintOfTypeParameter(typeParameter) { - return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; - } - function getConstraintOfIndexedAccess(type) { - var baseObjectType = getBaseConstraintOfType(type.objectType); - var baseIndexType = getBaseConstraintOfType(type.indexType); - return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; - } - function getBaseConstraintOfType(type) { - if (type.flags & (540672 | 196608)) { - var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } - } - else if (type.flags & 262144) { - return stringType; - } - return undefined; - } - function hasNonCircularBaseConstraint(type) { - return getResolvedBaseConstraint(type) !== circularConstraintType; - } - function getResolvedBaseConstraint(type) { - var typeStack; - var circular; - if (!type.resolvedBaseConstraint) { - typeStack = []; - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); - } - return type.resolvedBaseConstraint; - function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { - circular = true; - return undefined; - } - typeStack.push(t); - var result = computeBaseConstraint(t); - typeStack.pop(); - return result; - } - function computeBaseConstraint(t) { - if (t.flags & 16384) { - var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; - } - if (t.flags & 196608) { - var types = t.types; - var baseTypes = []; - 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); - } - } - return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : - undefined; - } - if (t.flags & 262144) { - return stringType; - } - if (t.flags & 524288) { - var baseObjectType = getBaseConstraint(t.objectType); - var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; - return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; - } - return t; - } - } - function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); - } - function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameter(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; - } - function getApparentType(type) { - var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 ? globalStringType : - t.flags & 84 ? globalNumberType : - t.flags & 136 ? globalBooleanType : - t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : - t; - } - function createUnionOrIntersectionProperty(containingType, name) { - var props; - var types = containingType.types; - var isUnion = containingType.flags & 65536; - var excludeModifiers = isUnion ? 24 : 0; - var commonFlags = isUnion ? 0 : 67108864; - var syntheticFlag = 4; - var checkFlags = 0; - 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { - commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } - checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | - (!(modifiers & 24) ? 64 : 0) | - (modifiers & 16 ? 128 : 0) | - (modifiers & 8 ? 256 : 0) | - (modifiers & 32 ? 512 : 0); - if (!isMethodLike(prop)) { - syntheticFlag = 2; - } - } - else if (isUnion) { - checkFlags |= 16; - } - } - } - if (!props) { - return undefined; - } - if (props.length === 1 && !(checkFlags & 16)) { - return props[0]; - } - var propTypes = []; - var declarations = []; - var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; - if (prop.declarations) { - ts.addRange(declarations, prop.declarations); - } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - checkFlags |= 32; - } - propTypes.push(type); - } - var result = createSymbol(4 | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; - result.containingType = containingType; - result.declarations = declarations; - result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); - return result; - } - function getUnionOrIntersectionProperty(type, name) { - var properties = type.propertyCache || (type.propertyCache = ts.createMap()); - var property = properties.get(name); - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties.set(name, property); - } - } - return property; - } - function getPropertyOfUnionOrIntersectionType(type, name) { - var property = getUnionOrIntersectionProperty(type, name); - return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; - } - function getPropertyOfType(type, name) { - type = getApparentType(type); - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; - } - } - return getPropertyOfObjectType(globalObjectType, name); - } - if (type.flags & 196608) { - return getPropertyOfUnionOrIntersectionType(type, name); - } - return undefined; - } - function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; - } - return emptyArray; - } - function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); - } - function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; - } - } - function getIndexTypeOfStructuredType(type, kind) { - var info = getIndexInfoOfStructuredType(type, kind); - return info && info.type; - } - function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); - } - function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); - } - function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { - var propTypes = []; - for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.name)) { - propTypes.push(getTypeOfSymbol(prop)); - } - } - if (propTypes.length) { - return getUnionType(propTypes, true); - } - } - return undefined; - } - function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 65536) { - var templateTag = ts.getJSDocTemplateTag(declaration); - if (templateTag) { - return getTypeParametersFromDeclaration(templateTag.typeParameters); - } - } - return undefined; - } - function getTypeParametersFromDeclaration(typeParameterDeclarations) { - var result = []; - ts.forEach(typeParameterDeclarations, function (node) { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - result.push(tp); - } - }); - return result; - } - function symbolsToArray(symbols) { - var result = []; - symbols.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - result.push(symbol); - } - }); - return result; - } - function isJSDocOptionalParameter(node) { - if (node.flags & 65536) { - if (node.type && node.type.kind === 278) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 278; - } - } - } - } - } - function tryFindAmbientModule(moduleName, withAugmentations) { - if (ts.isExternalModuleNameRelative(moduleName)) { - return undefined; - } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); - return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; - } - function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { - return true; - } - if (node.initializer) { - var signatureDeclaration = node.parent; - var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); - ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; - } - var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); - if (iife) { - return !node.type && - !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; - } - return false; - } - function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 71) { - var parameterName = node.parameterName; - return { - kind: 1, - parameterName: parameterName ? parameterName.text : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; - } - else { - return { - kind: 0, - type: getTypeFromTypeNode(node.type) - }; - } - } - function getMinTypeArgumentCount(typeParameters) { - var minTypeArgumentCount = 0; - if (typeParameters) { - for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { - minTypeArgumentCount = i + 1; - } - } - } - return minTypeArgumentCount; - } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { - var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { - if (!typeArguments) { - typeArguments = []; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = isJavaScript ? anyType : emptyObjectType; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : isJavaScript ? anyType : emptyObjectType; - } - } - } - return typeArguments; - } - function getSignatureFromDeclaration(declaration) { - var links = getNodeLinks(declaration); - if (!links.resolvedSignature) { - var parameters = []; - var hasLiteralTypes = false; - var minArgumentCount = 0; - var thisParameter = undefined; - var hasThisParameter = void 0; - var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); - var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); - for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { - var param = declaration.parameters[i]; - var paramSymbol = param.symbol; - if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.name, 107455, undefined, undefined); - paramSymbol = resolvedSymbol; - } - if (i === 0 && paramSymbol.name === "this") { - hasThisParameter = true; - thisParameter = param.symbol; - } - else { - parameters.push(paramSymbol); - } - if (param.type && param.type.kind === 173) { - hasLiteralTypes = true; - } - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; - if (!isOptionalParameter_1) { - minArgumentCount = parameters.length; - } - } - if ((declaration.kind === 153 || declaration.kind === 154) && - !ts.hasDynamicName(declaration) && - (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 ? 154 : 153; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); - if (other) { - thisParameter = getAnnotatedAccessorThisParameter(other); - } - } - var classType = declaration.kind === 152 ? - getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) - : undefined; - var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : - getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); - } - return links.resolvedSignature; - } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); - } - else if (classType) { - return classType; - } - else if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.flags & 65536) { - var type = getReturnTypeFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } - } - function containsArgumentsReference(declaration) { - var links = getNodeLinks(declaration); - if (links.containsArgumentsReference === undefined) { - if (links.flags & 8192) { - links.containsArgumentsReference = true; - } - else { - links.containsArgumentsReference = traverse(declaration.body); - } - } - return links.containsArgumentsReference; - function traverse(node) { - if (!node) - return false; - switch (node.kind) { - case 71: - return node.text === "arguments" && ts.isPartOfExpression(node); - case 149: - case 151: - case 153: - case 154: - return node.name.kind === 144 - && traverse(node.name); - default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); - } - } - } - function getSignaturesOfSymbol(symbol) { - if (!symbol) - return emptyArray; - var result = []; - for (var i = 0; i < symbol.declarations.length; i++) { - var node = symbol.declarations[i]; - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 279: - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); - } - } - return result; - } - function resolveExternalModuleTypeByLiteral(name) { - var moduleSym = resolveExternalModuleName(name, name); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - return getTypeOfSymbol(resolvedModuleSymbol); - } - } - return anyType; - } - function getThisTypeOfSignature(signature) { - if (signature.thisParameter) { - return getTypeOfSymbol(signature.thisParameter); - } - } - function getReturnTypeOfSignature(signature) { - if (!signature.resolvedReturnType) { - if (!pushTypeResolution(signature, 3)) { - return unknownType; - } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - 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); - } - } - } - signature.resolvedReturnType = type; - } - return signature.resolvedReturnType; - } - function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; - } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); - var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); - var id = getTypeListId(typeArguments); - var instantiation = instantiations.get(id); - if (!instantiation) { - instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); - } - return instantiation; - } - function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); - } - function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); - } - return signature.erasedSignatureCache; - } - function getOrCreateTypeFromSignature(signature) { - if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; - var type = createObjectType(16); - type.members = emptySymbols; - type.properties = emptyArray; - type.callSignatures = !isConstructor ? [signature] : emptyArray; - type.constructSignatures = isConstructor ? [signature] : emptyArray; - signature.isolatedSignatureType = type; - } - return signature.isolatedSignatureType; - } - function getIndexSymbol(symbol) { - return symbol.members.get("__index"); - } - function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 133 : 136; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var node = decl; - if (node.parameters.length === 1) { - var parameter = node.parameters[0]; - if (parameter && parameter.type && parameter.type.kind === syntaxKind) { - return node; - } - } - } - } - return undefined; - } - function createIndexInfo(type, isReadonly, declaration) { - return { type: type, isReadonly: isReadonly, declaration: declaration }; - } - function getIndexInfoOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); - } - return undefined; - } - function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145).constraint; - } - function getConstraintFromTypeParameter(typeParameter) { - if (!typeParameter.constraint) { - if (typeParameter.target) { - var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); - typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; - } - else { - var constraintDeclaration = getConstraintDeclaration(typeParameter); - typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; - } - } - return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; - } - function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); - } - function getTypeListId(types) { - var result = ""; - if (types) { - var length_4 = types.length; - var i = 0; - while (i < length_4) { - var startId = types[i].id; - var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; - } - } - return result; - } - function getPropagatingFlagsOfTypes(types, excludeKinds) { - var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; - if (!(type.flags & excludeKinds)) { - result |= type.flags; - } - } - return result & 14680064; - } - function createTypeReference(target, typeArguments) { - var id = getTypeListId(typeArguments); - var type = target.instantiations.get(id); - if (!type) { - type = createObjectType(4, target.symbol); - target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - type.target = target; - type.typeArguments = typeArguments; - } - return type; - } - function cloneTypeReference(source) { - var type = createType(source.flags); - type.symbol = source.symbol; - type.objectFlags = source.objectFlags; - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return ts.length(type.target.typeParameters); - } - function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { - var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); - var typeParameters = type.localTypeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : 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(typeArgs, typeParameters, minTypeArgumentCount, node)); - return createTypeReference(type, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - return unknownType; - } - return type; - } - function getTypeAliasInstantiation(symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var links = getSymbolLinks(symbol); - var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); - var instantiation = links.instantiations.get(id); - if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); - } - return instantiation; - } - function getTypeFromTypeAliasReference(node, symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeParameters = getSymbolLinks(symbol).typeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); - return unknownType; - } - return getTypeAliasInstantiation(symbol, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return type; - } - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } - function getTypeReferenceName(node) { - switch (node.kind) { - case 159: - return node.typeName; - case 277: - return node.name; - case 201: - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; - } - } - return undefined; - } - function resolveTypeReferenceName(typeReferenceName) { - if (!typeReferenceName) { - return unknownSymbol; - } - 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, typeArguments); - } - if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol, typeArguments); - } - if (symbol.flags & 107455 && node.kind === 277) { - return getTypeOfSymbol(symbol); - } - return getTypeFromNonGenericTypeReference(node, symbol); - } - function getPrimitiveTypeFromJSDocTypeReference(node) { - if (ts.isIdentifier(node.name)) { - switch (node.name.text) { - case "String": - return stringType; - case "Number": - return numberType; - case "Boolean": - return booleanType; - case "Void": - return voidType; - case "Undefined": - return undefinedType; - case "Null": - return nullType; - case "Object": - return anyType; - case "Function": - return anyFunctionType; - case "Array": - case "array": - return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined; - case "Promise": - case "promise": - return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; - } - } - } - function getTypeFromJSDocNullableTypeNode(node) { - var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; - } - function getTypeFromTypeReference(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var symbol = void 0; - var type = void 0; - if (node.kind === 277) { - type = getPrimitiveTypeFromJSDocTypeReference(node); - if (!type) { - var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(typeReferenceName); - type = getTypeReferenceType(node, symbol); - } - } - else { - var typeNameOrExpression = node.kind === 159 - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - 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) { - links.resolvedType = getWidenedType(checkExpression(node.exprName)); - } - return links.resolvedType; - } - function getTypeOfGlobalSymbol(symbol, arity) { - function getTypeDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; - switch (declaration.kind) { - case 229: - case 230: - case 232: - return declaration; - } - } - } - if (!symbol) { - return arity ? emptyGenericType : emptyObjectType; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return arity ? emptyGenericType : emptyObjectType; - } - if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return arity ? emptyGenericType : emptyObjectType; - } - return type; - } - function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); - } - function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); - } - function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); - } - function getGlobalType(name, arity, reportErrors) { - var symbol = getGlobalTypeSymbol(name, reportErrors); - return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; - } - function getGlobalTypedPropertyDescriptorType() { - return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; - } - function getGlobalTemplateStringsArrayType() { - return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; - } - function getGlobalESSymbolConstructorSymbol(reportErrors) { - return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); - } - function getGlobalESSymbolType(reportErrors) { - return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; - } - function getGlobalPromiseType(reportErrors) { - return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; - } - function getGlobalPromiseConstructorSymbol(reportErrors) { - return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); - } - function getGlobalPromiseConstructorLikeType(reportErrors) { - return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; - } - function getGlobalAsyncIterableType(reportErrors) { - return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIteratorType(reportErrors) { - return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIterableIteratorType(reportErrors) { - return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableType(reportErrors) { - return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIteratorType(reportErrors) { - return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableIteratorType(reportErrors) { - return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalTypeOrUndefined(name, arity) { - if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064, undefined); - return symbol && getTypeOfGlobalSymbol(symbol, arity); - } - function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); - return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); - } - function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { - return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; - } - function createTypedPropertyDescriptorType(propertyType) { - return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); - } - function createAsyncIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); - } - function createAsyncIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); - } - function createIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); - } - function createIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); - } - function createArrayType(elementType) { - return createTypeFromGenericGlobalType(globalArrayType, [elementType]); - } - function getTypeFromArrayTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); - } - return links.resolvedType; - } - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); - typeParameters.push(typeParameter); - var property = createSymbol(4, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(8 | 4); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384); - type.thisType.isThisType = true; - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); - } - function getTypeFromTupleTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); - } - return links.resolvedType; - } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - var flags = type.flags; - if (flags & 65536) { - addTypesToUnion(typeSet, type.types); - } - else if (flags & 1) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && flags & 6144) { - if (flags & 2048) - typeSet.containsUndefined = true; - if (flags & 4096) - typeSet.containsNull = true; - if (!(flags & 2097152)) - typeSet.containsNonWideningType = true; - } - else if (!(flags & 8192)) { - if (flags & 2) - typeSet.containsString = true; - if (flags & 4) - typeSet.containsNumber = true; - if (flags & 96) - typeSet.containsStringOrNumberLiteral = true; - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } - } - } - function addTypesToUnion(typeSet, types) { - 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_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function isSubtypeOfAny(candidate, types) { - 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; - } - } - return false; - } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 256) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types) { - if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { - return; - } - var i = types.length; - while (i > 0) { - i--; - if (isSubtypeOfAny(types[i], types)) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function removeRedundantLiteralTypes(types) { - var i = types.length; - while (i > 0) { - i--; - var t = types[i]; - var remove = t.flags & 32 && types.containsString || - t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); - if (remove) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var typeSet = []; - addTypesToUnion(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsStringOrNumberLiteral) { - removeRedundantLiteralTypes(typeSet); - } - if (typeSet.length === 0) { - return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : - typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); - var type = unionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = createType(65536 | propagatedFlags); - unionTypes.set(id, type); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromUnionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { - typeSet.containsEmptyObject = true; - } - else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768) { - typeSet.containsObjectType = true; - } - if (type.flags & 65536 && typeSet.unionIndex === undefined) { - typeSet.unionIndex = typeSet.length; - } - if (!(type.flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.push(type); - } - } - } - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - addTypeToIntersection(typeSet, type); - } - } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } - var typeSet = []; - addTypesToIntersection(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { - typeSet.push(emptyObjectType); - } - if (typeSet.length === 1) { - return typeSet[0]; - } - var unionIndex = typeSet.unionIndex; - if (unionIndex !== undefined) { - var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); - } - var id = getTypeListId(typeSet); - var type = intersectionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = createType(131072 | propagatedFlags); - intersectionTypes.set(id, type); - type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromIntersectionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function getIndexTypeForGenericType(type) { - if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144); - type.resolvedIndexType.type = type; - } - return type.resolvedIndexType; - } - function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? - neverType : - getLiteralType(ts.unescapeIdentifier(prop.name)); - } - function getLiteralTypeFromPropertyNames(type) { - return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); - } - function getIndexType(type) { - return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : - type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : - getLiteralTypeFromPropertyNames(type); - } - function getIndexTypeOrString(type) { - var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; - } - function getTypeFromTypeOperatorNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); - } - return links.resolvedType; - } - function createIndexedAccessType(objectType, indexType) { - var type = createType(524288); - type.objectType = objectType; - type.indexType = indexType; - return type; - } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & 96 ? - "" + indexType.value : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : - undefined; - if (propName !== undefined) { - var prop = getPropertyOfType(objectType, propName); - if (prop) { - if (accessExpression) { - if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return unknownType; - } - if (cacheSymbol) { - getNodeLinks(accessNode).resolvedSymbol = prop; - } - } - return getTypeOfSymbol(prop); - } - } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { - if (isTypeAny(objectType)) { - return anyType; - } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || - getIndexInfoOfType(objectType, 0) || - undefined; - if (indexInfo) { - if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; - } - return indexInfo.type; - } - if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1)) { - error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); - } - } - return anyType; - } - } - 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.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)); - } - else { - error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); - } - return unknownType; - } - return anyType; - } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } - function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || - maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || - isGenericMappedType(objectType)) { - if (objectType.flags & 1) { - return objectType; - } - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - var id = objectType.id + "," + indexType.id; - var type = indexedAccessTypes.get(id); - if (!type) { - indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); - } - return type; - } - var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8190)) { - var propTypes = []; - for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { - var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); - if (propType === unknownType) { - return unknownType; - } - propTypes.push(propType); - } - return getUnionType(propTypes); - } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); - } - function getTypeFromIndexedAccessTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); - } - return links.resolvedType; - } - function getTypeFromMappedTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = createObjectType(32, node.symbol); - type.declaration = node; - type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - getConstraintTypeFromMappedType(type); - } - return links.resolvedType; - } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { - links.resolvedType = emptyTypeLiteralType; - } - else { - var type = createObjectType(16, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - } - } - return links.resolvedType; - } - function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; - } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); - return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; - } - function getSpreadType(left, right) { - if (left.flags & 1 || right.flags & 1) { - return anyType; - } - left = filterType(left, function (t) { return !(t.flags & 6144); }); - if (left.flags & 8192) { - return right; - } - right = filterType(right, function (t) { return !(t.flags & 6144); }); - if (right.flags & 8192) { - return left; - } - if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); - } - if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); - } - if (right.flags & 16777216) { - return emptyObjectType; - } - var members = ts.createMap(); - var skippedPrivateMembers = ts.createMap(); - var stringIndexInfo; - var numberIndexInfo; - if (left === emptyObjectType) { - stringIndexInfo = getIndexInfoOfType(right, 0); - numberIndexInfo = getIndexInfoOfType(right, 1); - } - else { - stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); - numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); - } - for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { - var rightProp = _a[_i]; - var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { - skippedPrivateMembers.set(rightProp.name, true); - } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { - members.set(rightProp.name, getNonReadonlySymbol(rightProp)); - } - } - for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { - var leftProp = _c[_b]; - if (leftProp.flags & 65536 && !(leftProp.flags & 32768) - || skippedPrivateMembers.has(leftProp.name) - || isClassMethod(leftProp)) { - continue; - } - if (members.has(leftProp.name)) { - var rightProp = members.get(leftProp.name); - var rightType = getTypeOfSymbol(rightProp); - 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), rightType]); - result.leftSpread = leftProp; - result.rightSpread = rightProp; - result.declarations = declarations; - members.set(leftProp.name, result); - } - } - else { - members.set(leftProp.name, getNonReadonlySymbol(leftProp)); - } - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { - return prop; - } - var flags = 4 | (prop.flags & 67108864); - var result = createSymbol(flags, prop.name); - result.type = getTypeOfSymbol(prop); - result.declarations = prop.declarations; - result.syntheticOrigin = prop; - return result; - } - function isClassMethod(prop) { - return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } - function createLiteralType(flags, value, symbol) { - var type = createType(flags); - 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.value, type.symbol); - freshType.regularType = type; - type.freshType = freshType; - } - return type.freshType; - } - return type; - } - function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; - } - 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) { - var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); - literalTypes.set(key, type = createLiteralType(flags, value, symbol)); - } - return type; - } - function getTypeFromLiteralTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); - } - return links.resolvedType; - } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; - } - return links.resolvedType; - } - function getTypeFromJSDocTupleType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); - links.resolvedType = createTupleType(types); - } - return links.resolvedType; - } - function getThisType(node) { - var container = ts.getThisContainer(node, false); - var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { - if (!(ts.getModifierFlags(container) & 32) && - (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { - return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; - } - } - error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); - return unknownType; - } - function getTypeFromThisTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getThisType(node); - } - return links.resolvedType; - } - function getTypeFromTypeNode(node) { - switch (node.kind) { - case 119: - case 268: - case 269: - return anyType; - case 136: - return stringType; - case 133: - return numberType; - case 122: - return booleanType; - case 137: - return esSymbolType; - case 105: - return voidType; - case 139: - return undefinedType; - case 95: - return nullType; - case 130: - return neverType; - case 134: - return nonPrimitiveType; - case 169: - case 99: - return getTypeFromThisTypeNode(node); - case 173: - return getTypeFromLiteralTypeNode(node); - case 293: - return getTypeFromLiteralTypeNode(node.literal); - case 159: - case 277: - return getTypeFromTypeReference(node); - case 158: - return booleanType; - case 201: - return getTypeFromTypeReference(node); - case 162: - return getTypeFromTypeQueryNode(node); - case 164: - case 270: - return getTypeFromArrayTypeNode(node); - case 165: - return getTypeFromTupleTypeNode(node); - case 166: - case 271: - return getTypeFromUnionTypeNode(node); - case 167: - return getTypeFromIntersectionTypeNode(node); - case 273: - return getTypeFromJSDocNullableTypeNode(node); - case 168: - case 274: - case 281: - case 282: - case 278: - return getTypeFromTypeNode(node.type); - case 275: - return getTypeFromTypeNode(node.literal); - case 160: - case 161: - case 163: - case 292: - case 279: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170: - return getTypeFromTypeOperatorNode(node); - case 171: - return getTypeFromIndexedAccessTypeNode(node); - case 172: - return getTypeFromMappedTypeNode(node); - case 71: - case 143: - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - case 272: - return getTypeFromJSDocTupleType(node); - case 280: - return getTypeFromJSDocVariadicType(node); - default: - return unknownType; - } - } - function instantiateList(items, mapper, instantiator) { - if (items && items.length) { - var result = []; - for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { - var v = items_1[_i]; - result.push(instantiator(v, mapper)); - } - return result; - } - return items; - } - function instantiateTypes(types, mapper) { - return instantiateList(types, mapper, instantiateType); - } - function instantiateSignatures(signatures, mapper) { - return instantiateList(signatures, mapper, instantiateSignature); - } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } - function makeUnaryTypeMapper(source, target) { - return function (t) { return t === source ? target : t; }; - } - function makeBinaryTypeMapper(source1, target1, source2, target2) { - return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; - } - function makeArrayTypeMapper(sources, targets) { - return function (t) { - for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) { - return targets ? targets[i] : anyType; - } - } - return t; - }; - } - function createTypeMapper(sources, targets) { - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : - sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : - makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; - } - function createTypeEraser(sources) { - return createTypeMapper(sources, undefined); - } - function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; - } - function getInferenceMapper(context) { - if (!context.mapper) { - var mapper = function (t) { - var typeParameters = context.signature.typeParameters; - for (var i = 0; i < typeParameters.length; i++) { - if (t === typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); - } - } - return t; - }; - mapper.mappedTypes = context.signature.typeParameters; - mapper.context = context; - context.mapper = mapper; - } - return context.mapper; - } - function identityMapper(type) { - return type; - } - function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; - } - function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; - } - function cloneTypeParameter(typeParameter) { - var result = createType(16384); - result.symbol = typeParameter.symbol; - result.target = typeParameter; - return result; - } - function cloneTypePredicate(predicate, mapper) { - if (ts.isIdentifierTypePredicate(predicate)) { - return { - kind: 1, - parameterName: predicate.parameterName, - parameterIndex: predicate.parameterIndex, - type: instantiateType(predicate.type, mapper) - }; - } - else { - return { - kind: 0, - type: instantiateType(predicate.type, mapper) - }; - } - } - function instantiateSignature(signature, mapper, eraseTypeParameters) { - var freshTypeParameters; - var freshTypePredicate; - if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); - mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); - for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { - var tp = freshTypeParameters_1[_i]; - tp.mapper = mapper; - } - } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); - result.target = signature; - result.mapper = mapper; - return result; - } - function instantiateSymbol(symbol, mapper) { - if (ts.getCheckFlags(symbol) & 1) { - var links = getSymbolLinks(symbol); - symbol = links.target; - mapper = combineTypeMappers(links.mapper, mapper); - } - var result = createSymbol(symbol.flags, symbol.name); - result.checkFlags = 1; - result.declarations = symbol.declarations; - result.parent = symbol.parent; - result.target = symbol; - result.mapper = mapper; - if (symbol.valueDeclaration) { - result.valueDeclaration = symbol.valueDeclaration; - } - return result; - } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 | 64, type.symbol); - result.target = type.objectFlags & 64 ? type.target : type; - result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function instantiateMappedType(type, mapper) { - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); - } - return t; - }); - } - } - } - return instantiateMappedObjectType(type, mapper); - } - function isMappableType(type) { - return type.flags & (16384 | 32768 | 131072 | 524288); - } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 | 64, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 || node.kind === 265) { - return "quit"; - } - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 229: - case 199: - case 230: - case 231: - var declaration = node; - if (declaration.typeParameters) { - for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { - var d = _a[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 279: - var func = node; - for (var _b = 0, _c = func.parameters; _b < _c.length; _b++) { - var p = _c[_b]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 || parentKind === 234; - } - return false; - } - function instantiateType(type, mapper) { - if (type && mapper !== identityMapper) { - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - return type; - } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384) { - return mapper(type); - } - if (type.flags & 32768) { - if (type.objectFlags & 16) { - return type.symbol && - type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; - } - if (type.objectFlags & 32) { - return instantiateCached(type, mapper, instantiateMappedType); - } - if (type.objectFlags & 4) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); - } - } - if (type.flags & 65536 && !(type.flags & 8190)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - return type; - } - function instantiateIndexInfo(info, mapper) { - return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); - } - function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - switch (node.kind) { - case 186: - case 187: - return isContextSensitiveFunctionLikeDeclaration(node); - case 178: - return ts.forEach(node.properties, isContextSensitive); - case 177: - return ts.forEach(node.elements, isContextSensitive); - case 195: - return isContextSensitive(node.whenTrue) || - isContextSensitive(node.whenFalse); - case 194: - return node.operatorToken.kind === 54 && - (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261: - return isContextSensitive(node.initializer); - case 151: - case 150: - return isContextSensitiveFunctionLikeDeclaration(node); - case 185: - return isContextSensitive(node.expression); - case 254: - return ts.forEach(node.properties, isContextSensitive); - case 253: - return node.initializer && isContextSensitive(node.initializer); - case 256: - return node.expression && isContextSensitive(node.expression); - } - return false; - } - function isContextSensitiveFunctionLikeDeclaration(node) { - if (node.typeParameters) { - return false; - } - if (ts.forEach(node.parameters, function (p) { return !p.type; })) { - return true; - } - if (node.kind === 187) { - return false; - } - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); - } - function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); - } - function getTypeWithoutSignatures(type) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { - var result = createObjectType(16, type.symbol); - result.members = resolved.members; - result.properties = resolved.properties; - result.callSignatures = emptyArray; - result.constructSignatures = emptyArray; - return result; - } - } - else if (type.flags & 131072) { - return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); - } - return type; - } - function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); - } - function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; - } - function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; - } - function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); - } - function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); - } - function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); - } - function areTypesComparable(type1, type2) { - return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); - } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); - } - function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; - } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { - if (source === target) { - return -1; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType && sourceThisType !== voidType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType, false) - || compareTypes(targetThisType, sourceThisType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); - } - return 0; - } - result &= related; - } - } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); - var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); - } - return 0; - } - result &= related; - } - if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) { - return result; - } - var sourceReturnType = getReturnTypeOfSignature(source); - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); - } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0; - } - } - else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || - compareTypes(sourceReturnType, targetReturnType, reportErrors); - } - } - return result; - } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { - if (source.kind !== target.kind) { - if (reportErrors) { - errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0; - } - if (source.kind === 1) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0; - } - } - var related = compareTypes(source.type, target.type, reportErrors); - if (related === 0 && reportErrors) { - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return related; - } - function isImplementationCompatibleWithOverload(implementation, overload) { - var erasedSource = getErasedSignature(implementation); - var erasedTarget = getErasedSignature(overload); - var sourceReturnType = getReturnTypeOfSignature(erasedSource); - var targetReturnType = getReturnTypeOfSignature(erasedTarget); - if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - return isSignatureAssignableTo(erasedSource, erasedTarget, true); - } - return false; - } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } - function isEmptyResolvedType(t) { - return t.properties.length === 0 && - t.callSignatures.length === 0 && - t.constructSignatures.length === 0 && - !t.stringIndexInfo && - !t.numberIndexInfo; - } - function isEmptyObjectType(type) { - return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : - false; - } - function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { - if (sourceSymbol === targetSymbol) { - return true; - } - var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); - var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; - } - if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { - enumRelation.set(id, false); - return false; - } - 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(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); - } - enumRelation.set(id, false); - return false; - } - } - } - enumRelation.set(id, true); - return true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - var s = source.flags; - var t = target.flags; - if (t & 8192) - return false; - if (t & 1 || s & 8192) - return true; - if (s & 262178 && t & 2) - return true; - if (s & 32 && s & 256 && - t & 32 && !(t & 256) && - source.value === target.value) - return true; - if (s & 84 && t & 4) - return true; - if (s & 64 && s & 256 && - t & 64 && !(t & 256) && - source.value === target.value) - return true; - if (s & 136 && t & 8) - return true; - if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; - 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 (s & 4096 && (!strictNullChecks || t & 4096)) - return true; - if (s & 32768 && t & 16777216) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1) - return true; - if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) - return true; - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 1048576) { - source = source.regularType; - } - if (target.flags & 96 && target.flags & 1048576) { - target = target.regularType; - } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 32768 && target.flags & 32768) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - return related === 1; - } - } - if (source.flags & 1032192 || target.flags & 1032192) { - return checkTypeRelatedTo(source, target, relation, undefined); - } - return false; - } - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { - var errorInfo; - var sourceStack; - var targetStack; - var maybeStack; - var expandingFlags; - var depth = 0; - var overflow = false; - ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, !!errorNode, headMessage); - if (overflow) { - error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); - } - else if (errorInfo) { - if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return result !== 0; - function reportError(message, arg0, arg1, arg2) { - ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - } - function reportRelationError(message, source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 128); - targetType = typeToString(target, undefined, 128); - } - if (!message) { - if (relation === comparableRelation) { - message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; - } - else if (sourceType === targetType) { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; - } - else { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; - } - } - reportError(message, sourceType, targetType); - } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType(false) === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } - function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608)) { - return false; - } - var seenNonNullable = false; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 6144) { - continue; - } - if (seenNonNullable) { - return true; - } - seenNonNullable = true; - } - return false; - } - function isRelatedTo(source, target, reportErrors, headMessage) { - var result; - if (source.flags & 96 && source.flags & 1048576) { - source = source.regularType; - } - if (target.flags & 96 && target.flags & 1048576) { - target = target.regularType; - } - if (source === target) - return -1; - if (relation === identityRelation) { - return isIdenticalTo(source, target); - } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1; - if (getObjectFlags(source) & 128 && source.flags & 1048576) { - if (hasExcessProperties(source, target, reportErrors)) { - if (reportErrors) { - reportRelationError(headMessage, source, target); - } - return 0; - } - if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { - source = getRegularTypeOfObjectLiteral(source); - } - } - var saveErrorInfo = errorInfo; - if (source.flags & 65536) { - if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); - } - else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); - } - if (result) { - return result; - } - } - else { - if (target.flags & 65536) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { - return result; - } - } - else if (target.flags & 131072) { - if (result = typeRelatedToEachType(source, target, reportErrors)) { - return result; - } - } - else if (source.flags & 131072) { - if (result = someTypeRelatedToType(source, target, false)) { - return result; - } - } - if (source.flags & 1032192 || target.flags & 1032192) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (reportErrors) { - if (source.flags & 32768 && target.flags & 8190) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 32768 && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - reportRelationError(headMessage, source, target); - } - return 0; - } - function isIdenticalTo(source, target) { - var result; - if (source.flags & 32768 && target.flags & 32768) { - return recursiveTypeRelatedTo(source, target, false); - } - if (source.flags & 65536 && target.flags & 65536 || - source.flags & 131072 && target.flags & 131072) { - if (result = eachTypeRelatedToSomeType(source, target)) { - if (result &= eachTypeRelatedToSomeType(target, source)) { - return result; - } - } - } - return 0; - } - function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { - var isComparingJsxAttributes = !!(source.flags & 33554432); - if ((relation === assignableRelation || relation === comparableRelation) && - (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { - return false; - } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { - if (reportErrors) { - ts.Debug.assert(!!errorNode); - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); - } - else { - errorNode = prop.valueDeclaration; - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); - } - } - return true; - } - } - } - return false; - } - function eachTypeRelatedToSomeType(source, target) { - var result = -1; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { - var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function typeRelatedToSomeType(source, target, reportErrors) { - var targetTypes = target.types; - if (target.flags & 65536 && containsType(targetTypes, source)) { - return -1; - } - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var type = targetTypes_1[_i]; - var related = isRelatedTo(source, type, false); - if (related) { - return related; - } - } - if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); - } - return 0; - } - function findMatchingDiscriminantType(source, target) { - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.name)) { - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); - if (targetType && isRelatedTo(sourceType, targetType)) { - return type; - } - } - } - } - } - } - function typeRelatedToEachType(source, target, reportErrors) { - var result = -1; - var targetTypes = target.types; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function someTypeRelatedToType(source, target, reportErrors) { - var sourceTypes = source.types; - if (source.flags & 65536 && containsType(sourceTypes, target)) { - return -1; - } - var len = sourceTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); - if (related) { - return related; - } - } - return 0; - } - function eachTypeRelatedToType(source, target, reportErrors) { - var result = -1; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; - var related = isRelatedTo(sourceType, target, reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function typeArgumentsRelatedTo(source, target, reportErrors) { - var sources = source.typeArguments || emptyArray; - var targets = target.typeArguments || emptyArray; - if (sources.length !== targets.length && relation === identityRelation) { - return 0; - } - var length = sources.length <= targets.length ? sources.length : targets.length; - var result = -1; - for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function recursiveTypeRelatedTo(source, target, reportErrors) { - if (overflow) { - return 0; - } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - if (reportErrors && related === 2) { - relation.set(id, 3); - } - else { - return related === 1 ? -1 : 0; - } - } - if (depth > 0) { - for (var i = 0; i < depth; i++) { - if (maybeStack[i].get(id)) { - return 1; - } - } - if (depth === 100) { - overflow = true; - return 0; - } - } - else { - sourceStack = []; - targetStack = []; - maybeStack = []; - expandingFlags = 0; - } - sourceStack[depth] = source; - targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); - maybeStack[depth].set(id, 1); - depth++; - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; - expandingFlags = saveExpandingFlags; - depth--; - if (result) { - var maybeCache = maybeStack[depth]; - var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyEntries(maybeCache, destinationCache); - } - else { - relation.set(id, reportErrors ? 3 : 2); - } - return result; - } - function structuredTypeRelatedTo(source, target, reportErrors) { - var result; - var saveErrorInfo = errorInfo; - if (target.flags & 16384) { - if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { - if (!source.declaration.questionToken) { - var templateType = getTemplateTypeFromMappedType(source); - var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); - if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { - return result; - } - } - } - } - else if (target.flags & 262144) { - if (source.flags & 262144) { - if (result = isRelatedTo(target.type, source.type, false)) { - return result; - } - } - var constraint = getConstraintOfType(target.type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { - return result; - } - } - } - else if (target.flags & 524288) { - var constraint = getConstraintOfType(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (source.flags & 16384) { - if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else { - var constraint = getConstraintOfTypeParameter(source); - if (constraint || !(target.flags & 16777216)) { - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; - } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - } - else if (source.flags & 524288) { - var constraint = getConstraintOfType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else if (target.flags & 524288 && source.indexType === target.indexType) { - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - return result; - } - } - } - else { - if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { - return result; - } - } - var sourceIsPrimitive = !!(source.flags & 8190); - if (relation !== identityRelation) { - source = getApparentType(source); - } - if (source.flags & (32768 | 131072) && target.flags & 32768) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isGenericMappedType(source) || isGenericMappedType(target)) { - result = mappedTypeRelatedTo(source, target, reportStructuralErrors); - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); - } - } - } - } - } - if (result) { - errorInfo = saveErrorInfo; - return result; - } - } - } - return 0; - } - function mappedTypeRelatedTo(source, target, reportErrors) { - if (isGenericMappedType(target)) { - if (isGenericMappedType(source)) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; - if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); - } - } - } - else if (target.declaration.questionToken && isEmptyObjectType(source)) { - return -1; - } - } - else if (relation !== identityRelation) { - var resolved = resolveStructuredTypeMembers(target); - if (isEmptyResolvedType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & 1) { - return -1; - } - } - return 0; - } - function propertiesRelatedTo(source, target, reportErrors) { - if (relation === identityRelation) { - return propertiesIdenticalTo(source, target); - } - var result = -1; - var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var targetProp = properties_4[_i]; - var sourceProp = getPropertyOfType(source, targetProp.name); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 67108864) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0; - } - } - else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); - if (sourcePropFlags & 8 || targetPropFlags & 8) { - 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)); - } - return 0; - } - if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { - if (reportErrors) { - if (sourcePropFlags & 8 && targetPropFlags & 8) { - reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); - } - else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); - } - } - return 0; - } - } - else if (targetPropFlags & 16) { - if (!isValidOverrideOf(sourceProp, targetProp)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); - } - return 0; - } - } - else if (sourcePropFlags & 16) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0; - } - var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); - } - return 0; - } - result &= related; - if (relation !== comparableRelation && sourceProp.flags & 67108864 && !(targetProp.flags & 67108864)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0; - } - } - } - } - return result; - } - function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 && target.flags & 32768)) { - return 0; - } - var sourceProperties = getPropertiesOfObjectType(source); - var targetProperties = getPropertiesOfObjectType(target); - if (sourceProperties.length !== targetProperties.length) { - return 0; - } - var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; - var targetProp = getPropertyOfObjectType(target, sourceProp.name); - if (!targetProp) { - return 0; - } - var related = compareProperties(sourceProp, targetProp, isRelatedTo); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function signaturesRelatedTo(source, target, kind, reportErrors) { - if (relation === identityRelation) { - return signaturesIdenticalTo(source, target, kind); - } - if (target === anyFunctionType || source === anyFunctionType) { - return -1; - } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (kind === 1 && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0; - } - if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { - return 0; - } - } - var result = -1; - var saveErrorInfo = errorInfo; - 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; - } - result &= related; - } - } - 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 result; - } - function signatureRelatedTo(source, target, reportErrors) { - return compareSignaturesRelated(source, target, false, false, reportErrors, reportError, isRelatedTo); - } - function signaturesIdenticalTo(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (sourceSignatures.length !== targetSignatures.length) { - return 0; - } - var result = -1; - for (var i = 0; i < sourceSignatures.length; i++) { - var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function eachPropertyRelatedTo(source, target, kind, reportErrors) { - var result = -1; - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.name)) { - var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); - } - return 0; - } - result &= related; - } - } - return result; - } - function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { - var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); - if (!related && reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return related; - } - function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(source, target, kind); - } - var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 && !sourceIsPrimitive) { - return -1; - } - var sourceInfo = getIndexInfoOfType(source, kind) || - kind === 1 && getIndexInfoOfType(source, 0); - if (sourceInfo) { - return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); - } - if (isObjectLiteralType(source)) { - var related = -1; - if (kind === 0) { - var sourceNumberInfo = getIndexInfoOfType(source, 1); - if (sourceNumberInfo) { - related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); - } - } - if (related) { - related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); - } - return related; - } - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0; - } - function indexTypesIdenticalTo(source, target, indexKind) { - var targetInfo = getIndexInfoOfType(target, indexKind); - var sourceInfo = getIndexInfoOfType(source, indexKind); - if (!sourceInfo && !targetInfo) { - return -1; - } - if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { - return isRelatedTo(sourceInfo.type, targetInfo.type); - } - return 0; - } - function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { - if (!sourceSignature.declaration || !targetSignature.declaration) { - return true; - } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; - if (targetAccessibility === 8) { - return true; - } - if (targetAccessibility === 16 && sourceAccessibility !== 8) { - return true; - } - if (targetAccessibility !== 16 && !sourceAccessibility) { - return true; - } - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); - } - return false; - } - } - function forEachProperty(prop, callback) { - 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); - var result = p && forEachProperty(p, callback); - if (result) { - return result; - } - } - return undefined; - } - return callback(prop); - } - function getDeclaringClass(prop) { - return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; - } - function isPropertyInClassDerivedFrom(prop, baseClass) { - return forEachProperty(prop, function (sp) { - var sourceClass = getDeclaringClass(sp); - return sourceClass ? hasBaseType(sourceClass, baseClass) : false; - }); - } - function isValidOverrideOf(sourceProp, targetProp) { - 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 ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? - !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; - } - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128) { - return true; - } - } - } - return false; - } - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 32768) { - var symbol = type.symbol; - if (symbol) { - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 32768 && t.symbol === symbol) { - count++; - if (count >= 5) - return true; - } - } - } - } - return false; - } - function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; - } - function compareProperties(sourceProp, targetProp, compareTypes) { - if (sourceProp === targetProp) { - return -1; - } - var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; - if (sourcePropAccessibility !== targetPropAccessibility) { - return 0; - } - if (sourcePropAccessibility) { - if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { - return 0; - } - } - else { - if ((sourceProp.flags & 67108864) !== (targetProp.flags & 67108864)) { - return 0; - } - } - if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { - return 0; - } - return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - function isMatchingSignature(source, target, partialMatch) { - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { - return true; - } - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { - return true; - } - return false; - } - function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { - if (source === target) { - return -1; - } - if (!(isMatchingSignature(source, target, partialMatch))) { - return 0; - } - if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { - return 0; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - if (!ignoreThisTypes) { - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType); - if (!related) { - return 0; - } - result &= related; - } - } - } - var targetLen = target.parameters.length; - for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); - var related = compareTypes(s, t); - if (!related) { - return 0; - } - result &= related; - } - if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - return result; - } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } - function isSupertypeOfEach(candidate, types) { - 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; - } - return true; - } - function literalTypesWithSameBaseType(types) { - var commonBaseType; - 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; - } - if (baseType === t || baseType !== commonBaseType) { - return false; - } - } - return true; - } - function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); - } - function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); - } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); - if (!primaryTypes.length) { - return getUnionType(types, true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - if (bestSupertypeScore === types.length - 1) { - break; - } - } - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); - } - function isArrayType(type) { - return getObjectFlags(type) & 4 && type.target === globalArrayType; - } - function isArrayLikeType(type) { - return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); - } - function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); - } - function isUnitType(type) { - return (type.flags & (224 | 2048 | 4096)) !== 0; - } - function isLiteralType(type) { - return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfLiteralType(type) { - 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 & 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) { - return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); - } - function getFalsyFlagsOfTypes(types) { - var result = 0; - 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.value === "" ? 32 : 0 : - type.flags & 64 ? type.value === 0 ? 64 : 0 : - type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; - } - 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; - } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && - getSignaturesOfType(type, 0).length === 0 && - getSignaturesOfType(type, 1).length === 0; - } - function createSymbolWithType(source, type) { - var symbol = createSymbol(source.flags, source.name); - symbol.declarations = source.declarations; - symbol.parent = source.parent; - symbol.type = type; - symbol.target = source; - if (source.valueDeclaration) { - symbol.valueDeclaration = source.valueDeclaration; - } - return symbol; - } - function transformTypeOfMembers(type, f) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var property = _a[_i]; - var original = getTypeOfSymbol(property); - var updated = f(original); - members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); - } - return members; - } - function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { - return type; - } - var regularType = type.regularType; - if (regularType) { - return regularType; - } - var resolved = type; - var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); - var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; - regularNew.objectFlags |= 128; - type.regularType = regularNew; - return regularNew; - } - function getWidenedProperty(prop) { - var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); - return widened === original ? prop : createSymbolWithType(prop, widened); - } - function getWidenedTypeOfObjectLiteral(type) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - members.set(prop.name, prop.flags & 4 ? getWidenedProperty(prop) : prop); - } - var stringIndexInfo = getIndexInfoOfType(type, 0); - var numberIndexInfo = getIndexInfoOfType(type, 1); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - } - function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); - } - function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 6144) { - return anyType; - } - if (getObjectFlags(type) & 128) { - return getWidenedTypeOfObjectLiteral(type); - } - if (type.flags & 65536) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); - } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); - } - } - return type; - } - function reportWideningErrorsInType(type) { - var errorReported = false; - if (type.flags & 65536) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (getObjectFlags(type) & 128) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); - } - errorReported = true; - } - } - } - return errorReported; - } - function reportImplicitAnyError(declaration, type) { - var typeAsString = typeToString(getWidenedType(type)); - var diagnostic; - switch (declaration.kind) { - case 149: - case 148: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; - break; - case 146: - diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; - break; - case 176: - diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; - break; - case 228: - case 151: - case 150: - case 153: - case 154: - case 186: - case 187: - if (!declaration.name) { - error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); - return; - } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; - break; - default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; - } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); - } - function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { - if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); - } - } - } - function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { - callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); - } - } - function createInferenceContext(signature, inferUnionTypes, useAnyForNoInferences) { - var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); - return { - signature: signature, - inferUnionTypes: inferUnionTypes, - inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length), - useAnyForNoInferences: useAnyForNoInferences - }; - } - function createTypeInferencesObject() { - return { - primary: undefined, - secondary: undefined, - topLevel: true, - isFixed: false, - }; - } - function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 || - objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || - objectFlags & 16 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - objectFlags & 32 || - type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); - } - function couldUnionOrIntersectionContainTypeVariables(type) { - if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); - } - return type.couldContainTypeVariables; - } - function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); - } - function inferTypeForHomomorphicMappedType(source, target) { - var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0); - if (properties.length === 0 && !indexInfo) { - return undefined; - } - var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var typeVariableArray = [typeVariable]; - var typeInferences = createTypeInferencesObject(); - var typeInferencesArray = [typeInferences]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 67108864; - 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)); - if (!inferredPropType) { - return undefined; - } - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.name); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; - inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; - members.set(prop.name, inferredProp); - } - if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - typeInferences.primary = undefined; - typeInferences.secondary = undefined; - inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); - var inferences = typeInferences.primary || typeInferences.secondary; - return inferences && getUnionType(inferences, true); - } - } - function inferTypesWithContext(context, originalSource, originalTarget) { - inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); - } - function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var symbolStack; - var visited; - var inferiority = 0; - inferFromTypes(originalSource, originalTarget); - function inferFromTypes(source, target) { - if (!couldContainTypeVariables(target)) { - return; - } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - var sourceTypes = source.aliasTypeArguments; - var targetTypes = target.aliasTypeArguments; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - return; - } - 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++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } - var matchingTypes = void 0; - for (var _b = 0, _c = source.types; _b < _c.length; _b++) { - var t = _c[_b]; - if (typeIdenticalToSomeType(t, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t); - inferFromTypes(t, t); - } - else if (t.flags & (64 | 32)) { - var b = getBaseTypeOfLiteralType(t); - if (typeIdenticalToSomeType(b, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t, b); - } - } - } - if (matchingTypes) { - source = removeTypesFromUnionOrIntersection(source, matchingTypes); - target = removeTypesFromUnionOrIntersection(target, matchingTypes); - } - } - if (target.flags & 540672) { - if (source.flags & 8388608) { - return; - } - for (var i = 0; i < typeVariables.length; i++) { - if (target === typeVariables[i]) { - var inferences = typeInferences[i]; - if (!inferences.isFixed) { - var candidates = inferiority ? - inferences.secondary || (inferences.secondary = []) : - inferences.primary || (inferences.primary = []); - if (!ts.contains(candidates, source)) { - candidates.push(source); - } - if (target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { - inferences.topLevel = false; - } - } - return; - } - } - } - else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - var sourceTypes = source.typeArguments || emptyArray; - var targetTypes = target.typeArguments || emptyArray; - var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; - for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 196608) { - var targetTypes = target.types; - var typeVariableCount = 0; - var typeVariable = void 0; - for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { - var t = targetTypes_3[_d]; - if (t.flags & 540672 && ts.contains(typeVariables, t)) { - typeVariable = t; - typeVariableCount++; - } - else { - inferFromTypes(source, t); - } - } - if (typeVariableCount === 1) { - inferiority++; - inferFromTypes(source, typeVariable); - inferiority--; - } - } - else if (source.flags & 196608) { - var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; - inferFromTypes(sourceType, target); - } - } - else { - source = getApparentType(source); - if (source.flags & 32768) { - var key = source.id + "," + target.id; - if (visited && visited.get(key)) { - return; - } - (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); - } - } - } - } - function inferFromObjectTypes(source, target) { - if (getObjectFlags(target) & 32) { - var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144) { - var index = ts.indexOf(typeVariables, constraintType.type); - if (index >= 0 && !typeInferences[index].isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - inferiority++; - inferFromTypes(inferredType, typeVariables[index]); - inferiority--; - } - } - return; - } - if (constraintType.flags & 16384) { - inferFromTypes(getIndexType(source), constraintType); - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); - return; - } - } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); - } - function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.name); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - } - } - function inferFromSignatures(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - var sourceLen = sourceSignatures.length; - var targetLen = targetSignatures.length; - var len = sourceLen < targetLen ? sourceLen : targetLen; - for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); - } - } - function inferFromParameterTypes(source, target) { - return inferFromTypes(source, target); - } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromParameterTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - } - function inferFromIndexTypes(source, target) { - var targetStringIndexType = getIndexTypeOfType(target, 0); - if (targetStringIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 0); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetStringIndexType); - } - } - var targetNumberIndexType = getIndexTypeOfType(target, 1); - if (targetNumberIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 1) || - getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 1); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetNumberIndexType); - } - } - } - } - function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function removeTypesFromUnionOrIntersection(type, typesToRemove) { - var reducedTypes = []; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!typeIdenticalToSomeType(t, typesToRemove)) { - reducedTypes.push(t); - } - } - return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); - } - function getInferenceCandidates(context, index) { - var inferences = context.inferences[index]; - return inferences.primary || inferences.secondary || emptyArray; - } - function hasPrimitiveConstraint(type) { - var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 | 262144); - } - function getInferredType(context, index) { - var inferredType = context.inferredTypes[index]; - var inferenceSucceeded; - if (!inferredType) { - var inferences = getInferenceCandidates(context, index); - if (inferences.length) { - var signature = context.signature; - var widenLiteralTypes = context.inferences[index].topLevel && - !hasPrimitiveConstraint(signature.typeParameters[index]) && - (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; - var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; - } - else { - var defaultType = getDefaultFromTypeParameter(context.signature.typeParameters[index]); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), getInferenceMapper(context))); - } - else { - inferredType = context.useAnyForNoInferences ? anyType : emptyObjectType; - } - inferenceSucceeded = true; - } - context.inferredTypes[index] = inferredType; - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - context.inferredTypes[index] = inferredType = instantiatedConstraint; - } - } - } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - context.failedTypeParameterIndex = index; - } - } - return inferredType; - } - function getInferredTypes(context) { - for (var i = 0; i < context.inferredTypes.length; i++) { - getInferredType(context, i); - } - return context.inferredTypes; - } - 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, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; - } - return links.resolvedSymbol; - } - function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); - } - function getFlowCacheKey(node) { - if (node.kind === 71) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 99) { - return "0"; - } - if (node.kind === 179) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + node.name.text; - } - return undefined; - } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71: - case 99: - return node; - case 179: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } - function isMatchingReference(source, target) { - switch (source.kind) { - case 71: - return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 || target.kind === 176) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99: - return target.kind === 99; - case 97: - return target.kind === 97; - case 179: - return target.kind === 179 && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } - return false; - } - function containsMatchingReference(source, target) { - while (source.kind === 179) { - source = source.expression; - if (isMatchingReference(source, target)) { - return true; - } - } - return false; - } - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 179) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } - function isOrContainsMatchingReference(source, target) { - return isMatchingReference(source, target) || containsMatchingReference(source, target); - } - function hasMatchingArgument(callExpression, reference) { - if (callExpression.arguments) { - for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isOrContainsMatchingReference(reference, argument)) { - return true; - } - } - } - if (callExpression.expression.kind === 179 && - isOrContainsMatchingReference(reference, callExpression.expression.expression)) { - return true; - } - return false; - } - function getFlowNodeId(flow) { - if (!flow.id) { - flow.id = nextFlowId; - nextFlowId++; - } - return flow.id; - } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } - function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 8192) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192)) { - return reducedType; - } - } - return declaredType; - } - function getTypeFactsOfTypes(types) { - var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); - } - function getTypeFacts(type) { - var flags = type.flags; - if (flags & 2) { - return strictNullChecks ? 4079361 : 4194049; - } - if (flags & 32) { - var isEmpty = type.value === ""; - return strictNullChecks ? - isEmpty ? 3030785 : 1982209 : - isEmpty ? 3145473 : 4194049; - } - if (flags & (4 | 16)) { - return strictNullChecks ? 4079234 : 4193922; - } - if (flags & 64) { - var isZero = type.value === 0; - return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; - } - if (flags & 8) { - return strictNullChecks ? 4078980 : 4193668; - } - if (flags & 136) { - return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; - } - if (flags & 32768) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; - } - if (flags & (1024 | 2048)) { - return 2457472; - } - if (flags & 4096) { - return 2340752; - } - if (flags & 512) { - return strictNullChecks ? 1981320 : 4193160; - } - if (flags & 16777216) { - return strictNullChecks ? 6166480 : 8378320; - } - if (flags & 540672) { - return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); - } - if (flags & 196608) { - return getTypeFactsOfTypes(type.types); - } - return 8388607; - } - function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); - } - function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072), defaultType]); - } - return type; - } - function getTypeOfDestructuredProperty(type, name) { - var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || - isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || - getIndexTypeOfType(type, 0) || - unknownType; - } - function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || - checkIteratedTypeOrElementType(type, undefined, false, false) || - unknownType; - } - function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); - } - function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); - return isDestructuringDefaultAssignment ? - getTypeWithDefault(getAssignedType(node), node.right) : - getTypeOfExpression(node.right); - } - function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 && parent.parent.left === parent || - parent.parent.kind === 216 && parent.parent.initializer === parent; - } - function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); - } - function getAssignedTypeOfSpreadExpression(node) { - return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); - } - function getAssignedTypeOfPropertyAssignment(node) { - return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); - } - function getAssignedTypeOfShorthandPropertyAssignment(node) { - return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); - } - function getAssignedType(node) { - var parent = node.parent; - switch (parent.kind) { - case 215: - return stringType; - case 216: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194: - return getAssignedTypeOfBinaryExpression(parent); - case 188: - return undefinedType; - case 177: - return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198: - return getAssignedTypeOfSpreadExpression(parent); - case 261: - return getAssignedTypeOfPropertyAssignment(parent); - case 262: - return getAssignedTypeOfShorthandPropertyAssignment(parent); - } - return unknownType; - } - function getInitialTypeOfBindingElement(node) { - var pattern = node.parent; - var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 ? - getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : - !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadExpression(parentType); - return getTypeWithDefault(type, node.initializer); - } - function getTypeOfInitializer(node) { - var links = getNodeLinks(node); - return links.resolvedType || getTypeOfExpression(node); - } - function getInitialTypeOfVariableDeclaration(node) { - if (node.initializer) { - return getTypeOfInitializer(node.initializer); - } - if (node.parent.parent.kind === 215) { - return stringType; - } - if (node.parent.parent.kind === 216) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; - } - return unknownType; - } - function getInitialType(node) { - return node.kind === 226 ? - getInitialTypeOfVariableDeclaration(node) : - getInitialTypeOfBindingElement(node); - } - function getInitialOrAssignedType(node) { - return node.kind === 226 || node.kind === 176 ? - getInitialType(node) : - getAssignedType(node); - } - function isEmptyArrayAssignment(node) { - return node.kind === 226 && node.initializer && - isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 && node.parent.kind === 194 && - isEmptyArrayLiteral(node.parent.right); - } - function getReferenceCandidate(node) { - switch (node.kind) { - case 185: - return getReferenceCandidate(node.expression); - case 194: - switch (node.operatorToken.kind) { - case 58: - return getReferenceCandidate(node.left); - case 26: - return getReferenceCandidate(node.right); - } - } - return node; - } - function getReferenceRoot(node) { - var parent = node.parent; - return parent.kind === 185 || - parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || - parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? - getReferenceRoot(parent) : node; - } - function getTypeOfSwitchClause(clause) { - if (clause.kind === 257) { - var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); - return isUnitType(caseType) ? caseType : undefined; - } - return neverType; - } - function getSwitchClauseTypes(switchStatement) { - var links = getNodeLinks(switchStatement); - if (!links.switchTypes) { - var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; - } - return links.switchTypes; - } - function eachTypeContainedIn(source, types) { - return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { - return true; - } - return containsType(target.types, source); - } - function forEachType(type, f) { - return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); - } - function filterType(type, f) { - if (type.flags & 65536) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; - } - function mapType(type, mapper) { - if (!(type.flags & 65536)) { - return mapper(type); - } - var types = type.types; - var mappedType; - var mappedTypes; - 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) { - mappedType = t; - } - else if (!mappedTypes) { - mappedTypes = [mappedType, t]; - } - else { - mappedTypes.push(t); - } - } - } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; - } - function extractTypesOfKind(type, kind) { - return filterType(type, function (t) { return (t.flags & kind) !== 0; }); - } - function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { - return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : - t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : - t; - }); - } - return typeWithPrimitives; - } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function createEvolvingArrayType(elementType) { - var result = createObjectType(256); - result.elementType = elementType; - return result; - } - function getEvolvingArrayType(elementType) { - return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); - } - function addEvolvingArrayElementType(evolvingArrayType, node) { - var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); - return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); - } - function createFinalArrayType(elementType) { - return elementType.flags & 8192 ? - autoArrayType : - createArrayType(elementType.flags & 65536 ? - getUnionType(elementType.types, true) : - elementType); - } - function getFinalArrayType(evolvingArrayType) { - return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); - } - function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; - } - function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? type.elementType : neverType; - } - function isEvolvingArrayTypeList(types) { - var hasEvolvingArrayType = false; - 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; - } - hasEvolvingArrayType = true; - } - } - return hasEvolvingArrayType; - } - function getUnionOrEvolvingArrayType(types, subtypeReduction) { - return isEvolvingArrayTypeList(types) ? - getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : - getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); - } - function isEvolvingArrayOperationTarget(node) { - var root = getReferenceRoot(node); - var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.text === "length" || - parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 && - parent.expression === root && - parent.parent.kind === 194 && - parent.parent.operatorToken.kind === 58 && - parent.parent.left === parent && - !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); - return isLengthPushOrUnshift || isElementAssignment; - } - function maybeTypePredicateCall(node) { - var links = getNodeLinks(node); - if (links.maybeTypePredicate === undefined) { - links.maybeTypePredicate = getMaybeTypePredicate(node); - } - return links.maybeTypePredicate; - } - function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97) { - var funcType = checkNonNullExpression(node.expression); - if (funcType !== silentNeverType) { - var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } - } - } - return false; - } - function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { - if (initialType === void 0) { initialType = declaredType; } - var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { - return declaredType; - } - var visitedFlowStart = visitedFlowCount; - var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; - var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { - return declaredType; - } - return resultType; - function getTypeAtFlowNode(flow) { - while (true) { - if (flow.flags & 1024) { - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; - } - } - } - var type = void 0; - if (flow.flags & 4096) { - flow.locked = true; - type = getTypeAtFlowNode(flow.antecedent); - flow.locked = false; - } - else if (flow.flags & 2048) { - flow = flow.antecedent; - continue; - } - else if (flow.flags & 16) { - type = getTypeAtFlowAssignment(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 96) { - type = getTypeAtFlowCondition(flow); - } - else if (flow.flags & 128) { - type = getTypeAtSwitchClause(flow); - } - else if (flow.flags & 12) { - if (flow.antecedents.length === 1) { - flow = flow.antecedents[0]; - continue; - } - type = flow.flags & 4 ? - getTypeAtFlowBranchLabel(flow) : - getTypeAtFlowLoopLabel(flow); - } - else if (flow.flags & 256) { - type = getTypeAtFlowArrayMutation(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 2) { - var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { - flow = container.flowNode; - continue; - } - type = initialType; - } - else { - type = convertAutoToAny(declaredType); - } - if (flow.flags & 1024) { - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; - } - return type; - } - } - function getTypeAtFlowAssignment(flow) { - var node = flow.node; - if (isMatchingReference(reference, node)) { - if (ts.getAssignmentTargetKind(node) === 2) { - var flowType = getTypeAtFlowNode(flow.antecedent); - return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); - } - if (declaredType === autoType || declaredType === autoArrayType) { - if (isEmptyArrayAssignment(node)) { - return getEvolvingArrayType(neverType); - } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); - return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; - } - if (declaredType.flags & 65536) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); - } - return declaredType; - } - if (containsMatchingReference(reference, node)) { - return declaredType; - } - return undefined; - } - function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { - var evolvedType_1 = type; - if (node.kind === 181) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); - } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); - } - } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); - } - return flowType; - } - return undefined; - } - function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (type.flags & 8192) { - return flowType; - } - var assumeTrue = (flow.flags & 32) !== 0; - var nonEvolvingType = finalizeEvolvingArrayType(type); - var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); - if (narrowedType === nonEvolvingType) { - return flowType; - } - var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; - return createFlowType(resultType, incomplete); - } - function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); - } - function getTypeAtFlowBranchLabel(flow) { - var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - if (antecedent.flags & 2048 && antecedent.lock.locked) { - continue; - } - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); - if (type === declaredType && declaredType === initialType) { - return type; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } - } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); - } - function getTypeAtFlowLoopLabel(flow) { - var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); - if (!key) { - key = getFlowCacheKey(reference); - } - var cached = cache.get(key); - if (cached) { - return cached; - } - for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); - } - } - var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; - flowLoopNodes[flowLoopCount] = flow; - flowLoopKeys[flowLoopCount] = key; - flowLoopTypes[flowLoopCount] = antecedentTypes; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); - flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); - var cached_1 = cache.get(key); - if (cached_1) { - return cached_1; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (type === declaredType) { - break; - } - } - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, true); - } - cache.set(key, result); - return result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 179 && - declaredType.flags & 65536 && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); - } - function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; - } - function narrowTypeByBinaryExpression(type, expr, assumeTrue) { - switch (expr.operatorToken.kind) { - case 58: - return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32: - case 33: - case 34: - case 35: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 && right_1.kind === 9) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); - } - if (right_1.kind === 189 && left_1.kind === 9) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); - } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); - } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); - } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); - } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; - } - break; - case 93: - return narrowTypeByInstanceof(type, expr, assumeTrue); - case 26: - return narrowType(type, expr.right, assumeTrue); - } - return type; - } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1) { - return type; - } - if (operator === 33 || operator === 35) { - assumeTrue = !assumeTrue; - } - var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 32 || operator === 33; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - value.kind === 95 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); - } - if (type.flags & 16810497) { - return type; - } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); - } - if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); - } - return type; - } - function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceCandidate(typeOfExpr.expression); - if (!isMatchingReference(reference, target)) { - if (containsMatchingReference(reference, target)) { - return declaredType; - } - return type; - } - if (operator === 33 || operator === 35) { - assumeTrue = !assumeTrue; - } - if (assumeTrue && !(type.flags & 65536)) { - var targetType = typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & 540672) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } - } - } - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; - return getTypeWithFacts(type, facts); - } - function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - var switchTypes = getSwitchClauseTypes(switchStatement); - if (!switchTypes.length) { - return type; - } - var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); - if (!hasDefaultClause) { - return caseType; - } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); - } - function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { - return declaredType; - } - return type; - } - var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { - return type; - } - var targetType; - var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (prototypeProperty) { - var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (!isTypeAny(prototypePropertyType)) { - targetType = prototypePropertyType; - } - } - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } - if (!targetType) { - var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (getObjectFlags(rightType) & 16) { - constructSignatures = getSignaturesOfType(rightType, 1); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } - } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); - } - return type; - } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { - if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); - } - if (type.flags & 65536) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192)) { - return assignableType; - } - } - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); - } - function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { - return type; - } - var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; - if (!predicate) { - return type; - } - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; - if (predicateArgument) { - if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } - } - } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } - return type; - } - function narrowType(type, expr, assumeTrue) { - switch (expr.kind) { - case 71: - case 99: - case 97: - case 179: - return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181: - return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185: - return narrowType(type, expr.expression, assumeTrue); - case 194: - return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192: - if (expr.operator === 51) { - return narrowType(type, expr.operand, !assumeTrue); - } - break; - } - return type; - } - } - function getTypeOfSymbolAtLocation(symbol, location) { - if (location.kind === 71) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { - location = location.parent; - } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { - var type = getTypeOfExpression(location); - if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { - return type; - } - } - } - return getTypeOfSymbol(symbol); - } - function getControlFlowContainer(node) { - return ts.findAncestor(node.parent, function (node) { - return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 || - node.kind === 265 || - node.kind === 149; - }); - } - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); - } - function markParameterAssignments(node) { - if (node.kind === 71) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); - } - } - function isConstVariable(symbol) { - return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; - } - function removeOptionalityFromDeclaredType(declaredType, declaration) { - var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 && - declaration.initializer && - getFalsyFlags(declaredType) & 2048 && - !(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) { - return unknownType; - } - if (symbol === argumentsSymbol) { - var container = ts.getContainingFunction(node); - if (languageVersion < 2) { - if (container.kind === 187) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); - } - else if (ts.hasModifier(container, 256)) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); - } - } - getNodeLinks(container).flags |= 8192; - return getTypeOfSymbol(symbol); - } - if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); - } - var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (localOrExportSymbol.flags & 32) { - var declaration_1 = localOrExportSymbol.valueDeclaration; - if (declaration_1.kind === 229 - && ts.nodeIsDecorated(declaration_1)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === declaration_1 && container.name !== node) { - getNodeLinks(declaration_1).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; - break; - } - container = ts.getContainingClass(container); - } - } - else if (declaration_1.kind === 199) { - var container = ts.getThisContainer(node, false); - while (container !== undefined) { - if (container.parent === declaration_1) { - if (container.kind === 149 && ts.hasModifier(container, 32)) { - getNodeLinks(declaration_1).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; - } - break; - } - container = ts.getThisContainer(container, false); - } - } - } - checkCollisionWithCapturedSuperVariable(node, node); - checkCollisionWithCapturedThisVariable(node, node); - checkCollisionWithCapturedNewTargetVariable(node, node); - checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); - var declaration = localOrExportSymbol.valueDeclaration; - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); - return unknownType; - } - if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); - return unknownType; - } - } - if (!(localOrExportSymbol.flags & 3) || assignmentKind === 1 || !declaration) { - return type; - } - var isParameter = ts.getRootDeclaration(declaration).kind === 146; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || - flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && - (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - var assumeInitialized = isParameter || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || - ts.isInAmbientContext(declaration); - var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : - type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048); - var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); - if (type === autoType || type === autoArrayType) { - if (flowType === autoType || flowType === autoArrayType) { - if (noImplicitAny) { - 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); - } - } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - return type; - } - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); - } - function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 || - (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 260) { - return; - } - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { - getNodeLinks(current).flags |= 65536; - } - if (container.kind === 214 && - ts.getAncestor(symbol.valueDeclaration, 227).parent === container && - isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152; - } - getNodeLinks(symbol.valueDeclaration).flags |= 262144; - } - if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072; - } - } - function isAssignedInBodyOfForStatement(node, container) { - var current = node; - while (current.parent.kind === 185) { - current = current.parent; - } - var isAssigned = false; - if (ts.isAssignmentTarget(current)) { - isAssigned = true; - } - else if ((current.parent.kind === 192 || current.parent.kind === 193)) { - var expr = current.parent; - isAssigned = expr.operator === 43 || expr.operator === 44; - } - if (!isAssigned) { - return false; - } - return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); - } - function captureLexicalThis(node, container) { - getNodeLinks(node).flags |= 2; - if (container.kind === 149 || container.kind === 152) { - var classNode = container.parent; - getNodeLinks(classNode).flags |= 4; - } - else { - getNodeLinks(container).flags |= 4; - } - } - function findFirstSuperCall(n) { - if (ts.isSuperCall(n)) { - return n; - } - else if (ts.isFunctionLike(n)) { - return undefined; - } - return ts.forEachChild(n, findFirstSuperCall); - } - function getSuperCallInConstructor(constructor) { - var links = getNodeLinks(constructor); - if (links.hasSuperCall === undefined) { - links.superCall = findFirstSuperCall(constructor.body); - links.hasSuperCall = links.superCall ? true : false; - } - return links.superCall; - } - function classDeclarationExtendsNull(classDecl) { - var classSymbol = getSymbolOfNode(classDecl); - var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); - return baseConstructorType === nullWideningType; - } - function checkThisBeforeSuper(node, container, diagnosticMessage) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, diagnosticMessage); - } - } - } - function checkThisExpression(node) { - var container = ts.getThisContainer(node, true); - var needToCaptureLexicalThis = false; - if (container.kind === 152) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - if (container.kind === 187) { - container = ts.getThisContainer(container, false); - needToCaptureLexicalThis = (languageVersion < 2); - } - switch (container.kind) { - case 233: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); - break; - case 232: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - break; - case 152: - if (isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); - } - break; - case 149: - case 148: - if (ts.getModifierFlags(container) & 32) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); - } - break; - case 144: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); - break; - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node, container); - } - if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 186 && - container.parent.kind === 194 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; - var classSymbol = checkExpression(className).symbol; - if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { - return getInferredClassType(classSymbol); - } - } - var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); - if (thisType) { - return thisType; - } - } - if (ts.isClassLike(container.parent)) { - var symbol = getSymbolOfNode(container.parent); - var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type); - } - if (ts.isInJavaScriptFile(node)) { - var type = getTypeForThisExpressionFromJSDoc(container); - if (type && type !== unknownType) { - return type; - } - } - if (noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; - } - function getTypeForThisExpressionFromJSDoc(node) { - var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 279) { - var jsDocFunctionType = jsdocType; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 282) { - return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); - } - } - } - function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); - } - function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; - var container = ts.getSuperContainer(node, true); - var needToCaptureLexicalThis = false; - if (!isCallExpression) { - while (container && container.kind === 187) { - container = ts.getSuperContainer(container, true); - needToCaptureLexicalThis = languageVersion < 2; - } - } - var canUseSuperExpression = isLegalUsageOfSuperExpression(container); - var nodeCheckFlag = 0; - if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); - if (current && current.kind === 144) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); - } - else if (isCallExpression) { - error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); - } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); - } - else { - error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); - } - return unknownType; - } - if (!isCallExpression && container.kind === 152) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); - } - if ((ts.getModifierFlags(container) & 32) || isCallExpression) { - nodeCheckFlag = 512; - } - else { - nodeCheckFlag = 256; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.getModifierFlags(container) & 256) { - if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096; - } - else { - getNodeLinks(container).flags |= 2048; - } - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node.parent, container); - } - if (container.parent.kind === 178) { - if (languageVersion < 2) { - error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); - return unknownType; - } - else { - return anyType; - } - } - var classLikeDeclaration = container.parent; - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } - if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); - return unknownType; - } - return nodeCheckFlag === 512 - ? getBaseConstructorTypeOfClass(classType) - : getTypeWithThisArgument(baseClassType, classType.thisType); - function isLegalUsageOfSuperExpression(container) { - if (!container) { - return false; - } - if (isCallExpression) { - return container.kind === 152; - } - else { - if (ts.isClassLike(container.parent) || container.parent.kind === 178) { - if (ts.getModifierFlags(container) & 32) { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154; - } - else { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154 || - container.kind === 149 || - container.kind === 148 || - container.kind === 152; - } - } - } - return false; - } - } - function getContainingObjectLiteral(func) { - return (func.kind === 151 || - func.kind === 153 || - func.kind === 154) && func.parent.kind === 178 ? func.parent : - func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : - undefined; - } - function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; - } - function getThisTypeFromContextualType(type) { - return mapType(type, function (t) { - return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); - }); - } - function getContextualThisParameterType(func) { - if (func.kind === 187) { - return undefined; - } - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var thisParameter = contextualSignature.thisParameter; - if (thisParameter) { - return getTypeOfSymbol(thisParameter); - } - } - } - if (noImplicitThis) { - var containingLiteral = getContainingObjectLiteral(func); - if (containingLiteral) { - var contextualType = getApparentTypeOfContextualType(containingLiteral); - var literal = containingLiteral; - var type = contextualType; - while (type) { - var thisType = getThisTypeFromContextualType(type); - if (thisType) { - return instantiateType(thisType, getContextualMapper(containingLiteral)); - } - if (literal.parent.kind !== 261) { - break; - } - literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); - } - return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); - } - if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { - var target = func.parent.left; - if (target.kind === 179 || target.kind === 180) { - return checkExpressionCached(target.expression); - } - } - } - return undefined; - } - function getContextuallyTypedParameterType(parameter) { - var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; - } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; - } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } - } - } - return undefined; - } - function getContextualTypeForInitializerExpression(node) { - var declaration = node.parent; - if (node === declaration.initializer) { - if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.kind === 146) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true, false); - } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176 && - parentDeclaration.type && - !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); - } - } - } - } - return undefined; - } - function getContextualTypeForReturnExpression(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return undefined; - } - var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) - : contextualReturnType; - } - return undefined; - } - function getContextualTypeForYieldOperand(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); - if (contextualReturnType) { - return node.asteriskToken - ? contextualReturnType - : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); - } - } - return undefined; - } - function isInParameterInitializerBeforeContainingFunction(node) { - while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } - function getContextualReturnType(functionDecl) { - if (functionDecl.type || - functionDecl.kind === 152 || - functionDecl.kind === 153 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 154))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); - } - var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { - return getReturnTypeOfSignature(signature); - } - return undefined; - } - function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); - if (argIndex >= 0) { - var signature = getResolvedOrAnySignature(callTarget); - return getTypeAtPosition(signature, argIndex); - } - return undefined; - } - function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183) { - return getContextualTypeForArgument(template.parent, substitutionExpression); - } - return undefined; - } - function getContextualTypeForBinaryOperand(node) { - var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (operator >= 58 && operator <= 70) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { - return undefined; - } - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } - } - else if (operator === 54) { - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); - } - return type; - } - else if (operator === 53 || operator === 26) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } - } - return undefined; - } - function getTypeOfPropertyOfContextualType(type, name) { - return mapType(type, function (t) { - var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; - }); - } - function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); - } - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } - function getContextualTypeForObjectLiteralMethod(node) { - ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { - return undefined; - } - return getContextualTypeForObjectLiteralElement(node); - } - function getContextualTypeForObjectLiteralElement(element) { - var objectLiteral = element.parent; - var type = getApparentTypeOfContextualType(objectLiteral); - if (type) { - if (!ts.hasDynamicName(element)) { - var symbolName = getSymbolOfNode(element).name; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); - if (propertyType) { - return propertyType; - } - } - return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || - getIndexTypeOfContextualType(type, 0); - } - return undefined; - } - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1) - || getIteratedTypeOrElementType(type, undefined, false, false, false); - } - return undefined; - } - function getContextualTypeForConditionalOperand(node) { - var conditional = node.parent; - return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; - } - function getContextualTypeForJsxExpression(node) { - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - node.parent.openingElement.attributes; - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfType(attributesType, node.parent.name.text); - } - else if (node.parent.kind === 249) { - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - return attributesType; - } - } - function getContextualTypeForJsxAttribute(attribute) { - var attributesType = getContextualType(attribute.parent); - if (ts.isJsxAttribute(attribute)) { - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - return getTypeOfPropertyOfType(attributesType, attribute.name.text); - } - else { - return attributesType; - } - } - function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); - } - function getContextualType(node) { - if (isInsideWithStatementBody(node)) { - return undefined; - } - if (node.contextualType) { - return node.contextualType; - } - var parent = node.parent; - switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 176: - return getContextualTypeForInitializerExpression(node); - case 187: - case 219: - return getContextualTypeForReturnExpression(node); - case 197: - return getContextualTypeForYieldOperand(parent); - case 181: - case 182: - return getContextualTypeForArgument(parent, node); - case 184: - case 202: - return getTypeFromTypeNode(parent.type); - case 194: - return getContextualTypeForBinaryOperand(node); - case 261: - case 262: - return getContextualTypeForObjectLiteralElement(parent); - case 263: - return getApparentTypeOfContextualType(parent.parent); - case 177: - return getContextualTypeForElementExpression(node); - case 195: - return getContextualTypeForConditionalOperand(node); - case 205: - ts.Debug.assert(parent.parent.kind === 196); - return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: - return getContextualType(parent); - case 256: - return getContextualTypeForJsxExpression(parent); - case 253: - case 255: - return getContextualTypeForJsxAttribute(parent); - case 251: - case 250: - return getAttributesTypeFromJsxOpeningLikeElement(parent); - } - return undefined; - } - function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; - } - function getNonGenericSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!signature.typeParameters && !isAritySmaller(signature, node)) { - return signature; - } - } - } - function isAritySmaller(signature, target) { - var targetParameterCount = 0; - for (; targetParameterCount < target.parameters.length; targetParameterCount++) { - var param = target.parameters[targetParameterCount]; - if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { - break; - } - } - if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { - targetParameterCount--; - } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; - } - function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 || node.kind === 187; - } - function getContextualSignatureForFunctionLikeDeclaration(node) { - return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) - ? getContextualSignature(node) - : undefined; - } - function getContextualTypeForFunctionLikeDeclaration(node) { - return ts.isObjectLiteralMethod(node) ? - getContextualTypeForObjectLiteralMethod(node) : - getApparentTypeOfContextualType(node); - } - function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); - if (!type) { - return undefined; - } - if (!(type.flags & 65536)) { - return getNonGenericSignature(type, node); - } - var signatureList; - var types = type.types; - 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) { - signatureList = [signature]; - } - else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { - return undefined; - } - else { - signatureList.push(signature); - } - } - } - var result; - if (signatureList) { - result = cloneSignature(signatureList[0]); - result.resolvedReturnType = undefined; - result.unionSignatures = signatureList; - } - return result; - } - function checkSpreadExpression(node, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 1536); - } - var arrayOrIterableType = checkExpression(node.expression, checkMode); - return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); - } - function hasDefaultValue(node) { - return (node.kind === 176 && !!node.initializer) || - (node.kind === 194 && node.operatorToken.kind === 58); - } - function checkArrayLiteral(node, checkMode) { - var elements = node.elements; - var hasSpreadElement = false; - var elementTypes = []; - var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 198) { - var restArrayType = checkExpression(e.expression, checkMode); - var restElementType = getIndexTypeOfType(restArrayType, 1) || - getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); - if (restElementType) { - elementTypes.push(restElementType); - } - } - else { - var type = checkExpressionForMutableLocation(e, checkMode); - elementTypes.push(type); - } - hasSpreadElement = hasSpreadElement || e.kind === 198; - } - if (!hasSpreadElement) { - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); - type.pattern = node; - return type; - } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { - var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else { - if (patternElement.kind !== 200) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(unknownType); - } - } - } - if (elementTypes.length) { - return createTupleType(elementTypes); - } - } - } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); - } - function isNumericName(name) { - return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); - } - function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); - } - function isInfinityOrNaNString(name) { - return name === "Infinity" || name === "-Infinity" || name === "NaN"; - } - function isNumericLiteralName(name) { - return (+name).toString() === name; - } - function checkComputedPropertyName(node) { - var links = getNodeLinks(node.expression); - if (!links.resolvedType) { - links.resolvedType = checkExpression(node.expression); - 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 { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); - } - } - return links.resolvedType; - } - function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { - var propTypes = []; - for (var i = 0; i < properties.length; i++) { - if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { - propTypes.push(getTypeOfSymbol(properties[i])); - } - } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; - return createIndexInfo(unionType, false); - } - function checkObjectLiteral(node, checkMode) { - var inDestructuringPattern = ts.isAssignmentTarget(node); - checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); - var propertiesArray = []; - var spread = emptyObjectType; - var propagatedFlags = 0; - var contextualType = getApparentTypeOfContextualType(node); - var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); - var typeFlags = 0; - var patternWithComputedProperties = false; - var hasComputedStringProperty = false; - var hasComputedNumberProperty = false; - var offset = 0; - for (var i = 0; i < node.properties.length; i++) { - var memberDecl = node.properties[i]; - var member = memberDecl.symbol; - if (memberDecl.kind === 261 || - memberDecl.kind === 262 || - ts.isObjectLiteralMethod(memberDecl)) { - var type = void 0; - if (memberDecl.kind === 261) { - type = checkPropertyAssignment(memberDecl, checkMode); - } - else if (memberDecl.kind === 151) { - type = checkObjectLiteralMethod(memberDecl, checkMode); - } - else { - ts.Debug.assert(memberDecl.kind === 262); - type = checkExpressionForMutableLocation(memberDecl.name, checkMode); - } - typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, member.name); - if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); - if (isOptional) { - prop.flags |= 67108864; - } - if (ts.hasDynamicName(memberDecl)) { - patternWithComputedProperties = true; - } - } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { - var impliedProp = getPropertyOfType(contextualType, member.name); - if (impliedProp) { - prop.flags |= impliedProp.flags & 67108864; - } - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { - error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); - } - } - prop.declarations = member.declarations; - prop.parent = member.parent; - if (member.valueDeclaration) { - prop.valueDeclaration = member.valueDeclaration; - } - prop.type = type; - prop.target = member; - member = prop; - } - else if (memberDecl.kind === 263) { - if (languageVersion < 2) { - checkExternalEmitHelpers(memberDecl, 2); - } - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - propertiesArray = []; - propertiesTable = ts.createMap(); - hasComputedStringProperty = false; - hasComputedNumberProperty = false; - typeFlags = 0; - } - var type = checkExpression(memberDecl.expression); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return unknownType; - } - spread = getSpreadType(spread, type); - offset = i + 1; - continue; - } - else { - ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); - checkNodeDeferred(memberDecl); - } - if (ts.hasDynamicName(memberDecl)) { - if (isNumericName(memberDecl.name)) { - hasComputedNumberProperty = true; - } - else { - hasComputedStringProperty = true; - } - } - else { - propertiesTable.set(member.name, member); - } - propertiesArray.push(member); - } - if (contextualTypeHasPattern) { - for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 67108864)) { - error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - propertiesTable.set(prop.name, prop); - propertiesArray.push(prop); - } - } - } - if (spread !== emptyObjectType) { - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; - } - return spread; - } - return createObjectLiteralType(); - function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); - result.objectFlags |= 128; - if (patternWithComputedProperties) { - result.objectFlags |= 512; - } - if (inDestructuringPattern) { - result.pattern = node; - } - if (!(result.flags & 6144)) { - propagatedFlags |= (result.flags & 14680064); - } - return result; - } - } - function isValidSpreadType(type) { - return !!(type.flags & (1 | 4096 | 2048 | 16777216) || - type.flags & 32768 && !isGenericMappedType(type) || - type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); - } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); - return getJsxGlobalElementType() || anyType; - } - function checkJsxElement(node) { - checkJsxOpeningLikeElement(node.openingElement); - if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { - getIntrinsicTagSymbol(node.closingElement); - } - else { - checkExpression(node.closingElement.tagName); - } - return getJsxGlobalElementType() || anyType; - } - function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; - } - function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 179 || tagName.kind === 99) { - return false; - } - else { - return ts.isIntrinsicJsxName(tagName.text); - } - } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { - var attributes = openingLikeElement.attributes; - 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; - if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; - var attributeSymbol = createSymbol(4 | 134217728 | member.flags, member.name); - attributeSymbol.declarations = member.declarations; - attributeSymbol.parent = member.parent; - if (member.valueDeclaration) { - attributeSymbol.valueDeclaration = member.valueDeclaration; - } - attributeSymbol.type = exprType; - 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); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - var exprType = checkExpression(attributeDecl.expression); - if (isTypeAny(exprType)) { - hasSpreadAnyType = true; - } - if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); - } - else { - typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; - } - } - } - if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - } - attributesArray = getPropertiesOfType(spread); - } - 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 _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - if (child.kind === 10) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } - 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); - childrenPropSymbol.type = childrenTypes.length === 1 ? - childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); - } - } - 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); - result.flags |= 33554432 | 4194304; - result.objectFlags |= 128; - return result; - } - } - function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); - } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; - } - function getIntrinsicTagSymbol(node) { - var links = getNodeLinks(node); - if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); - if (intrinsicProp) { - links.jsxFlags |= 1; - return links.resolvedSymbol = intrinsicProp; - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - links.jsxFlags |= 2; - return links.resolvedSymbol = intrinsicElementsType.symbol; - } - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return links.resolvedSymbol = unknownSymbol; - } - else { - if (noImplicitAny) { - error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); - } - return links.resolvedSymbol = unknownSymbol; - } - } - return links.resolvedSymbol; - } - function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536)); - if (isTypeAny(valueType)) { - return anyType; - } - var signatures = getSignaturesOfType(valueType, 1); - if (signatures.length === 0) { - signatures = getSignaturesOfType(valueType, 0); - if (signatures.length === 0) { - error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); - return unknownType; - } - } - 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); - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); - var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); - var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); - if (propertiesOfJsxElementAttribPropInterface) { - if (propertiesOfJsxElementAttribPropInterface.length === 0) { - return ""; - } - else if (propertiesOfJsxElementAttribPropInterface.length === 1) { - return propertiesOfJsxElementAttribPropInterface[0].name; - } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { - error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, nameOfAttribPropContainer); - } - } - return undefined; - } - function getJsxElementPropertiesName() { - if (!_hasComputedJsxElementPropertiesName) { - _hasComputedJsxElementPropertiesName = true; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; - } - function getJsxElementChildrenPropertyname() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - 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)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); - 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) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - 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++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.text) && - !getPropertyOfType(paramType, attribute.name.text)) { - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - if (!result) { - result = allMatchingAttributesType; - } - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttributes !== unknownType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } - if (elementType.flags & 65536) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), true); - } - if (elementType.flags & 2) { - return anyType; - } - else if (elementType.flags & 32) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - return anyType; - } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - return anyType; - } - else if (propsName === "") { - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - return attributesType; - } - else { - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } - } - function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { - ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var symbol = getIntrinsicTagSymbol(node); - if (links.jsxFlags & 1) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); - } - else if (links.jsxFlags & 2) { - return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; - } - else { - return links.resolvedJsxElementAttributesType = unknownType; - } - } - return links.resolvedJsxElementAttributesType; - } - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); - } - return links.resolvedJsxElementAttributesType; - } - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, true); - } - } - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, false); - } - } - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.text); - return prop || unknownSymbol; - } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; - } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; - } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } - } - return deferredJsxStatelessElementType; - } - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); - return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; - } - function checkJsxPreconditions(errorNode) { - if ((compilerOptions.jsx || 0) === 0) { - error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); - } - if (getJsxGlobalElementType() === undefined) { - if (noImplicitAny) { - error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); - } - } - } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); - checkJsxPreconditions(node); - var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); - if (reactSym) { - reactSym.isReferenced = true; - if (reactSym.flags & 8388608 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { - markAliasSymbolAsReferenced(reactSym); - } - } - 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) : - getCustomJsxElementAttributesType(openingLikeElement, false); - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.name) || !!(getPropertyOfType(targetAttributesType, attribute.name)); - }); - if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); - } - else { - 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) { - if (node.expression) { - var type = checkExpression(node.expression, checkMode); - if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); - } - return type; - } - else { - return unknownType; - } - } - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149; - } - function getDeclarationNodeFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; - } - function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); - } - function checkPropertyAccessibility(node, left, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 || node.kind === 226 ? - node.name : - node.right; - 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; - } - if (left.kind === 97) { - if (languageVersion < 2) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 && propKind !== 150; - }); - if (hasNonMethodDeclaration) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - return false; - } - } - if (flags & 128) { - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - } - if (!(flags & 24)) { - return true; - } - if (flags & 8) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - return true; - } - if (left.kind === 97) { - return true; - } - var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { - var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; - }); - if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); - return false; - } - if (flags & 32) { - return true; - } - if (type.flags & 16384 && type.isThisType) { - type = getConstraintOfTypeParameter(type); - } - if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); - return false; - } - return true; - } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); - } - function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; - if (kind) { - error(errorNode, kind & 2048 ? kind & 4096 ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); - var t = getNonNullableType(type); - return t.flags & (6144 | 8192) ? unknownType : t; - } - return type; - } - function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); - } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); - } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { - return propType; - } - 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 - : node.left; - var type = checkExpression(left); - if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop) { - return checkPropertyAccessibility(node, left, type, prop); - } - } - return true; - } - function getForInVariableSymbol(node) { - var initializer = node.initializer; - if (initializer.kind === 227) { - var variable = initializer.declarations[0]; - if (variable && !ts.isBindingPattern(variable.name)) { - return getSymbolOfNode(variable); - } - } - else if (initializer.kind === 71) { - return getResolvedSymbol(initializer); - } - return undefined; - } - function hasNumericPropertyNames(type) { - return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); - } - function isForInVariableForNumericPropertyNames(expr) { - var e = ts.skipParentheses(expr); - if (e.kind === 71) { - var symbol = getResolvedSymbol(e); - if (symbol.flags & 3) { - var child = expr; - var node = expr.parent; - while (node) { - if (node.kind === 215 && - child === node.statement && - getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(getTypeOfExpression(node.expression))) { - return true; - } - child = node; - node = node.parent; - } - } - } - return false; - } - function checkIndexedAccess(node) { - var objectType = checkNonNullExpression(node.expression); - var indexExpression = node.argumentExpression; - if (!indexExpression) { - var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 && node.parent.expression === node) { - var start = ts.skipTrivia(sourceFile.text, node.expression.end); - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); - } - else { - var start = node.end - "]".length; - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); - } - return unknownType; - } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); - if (objectType === unknownType || objectType === silentNeverType) { - return objectType; - } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { - error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); - return unknownType; - } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === unknownType) { - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - if ((expressionType.flags & 512) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); - if (!globalESSymbol) { - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - 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); - } - else if (node.kind !== 147) { - ts.forEach(node.arguments, function (argument) { - checkExpression(argument); - }); - } - return anySignature; - } - function resolveErrorCall(node) { - resolveUntypedCall(node); - return unknownSignature; - } - function reorderCandidates(signatures, result) { - var lastParent; - var lastSymbol; - var cutoffIndex = 0; - var index; - var specializedIndex = -1; - var spliceIndex; - ts.Debug.assert(!result.length); - 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) { - if (lastParent && parent === lastParent) { - index++; - } - else { - lastParent = parent; - index = cutoffIndex; - } - } - else { - index = cutoffIndex = result.length; - lastParent = parent; - } - lastSymbol = symbol; - if (signature.hasLiteralTypes) { - specializedIndex++; - spliceIndex = specializedIndex; - cutoffIndex++; - } - else { - spliceIndex = index; - } - result.splice(spliceIndex, 0, signature); - } - } - function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 198) { - return i; - } - } - return -1; - } - function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; - var typeArguments; - var callIsIncomplete; - var isDecorator; - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - return true; - } - if (node.kind === 183) { - var tagExpression = node; - argCount = args.length; - typeArguments = undefined; - if (tagExpression.template.kind === 196) { - var templateExpression = tagExpression.template; - var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); - ts.Debug.assert(lastSpan !== undefined); - callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; - } - else { - var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 13); - callIsIncomplete = !!templateLiteral.isUnterminated; - } - } - else if (node.kind === 147) { - isDecorator = true; - typeArguments = undefined; - argCount = getEffectiveArgumentCount(node, undefined, signature); - } - else { - var callExpression = node; - if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 182); - return signature.minArgumentCount === 0; - } - argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; - callIsIncomplete = callExpression.arguments.end === callExpression.end; - typeArguments = callExpression.typeArguments; - spreadArgIndex = getSpreadArgumentIndex(args); - } - var numTypeParameters = ts.length(signature.typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { - return false; - } - if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; - } - if (!signature.hasRestParameter && argCount > signature.parameters.length) { - return false; - } - var hasEnoughArguments = argCount >= signature.minArgumentCount; - return callIsIncomplete || hasEnoughArguments; - } - function getSingleCallSignature(type) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - return resolved.callSignatures[0]; - } - } - return undefined; - } - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, true, false); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - inferTypesWithContext(context, instantiateType(source, contextualMapper), target); - }); - return getSignatureInstantiation(signature, getInferredTypes(context)); - } - function inferTypeArguments(node, signature, args, excludeArgument, context) { - var typeParameters = signature.typeParameters; - var inferenceMapper = getInferenceMapper(context); - for (var i = 0; i < typeParameters.length; i++) { - if (!context.inferences[i].isFixed) { - context.inferredTypes[i] = undefined; - } - } - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } - var thisType = getThisTypeOfSignature(signature); - if (thisType) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypesWithContext(context, thisArgumentType, thisType); - } - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } - inferTypesWithContext(context, argType, paramType); - } - } - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); - } - } - } - getInferredTypes(context); - } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { - var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; - var mapper; - for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } - } - } - return typeArgumentsAreAssignable; - } - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - var callIsIncomplete = node.attributes.end === node.end; - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.name) && isUnhyphenatedJsxName(arg.name)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); - } - function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); - } - var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; - var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { - return false; - } - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - } - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { - return false; - } - } - } - return true; - } - function getThisArgumentOfCall(node) { - if (node.kind === 181) { - var callee = node.expression; - if (callee.kind === 179) { - return callee.expression; - } - else if (callee.kind === 180) { - return callee.expression; - } - } - } - function getEffectiveCallArguments(node) { - var args; - if (node.kind === 183) { - var template = node.template; - args = [undefined]; - if (template.kind === 196) { - ts.forEach(template.templateSpans, function (span) { - args.push(span.expression); - }); - } - } - else if (node.kind === 147) { - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - args = node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; - } - else { - args = node.arguments || emptyArray; - } - return args; - } - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147) { - switch (node.parent.kind) { - case 229: - case 199: - return 1; - case 149: - return 2; - case 151: - case 153: - case 154: - if (languageVersion === 0) { - return 2; - } - return signature.parameters.length >= 3 ? 3 : 2; - case 146: - return 3; - } - } - else { - return args.length; - } - } - function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 229) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 146) { - node = node.parent; - if (node.kind === 152) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 229) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return unknownType; - } - if (node.kind === 146) { - node = node.parent; - if (node.kind === 152) { - return anyType; - } - } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - var element = node; - switch (element.name.kind) { - case 71: - case 8: - case 9: - return getLiteralType(element.name.text); - case 144: - var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return unknownType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 229) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 146) { - return numberType; - } - if (node.kind === 149) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return unknownType; - } - function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 147) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 183) { - return getGlobalTemplateStringsArrayType(); - } - return undefined; - } - function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 147 || - (argIndex === 0 && node.kind === 183)) { - return undefined; - } - return args[argIndex]; - } - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147) { - return node.expression; - } - else if (argIndex === 0 && node.kind === 183) { - return node.template; - } - else { - return arg; - } - } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183; - var isDecorator = node.kind === 147; - var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); - var typeArguments; - if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { - typeArguments = node.typeArguments; - if (node.expression.kind !== 97) { - ts.forEach(typeArguments, checkSourceElement); - } - } - if (signatures.length === 1) { - var declaration = signatures[0].declaration; - if (declaration && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration)) { - if (containsArgumentsReference(declaration)) { - var signatureWithRest = cloneSignature(signatures[0]); - var syntheticArgsSymbol = createSymbol(3, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - signatureWithRest.parameters = ts.concatenate(signatureWithRest.parameters, [syntheticArgsSymbol]); - signatureWithRest.hasRestParameter = true; - signatures = [signatureWithRest]; - } - } - } - var candidates = candidatesOutArray || []; - reorderCandidates(signatures, candidates); - if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); - return resolveErrorCall(node); - } - var args = getEffectiveCallArguments(node); - var excludeArgument; - if (!isDecorator) { - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - } - } - } - var candidateForArgumentError; - var candidateForTypeArgumentError; - var resultOfFailedInference; - var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; - if (candidates.length > 1) { - result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); - } - if (!result) { - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; - result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); - } - if (result) { - return result; - } - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - return candidateForArgumentError; - } - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); - } - else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - 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 (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } - } - 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 _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)); - } - return candidate; - } - } - } - return resolveErrorCall(node); - function chooseOverload(candidates, relation, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { - var originalCandidate = candidates_2[_i]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { - continue; - } - var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, false, ts.isInJavaScriptFile(node)) - : undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); - } - else { - inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentTypes = inferenceContext.inferredTypes; - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; - } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { - break; - } - var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; - if (index < 0) { - return candidate; - } - excludeArgument[index] = false; - } - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } - } - return undefined; - } - } - function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 97) { - var superType = checkSuperExpression(node.expression); - if (superType !== unknownType) { - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - if (baseTypeNode) { - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); - } - } - return resolveUntypedCall(node); - } - var funcType = checkNonNullExpression(node.expression); - if (funcType === silentNeverType) { - return silentNeverSignature; - } - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - if (funcType !== unknownType && node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - if (constructSignatures.length) { - error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); - } - else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - } - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 65536) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } - function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 1) { - var spreadIndex = getSpreadArgumentIndex(node.arguments); - if (spreadIndex >= 0) { - error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); - } - } - var expressionType = checkNonNullExpression(node.expression); - if (expressionType === silentNeverType) { - return silentNeverSignature; - } - expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { - return resolveErrorCall(node); - } - 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(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } - if (isTypeAny(expressionType)) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - var constructSignatures = getSignaturesOfType(expressionType, 1); - if (constructSignatures.length) { - if (!isConstructorAccessible(node, constructSignatures[0])) { - return resolveErrorCall(node); - } - return resolveCall(node, constructSignatures, candidatesOutArray); - } - var callSignatures = getSignaturesOfType(expressionType, 0); - if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); - } - return signature; - } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); - return resolveErrorCall(node); - } - function isConstructorAccessible(node, signature) { - if (!signature || !signature.declaration) { - return true; - } - var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - if (!(modifiers & 24)) { - return true; - } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); - var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); - } - } - if (modifiers & 8) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - if (modifiers & 16) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - return false; - } - return true; - } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { - var tagType = checkExpression(node.tag); - var apparentType = getApparentType(tagType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - function getDiagnosticHeadMessageForDecoratorResolution(node) { - switch (node.parent.kind) { - case 229: - case 199: - return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146: - return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151: - case 153: - case 154: - return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; - } - } - function resolveDecorator(node, candidatesOutArray) { - var funcType = checkExpression(node.expression); - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); - } - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; - } - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 65536) { - var types = elementType.types; - var result = void 0; - 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; - } - var callSignatures = elementType && getSignaturesOfType(elementType, 0); - if (callSignatures && callSignatures.length > 0) { - var callSignature = void 0; - callSignature = resolveCall(openingLikeElement, callSignatures, candidatesOutArray); - return callSignature; - } - return undefined; - } - function resolveSignature(node, candidatesOutArray) { - switch (node.kind) { - case 181: - return resolveCallExpression(node, candidatesOutArray); - case 182: - return resolveNewExpression(node, candidatesOutArray); - case 183: - return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147: - return resolveDecorator(node, candidatesOutArray); - case 251: - case 250: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); - } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); - } - function getResolvedSignature(node, candidatesOutArray) { - var links = getNodeLinks(node); - var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { - return cached; - } - links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); - links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; - return result; - } - function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); - } - function getInferredClassType(symbol) { - var links = getSymbolLinks(symbol); - if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); - } - return links.inferredClassType; - } - function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - var signature = getResolvedSignature(node); - if (node.expression.kind === 97) { - return voidType; - } - if (node.kind === 182) { - var declaration = signature.declaration; - if (declaration && - declaration.kind !== 152 && - declaration.kind !== 156 && - declaration.kind !== 161 && - !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 71 ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.members && funcSymbol.flags & 16) { - return getInferredClassType(funcSymbol); - } - else if (noImplicitAny) { - error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); - } - return anyType; - } - } - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { - return resolveExternalModuleTypeByLiteral(node.arguments[0]); - } - return getReturnTypeOfSignature(signature); - } - function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, true)) { - return false; - } - var resolvedRequire = resolveName(node.expression, node.expression.text, 107455, undefined, undefined); - if (!resolvedRequire) { - return true; - } - if (resolvedRequire.flags & 8388608) { - return false; - } - var targetDeclarationKind = resolvedRequire.flags & 16 - ? 228 - : resolvedRequire.flags & 3 - ? 226 - : 0; - if (targetDeclarationKind !== 0) { - var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - return ts.isInAmbientContext(decl); - } - return false; - } - function checkTaggedTemplateExpression(node) { - return getReturnTypeOfSignature(getResolvedSignature(node)); - } - function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); - checkSourceElement(node.type); - var targetType = getTypeFromTypeNode(node.type); - if (produceDiagnostics && targetType !== unknownType) { - var widenedType = getWidenedType(exprType); - if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, node, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); - } - } - return targetType; - } - function checkNonNullAssertion(node) { - return getNonNullableType(checkExpression(node.expression)); - } - function checkMetaProperty(node) { - checkGrammarMetaProperty(node); - var container = ts.getNewTargetContainer(node); - if (!container) { - error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); - return unknownType; - } - else if (container.kind === 152) { - var symbol = getSymbolOfNode(container.parent); - return getTypeOfSymbol(symbol); - } - else { - var symbol = getSymbolOfNode(container); - return getTypeOfSymbol(symbol); - } - } - function getTypeOfParameter(symbol) { - var type = getTypeOfSymbol(symbol); - if (strictNullChecks) { - var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { - return getNullableType(type, 2048); - } - } - return type; - } - function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; - } - function getTypeOfFirstParameterOfSignature(signature) { - return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; - } - function assignContextualParameterTypes(signature, context, mapper, checkMode) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (checkMode === 2) { - for (var i = 0; i < len; i++) { - var declaration = signature.parameters[i].valueDeclaration; - if (declaration.type) { - inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); - } - } - } - if (context.thisParameter) { - var parameter = signature.thisParameter; - if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { - if (!parameter) { - signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper, checkMode); - } - } - for (var i = 0; i < len; i++) { - var parameter = signature.parameters[i]; - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - var parameter = ts.lastOrUndefined(signature.parameters); - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - } - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); - } - } - } - } - function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper, checkMode) { - var links = getSymbolLinks(parameter); - if (!links.type) { - links.type = instantiateType(contextualType, mapper); - var name = ts.getNameOfDeclaration(parameter.valueDeclaration); - if (links.type === emptyObjectType && - (name.kind === 174 || name.kind === 175)) { - links.type = getTypeFromBindingPattern(name); - } - assignBindingElementTypes(parameter.valueDeclaration); - } - else if (checkMode === 2) { - inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); - } - } - function getReturnTypeFromJSDocComment(func) { - var returnTag = ts.getJSDocReturnTag(func); - if (returnTag && returnTag.typeExpression) { - return getTypeFromTypeNode(returnTag.typeExpression.type); - } - return undefined; - } - function createPromiseType(promisedType) { - var globalPromiseType = getGlobalPromiseType(true); - if (globalPromiseType !== emptyGenericType) { - promisedType = getAwaitedType(promisedType) || emptyObjectType; - return createTypeReference(globalPromiseType, [promisedType]); - } - return emptyObjectType; - } - function createPromiseReturnType(func, promisedType) { - var promiseType = createPromiseType(promisedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); - return unknownType; - } - else if (!getGlobalPromiseConstructorSymbol(true)) { - error(func, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - return promiseType; - } - function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!func.body) { - return unknownType; - } - var functionFlags = ts.getFunctionFlags(func); - var type; - if (func.body.kind !== 207) { - type = checkExpressionCached(func.body, checkMode); - if (functionFlags & 2) { - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - } - else { - var types = void 0; - if (functionFlags & 1) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); - if (!types || types.length === 0) { - var iterableIteratorAny = functionFlags & 2 - ? createAsyncIterableIteratorType(anyType) - : createIterableIteratorType(anyType); - if (noImplicitAny) { - error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); - } - return iterableIteratorAny; - } - } - else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (!types) { - return functionFlags & 2 - ? createPromiseReturnType(func, neverType) - : neverType; - } - if (types.length === 0) { - return functionFlags & 2 - ? createPromiseReturnType(func, voidType) - : voidType; - } - } - type = getUnionType(types, true); - if (functionFlags & 1) { - type = functionFlags & 2 - ? createAsyncIterableIteratorType(type) - : createIterableIteratorType(type); - } - } - if (!contextualSignature) { - reportErrorsFromWidening(func, type); - } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); - } - var widenedType = getWidenedType(type); - return (functionFlags & 3) === 2 - ? createPromiseReturnType(func, widenedType) - : widenedType; - } - function checkAndAggregateYieldOperandTypes(func, checkMode) { - var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); - ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); - } - if (functionFlags & 2) { - type = checkAwaitedType(type, expr, yieldExpression.asteriskToken - ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - }); - return aggregatedTypes; - } - function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { - return false; - } - var type = getTypeOfExpression(node.expression); - if (!isLiteralType(type)) { - return false; - } - var switchTypes = getSwitchClauseTypes(node); - if (!switchTypes.length) { - return false; - } - return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); - } - function functionHasImplicitReturn(func) { - if (!(func.flags & 128)) { - return false; - } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { - return false; - } - return true; - } - function checkAndAggregateReturnExpressionTypes(func, checkMode) { - var functionFlags = ts.getFunctionFlags(func); - var aggregatedTypes = []; - var hasReturnWithNoExpression = functionHasImplicitReturn(func); - var hasReturnOfTypeNever = false; - ts.forEachReturnStatement(func.body, function (returnStatement) { - var expr = returnStatement.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (functionFlags & 2) { - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (type.flags & 8192) { - hasReturnOfTypeNever = true; - } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - else { - hasReturnWithNoExpression = true; - } - }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 || func.kind === 187)) { - return undefined; - } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } - } - return aggregatedTypes; - } - function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { - if (!produceDiagnostics) { - return; - } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { - return; - } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { - return; - } - var hasExplicitReturn = func.flags & 256; - if (returnType && returnType.flags & 8192) { - error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); - } - else if (returnType && !hasExplicitReturn) { - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); - } - else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { - error(func.type, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); - } - else if (compilerOptions.noImplicitReturns) { - if (!returnType) { - if (!hasExplicitReturn) { - return; - } - var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { - return; - } - } - error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { - checkGrammarForGenerator(node); - } - if (checkMode === 1 && isContextSensitive(node)) { - checkNodeDeferred(node); - return anyFunctionType; - } - var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); - var contextSensitive = isContextSensitive(node); - var mightFixTypeParameters = contextSensitive && checkMode === 2; - if (mightFixTypeParameters || !(links.flags & 1024)) { - var contextualSignature = getContextualSignature(node); - var contextChecked = !!(links.flags & 1024); - if (mightFixTypeParameters || !contextChecked) { - links.flags |= 1024; - if (contextualSignature) { - var signature = getSignaturesOfType(type, 0)[0]; - if (contextSensitive) { - assignContextualParameterTypes(signature, contextualSignature, getContextualMapper(node), checkMode); - } - if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { - var returnType = getReturnTypeFromBody(node, checkMode); - if (!signature.resolvedReturnType) { - signature.resolvedReturnType = returnType; - } - } - } - if (!contextChecked) { - checkSignatureDeclaration(node); - checkNodeDeferred(node); - } - } - } - if (produceDiagnostics && node.kind !== 151) { - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - } - return type; - } - function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var functionFlags = ts.getFunctionFlags(node); - var returnOrPromisedType = node.type && - ((functionFlags & 3) === 2 ? - checkAsyncFunctionReturnType(node) : - getTypeFromTypeNode(node.type)); - if ((functionFlags & 1) === 0) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (node.body) { - if (!node.type) { - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - if (node.body.kind === 207) { - checkSourceElement(node.body); - } - else { - var exprType = checkExpression(node.body); - if (returnOrPromisedType) { - if ((functionFlags & 3) === 2) { - 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); - } - else { - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); - } - } - } - registerForUnusedIdentifiersCheck(node); - } - } - function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { - error(operand, diagnostic); - return false; - } - return true; - } - function isReadonlySymbol(symbol) { - 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); - } - function isReferenceToReadonlyEntity(expr, symbol) { - if (isReadonlySymbol(symbol)) { - if (symbol.flags & 4 && - (expr.kind === 179 || expr.kind === 180) && - expr.expression.kind === 99) { - var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152)) - return true; - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); - } - return true; - } - return false; - } - function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 || expr.kind === 180) { - var node = ts.skipParentheses(expr.expression); - if (node.kind === 71) { - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol.flags & 8388608) { - var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240; - } - } - } - return false; - } - function checkReferenceExpression(expr, invalidReferenceMessage) { - var node = ts.skipParentheses(expr); - if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { - error(expr, invalidReferenceMessage); - return false; - } - return true; - } - function checkDeleteExpression(node) { - checkExpression(node.expression); - var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 && expr.kind !== 180) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); - return booleanType; - } - var links = getNodeLinks(expr); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); - } - return booleanType; - } - function checkTypeOfExpression(node) { - checkExpression(node.expression); - return typeofType; - } - function checkVoidExpression(node) { - checkExpression(node.expression); - return undefinedWideningType; - } - function checkAwaitExpression(node) { - if (produceDiagnostics) { - if (!(node.flags & 16384)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - var operandType = checkExpression(node.expression); - return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkPrefixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - switch (node.operator) { - case 37: - case 38: - case 52: - checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512)) { - error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); - } - return numberType; - case 51: - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : - booleanType; - case 43: - case 44: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - return unknownType; - } - function checkPostfixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - function maybeTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 196608) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (maybeTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 65536) { - var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; - } - if (type.flags & 131072) { - var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); - } - function isConstEnumSymbol(symbol) { - return (symbol.flags & 128) !== 0; - } - function checkInstanceOfExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (isTypeOfKind(leftType, 8190)) { - error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0).length || - getSignaturesOfType(rightType, 1).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); - } - return booleanType; - } - function checkInExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - 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)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - return booleanType; - } - function checkObjectLiteralAssignment(node, sourceType) { - var properties = node.properties; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); - } - return sourceType; - } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 || property.kind === 262) { - var name = property.name; - if (name.kind === 144) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || - getIndexTypeOfType(objectLiteralType, 0); - if (type) { - if (property.kind === 262) { - return checkDestructuringAssignment(property, type); - } - else { - return checkDestructuringAssignment(property.initializer, type); - } - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); - } - } - else if (property.kind === 263) { - if (languageVersion < 5) { - checkExternalEmitHelpers(property, 4); - } - var nonRestNames = []; - if (allProperties) { - for (var i = 0; i < allProperties.length - 1; i++) { - nonRestNames.push(allProperties[i].name); - } - } - var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); - return checkDestructuringAssignment(property.expression, type); - } - else { - error(property, ts.Diagnostics.Property_assignment_expected); - } - } - function checkArrayLiteralAssignment(node, sourceType, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); - } - var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || unknownType; - var elements = node.elements; - for (var i = 0; i < elements.length; i++) { - checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); - } - return sourceType; - } - function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { - var elements = node.elements; - var element = elements[elementIndex]; - if (element.kind !== 200) { - if (element.kind !== 198) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; - if (type) { - return checkDestructuringAssignment(element, type, checkMode); - } - else { - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } - } - } - else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - else { - var restExpression = element.expression; - if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); - } - } - } - } - return undefined; - } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { - var target; - if (exprOrAssignment.kind === 262) { - var prop = exprOrAssignment; - if (prop.objectAssignmentInitializer) { - if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { - sourceType = getTypeWithFacts(sourceType, 131072); - } - checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); - } - target = exprOrAssignment.name; - } - else { - target = exprOrAssignment; - } - if (target.kind === 194 && target.operatorToken.kind === 58) { - checkBinaryExpression(target, checkMode); - target = target.left; - } - if (target.kind === 178) { - return checkObjectLiteralAssignment(target, sourceType); - } - if (target.kind === 177) { - return checkArrayLiteralAssignment(target, sourceType, checkMode); - } - return checkReferenceAssignment(target, sourceType, checkMode); - } - function checkReferenceAssignment(target, sourceType, checkMode) { - var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 ? - ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : - ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, undefined); - } - return sourceType; - } - function isSideEffectFree(node) { - node = ts.skipParentheses(node); - switch (node.kind) { - case 71: - case 9: - case 12: - case 183: - case 196: - case 13: - case 8: - case 101: - case 86: - case 95: - case 139: - case 186: - case 199: - case 187: - case 177: - case 178: - case 189: - case 203: - case 250: - case 249: - return true; - case 195: - return isSideEffectFree(node.whenTrue) && - isSideEffectFree(node.whenFalse); - case 194: - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return false; - } - return isSideEffectFree(node.left) && - isSideEffectFree(node.right); - case 192: - case 193: - switch (node.operator) { - case 51: - case 37: - case 38: - case 52: - return true; - } - return false; - case 190: - case 184: - case 202: - default: - return false; - } - } - function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); - } - function checkBinaryExpression(node, checkMode) { - return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); - } - function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { - var operator = operatorToken.kind; - if (operator === 58 && (left.kind === 178 || left.kind === 177)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); - } - var leftType = checkExpression(left, checkMode); - var rightType = checkExpression(right, checkMode); - switch (operator) { - case 39: - case 40: - case 61: - case 62: - case 41: - case 63: - case 42: - case 64: - case 38: - case 60: - case 45: - case 65: - case 46: - case 66: - case 47: - case 67: - case 49: - case 69: - case 50: - case 70: - case 48: - case 68: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - var suggestedOperator = void 0; - if ((leftType.flags & 136) && - (rightType.flags & 136) && - (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { - error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); - } - else { - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); - } - } - return numberType; - case 37: - case 59: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - } - var resultType = void 0; - if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { - resultType = numberType; - } - else { - if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } - } - if (!resultType) { - reportOperatorError(); - return anyType; - } - if (operator === 59) { - checkAssignmentOperator(resultType); - } - return resultType; - case 27: - case 29: - case 30: - case 31: - if (checkForDisallowedESSymbolOperand(operator)) { - leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); - rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { - reportOperatorError(); - } - } - return booleanType; - case 32: - case 33: - case 34: - case 35: - var leftIsLiteral = isLiteralType(leftType); - var rightIsLiteral = isLiteralType(rightType); - if (!leftIsLiteral || !rightIsLiteral) { - leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; - rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; - } - if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { - reportOperatorError(); - } - return booleanType; - case 93: - return checkInstanceOfExpression(left, right, leftType, rightType); - case 92: - return checkInExpression(left, right, leftType, rightType); - case 53: - return getTypeFacts(leftType) & 1048576 ? - getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : - leftType; - case 54: - return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; - case 58: - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); - case 26: - if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { - error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); - } - return rightType; - } - function isEvalNode(node) { - return node.kind === 71 && node.text === "eval"; - } - function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : - undefined; - if (offendingSymbolOperand) { - error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); - return false; - } - return true; - } - function getSuggestedBooleanOperator(operator) { - switch (operator) { - case 49: - case 69: - return 54; - case 50: - case 70: - return 35; - case 48: - case 68: - return 53; - default: - return undefined; - } - } - function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 58 && operator <= 70) { - if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { - checkTypeAssignableTo(valueType, leftType, left, undefined); - } - } - } - function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); - } - } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } - function checkYieldExpression(node) { - if (produceDiagnostics) { - if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - if (node.expression) { - var func = ts.getContainingFunction(node); - var functionFlags = func && ts.getFunctionFlags(func); - if (node.asteriskToken) { - if ((functionFlags & 3) === 3 && - languageVersion < 5) { - checkExternalEmitHelpers(node, 26624); - } - if ((functionFlags & 3) === 1 && - languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256); - } - } - if (functionFlags & 1) { - var expressionType = checkExpressionCached(node.expression, undefined); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); - } - if (func.type) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(func.type), (functionFlags & 2) !== 0) || anyType; - if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 - ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionElementType, signatureElementType, node.expression, undefined); - } - else { - checkTypeAssignableTo(functionFlags & 2 - ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionType, signatureElementType, node.expression, undefined); - } - } - } - } - return anyType; - } - function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); - var type1 = checkExpression(node.whenTrue, checkMode); - var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); - } - function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8: - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: - return trueType; - case 86: - return falseType; - } - } - function checkTemplateExpression(node) { - ts.forEach(node.templateSpans, function (templateSpan) { - checkExpression(templateSpan.expression); - }); - return stringType; - } - function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; - var checkMode = contextualMapper === identityMapper ? 1 : - contextualMapper ? 2 : 0; - var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; - return result; - } - function checkExpressionCached(node, checkMode) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var saveFlowLoopStart = flowLoopStart; - flowLoopStart = flowLoopCount; - links.resolvedType = checkExpression(node, checkMode); - flowLoopStart = saveFlowLoopStart; - } - return links.resolvedType; - } - function isTypeAssertion(node) { - node = ts.skipParentheses(node); - return node.kind === 184 || node.kind === 202; - } - function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, true); - return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); - } - function isLiteralContextualType(contextualType) { - if (contextualType) { - if (contextualType.flags & 540672) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - if (constraint.flags & (2 | 4 | 8 | 16)) { - return true; - } - contextualType = constraint; - } - return maybeTypeOfKind(contextualType, (224 | 262144)); - } - return false; - } - function checkExpressionForMutableLocation(node, checkMode) { - var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); - } - function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - return checkExpressionForMutableLocation(node.initializer, checkMode); - } - function checkObjectLiteralMethod(node, checkMode) { - checkGrammarMethod(node); - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { - if (checkMode === 2) { - var signature = getSingleCallSignature(type); - if (signature && signature.typeParameters) { - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType) { - var contextualSignature = getSingleCallSignature(contextualType); - if (contextualSignature && !contextualSignature.typeParameters) { - return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); - } - } - } - } - return type; - } - function getTypeOfExpression(node, cache) { - if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { - var funcType = checkNonNullExpression(node.expression); - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return getReturnTypeOfSignature(signature); - } - } - return cache ? checkExpressionCached(node) : checkExpression(node); - } - function getContextFreeTypeOfExpression(node) { - var saveContextualType = node.contextualType; - node.contextualType = anyType; - var type = getTypeOfExpression(node); - node.contextualType = saveContextualType; - return type; - } - function checkExpression(node, checkMode) { - var type; - if (node.kind === 143) { - type = checkQualifiedName(node); - } - else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); - type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 179 && node.parent.expression === node) || - (node.parent.kind === 180 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); - if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); - } - } - return type; - } - function checkExpressionWorker(node, checkMode) { - switch (node.kind) { - case 71: - return checkIdentifier(node); - case 99: - return checkThisExpression(node); - case 97: - return checkSuperExpression(node); - case 95: - return nullWideningType; - case 9: - case 8: - case 101: - case 86: - return checkLiteralExpression(node); - case 196: - return checkTemplateExpression(node); - case 13: - return stringType; - case 12: - return globalRegExpType; - case 177: - return checkArrayLiteral(node, checkMode); - case 178: - return checkObjectLiteral(node, checkMode); - case 179: - return checkPropertyAccessExpression(node); - case 180: - return checkIndexedAccess(node); - case 181: - case 182: - return checkCallExpression(node); - case 183: - return checkTaggedTemplateExpression(node); - case 185: - return checkExpression(node.expression, checkMode); - case 199: - return checkClassExpression(node); - case 186: - case 187: - return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189: - return checkTypeOfExpression(node); - case 184: - case 202: - return checkAssertion(node); - case 203: - return checkNonNullAssertion(node); - case 204: - return checkMetaProperty(node); - case 188: - return checkDeleteExpression(node); - case 190: - return checkVoidExpression(node); - case 191: - return checkAwaitExpression(node); - case 192: - return checkPrefixUnaryExpression(node); - case 193: - return checkPostfixUnaryExpression(node); - case 194: - return checkBinaryExpression(node, checkMode); - case 195: - return checkConditionalExpression(node, checkMode); - case 198: - return checkSpreadExpression(node, checkMode); - case 200: - return undefinedWideningType; - case 197: - return checkYieldExpression(node); - case 256: - return checkJsxExpression(node, checkMode); - case 249: - return checkJsxElement(node); - case 250: - return checkJsxSelfClosingElement(node); - case 254: - return checkJsxAttributes(node, checkMode); - case 251: - ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); - } - return unknownType; - } - function checkTypeParameter(node) { - if (node.expression) { - grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); - } - checkSourceElement(node.constraint); - checkSourceElement(node.default); - var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); - } - var constraintType = getConstraintOfTypeParameter(typeParameter); - var defaultType = getDefaultFromTypeParameter(typeParameter); - if (constraintType && defaultType) { - checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); - } - } - function checkParameter(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkVariableLikeDeclaration(node); - var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { - error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); - } - } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { - error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); - } - if (node.name.text === "this") { - if (ts.indexOf(func.parameters, node) !== 0) { - error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); - } - if (func.kind === 152 || func.kind === 156 || func.kind === 161) { - error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); - } - } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { - error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); - } - } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 && - param.name.text === parameter.text) { - return i; - } - } - } - return -1; - } - function checkTypePredicate(node) { - var parent = getTypePredicateParent(node); - if (!parent) { - error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - return; - } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; - if (!typePredicate) { - return; - } - var parameterName = node.parameterName; - if (ts.isThisTypePredicate(typePredicate)) { - getTypeFromThisTypeNode(parameterName); - } - else { - if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { - error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); - } - else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); - } - } - else if (parameterName) { - var hasReportedError = false; - for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name = _a[_i].name; - if (ts.isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { - hasReportedError = true; - break; - } - } - if (!hasReportedError) { - error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); - } - } - } - } - function getTypePredicateParent(node) { - switch (node.parent.kind) { - case 187: - case 155: - case 228: - case 186: - case 160: - case 151: - case 150: - var parent = node.parent; - if (node === parent.type) { - return parent; - } - } - } - function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (ts.isOmittedExpression(element)) { - continue; - } - var name = element.name; - if (name.kind === 71 && - name.text === predicateVariableName) { - error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); - return true; - } - else if (name.kind === 175 || - name.kind === 174) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { - return true; - } - } - } - } - function checkSignatureDeclaration(node) { - if (node.kind === 157) { - checkGrammarIndexSignature(node); - } - else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || - node.kind === 155 || node.kind === 152 || - node.kind === 156) { - checkGrammarFunctionLikeDeclaration(node); - } - var functionFlags = ts.getFunctionFlags(node); - if (!(functionFlags & 4)) { - if ((functionFlags & 3) === 3 && languageVersion < 5) { - checkExternalEmitHelpers(node, 6144); - } - if ((functionFlags & 3) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - } - if ((functionFlags & 3) !== 0 && languageVersion < 2) { - checkExternalEmitHelpers(node, 128); - } - } - checkTypeParameters(node.typeParameters); - ts.forEach(node.parameters, checkParameter); - if (node.type) { - checkSourceElement(node.type); - } - if (produceDiagnostics) { - checkCollisionWithArgumentsInGeneratedCode(node); - if (noImplicitAny && !node.type) { - switch (node.kind) { - case 156: - error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - case 155: - error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - } - } - if (node.type) { - var functionFlags_1 = ts.getFunctionFlags(node); - 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); - } - else { - var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; - var iterableIteratorInstantiation = functionFlags_1 & 2 - ? createAsyncIterableIteratorType(generatorElementType) - : createIterableIteratorType(generatorElementType); - checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); - } - } - else if ((functionFlags_1 & 3) === 2) { - checkAsyncFunctionReturnType(node); - } - } - if (noUnusedIdentifiers && !node.body) { - checkUnusedTypeParameters(node); - } - } - } - 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++) { - var member = _a[_i]; - if (member.kind === 152) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var param = _c[_b]; - if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3); - } - } - } - else { - var isStatic = ts.getModifierFlags(member) & 32; - var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { - switch (member.kind) { - case 153: - addName(names, member.name, memberName, 1); - break; - case 154: - addName(names, member.name, memberName, 2); - break; - case 149: - addName(names, member.name, memberName, 3); - break; - case 151: - addName(names, member.name, memberName, 4); - break; - } - } - } - } - function addName(names, location, name, meaning) { - var prev = names.get(name); - if (prev) { - if (prev & 4) { - if (meaning !== 4) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - else { - names.set(name, prev | meaning); - } - } - else { - names.set(name, meaning); - } - } - } - function checkClassForStaticPropertyNameConflicts(node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32; - if (isStatic && memberNameNode) { - var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); - switch (memberName) { - case "name": - case "length": - case "caller": - case "arguments": - case "prototype": - var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); - error(memberNameNode, message, memberName, className); - break; - } - } - } - } - function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148) { - var memberName = void 0; - switch (member.name.kind) { - case 9: - case 8: - case 71: - memberName = member.name.text; - break; - default: - continue; - } - if (names.get(memberName)) { - error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); - error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); - } - else { - names.set(memberName, true); - } - } - } - } - function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230) { - var nodeSymbol = getSymbolOfNode(node); - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { - return; - } - } - var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { - var seenNumericIndexer = false; - var seenStringIndexer = false; - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var declaration = decl; - if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type.kind) { - case 136: - if (!seenStringIndexer) { - seenStringIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_string_index_signature); - } - break; - case 133: - if (!seenNumericIndexer) { - seenNumericIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_number_index_signature); - } - break; - } - } - } - } - } - function checkPropertyDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); - checkVariableLikeDeclaration(node); - } - function checkMethodDeclaration(node) { - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - checkFunctionOrMethodDeclaration(node); - if (ts.getModifierFlags(node) & 128 && node.body) { - error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); - } - } - function checkConstructorDeclaration(node) { - checkSignatureDeclaration(node); - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - var symbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(symbol); - } - if (ts.nodeIsMissing(node.body)) { - return; - } - if (!produceDiagnostics) { - return; - } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } - function markThisReferencesAsErrors(n) { - if (n.kind === 99) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 && n.kind !== 228) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } - function isInstancePropertyWithInitializer(n) { - return n.kind === 149 && - !(ts.getModifierFlags(n) & 32) && - !!n.initializer; - } - var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - captureLexicalThis(node.parent, containingClassDecl); - var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); - var superCall = getSuperCallInConstructor(node); - if (superCall) { - if (classExtendsNull) { - error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); - } - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); - if (superCallShouldBeFirst) { - var statements = node.body.statements; - var superCallStatement = void 0; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { - superCallStatement = statement; - break; - } - if (!ts.isPrologueDirective(statement)) { - break; - } - } - if (!superCallStatement) { - error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); - } - } - } - else if (!classExtendsNull) { - error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); - } - } - } - function checkAccessorDeclaration(node) { - if (produceDiagnostics) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - checkDecorators(node); - checkSignatureDeclaration(node); - if (node.kind === 153) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { - if (!(node.flags & 256)) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); - } - } - } - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 153 ? 154 : 153; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); - if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); - } - if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); - } - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); - } - } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } - } - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } - } - function checkMissingDeclaration(node) { - checkDecorators(node); - } - function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var typeArguments; - var mapper; - var result = true; - for (var i = 0; i < typeParameters.length; i++) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); - mapper = createTypeMapper(typeParameters, typeArguments); - } - var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - } - return result; - } - function checkTypeReferenceNode(node) { - checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReference(node); - if (type !== unknownType) { - if (node.typeArguments) { - ts.forEach(node.typeArguments, checkSourceElement); - if (produceDiagnostics) { - var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; - checkTypeArgumentConstraints(typeParameters, node.typeArguments); - } - } - 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)); - } - } - } - function checkTypeQuery(node) { - getTypeFromTypeQueryNode(node); - } - function checkTypeLiteral(node) { - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - checkObjectTypeForDuplicateDeclarations(node); - } - } - function checkArrayType(node) { - checkSourceElement(node.elementType); - } - function checkTupleType(node) { - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); - } - ts.forEach(node.elementTypes, checkSourceElement); - } - function checkUnionOrIntersectionType(node) { - ts.forEach(node.types, checkSourceElement); - } - function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288)) { - return type; - } - var objectType = type.objectType; - var indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - return type; - } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1)) { - return type; - } - } - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); - return type; - } - function checkIndexedAccessType(node) { - checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); - } - function checkMappedType(node) { - checkSourceElement(node.typeParameter); - checkSourceElement(node.type); - var type = getTypeFromMappedTypeNode(node); - var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); - } - function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); - } - function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 230 && - n.parent.kind !== 229 && - n.parent.kind !== 199 && - ts.isInAmbientContext(n)) { - if (!(flags & 2)) { - flags |= 1; - } - flags |= 2; - } - return flags & flagsToCheck; - } - function checkFunctionOrConstructorSymbol(symbol) { - if (!produceDiagnostics) { - return; - } - function getCanonicalOverload(overloads, implementation) { - var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; - return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; - } - function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { - var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; - if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); - ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; - if (deviation & 1) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - } - else if (deviation & 2) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - } - else if (deviation & (8 | 16)) { - error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - } - else if (deviation & 128) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); - } - }); - } - } - function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { - if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); - ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; - if (deviation) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); - } - }); - } - } - var flagsToCheck = 1 | 2 | 8 | 16 | 128; - var someNodeFlags = 0; - var allNodeFlags = flagsToCheck; - var someHaveQuestionToken = false; - var allHaveQuestionToken = true; - var hasOverloads = false; - var bodyDeclaration; - var lastSeenNonAmbientDeclaration; - var previousDeclaration; - var declarations = symbol.declarations; - var isConstructor = (symbol.flags & 16384) !== 0; - function reportImplementationExpectedError(node) { - if (node.name && ts.nodeIsMissing(node.name)) { - return; - } - var seen = false; - var subsequentNode = ts.forEachChild(node.parent, function (c) { - if (seen) { - return c; - } - else { - seen = c === node; - } - }); - if (subsequentNode && subsequentNode.pos === node.end) { - if (subsequentNode.kind === node.kind) { - var errorNode_1 = subsequentNode.name || subsequentNode; - if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 151 || node.kind === 150) && - (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); - if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); - } - return; - } - else if (ts.nodeIsPresent(subsequentNode.body)) { - error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); - return; - } - } - } - var errorNode = node.name || node; - if (isConstructor) { - error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); - } - else { - if (ts.getModifierFlags(node) & 128) { - error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); - } - else { - error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); - } - } - } - var duplicateFunctionDeclaration = false; - var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; - var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; - if (inAmbientContextOrInterface) { - previousDeclaration = undefined; - } - if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - if (ts.nodeIsPresent(node.body) && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; - } - else { - duplicateFunctionDeclaration = true; - } - } - else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (ts.nodeIsPresent(node.body)) { - if (!bodyDeclaration) { - bodyDeclaration = node; - } - } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } - } - } - if (multipleConstructorImplementation) { - ts.forEach(declarations, function (declaration) { - error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); - }); - } - if (duplicateFunctionDeclaration) { - ts.forEach(declarations, function (declaration) { - error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); - }); - } - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { - reportImplementationExpectedError(lastSeenNonAmbientDeclaration); - } - if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); - if (bodyDeclaration) { - var signatures = getSignaturesOfSymbol(symbol); - var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - 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; - } - } - } - } - } - function checkExportsOnMergedDeclarations(node) { - if (!produceDiagnostics) { - return; - } - var symbol = node.localSymbol; - if (!symbol) { - symbol = getSymbolOfNode(node); - if (!(symbol.flags & 7340032)) { - return; - } - } - if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { - return; - } - var exportedDeclarationSpaces = 0; - var nonExportedDeclarationSpaces = 0; - var defaultExportedDeclarationSpaces = 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var d = _a[_i]; - var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); - if (effectiveDeclarationFlags & 1) { - if (effectiveDeclarationFlags & 512) { - defaultExportedDeclarationSpaces |= declarationSpaces; - } - else { - exportedDeclarationSpaces |= declarationSpaces; - } - } - else { - nonExportedDeclarationSpaces |= declarationSpaces; - } - } - var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; - var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; - var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; - if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { - 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); - } - } - } - function getDeclarationSpaces(d) { - switch (d.kind) { - case 230: - return 2097152; - case 233: - return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 - ? 4194304 | 1048576 - : 4194304; - case 229: - case 232: - return 2097152 | 1048576; - case 237: - var result_3 = 0; - var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - default: - return 1048576; - } - } - } - function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { - var promisedType = getPromisedTypeOfPromise(type, errorNode); - return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); - } - function getPromisedTypeOfPromise(promise, errorNode) { - if (isTypeAny(promise)) { - return undefined; - } - var typeAsPromise = promise; - if (typeAsPromise.promisedTypeOfPromise) { - return typeAsPromise.promisedTypeOfPromise; - } - if (isReferenceToType(promise, getGlobalPromiseType(false))) { - return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; - } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (isTypeAny(thenFunction)) { - return undefined; - } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; - if (thenSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); - } - return undefined; - } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); - if (isTypeAny(onfulfilledParameterType)) { - return undefined; - } - var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); - if (onfulfilledParameterSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); - } - return undefined; - } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); - } - function checkAwaitedType(type, errorNode, diagnosticMessage) { - return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; - } - function getAwaitedType(type, errorNode, diagnosticMessage) { - var typeAsAwaitable = type; - if (typeAsAwaitable.awaitedTypeOfType) { - return typeAsAwaitable.awaitedTypeOfType; - } - if (isTypeAny(type)) { - return typeAsAwaitable.awaitedTypeOfType = type; - } - if (type.flags & 65536) { - var types = void 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituentType = _a[_i]; - types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); - } - if (!types) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); - } - var promisedType = getPromisedTypeOfPromise(type); - if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); - } - return undefined; - } - awaitedTypeStack.push(type.id); - var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); - awaitedTypeStack.pop(); - if (!awaitedType) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = awaitedType; - } - var thenFunction = getTypeOfPropertyOfType(type, "then"); - if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { - if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); - error(errorNode, diagnosticMessage); - } - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = type; - } - function checkAsyncFunctionReturnType(node) { - var returnType = getTypeFromTypeNode(node.type); - if (languageVersion >= 2) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(true); - if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { - error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return unknownType; - } - } - else { - markTypeNodeAsReferenced(node.type); - if (returnType === unknownType) { - return unknownType; - } - var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); - if (promiseConstructorName === undefined) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return unknownType; - } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); - var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; - if (promiseConstructorType === unknownType) { - if (promiseConstructorName.kind === 71 && promiseConstructorName.text === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { - error(node.type, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - else { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - } - return unknownType; - } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); - if (globalPromiseConstructorLikeType === emptyObjectType) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return unknownType; - } - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.text, 107455); - if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - } - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkDecorator(node) { - var signature = getResolvedSignature(node); - var returnType = getReturnTypeOfSignature(signature); - if (returnType.flags & 1) { - return; - } - var expectedReturnType; - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - var errorInfo; - switch (node.parent.kind) { - case 229: - var classSymbol = getSymbolOfNode(node.parent); - var classConstructorType = getTypeOfSymbol(classSymbol); - expectedReturnType = getUnionType([classConstructorType, voidType]); - break; - case 146: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); - break; - case 149: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); - break; - case 151: - case 153: - case 154: - var methodType = getTypeOfNode(node.parent); - var descriptorType = createTypedPropertyDescriptorType(methodType); - expectedReturnType = getUnionType([descriptorType, voidType]); - break; - } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); - } - function markTypeNodeAsReferenced(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 - && rootSymbol.flags & 8388608 - && symbolIsValue(rootSymbol) - && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - 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; - } - function checkDecorators(node) { - if (!node.decorators) { - return; - } - if (!ts.nodeCanBeDecorated(node)) { - return; - } - if (!compilerOptions.experimentalDecorators) { - error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); - } - var firstDecorator = node.decorators[0]; - checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 146) { - checkExternalEmitHelpers(firstDecorator, 32); - } - if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16); - switch (node.kind) { - case 229: - var constructor = ts.getFirstConstructorWithBody(node); - if (constructor) { - for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - } - break; - case 151: - case 153: - case 154: - for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - case 149: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); - break; - case 146: - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - } - } - ts.forEach(node.decorators, checkDecorator); - } - function checkFunctionDeclaration(node) { - if (produceDiagnostics) { - checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function checkFunctionOrMethodDeclaration(node) { - checkDecorators(node); - checkSignatureDeclaration(node); - var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - var symbol = getSymbolOfNode(node); - var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.forEach(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? - declaration : undefined; }); - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(localSymbol); - } - if (symbol.parent) { - if (ts.getDeclarationOfKind(symbol, node.kind) === node) { - checkFunctionOrConstructorSymbol(symbol); - } - } - } - checkSourceElement(node.body); - if ((functionFlags & 1) === 0) { - var returnOrPromisedType = node.type && (functionFlags & 2 - ? checkAsyncFunctionReturnType(node) - : getTypeFromTypeNode(node.type)); - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (produceDiagnostics && !node.type) { - if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); - } - if (functionFlags & 1 && ts.nodeIsPresent(node.body)) { - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - } - registerForUnusedIdentifiersCheck(node); - } - function registerForUnusedIdentifiersCheck(node) { - if (deferredUnusedIdentifierNodes) { - deferredUnusedIdentifierNodes.push(node); - } - } - function checkUnusedIdentifiers() { - if (deferredUnusedIdentifierNodes) { - for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { - var node = deferredUnusedIdentifierNodes_1[_i]; - switch (node.kind) { - case 265: - case 233: - checkUnusedModuleMembers(node); - break; - case 229: - case 199: - checkUnusedClassMembers(node); - checkUnusedTypeParameters(node); - break; - case 230: - checkUnusedTypeParameters(node); - break; - case 207: - case 235: - case 214: - case 215: - case 216: - checkUnusedLocalsAndParameters(node); - break; - case 152: - case 186: - case 228: - case 187: - case 151: - case 153: - case 154: - if (node.body) { - checkUnusedLocalsAndParameters(node); - } - checkUnusedTypeParameters(node); - break; - case 150: - case 155: - case 156: - case 157: - case 160: - case 161: - checkUnusedTypeParameters(node); - break; - } - } - } - } - function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - 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(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(ts.getNameOfDeclaration(d) || d, local.name); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } - function errorUnusedLocal(node, name) { - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 && - (declaration.parent.parent.kind === 215 || - declaration.parent.parent.kind === 216)) { - return; - } - } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); - } - } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && node.text.charCodeAt(0) === 95; - } - function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 151 || member.kind === 149) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); - } - } - else if (member.kind === 152) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); - } - } - } - } - } - } - } - function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.typeParameters) { - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } - for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { - var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); - } - } - } - } - } - function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); - } - } - } - }); - } - } - function checkBlock(node) { - if (node.kind === 207) { - checkGrammarStatementInAmbientContext(node); - } - ts.forEach(node.statements, checkSourceElement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { - return; - } - ts.forEach(node.parameters, function (p) { - if (p.name && !ts.isBindingPattern(p.name) && p.name.text === argumentsSymbol.name) { - error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); - } - }); - } - function needCollisionCheckForIdentifier(node, identifier, name) { - if (!(identifier && identifier.text === name)) { - return false; - } - if (node.kind === 149 || - node.kind === 148 || - node.kind === 151 || - node.kind === 150 || - node.kind === 153 || - node.kind === 154) { - return false; - } - if (ts.isInAmbientContext(node)) { - return false; - } - var root = ts.getRootDeclaration(node); - if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { - return false; - } - return true; - } - function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { - potentialThisCollisions.push(node); - } - } - function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { - potentialNewTargetCollisions.push(node); - } - } - function checkIfThisIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 71; - if (isDeclaration_1) { - 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); - } - return true; - } - }); - } - function checkIfNewTargetIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 8) { - var isDeclaration_2 = node.kind !== 71; - if (isDeclaration_2) { - 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); - } - return true; - } - }); - } - function checkCollisionWithCapturedSuperVariable(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "_super")) { - return; - } - var enclosingClass = ts.getContainingClass(node); - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { - return; - } - if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71; - if (isDeclaration_3) { - error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); - } - else { - error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); - } - } - } - function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - if (modulekind >= ts.ModuleKind.ES2015) { - return; - } - if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { - return; - } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { - return; - } - var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { - return; - } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { - return; - } - var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { - return; - } - if (node.kind === 226 && !node.initializer) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol.flags & 1) { - var localDeclarationSymbol = resolveName(node, node.name.text, 3, undefined, undefined); - if (localDeclarationSymbol && - localDeclarationSymbol !== symbol && - localDeclarationSymbol.flags & 2) { - if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); - var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent - ? varDeclList.parent.parent - : undefined; - var namesShareScope = container && - (container.kind === 207 && ts.isFunctionLike(container.parent) || - container.kind === 234 || - container.kind === 233 || - container.kind === 265); - if (!namesShareScope) { - var name = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); - } - } - } - } - } - function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146) { - return; - } - var func = ts.getContainingFunction(node); - visit(node.initializer); - function visit(n) { - if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { - return; - } - if (n.kind === 179) { - return visit(n.expression); - } - else if (n.kind === 71) { - var symbol = resolveName(n, n.text, 107455 | 8388608, undefined, undefined); - if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { - return; - } - if (symbol.valueDeclaration === node) { - error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); - return; - } - var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 || - symbol.valueDeclaration.kind === 176) { - if (symbol.valueDeclaration.pos < node.pos) { - return; - } - if (ts.findAncestor(n, function (current) { - if (current === node.initializer) { - return "quit"; - } - return ts.isFunctionLike(current.parent) || - (current.parent.kind === 149 && - !(ts.hasModifier(current.parent, 32)) && - ts.isClassLike(current.parent.parent)); - })) { - return; - } - } - error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); - } - } - else { - return ts.forEachChild(n, visit); - } - } - } - function convertAutoToAny(type) { - return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; - } - function checkVariableLikeDeclaration(node) { - checkDecorators(node); - checkSourceElement(node.type); - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - if (node.initializer) { - checkExpressionCached(node.initializer); - } - } - if (node.kind === 176) { - if (node.parent.kind === 174 && languageVersion < 5) { - checkExternalEmitHelpers(node, 4); - } - if (node.propertyName && node.propertyName.kind === 144) { - checkComputedPropertyName(node.propertyName); - } - var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); - var name = node.propertyName || node.name; - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); - } - } - if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); - } - ts.forEach(node.name.elements, checkSourceElement); - } - if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { - error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); - return; - } - if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); - checkParameterInitializer(node); - } - return; - } - var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); - if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); - checkParameterInitializer(node); - } - } - else { - var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.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(node.name), typeToString(type), typeToString(declarationType)); - } - if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); - } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - 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)); - } - } - if (node.kind !== 149 && node.kind !== 148) { - checkExportsOnMergedDeclarations(node); - if (node.kind === 226 || node.kind === 176) { - checkVarDeclaredNamesNotShadowed(node); - } - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 && right.kind === 226) || - (left.kind === 226 && right.kind === 146)) { - return true; - } - if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { - return false; - } - var interestingFlags = 8 | - 16 | - 256 | - 128 | - 64 | - 32; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); - } - function checkVariableDeclaration(node) { - checkGrammarVariableDeclaration(node); - return checkVariableLikeDeclaration(node); - } - function checkBindingElement(node) { - checkGrammarBindingElement(node); - return checkVariableLikeDeclaration(node); - } - function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); - ts.forEach(node.declarationList.declarations, checkSourceElement); - } - function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 178) { - if (ts.getFunctionFlags(node) & 2) { - if (node.modifiers.length > 1) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - } - function checkExpressionStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - } - function checkIfStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209) { - error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); - } - checkSourceElement(node.elseStatement); - } - function checkDoStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkSourceElement(node.statement); - checkExpression(node.expression); - } - function checkWhileStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.statement); - } - function checkForStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227) { - checkGrammarVariableDeclarationList(node.initializer); - } - } - if (node.initializer) { - if (node.initializer.kind === 227) { - ts.forEach(node.initializer.declarations, checkVariableDeclaration); - } - else { - checkExpression(node.initializer); - } - } - if (node.condition) - checkExpression(node.condition); - if (node.incrementor) - checkExpression(node.incrementor); - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForOfStatement(node) { - checkGrammarForInOrForOfStatement(node); - if (node.kind === 216) { - if (node.awaitModifier) { - var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { - checkExternalEmitHelpers(node, 16384); - } - } - else if (compilerOptions.downlevelIteration && languageVersion < 2) { - checkExternalEmitHelpers(node, 256); - } - } - if (node.initializer.kind === 227) { - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - if (varExpr.kind === 177 || varExpr.kind === 178) { - checkDestructuringAssignment(varExpr, iteratedType || unknownType); - } - else { - var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); - if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); - } - } - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInStatement(node) { - checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); - if (node.initializer.kind === 227) { - var variable = node.initializer.declarations[0]; - if (variable && ts.isBindingPattern(variable.name)) { - error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 || varExpr.kind === 178) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); - } - else { - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); - } - } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { - error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInOrForOfVariableDeclaration(iterationStatement) { - var variableDeclarationList = iterationStatement.initializer; - if (variableDeclarationList.declarations.length >= 1) { - var decl = variableDeclarationList.declarations[0]; - checkVariableDeclaration(decl); - } - } - function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { - var expressionType = checkNonNullExpression(rhsExpression); - return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); - } - function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable) { - if (isTypeAny(inputType)) { - return inputType; - } - return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, true) || anyType; - } - function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, checkAssignability) { - var uplevelIteration = languageVersion >= 2; - var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; - if (uplevelIteration || downlevelIteration || allowAsyncIterable) { - var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterable, allowAsyncIterable, checkAssignability); - if (iteratedType || uplevelIteration) { - return iteratedType; - } - } - var arrayType = inputType; - var reportedError = false; - var hasStringConstituent = false; - if (allowStringInput) { - if (arrayType.flags & 65536) { - var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); - if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, true); - } - } - else if (arrayType.flags & 262178) { - arrayType = neverType; - } - hasStringConstituent = arrayType !== inputType; - if (hasStringConstituent) { - if (languageVersion < 1) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); - reportedError = true; - } - } - if (arrayType.flags & 8192) { - return stringType; - } - } - } - if (!isArrayLikeType(arrayType)) { - if (errorNode && !reportedError) { - var diagnostic = !allowStringInput || hasStringConstituent - ? downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type - : downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; - error(errorNode, diagnostic, typeToString(arrayType)); - } - return hasStringConstituent ? stringType : undefined; - } - var arrayElementType = getIndexTypeOfType(arrayType, 1); - if (hasStringConstituent && arrayElementType) { - if (arrayElementType.flags & 262178) { - return stringType; - } - return getUnionType([arrayElementType, stringType], true); - } - return arrayElementType; - } - function getIteratedTypeOfIterable(type, errorNode, isAsyncIterable, allowNonAsyncIterables, checkAssignability) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterable = type; - if (isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable) { - return isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable; - } - if (isAsyncIterable) { - if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || - isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { - return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; - } - } - if (!isAsyncIterable || allowNonAsyncIterables) { - if (isReferenceToType(type, getGlobalIterableType(false)) || - isReferenceToType(type, getGlobalIterableIteratorType(false))) { - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0] - : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; - } - } - var iteratorMethodSignatures; - var isNonAsyncIterable = false; - if (isAsyncIterable) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0); - } - if (!isAsyncIterable || (allowNonAsyncIterables && !ts.some(iteratorMethodSignatures))) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0); - isNonAsyncIterable = true; - } - if (ts.some(iteratorMethodSignatures)) { - var iteratorMethodReturnType = getUnionType(ts.map(iteratorMethodSignatures, getReturnTypeOfSignature), true); - var iteratedType = getIteratedTypeOfIterator(iteratorMethodReturnType, errorNode, !isNonAsyncIterable); - if (checkAssignability && errorNode && iteratedType) { - checkTypeAssignableTo(type, isNonAsyncIterable - ? createIterableType(iteratedType) - : createAsyncIterableType(iteratedType), errorNode); - } - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; - } - if (errorNode) { - error(errorNode, isAsyncIterable - ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); - } - return undefined; - } - function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterator = type; - if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { - return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; - } - var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; - if (isReferenceToType(type, getIteratorType(false))) { - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] - : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; - } - var nextMethod = getTypeOfPropertyOfType(type, "next"); - if (isTypeAny(nextMethod)) { - return undefined; - } - var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : emptyArray; - if (nextMethodSignatures.length === 0) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.An_async_iterator_must_have_a_next_method - : ts.Diagnostics.An_iterator_must_have_a_next_method); - } - return undefined; - } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); - if (isTypeAny(nextResult)) { - return undefined; - } - if (isAsyncIterator) { - nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); - if (isTypeAny(nextResult)) { - return undefined; - } - } - var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); - if (!nextValue) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property - : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue - : typeAsIterator.iteratedTypeOfIterator = nextValue; - } - function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { - if (isTypeAny(returnType)) { - return undefined; - } - return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, false, false) - || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); - } - function checkBreakOrContinueStatement(node) { - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); - } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 153 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154))); - } - function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 - ? getPromisedTypeOfPromise(returnType) - : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); - } - function checkReturnStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } - } - var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return; - } - if (func.kind === 154) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } - } - else if (func.kind === 152) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); - } - } - } - else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - } - function checkWithStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 16384) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); - } - } - checkExpression(node.expression); - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; - var end = node.statement.pos; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); - } - } - function checkSwitchStatement(node) { - checkGrammarStatementInAmbientContext(node); - var firstDefaultClause; - var hasDuplicateDefaultClause = false; - var expressionType = checkExpression(node.expression); - var expressionIsLiteral = isLiteralType(expressionType); - ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 258 && !hasDuplicateDefaultClause) { - if (firstDefaultClause === undefined) { - firstDefaultClause = clause; - } - else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); - hasDuplicateDefaultClause = true; - } - } - if (produceDiagnostics && clause.kind === 257) { - var caseClause = clause; - var caseType = checkExpression(caseClause.expression); - var caseIsLiteral = isLiteralType(caseType); - var comparedExpressionType = expressionType; - if (!caseIsLiteral || !expressionIsLiteral) { - caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; - comparedExpressionType = getBaseTypeOfLiteralType(expressionType); - } - if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { - checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); - } - } - ts.forEach(clause.statements, checkSourceElement); - }); - if (node.caseBlock.locals) { - registerForUnusedIdentifiersCheck(node.caseBlock); - } - } - function checkLabeledStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - ts.findAncestor(node.parent, function (current) { - if (ts.isFunctionLike(current)) { - return "quit"; - } - if (current.kind === 222 && current.label.text === node.label.text) { - var sourceFile = ts.getSourceFileOfNode(node); - grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); - return true; - } - }); - } - checkSourceElement(node.statement); - } - function checkThrowStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.expression === undefined) { - grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); - } - } - if (node.expression) { - checkExpression(node.expression); - } - } - function checkTryStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkBlock(node.tryBlock); - var catchClause = node.catchClause; - if (catchClause) { - if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.type) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); - } - else if (catchClause.variableDeclaration.initializer) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); - } - else { - var blockLocals_1 = catchClause.block.locals; - if (blockLocals_1) { - ts.forEachKey(catchClause.locals, function (caughtName) { - var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2) !== 0) { - grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); - } - }); - } - } - } - checkBlock(catchClause.block); - } - if (node.finallyBlock) { - checkBlock(node.finallyBlock); - } - } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); - var stringIndexType = getIndexTypeOfType(type, 0); - var numberIndexType = getIndexTypeOfType(type, 1); - if (stringIndexType || numberIndexType) { - ts.forEach(getPropertiesOfObjectType(type), function (prop) { - var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); - }); - if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); - } - } - } - } - var errorNode; - if (stringIndexType && numberIndexType) { - errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (getObjectFlags(type) & 2)) { - var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; - } - } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { - error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); - } - function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { - return; - } - var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { - return; - } - var errorNode; - if (propDeclaration && - (propDeclaration.kind === 194 || - ts.getNameOfDeclaration(propDeclaration).kind === 144 || - prop.parent === containingType.symbol)) { - errorNode = propDeclaration; - } - else if (indexDeclaration) { - errorNode = indexDeclaration; - } - else if (getObjectFlags(containingType) & 2) { - var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; - } - if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 - ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 - : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; - error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); - } - } - } - function checkTypeNameIsReserved(name, message) { - switch (name.text) { - case "any": - case "number": - case "boolean": - case "string": - case "symbol": - case "void": - case "object": - error(name, message, name.text); - } - } - function checkTypeParameters(typeParameterDeclarations) { - if (typeParameterDeclarations) { - var seenDefault = false; - for (var i = 0; i < typeParameterDeclarations.length; i++) { - var node = typeParameterDeclarations[i]; - checkTypeParameter(node); - if (produceDiagnostics) { - if (node.default) { - seenDefault = true; - } - else if (seenDefault) { - error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); - } - for (var j = 0; j < i; j++) { - if (typeParameterDeclarations[j].symbol === node.symbol) { - error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); - } - } - } - } - } - } - function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { - return; - } - var links = getSymbolLinks(symbol); - if (!links.typeParametersChecked) { - links.typeParametersChecked = true; - var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { - return; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { - var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); - } - } - } - } - function areTypeParametersIdentical(declarations, typeParameters) { - var maxTypeArgumentCount = ts.length(typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - var numTypeParameters = ts.length(declaration.typeParameters); - if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { - return false; - } - for (var i = 0; i < numTypeParameters; i++) { - var source = declaration.typeParameters[i]; - var target = typeParameters[i]; - if (source.name.text !== target.symbol.name) { - return false; - } - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; - } - var sourceDefault = source.default && getTypeFromTypeNode(source.default); - var targetDefault = getDefaultFromTypeParameter(target); - if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { - return false; - } - } - } - return true; - } - function checkClassExpression(node) { - checkClassLikeDeclaration(node); - checkNodeDeferred(node); - return getTypeOfSymbol(getSymbolOfNode(node)); - } - function checkClassExpressionDeferred(node) { - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); - } - checkClassLikeDeclaration(node); - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassLikeDeclaration(node) { - checkGrammarClassLikeDeclaration(node); - checkDecorators(node); - if (node.name) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkTypeParameters(node.typeParameters); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - var staticType = getTypeOfSymbol(symbol); - checkTypeParameterListsIdentical(symbol); - checkClassForDuplicateDeclarations(node); - if (!ts.isInAmbientContext(node)) { - checkClassForStaticPropertyNameConflicts(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - if (languageVersion < 2) { - checkExternalEmitHelpers(baseTypeNode.parent, 1); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length && produceDiagnostics) { - var baseType_1 = baseTypes[0]; - var baseConstructorType = getBaseConstructorTypeOfClass(type); - var staticBaseType = getApparentType(baseConstructorType); - checkBaseTypeAccessibility(staticBaseType, baseTypeNode); - checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { - ts.forEach(baseTypeNode.typeArguments, checkSourceElement); - for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { - var constructor = _a[_i]; - if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { - break; - } - } - } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { - error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); - } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { - var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); - } - } - checkKindsOfPropertyMemberOverrides(type, baseType_1); - } - } - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); - if (implementedTypeNodes) { - for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { - var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { - error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(typeRefNode); - if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); - if (t !== unknownType) { - if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); - } - else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); - } - } - } - } - } - if (produceDiagnostics) { - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - } - } - function checkBaseTypeAccessibility(type, node) { - var signatures = getSignaturesOfType(type, 1); - if (signatures.length) { - var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); - } - } - } - } - function getTargetSymbol(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; }); - } - function getClassOrInterfaceDeclarationsOfSymbol(symbol) { - return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 || d.kind === 230; - }); - } - function checkKindsOfPropertyMemberOverrides(type, baseType) { - var baseProperties = getPropertiesOfType(baseType); - for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; - var base = getTargetSymbol(baseProperty); - if (base.flags & 16777216) { - continue; - } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - 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) { - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { - if (derivedClassDecl.kind === 199) { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); - } - else { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); - } - } - } - else { - var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { - continue; - } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { - continue; - } - var errorMessage = void 0; - if (isMethodLike(base)) { - if (derived.flags & 98304) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; - } - } - else if (base.flags & 4) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; - } - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); - } - } - } - } - function isAccessor(kind) { - return kind === 153 || kind === 154; - } - function checkInheritedPropertiesAreIdentical(type, typeNode) { - var baseTypes = getBaseTypes(type); - if (baseTypes.length < 2) { - return true; - } - var seen = ts.createMap(); - ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.name, { prop: p, containingType: type }); }); - var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; - var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; - var existing = seen.get(prop.name); - if (!existing) { - seen.set(prop.name, { prop: prop, containingType: base }); - } - else { - var isInheritedProperty = existing.containingType !== type; - if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { - ok = false; - var typeName1 = typeToString(existing.containingType); - var typeName2 = typeToString(base); - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); - } - } - } - } - return ok; - } - function checkInterfaceDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); - checkTypeParameters(node.typeParameters); - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); - if (node === firstInterfaceDecl) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - if (checkInheritedPropertiesAreIdentical(type, node.name)) { - for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { - var baseType = _a[_i]; - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); - } - checkIndexConstraints(type); - } - } - checkObjectTypeForDuplicateDeclarations(node); - } - ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { - error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(heritageElement); - }); - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); - } - } - function checkTypeAliasDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); - checkTypeParameters(node.typeParameters); - checkSourceElement(node.type); - } - function computeEnumMemberValues(node) { - var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 16384)) { - nodeLinks.flags |= 16384; - var autoValue = 0; - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var value = computeMemberValue(member, autoValue); - getNodeLinks(member).enumMemberValue = value; - autoValue = typeof value === "number" ? value + 1 : undefined; - } - } - } - 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); - } - } - 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; - } - } - 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; - case 47: return left >>> right; - case 45: return left << right; - case 50: return left ^ right; - case 39: return left * right; - case 41: return left / right; - case 37: return left + right; - case 38: return left - right; - case 42: return left % right; - } - } - 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); - } - } - 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; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkExportsOnMergedDeclarations(node); - computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); - } - var enumSymbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); - if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { - ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); - } - }); - } - var seenEnumMissingInitialInitializer_1 = false; - ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 232) { - return false; - } - var enumDeclaration = declaration; - if (!enumDeclaration.members.length) { - return false; - } - var firstEnumMember = enumDeclaration.members[0]; - if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer_1) { - error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); - } - else { - seenEnumMissingInitialInitializer_1 = true; - } - } - }); - } - } - function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 229 || - (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { - return declaration; - } - } - return undefined; - } - function inSameLexicalScope(node1, node2) { - var container1 = ts.getEnclosingBlockScopeContainer(node1); - var container2 = ts.getEnclosingBlockScopeContainer(node2); - if (isGlobalSourceFile(container1)) { - return isGlobalSourceFile(container2); - } - else if (isGlobalSourceFile(container2)) { - return false; - } - else { - return container1 === container2; - } - } - function checkModuleDeclaration(node) { - if (produceDiagnostics) { - var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); - if (isGlobalAugmentation && !inAmbientContext) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); - } - var isAmbientExternalModule = ts.isAmbientModule(node); - var contextErrorMessage = isAmbientExternalModule - ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file - : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; - if (checkGrammarModuleElementContext(node, contextErrorMessage)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9) { - grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - } - if (ts.isIdentifier(node.name)) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - if (symbol.flags & 512 - && symbol.declarations.length > 1 - && !inAmbientContext - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { - var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); - if (firstNonAmbientClassOrFunc) { - if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); - } - else if (node.pos < firstNonAmbientClassOrFunc.pos) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); - } - } - var mergedClass = ts.getDeclarationOfKind(symbol, 229); - if (mergedClass && - inSameLexicalScope(node, mergedClass)) { - getNodeLinks(node).flags |= 32768; - } - } - if (isAmbientExternalModule) { - if (ts.isExternalModuleAugmentation(node)) { - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728); - if (checkBody && node.body) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - checkModuleAugmentationElement(statement, isGlobalAugmentation); - } - } - } - else if (isGlobalSourceFile(node.parent)) { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); - } - } - else { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else { - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); - } - } - } - } - if (node.body) { - checkSourceElement(node.body); - if (!ts.isGlobalScopeAugmentation(node)) { - registerForUnusedIdentifiersCheck(node); - } - } - } - function checkModuleAugmentationElement(node, isGlobalAugmentation) { - switch (node.kind) { - case 208: - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - checkModuleAugmentationElement(decl, isGlobalAugmentation); - } - break; - case 243: - case 244: - grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); - break; - case 237: - case 238: - grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); - break; - case 176: - case 226: - var name = node.name; - if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; - checkModuleAugmentationElement(el, isGlobalAugmentation); - } - break; - } - case 229: - case 232: - case 228: - case 230: - case 233: - case 231: - if (isGlobalAugmentation) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol) { - var reportError = !(symbol.flags & 134217728); - if (!reportError) { - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } - break; - } - } - function getFirstIdentifier(node) { - switch (node.kind) { - case 71: - return node; - case 143: - do { - node = node.left; - } while (node.kind !== 71); - return node; - case 179: - do { - node = node.expression; - } while (node.kind !== 71); - return node; - } - } - function checkExternalImportOrExportDeclaration(node) { - var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { - error(moduleName, ts.Diagnostics.String_literal_expected); - return false; - } - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 ? - ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : - ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); - return false; - } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - if (!isTopLevelInExternalModuleAugmentation(node)) { - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; - } - } - return true; - } - function checkAliasSymbol(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793064 ? 793064 : 0) | - (symbol.flags & 1920 ? 1920 : 0); - if (target.flags & excludedMeanings) { - var message = node.kind === 246 ? - ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : - 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) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkAliasSymbol(node); - } - function checkImportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); - } - if (checkExternalImportOrExportDeclaration(node)) { - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - checkImportBinding(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { - checkImportBinding(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, checkImportBinding); - } - } - } - } - } - function checkImportEqualsDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - return; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { - checkImportBinding(node); - if (ts.getModifierFlags(node) & 1) { - markExportAsReferenced(node); - } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveAlias(getSymbolOfNode(node)); - if (target !== unknownSymbol) { - if (target.flags & 107455) { - var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { - error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); - } - } - if (target.flags & 793064) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); - } - } - } - else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - grammarErrorOnNode(node, ts.Diagnostics.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); - } - } - } - } - function checkExportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); - } - if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { - error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); - } - } - else { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); - } - } - } - } - function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; - if (!isInAppropriateContext) { - grammarErrorOnFirstToken(node, errorMessage); - } - return !isInAppropriateContext; - } - function checkExportSpecifier(node) { - checkAliasSymbol(node); - if (!node.parent.parent.moduleSpecifier) { - var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); - } - else { - markExportAsReferenced(node); - } - } - } - function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { - return; - } - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { - if (node.isExportEquals) { - error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); - } - else { - error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); - } - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); - } - if (node.expression.kind === 71) { - markExportAsReferenced(node); - } - else { - checkExpressionCached(node.expression); - } - checkExternalModuleExports(container); - if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); - } - else if (modulekind === ts.ModuleKind.System) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); - } - } - } - function hasExportedMembers(moduleSymbol) { - return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); - } - function checkExternalModuleExports(node) { - var moduleSymbol = getSymbolOfNode(node); - var links = getSymbolLinks(moduleSymbol); - if (!links.exportsChecked) { - var exportEqualsSymbol = moduleSymbol.exports.get("export="); - if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { - var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration)) { - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); - } - } - var exports_1 = getExportsOfModule(moduleSymbol); - exports_1 && exports_1.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - if (flags & (1920 | 64 | 384)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); - if (flags & 524288 && exportedDeclarationsCount <= 2) { - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); - } - } - } - }); - links.exportsChecked = true; - } - function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || - !!declaration.body; - } - } - function checkSourceElement(node) { - if (!node) { - return; - } - var kind = node.kind; - if (cancellationToken) { - switch (kind) { - case 233: - case 229: - case 230: - case 228: - cancellationToken.throwIfCancellationRequested(); - } - } - switch (kind) { - case 145: - return checkTypeParameter(node); - case 146: - return checkParameter(node); - case 149: - case 148: - return checkPropertyDeclaration(node); - case 160: - case 161: - case 155: - case 156: - return checkSignatureDeclaration(node); - case 157: - return checkSignatureDeclaration(node); - case 151: - case 150: - return checkMethodDeclaration(node); - case 152: - return checkConstructorDeclaration(node); - case 153: - case 154: - return checkAccessorDeclaration(node); - case 159: - return checkTypeReferenceNode(node); - case 158: - return checkTypePredicate(node); - case 162: - return checkTypeQuery(node); - case 163: - return checkTypeLiteral(node); - case 164: - return checkArrayType(node); - case 165: - return checkTupleType(node); - case 166: - case 167: - return checkUnionOrIntersectionType(node); - case 168: - case 170: - return checkSourceElement(node.type); - case 171: - return checkIndexedAccessType(node); - case 172: - return checkMappedType(node); - case 228: - return checkFunctionDeclaration(node); - case 207: - case 234: - return checkBlock(node); - case 208: - return checkVariableStatement(node); - case 210: - return checkExpressionStatement(node); - case 211: - return checkIfStatement(node); - case 212: - return checkDoStatement(node); - case 213: - return checkWhileStatement(node); - case 214: - return checkForStatement(node); - case 215: - return checkForInStatement(node); - case 216: - return checkForOfStatement(node); - case 217: - case 218: - return checkBreakOrContinueStatement(node); - case 219: - return checkReturnStatement(node); - case 220: - return checkWithStatement(node); - case 221: - return checkSwitchStatement(node); - case 222: - return checkLabeledStatement(node); - case 223: - return checkThrowStatement(node); - case 224: - return checkTryStatement(node); - case 226: - return checkVariableDeclaration(node); - case 176: - return checkBindingElement(node); - case 229: - return checkClassDeclaration(node); - case 230: - return checkInterfaceDeclaration(node); - case 231: - return checkTypeAliasDeclaration(node); - case 232: - return checkEnumDeclaration(node); - case 233: - return checkModuleDeclaration(node); - case 238: - return checkImportDeclaration(node); - case 237: - return checkImportEqualsDeclaration(node); - case 244: - return checkExportDeclaration(node); - case 243: - return checkExportAssignment(node); - case 209: - checkGrammarStatementInAmbientContext(node); - return; - case 225: - checkGrammarStatementInAmbientContext(node); - return; - case 247: - return checkMissingDeclaration(node); - } - } - function checkNodeDeferred(node) { - if (deferredNodes) { - deferredNodes.push(node); - } - } - function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; - switch (node.kind) { - case 186: - case 187: - case 151: - case 150: - checkFunctionExpressionOrObjectLiteralMethodDeferred(node); - break; - case 153: - case 154: - checkAccessorDeclaration(node); - break; - case 199: - checkClassExpressionDeferred(node); - break; - } - } - } - function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); - checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); - } - function checkSourceFileWorker(node) { - var links = getNodeLinks(node); - if (!(links.flags & 1)) { - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { - return; - } - checkGrammarSourceFile(node); - potentialThisCollisions.length = 0; - potentialNewTargetCollisions.length = 0; - deferredNodes = []; - deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; - ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); - if (ts.isExternalModule(node)) { - registerForUnusedIdentifiersCheck(node); - } - if (!node.isDeclarationFile) { - checkUnusedIdentifiers(); - } - deferredNodes = undefined; - deferredUnusedIdentifierNodes = undefined; - if (ts.isExternalOrCommonJsModule(node)) { - checkExternalModuleExports(node); - } - if (potentialThisCollisions.length) { - ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); - potentialThisCollisions.length = 0; - } - if (potentialNewTargetCollisions.length) { - ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); - potentialNewTargetCollisions.length = 0; - } - links.flags |= 1; - } - } - function getDiagnostics(sourceFile, ct) { - try { - cancellationToken = ct; - return getDiagnosticsWorker(sourceFile); - } - finally { - cancellationToken = undefined; - } - } - function getDiagnosticsWorker(sourceFile) { - throwIfNonDiagnosticsProducing(); - if (sourceFile) { - var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; - checkSourceFile(sourceFile); - var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); - var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { - var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); - return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); - } - else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { - return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); - } - return semanticDiagnostics; - } - ts.forEach(host.getSourceFiles(), checkSourceFile); - return diagnostics.getDiagnostics(); - } - function getGlobalDiagnostics() { - throwIfNonDiagnosticsProducing(); - return diagnostics.getGlobalDiagnostics(); - } - function throwIfNonDiagnosticsProducing() { - if (!produceDiagnostics) { - throw new Error("Trying to get diagnostics from a type checker that does not produce them."); - } - } - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } - function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { - return []; - } - var symbols = ts.createMap(); - var memberFlags = 0; - populateSymbols(); - return symbolsToArray(symbols); - function populateSymbols() { - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - case 233: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); - break; - case 232: - copySymbols(getSymbolOfNode(location).exports, meaning & 8); - break; - case 199: - var className = location.name; - if (className) { - copySymbol(location.symbol, meaning); - } - case 229: - case 230: - if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); - } - break; - case 186: - var funcName = location.name; - if (funcName) { - copySymbol(location.symbol, meaning); - } - break; - } - if (ts.introducesArgumentsExoticObject(location)) { - copySymbol(argumentsSymbol, meaning); - } - memberFlags = ts.getModifierFlags(location); - location = location.parent; - } - copySymbols(globals, meaning); - } - function copySymbol(symbol, meaning) { - if (symbol.flags & meaning) { - var id = symbol.name; - if (!symbols.has(id)) { - symbols.set(id, symbol); - } - } - } - function copySymbols(source, meaning) { - if (meaning) { - source.forEach(function (symbol) { - copySymbol(symbol, meaning); - }); - } - } - } - function isTypeDeclarationName(name) { - return name.kind === 71 && - isTypeDeclaration(name.parent) && - name.parent.name === name; - } - function isTypeDeclaration(node) { - switch (node.kind) { - case 145: - case 229: - case 230: - case 231: - case 232: - return true; - } - } - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 143) { - node = node.parent; - } - return node.parent && (node.parent.kind === 159 || node.parent.kind === 277); - } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 179) { - node = node.parent; - } - return node.parent && node.parent.kind === 201; - } - function forEachEnclosingClass(node, callback) { - var result; - while (true) { - node = ts.getContainingClass(node); - if (!node) - break; - if (result = callback(node)) - break; - } - return result; - } - function isNodeWithinClass(node, classDeclaration) { - return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); - } - function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143) { - nodeOnRightSide = nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 237) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 243) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; - } - return undefined; - } - function isInRightSideOfImportOrExportAssignment(node) { - return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; - } - function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); - switch (specialPropertyAssignmentKind) { - case 1: - case 3: - return getSymbolOfNode(entityName.parent); - case 4: - case 2: - case 5: - return getSymbolOfNode(entityName.parent.parent); - } - } - function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { - if (ts.isDeclarationName(entityName)) { - return getSymbolOfNode(entityName.parent); - } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 && - entityName.parent === entityName.parent.parent.left) { - var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); - if (specialPropertyAssignmentSymbol) { - return specialPropertyAssignmentSymbol; - } - } - if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); - } - if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 237); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); - } - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = 0; - if (entityName.parent.kind === 201) { - meaning = 793064; - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455; - } - } - else { - meaning = 1920; - } - meaning |= 8388608; - var entityNameSymbol = resolveEntityName(entityName, meaning); - if (entityNameSymbol) { - return entityNameSymbol; - } - } - if (ts.isPartOfExpression(entityName)) { - if (ts.nodeIsMissing(entityName)) { - return undefined; - } - if (entityName.kind === 71) { - if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { - return getIntrinsicTagSymbol(entityName.parent); - } - return resolveEntityName(entityName, 107455, false, true); - } - else if (entityName.kind === 179) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkPropertyAccessExpression(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - else if (entityName.kind === 143) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkQualifiedName(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - } - else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 159 || entityName.parent.kind === 277) ? 793064 : 1920; - return resolveEntityName(entityName, meaning, false, true); - } - else if (entityName.parent.kind === 253) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 158) { - return resolveEntityName(entityName, 1); - } - return undefined; - } - function getSymbolAtLocation(node) { - if (node.kind === 265) { - return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; - } - if (isInsideWithStatementBody(node)) { - return undefined; - } - if (isDeclarationNameOrImportPropertyName(node)) { - return getSymbolOfNode(node.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); - } - if (node.kind === 71) { - if (isInRightSideOfImportOrExportAssignment(node)) { - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - } - else if (node.parent.kind === 176 && - node.parent.parent.kind === 174 && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); - if (propertyDeclaration) { - return propertyDeclaration; - } - } - } - switch (node.kind) { - case 71: - case 179: - case 143: - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99: - var container = ts.getThisContainer(node, false); - if (ts.isFunctionLike(container)) { - var sig = getSignatureFromDeclaration(container); - if (sig.thisParameter) { - return sig.thisParameter; - } - } - case 97: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; - case 169: - return getTypeFromTypeNode(node).symbol; - case 123: - var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152) { - return constructorDeclaration.parent.symbol; - } - return undefined; - case 9: - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { - return resolveExternalModuleName(node, node); - } - case 8: - if (node.parent.kind === 180 && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); - } - break; - } - return undefined; - } - function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 262) { - return resolveEntityName(location.name, 107455 | 8388608); - } - return undefined; - } - function getExportSpecifierLocalTargetSymbol(node) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); - } - function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { - return unknownType; - } - if (ts.isPartOfTypeNode(node)) { - var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; - } - if (ts.isPartOfExpression(node)) { - return getRegularTypeOfExpression(node); - } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); - } - if (isTypeDeclaration(node)) { - var symbol = getSymbolOfNode(node); - return getDeclaredTypeOfSymbol(symbol); - } - if (isTypeDeclarationName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - } - if (ts.isDeclaration(node)) { - var symbol = getSymbolOfNode(node); - return getTypeOfSymbol(symbol); - } - if (isDeclarationNameOrImportPropertyName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); - } - if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, true); - } - if (isInRightSideOfImportOrExportAssignment(node)) { - var symbol = getSymbolAtLocation(node); - var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); - return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); - } - return unknownType; - } - function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 || expr.kind === 177); - if (expr.parent.kind === 216) { - var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - if (expr.parent.kind === 194) { - var iteratedType = getTypeOfExpression(expr.parent.right); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - if (expr.parent.kind === 261) { - var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); - } - ts.Debug.assert(expr.parent.kind === 177); - var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); - } - function getPropertySymbolOfDestructuringAssignment(location) { - var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); - return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); - } - function getRegularTypeOfExpression(expr) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { - expr = expr.parent; - } - return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); - } - function getParentTypeOfClassElement(node) { - var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 - ? getTypeOfSymbol(classSymbol) - : getDeclaredTypeOfSymbol(classSymbol); - } - function getAugmentedPropertiesOfType(type) { - type = getApparentType(type); - var propsByName = createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName.has(p.name)) { - propsByName.set(p.name, p); - } - }); - } - return getNamedMembers(propsByName); - } - function getRootSymbols(symbol) { - 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_4.push(symbol); - } - }); - return symbols_4; - } - else if (symbol.flags & 134217728) { - if (symbol.leftSpread) { - var links = symbol; - return getRootSymbols(links.leftSpread).concat(getRootSymbols(links.rightSpread)); - } - if (symbol.syntheticOrigin) { - return getRootSymbols(symbol.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } - } - return [symbol]; - } - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; - return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; - } - } - return false; - } - function moduleExportsSomeValue(moduleReferenceExpression) { - var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return true; - } - var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - var symbolLinks = getSymbolLinks(moduleSymbol); - if (symbolLinks.exportsSomeValue === undefined) { - symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455) - : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); - } - return symbolLinks.exportsSomeValue; - function isValue(s) { - s = resolveSymbol(s); - return s && !!(s.flags & 107455); - } - } - function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; - } - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); - if (symbol) { - if (symbol.flags & 1048576) { - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol_1 = getParentOfSymbol(symbol); - if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { - var symbolFile = parentSymbol_1.valueDeclaration; - var referenceFile = ts.getSourceFileOfNode(node); - var symbolIsUmdExport = symbolFile !== referenceFile; - return symbolIsUmdExport ? undefined : symbolFile; - } - return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); - } - } - } - } - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && symbol.flags & 8388608) { - return getDeclarationOfAliasSymbol(symbol); - } - } - return undefined; - } - function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418) { - var links = getSymbolLinks(symbol); - if (links.isDeclarationWithCollidingName === undefined) { - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (ts.isStatementWithLocals(container)) { - var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.name, 107455, undefined, undefined)) { - links.isDeclarationWithCollidingName = true; - } - else if (nodeLinks_1.flags & 131072) { - var isDeclaredInLoop = nodeLinks_1.flags & 262144; - var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); - links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); - } - else { - links.isDeclarationWithCollidingName = false; - } - } - } - return links.isDeclarationWithCollidingName; - } - return false; - } - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { - return symbol.valueDeclaration; - } - } - } - return undefined; - } - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); - if (node) { - var symbol = getSymbolOfNode(node); - if (symbol) { - return isSymbolOfDeclarationWithCollidingName(symbol); - } - } - return false; - } - function isValueAliasDeclaration(node) { - switch (node.kind) { - case 237: - case 239: - case 240: - case 242: - case 246: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244: - var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243: - return node.expression - && node.expression.kind === 71 - ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) - : true; - } - return false; - } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { - return false; - } - var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); - return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); - } - function isAliasResolvedToValue(symbol) { - var target = resolveAlias(symbol); - if (target === unknownSymbol) { - return true; - } - return target.flags & 107455 && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); - } - function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; - } - function isReferencedAliasDeclaration(node, checkChildren) { - if (ts.isAliasSymbolDeclaration(node)) { - var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { - return true; - } - } - if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); - } - return false; - } - function isImplementationOfOverload(node) { - if (ts.nodeIsPresent(node.body)) { - var symbol = getSymbolOfNode(node); - var signaturesOfSymbol = getSignaturesOfSymbol(symbol); - return signaturesOfSymbol.length > 1 || - (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); - } - return false; - } - function isRequiredInitializedParameter(parameter) { - return strictNullChecks && - !isOptionalParameter(parameter) && - parameter.initializer && - !(ts.getModifierFlags(parameter) & 92); - } - function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; - } - function getEnumMemberValue(node) { - computeEnumMemberValues(node.parent); - return getNodeLinks(node).enumMemberValue; - } - function canHaveConstantValue(node) { - switch (node.kind) { - case 264: - case 179: - case 180: - return true; - } - return false; - } - function getConstantValue(node) { - if (node.kind === 264) { - return getEnumMemberValue(node); - } - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol && (symbol.flags & 8)) { - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); - } - } - return undefined; - } - function isFunctionType(type) { - return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; - } - function getTypeReferenceSerializationKind(typeName, location) { - var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); - var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); - if (valueSymbol && valueSymbol === typeSymbol) { - var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); - if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { - return ts.TypeReferenceSerializationKind.Promise; - } - var constructorType = getTypeOfSymbol(valueSymbol); - if (constructorType && isConstructorType(constructorType)) { - return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; - } - } - if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - var type = getDeclaredTypeOfSymbol(typeSymbol); - if (type === unknownType) { - return ts.TypeReferenceSerializationKind.Unknown; - } - else if (type.flags & 1) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { - return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; - } - else if (isTypeOfKind(type, 136)) { - return ts.TypeReferenceSerializationKind.BooleanType; - } - else if (isTypeOfKind(type, 84)) { - return ts.TypeReferenceSerializationKind.NumberLikeType; - } - else if (isTypeOfKind(type, 262178)) { - return ts.TypeReferenceSerializationKind.StringLikeType; - } - else if (isTupleType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else if (isTypeOfKind(type, 512)) { - return ts.TypeReferenceSerializationKind.ESSymbolType; - } - else if (isFunctionType(type)) { - return ts.TypeReferenceSerializationKind.TypeWithCallSignature; - } - else if (isArrayType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else { - return ts.TypeReferenceSerializationKind.ObjectType; - } - } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { - var symbol = getSymbolOfNode(declaration); - var type = symbol && !(symbol.flags & (2048 | 131072)) - ? getWidenedLiteralType(getTypeOfSymbol(symbol)) - : unknownType; - if (flags & 4096) { - type = getNullableType(type, 2048); - } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { - var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); - } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name) { - return globals.has(name); - } - function getReferencedValueSymbol(reference, startInDeclarationContainer) { - var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; - if (resolvedSymbol) { - return resolvedSymbol; - } - var location = reference; - if (startInDeclarationContainer) { - var parent = reference.parent; - if (ts.isDeclaration(parent) && reference === parent.name) { - location = getDeclarationContainer(parent); - } - } - return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); - } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); - if (reference) { - var symbol = getReferencedValueSymbol(reference); - if (symbol) { - return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; - } - } - } - return undefined; - } - function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 1048576); - } - return false; - } - function writeLiteralConstValue(node, writer) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); - } - function createResolver() { - var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); - var fileToDirective; - if (resolvedTypeReferenceDirectives) { - fileToDirective = ts.createFileMap(); - resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { - if (!resolvedDirective) { - return; - } - var file = host.getSourceFile(resolvedDirective.resolvedFileName); - fileToDirective.set(file.path, key); - }); - } - return { - getReferencedExportContainer: getReferencedExportContainer, - getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, - isDeclarationWithCollidingName: isDeclarationWithCollidingName, - isValueAliasDeclaration: function (node) { - node = ts.getParseTreeNode(node); - return node ? isValueAliasDeclaration(node) : true; - }, - hasGlobalName: hasGlobalName, - isReferencedAliasDeclaration: function (node, checkChildren) { - node = ts.getParseTreeNode(node); - return node ? isReferencedAliasDeclaration(node, checkChildren) : true; - }, - getNodeCheckFlags: function (node) { - node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; - }, - isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, - isDeclarationVisible: isDeclarationVisible, - isImplementationOfOverload: isImplementationOfOverload, - isRequiredInitializedParameter: isRequiredInitializedParameter, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, - isSymbolAccessible: isSymbolAccessible, - isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - collectLinkedAliases: collectLinkedAliases, - getReferencedValueDeclaration: getReferencedValueDeclaration, - getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, - isOptionalParameter: isOptionalParameter, - moduleExportsSomeValue: moduleExportsSomeValue, - isArgumentsLocalBinding: isArgumentsLocalBinding, - getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, - getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, - isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } - }; - function getTypeReferenceDirectivesForEntityName(node) { - if (!fileToDirective) { - return undefined; - } - var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) - ? 107455 | 1048576 - : 793064 | 1920; - var symbol = resolveEntityName(node, meaning, true); - return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; - } - function getTypeReferenceDirectivesForSymbol(symbol, meaning) { - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { - return undefined; - } - var typeReferenceDirectives; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); - if (typeReferenceDirective) { - (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); - } - else { - return undefined; - } - } - } - return typeReferenceDirectives; - } - function isSymbolFromTypeDeclarationFile(symbol) { - if (!symbol.declarations) { - return false; - } - var current = symbol; - while (true) { - var parent = getParentOfSymbol(current); - if (parent) { - current = parent; - } - else { - break; - } - } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { - return false; - } - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.contains(file.path)) { - return true; - } - } - return false; - } - } - function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); - if (!moduleSymbol) { - return undefined; - } - return ts.getDeclarationOfKind(moduleSymbol, 265); - } - function initializeTypeChecker() { - for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); - } - var augmentations; - for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); - } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); - } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); - } - if (file.symbol && file.symbol.globalExports) { - var source = file.symbol.globalExports; - source.forEach(function (sourceSymbol, id) { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); - } - }); - } - } - if (augmentations) { - for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { - var list = augmentations_1[_d]; - for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { - var augmentation = list_1[_e]; - mergeModuleAugmentation(augmentation); - } - } - } - addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); - getSymbolLinks(undefinedSymbol).type = undefinedWideningType; - getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); - getSymbolLinks(unknownSymbol).type = unknownType; - globalArrayType = getGlobalType("Array", 1, true); - globalObjectType = getGlobalType("Object", 0, true); - globalFunctionType = getGlobalType("Function", 0, true); - globalStringType = getGlobalType("String", 0, true); - globalNumberType = getGlobalType("Number", 0, true); - globalBooleanType = getGlobalType("Boolean", 0, true); - globalRegExpType = getGlobalType("RegExp", 0, true); - anyArrayType = createArrayType(anyType); - autoArrayType = createArrayType(autoType); - globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); - anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined("ThisType", 1); - } - function checkExternalEmitHelpers(location, helpers) { - if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { - var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { - var helpersModule = resolveHelpersModule(sourceFile, location); - if (helpersModule !== unknownSymbol) { - var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 16384; helper <<= 1) { - if (uncheckedHelpers & helper) { - var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); - if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); - } - } - } - } - requestedExternalEmitHelpers |= helpers; - } - } - } - function getHelperName(helper) { - switch (helper) { - case 1: return "__extends"; - case 2: return "__assign"; - case 4: return "__rest"; - case 8: return "__decorate"; - case 16: return "__metadata"; - case 32: return "__param"; - case 64: return "__awaiter"; - case 128: return "__generator"; - case 256: return "__values"; - case 512: return "__read"; - case 1024: return "__spread"; - case 2048: return "__await"; - case 4096: return "__asyncGenerator"; - case 8192: return "__asyncDelegator"; - case 16384: return "__asyncValues"; - default: ts.Debug.fail("Unrecognized helper."); - } - } - function resolveHelpersModule(node, errorNode) { - if (!externalHelpersModule) { - externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; - } - return externalHelpersModule; - } - function checkGrammarDecorators(node) { - if (!node.decorators) { - return false; - } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); - } - } - else if (node.kind === 153 || node.kind === 154) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); - } - } - return false; - } - function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; - } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; - var flags = 0; - for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { - var modifier = _a[_i]; - if (modifier.kind !== 131) { - if (node.kind === 148 || node.kind === 150) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); - } - if (node.kind === 157) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); - } - } - switch (modifier.kind) { - case 76: - if (node.kind !== 232 && node.parent.kind === 229) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); - } - break; - case 114: - case 113: - case 112: - var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113) { - lastProtected = modifier; - } - else if (modifier.kind === 112) { - lastPrivate = modifier; - } - if (flags & 28) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); - } - else if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); - } - else if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); - } - else if (node.parent.kind === 234 || node.parent.kind === 265) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); - } - else if (flags & 128) { - if (modifier.kind === 112) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); - } - else { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); - } - } - flags |= ts.modifierToFlag(modifier.kind); - break; - case 115: - if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); - } - else if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); - } - else if (node.parent.kind === 234 || node.parent.kind === 265) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); - } - else if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - flags |= 32; - lastStatic = modifier; - break; - case 131: - if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); - } - else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); - } - flags |= 64; - lastReadonly = modifier; - break; - case 84: - if (flags & 1) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); - } - else if (flags & 2) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); - } - else if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); - } - else if (node.parent.kind === 229) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); - } - flags |= 1; - break; - case 124: - if (flags & 2) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.parent.kind === 229) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); - } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { - return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); - } - flags |= 2; - lastDeclare = modifier; - break; - case 117: - if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); - } - if (node.kind !== 229) { - if (node.kind !== 151 && - node.kind !== 149 && - node.kind !== 153 && - node.kind !== 154) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); - } - if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); - } - if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - if (flags & 8) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); - } - } - flags |= 128; - break; - case 120: - if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); - } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); - } - flags |= 256; - lastAsync = modifier; - break; - } - } - if (node.kind === 152) { - if (flags & 32) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); - } - if (flags & 128) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); - } - else if (flags & 256) { - return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); - } - else if (flags & 64) { - return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); - } - return; - } - else if ((node.kind === 238 || node.kind === 237) && flags & 2) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); - } - else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); - } - else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); - } - if (flags & 256) { - return checkGrammarAsyncModifier(node, lastAsync); - } - } - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 153: - case 154: - case 152: - case 149: - case 148: - case 151: - case 150: - case 157: - case 233: - case 238: - case 237: - case 244: - case 243: - case 186: - case 187: - case 146: - return false; - default: - if (node.parent.kind === 234 || node.parent.kind === 265) { - return false; - } - switch (node.kind) { - case 228: - return nodeHasAnyModifiersExcept(node, 120); - case 229: - return nodeHasAnyModifiersExcept(node, 117); - case 230: - case 208: - case 231: - return true; - case 232: - return nodeHasAnyModifiersExcept(node, 76); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } - function checkGrammarAsyncModifier(node, asyncModifier) { - switch (node.kind) { - case 151: - case 228: - case 186: - case 187: - return false; - } - return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); - } - function checkGrammarForDisallowedTrailingComma(list) { - if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } - if (typeParameters && typeParameters.length === 0) { - var start = typeParameters.pos - "<".length; - var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; - return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); - } - } - function checkGrammarParameterList(parameters) { - var seenOptionalParameter = false; - var parameterCount = parameters.length; - for (var i = 0; i < parameterCount; i++) { - var parameter = parameters[i]; - if (parameter.dotDotDotToken) { - if (i !== (parameterCount - 1)) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); - } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); - } - } - else if (parameter.questionToken) { - seenOptionalParameter = true; - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); - } - } - else if (seenOptionalParameter && !parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); - } - } - } - function checkGrammarFunctionLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); - } - function checkGrammarClassLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); - } - function checkGrammarArrowFunction(node, file) { - if (node.kind === 187) { - var arrowFunction = node; - var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; - var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; - if (startLine !== endLine) { - return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); - } - } - return false; - } - function checkGrammarIndexSignatureParameters(node) { - var parameter = node.parameters[0]; - if (node.parameters.length !== 1) { - if (parameter) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - else { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - } - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); - } - if (ts.getModifierFlags(parameter) !== 0) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); - } - if (!parameter.type) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); - } - if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); - } - if (!node.type) { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); - } - } - function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); - } - function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { - if (typeArguments && typeArguments.length === 0) { - var sourceFile = ts.getSourceFileOfNode(node); - var start = typeArguments.pos - "<".length; - var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function checkGrammarTypeArguments(node, typeArguments) { - return checkGrammarForDisallowedTrailingComma(typeArguments) || - checkGrammarForAtLeastOneTypeArgument(node, typeArguments); - } - function checkGrammarForOmittedArgument(node, args) { - if (args) { - var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { - var arg = args_4[_i]; - if (arg.kind === 200) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); - } - } - } - } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); - } - function checkGrammarHeritageClause(node) { - var types = node.types; - if (checkGrammarForDisallowedTrailingComma(types)) { - return true; - } - if (types && types.length === 0) { - var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); - } - } - function checkGrammarClassDeclarationHeritageClauses(node) { - var seenExtendsClause = false; - var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); - } - if (heritageClause.types.length > 1) { - return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108); - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); - } - seenImplementsClause = true; - } - checkGrammarHeritageClause(heritageClause); - } - } - } - function checkGrammarInterfaceDeclaration(node) { - var seenExtendsClause = false; - if (node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108); - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); - } - checkGrammarHeritageClause(heritageClause); - } - } - return false; - } - function checkGrammarComputedPropertyName(node) { - if (node.kind !== 144) { - return false; - } - var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { - return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); - } - } - function checkGrammarForGenerator(node) { - if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 || - node.kind === 186 || - node.kind === 151); - if (ts.isInAmbientContext(node)) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); - } - if (!node.body) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); - } - } - } - function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } - } - function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 263) { - continue; - } - var name = prop.name; - if (name.kind === 144) { - checkGrammarComputedPropertyName(name); - } - if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); - } - if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { - var mod = _c[_b]; - if (mod.kind !== 120 || prop.kind !== 151) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); - } - } - } - var currentKind = void 0; - if (prop.kind === 261 || prop.kind === 262) { - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151) { - currentKind = Property; - } - else if (prop.kind === 153) { - currentKind = GetAccessor; - } - else if (prop.kind === 154) { - currentKind = SetAccessor; - } - else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); - } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name); - if (effectiveName === undefined) { - continue; - } - var existingKind = seen.get(effectiveName); - if (!existingKind) { - seen.set(effectiveName, currentKind); - } - else { - if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); - } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen.set(effectiveName, currentKind | existingKind); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); - } - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); - } - } - } - } - function checkGrammarJsxElement(node) { - var seen = ts.createMap(); - for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { - var attr = _a[_i]; - if (attr.kind === 255) { - continue; - } - var jsxAttr = attr; - var name = jsxAttr.name; - if (!seen.get(name.text)) { - seen.set(name.text, true); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); - } - var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 && !initializer.expression) { - return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); - } - } - } - function checkGrammarForInOrForOfStatement(forInOrOfStatement) { - if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { - return true; - } - if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 16384) === 0) { - return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - } - } - if (forInOrOfStatement.initializer.kind === 227) { - var variableList = forInOrOfStatement.initializer; - if (!checkGrammarVariableDeclarationList(variableList)) { - var declarations = variableList.declarations; - if (!declarations.length) { - return false; - } - if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement - : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; - return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); - } - var firstDeclaration = declarations[0]; - if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer - : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; - return grammarErrorOnNode(firstDeclaration.name, diagnostic); - } - if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation - : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; - return grammarErrorOnNode(firstDeclaration, diagnostic); - } - } - } - return false; - } - function checkGrammarAccessor(accessor) { - var kind = accessor.kind; - if (languageVersion < 1) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); - } - else if (ts.isInAmbientContext(accessor)) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); - } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - else if (accessor.body && ts.getModifierFlags(accessor) & 128) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); - } - else if (accessor.typeParameters) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); - } - else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 ? - ts.Diagnostics.A_get_accessor_cannot_have_parameters : - ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); - } - else if (kind === 154) { - if (accessor.type) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); - } - else { - var parameter = accessor.parameters[0]; - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); - } - else if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); - } - else if (parameter.initializer) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); - } - } - } - } - function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); - } - function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { - return ts.getThisParameter(accessor); - } - } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { - return grammarErrorOnNode(node, message); - } - } - function checkGrammarMethod(node) { - if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || - checkGrammarFunctionLikeDeclaration(node) || - checkGrammarForGenerator(node)) { - return true; - } - if (node.parent.kind === 178) { - if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { - return true; - } - else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - } - if (ts.isClassLike(node.parent)) { - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); - } - else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); - } - } - else if (node.parent.kind === 230) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); - } - else if (node.parent.kind === 163) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); - } - } - function checkGrammarBreakOrContinueStatement(node) { - var current = node; - while (current) { - if (ts.isFunctionLike(current)) { - return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); - } - switch (current.kind) { - case 222: - if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 217 - && !ts.isIterationStatement(current.statement, true); - if (isMisplacedContinueLabel) { - return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); - } - return false; - } - break; - case 221: - if (node.kind === 218 && !node.label) { - return false; - } - break; - default: - if (ts.isIterationStatement(current, false) && !node.label) { - return false; - } - break; - } - current = current.parent; - } - if (node.label) { - var message = node.kind === 218 - ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement - : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - else { - var message = node.kind === 218 - ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement - : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - } - function checkGrammarBindingElement(node) { - if (node.dotDotDotToken) { - var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - if (node.name.kind === 175 || node.name.kind === 174) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (node.initializer) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - } - } - function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && - expr.operand.kind === 8; - } - function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { - if (ts.isInAmbientContext(node)) { - if (node.initializer) { - if (ts.isConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - else if (!node.initializer) { - if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); - } - if (ts.isConst(node)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); - } - } - } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { - checkESModuleMarker(node.name); - } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); - return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); - } - function checkESModuleMarker(name) { - if (name.kind === 71) { - if (ts.unescapeIdentifier(name.text) === "__esModule") { - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; - if (!ts.isOmittedExpression(element)) { - return checkESModuleMarker(element.name); - } - } - } - } - function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71) { - if (name.originalKeywordKind === 110) { - return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; - if (!ts.isOmittedExpression(element)) { - checkGrammarNameInLetOrConstDeclarations(element.name); - } - } - } - } - function checkGrammarVariableDeclarationList(declarationList) { - var declarations = declarationList.declarations; - if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { - return true; - } - if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); - } - } - function allowLetAndConstDeclarations(parent) { - switch (parent.kind) { - case 211: - case 212: - case 213: - case 220: - case 214: - case 215: - case 216: - return false; - case 222: - return allowLetAndConstDeclarations(parent.parent); - } - return true; - } - function checkGrammarForDisallowedLetOrConstStatement(node) { - if (!allowLetAndConstDeclarations(node.parent)) { - if (ts.isLet(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); - } - else if (ts.isConst(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); - } - } - } - function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94) { - if (node.name.text !== "target") { - return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.text, ts.tokenToString(node.keywordToken), "target"); - } - } - } - function hasParseDiagnostics(sourceFile) { - return sourceFile.parseDiagnostics.length > 0; - } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorOnNode(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); - return true; - } - } - function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarProperty(node) { - if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - } - else if (node.parent.kind === 230) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); - } - } - else if (node.parent.kind === 163) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); - } - } - if (ts.isInAmbientContext(node) && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 230 || - node.kind === 231 || - node.kind === 238 || - node.kind === 237 || - node.kind === 244 || - node.kind === 243 || - node.kind === 236 || - ts.getModifierFlags(node) & (2 | 1 | 512)) { - return false; - } - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); - } - function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { - for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208) { - if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { - return true; - } - } - } - } - function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); - } - function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { - if (isAccessor(node.parent.kind)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = true; - } - var links = getNodeLinks(node); - if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); - } - if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { - var links_1 = getNodeLinks(node.parent); - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); - } - } - else { - } - } - } - function checkGrammarNumericLiteral(node) { - if (node.numericLiteralFlags & 4) { - var diagnosticMessage = void 0; - if (languageVersion >= 1) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 173)) { - diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 264)) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; - } - if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; - var literal = (withMinus ? "-" : "") + "0o" + node.text; - return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); - } - } - } - function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); - return true; - } - } - function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(global); - } - }); - return result; - } - } - 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) { @@ -41340,11 +42274,11 @@ var ts; 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)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), 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 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)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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: @@ -41352,9 +42286,9 @@ var ts; 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)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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: @@ -41362,9 +42296,9 @@ var ts; 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)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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: @@ -41384,7 +42318,7 @@ var ts; case 171: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); case 172: - 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)); + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), 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 174: @@ -41412,9 +42346,9 @@ var ts; case 185: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 186: - return ts.updateFunctionExpression(node, 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)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 188: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189: @@ -41438,7 +42372,7 @@ var ts; case 198: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); case 199: - return ts.updateClassExpression(node, 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)); + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 201: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 202: @@ -41488,13 +42422,13 @@ var ts; case 227: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 228: - 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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: @@ -41561,9 +42495,9 @@ var ts; return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); case 265: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 296: + case 288: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297: + case 289: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -41601,7 +42535,7 @@ var ts; case 209: case 200: case 225: - case 295: + case 287: break; case 143: result = reduceNode(node.left, cbNode, result); @@ -41761,9 +42695,6 @@ var ts; result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 203: - result = reduceNode(node.expression, cbNode, result); - break; case 205: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); @@ -41962,10 +42893,10 @@ var ts; case 265: result = reduceNodes(node.statements, cbNodes, result); break; - case 296: + case 288: result = reduceNode(node.expression, cbNode, result); break; - case 297: + case 289: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -42031,38 +42962,207 @@ var ts; } var Debug; (function (Debug) { + var isDebugInfoEnabled = false; Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } : ts.noop; Debug.assertEachNode = Debug.shouldAssert(1) - ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; Debug.assertNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } : ts.noop; Debug.assertOptionalNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } : ts.noop; Debug.assertOptionalToken = Debug.shouldAssert(1) - ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } : ts.noop; Debug.assertMissingNode = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; - function getFunctionName(func) { - if (typeof func !== "function") { - return ""; + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, + "__debugObjectFlags": { get: function () { return this.flags & 32768 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, + "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + "__debugGetText": { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } } - else if (func.hasOwnProperty("name")) { - return func.name; - } - else { - var text = Function.prototype.toString.call(func); - var match = /^function\s+([\w\$]+)\s*\(/.exec(text); - return match ? match[1] : ""; + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 238: + externalImports.push(node); + break; + case 237: + if (node.moduleReference.kind === 248) { + externalImports.push(node); + } + break; + case 244: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 243: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 208: + if (ts.hasModifier(node, 1)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 228: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 229: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; } } - })(Debug = ts.Debug || (ts.Debug = {})); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { + uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -42315,11 +43415,11 @@ var ts; } else if (ts.isStringOrNumericLiteral(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); - argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); return ts.createPropertyAccess(value, name); } } @@ -42396,6 +43496,22 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -42576,6 +43692,7 @@ var ts; case 147: case 231: case 149: + case 236: return undefined; case 152: return visitConstructor(node); @@ -42647,32 +43764,71 @@ var ts; function shouldEmitDecorateCallForParameter(parameter) { return parameter.decorators !== undefined && parameter.decorators.length > 0; } + function getClassFacts(node, staticProperties) { + var facts = 0; + if (ts.some(staticProperties)) + facts |= 1; + if (ts.getClassExtendsHeritageClauseElement(node)) + facts |= 64; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2; + if (ts.childIsDecorated(node)) + facts |= 4; + if (isExportOfNamespace(node)) + facts |= 8; + else if (isDefaultExternalModuleExport(node)) + facts |= 32; + else if (isNamedExternalModuleExport(node)) + facts |= 16; + if (languageVersion <= 1 && (facts & 7)) + facts |= 128; + return facts; + } function visitClassDeclaration(node) { var staticProperties = getInitializedProperties(node, true); - var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; - var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var name = node.name; - if (!name && (staticProperties.length > 0 || ts.childIsDecorated(node))) { - name = ts.getGeneratedNameForNode(node); + var facts = getClassFacts(node, staticProperties); + if (facts & 128) { + context.startLexicalEnvironment(); } - var classStatement = isDecoratedClass - ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) - : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var name = node.name || (facts & 5 ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; - if (staticProperties.length) { - addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); + if (facts & 1) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 ? ts.getInternalName(node) : ts.getLocalName(node)); } addClassElementDecorationStatements(statements, node, false); addClassElementDecorationStatements(statements, node, true); addConstructorDecorationStatement(statements, node); - if (isNamespaceExport(node)) { + if (facts & 128) { + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18); + var localName = ts.getInternalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 | 384); + statements.push(statement); + ts.addRange(statements, context.endLexicalEnvironment()); + var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + if (facts & 8) { addExportMemberAssignment(statements, node); } - else if (isDecoratedClass) { - if (isDefaultExternalModuleExport(node)) { + else if (facts & 128 || facts & 2) { + if (facts & 32) { statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); } - else if (isNamedExternalModuleExport(node)) { + else if (facts & 16) { statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); } } @@ -42682,10 +43838,13 @@ var ts; } return ts.singleOrMany(statements); } - function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { - var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause)); + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + var modifiers = !(facts & 128) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration(undefined, modifiers, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64) !== 0)); var emitFlags = ts.getEmitFlags(node); - if (hasStaticProperties) { + if (facts & 1) { emitFlags |= 32; } ts.setTextRange(classDeclaration, node); @@ -42693,12 +43852,12 @@ var ts; ts.setEmitFlags(classDeclaration, emitFlags); return classDeclaration; } - function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { + function createClassDeclarationHeadWithDecorators(node, name, facts) { var location = ts.moveRangePastDecorators(node); var classAlias = getClassAliasIfNeeded(node); var declName = ts.getLocalName(node, false, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, hasExtendsClause); + var members = transformClassMembers(node, (facts & 64) !== 0); var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -42952,8 +44111,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -43107,7 +44266,7 @@ var ts; var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { continue; } if (parameter.dotDotDotToken) { @@ -43207,13 +44366,13 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { return serializedIndividual; } else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || - serializedUnion.text !== serializedIndividual.text) { + serializedUnion.escapedText !== serializedIndividual.escapedText) { return ts.createIdentifier("Object"); } } @@ -43294,7 +44453,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeIdentifier(name.text)); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.getSynthesizedClone(name); @@ -43375,7 +44534,7 @@ var ts; return ts.createNotEmittedStatement(node); } var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var statements = [updated]; addExportMemberAssignment(statements, node); return statements; @@ -43406,7 +44565,7 @@ var ts; return parameter; } function visitVariableStatement(node) { - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); if (variables.length === 0) { return undefined; @@ -43523,16 +44682,16 @@ var ts; return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function hasNamespaceQualifiedExportName(node) { - return isNamespaceExport(node) + return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createMap(); + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); } if (!currentScopeFirstDeclarationsOfName.has(name)) { currentScopeFirstDeclarationsOfName.set(name, node); @@ -43541,7 +44700,7 @@ var ts; } function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { return currentScopeFirstDeclarationsOfName.get(name) === node; } @@ -43717,7 +44876,7 @@ var ts; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); ts.setEmitFlags(moduleReference, 1536 | 2048); - if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) ])), node), node); @@ -43726,7 +44885,7 @@ var ts; return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); } } - function isNamespaceExport(node) { + function isExportOfNamespace(node) { return currentNamespace !== undefined && ts.hasModifier(node, 1); } function isExternalModuleExport(node) { @@ -43745,7 +44904,7 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); - ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); var statement = ts.createStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); @@ -43770,7 +44929,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeIdentifier(node.name.text) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -43874,10 +45033,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_2 = ts.getSynthesizedClone(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; } } } @@ -44151,7 +45310,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -44441,8 +45600,10 @@ 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 createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 + ? ts.createYield(undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); @@ -44461,7 +45622,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ 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); + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, createDownlevelAwait(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -44470,7 +45631,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -44648,7 +45809,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -44906,8 +46067,8 @@ var ts; } else { var name = node.tagName; - if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.text)) { - return ts.createLiteral(name.text); + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.createExpressionFromEntityName(name); @@ -44916,11 +46077,11 @@ var ts; } function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(name.text)) { + if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { return name; } else { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } } function visitJsxExpression(node) { @@ -45357,11 +46518,58 @@ var ts; && node.kind === 219 && !node.expression; } + function isClassLikeVariableStatement(node) { + if (!ts.isVariableStatement(node)) + return false; + var variable = ts.singleOrUndefined(node.declarationList.declarations); + return variable + && variable.initializer + && ts.isIdentifier(variable.name) + && (ts.isClassLike(variable.initializer) + || (ts.isAssignmentExpression(variable.initializer) + && ts.isIdentifier(variable.initializer.left) + && ts.isClassLike(variable.initializer.right))); + } + function isTypeScriptClassWrapper(node) { + var call = ts.tryCast(node, ts.isCallExpression); + if (!call || ts.isParseTreeNode(call) || + ts.some(call.typeArguments) || + ts.some(call.arguments)) { + return false; + } + var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + if (!func || ts.isParseTreeNode(func) || + ts.some(func.typeParameters) || + ts.some(func.parameters) || + func.type || + !func.body) { + return false; + } + var statements = func.body.statements; + if (statements.length < 2) { + return false; + } + var firstStatement = statements[0]; + if (ts.isParseTreeNode(firstStatement) || + !ts.isClassLike(firstStatement) && + !isClassLikeVariableStatement(firstStatement)) { + return false; + } + var lastStatement = ts.elementAt(statements, -1); + var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); + if (!returnStatement || + !returnStatement.expression || + !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { + return false; + } + return true; + } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && ts.isStatement(node)) - || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); + || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) + || isTypeScriptClassWrapper(node); } function visitor(node) { if (shouldVisitNode(node)) { @@ -45546,7 +46754,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return node; } - if (node.text !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { return node; } return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); @@ -45554,7 +46762,7 @@ var ts; function visitBreakOrContinueStatement(node) { if (convertedLoopState) { var jump = node.kind === 218 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(node.label.text)) || + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; @@ -45570,12 +46778,12 @@ var ts; } else { if (node.kind === 218) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); + labelMarker = "break-" + node.label.escapedText; + setLabeledJump(convertedLoopState, true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); + labelMarker = "continue-" + node.label.escapedText; + setLabeledJump(convertedLoopState, false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -46218,9 +47426,9 @@ var ts; if (node.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 + var declarations = ts.flatMap(node.declarations, node.flags & 1 ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); + : visitVariableDeclaration); var declarationList = ts.createVariableDeclarationList(declarations); ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); @@ -46258,9 +47466,9 @@ var ts; return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_3 = ts.getMutableClone(node); - clone_3.initializer = ts.createVoidZero(); - return clone_3; + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; } return ts.visitEachChild(node, visitor, context); } @@ -46277,10 +47485,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(node.label.text, node.label.text); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); } function resetLabel(node) { - convertedLoopState.labels.set(node.label.text, undefined); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -46599,13 +47807,13 @@ var ts; loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); } else { - var clone_4 = ts.getMutableClone(node); - clone_4.statement = undefined; - clone_4 = ts.visitEachChild(clone_4, visitor, context); - clone_4.statement = ts.createBlock(convertedLoopBodyStatements, true); - clone_4.transformFlags = 0; - ts.aggregateTransformFlags(clone_4); - loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_3 = ts.getMutableClone(node); + clone_3.statement = undefined; + clone_3 = ts.visitEachChild(clone_3, visitor, context); + clone_3.statement = ts.createBlock(convertedLoopBodyStatements, true); + clone_3.transformFlags = 0; + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -46707,7 +47915,7 @@ var ts; else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeIdentifier(name.text)); + var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -46837,11 +48045,49 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { + if (isTypeScriptClassWrapper(node)) { + return visitTypeScriptClassWrapper(node); + } if (node.transformFlags & 64) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } + function visitTypeScriptClassWrapper(node) { + var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); + var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + ts.addRange(statements, remainingStatements); + ts.addRange(statements, classStatements, 1); + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, undefined, undefined, undefined, undefined, func.parameters, undefined, ts.updateBlock(func.body, statements))), undefined, call.arguments)))); + } function visitImmediateSuperCallInBody(node) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } @@ -46885,7 +48131,7 @@ var ts; if (ts.isCallExpression(firstSegment) && ts.isIdentifier(firstSegment.expression) && (ts.getEmitFlags(firstSegment.expression) & 4096) - && firstSegment.expression.text === "___spread") { + && firstSegment.expression.escapedText === "___spread") { return segments[0]; } } @@ -46894,7 +48140,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 177 + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -46902,7 +48148,7 @@ var ts; } } function partitionSpread(node) { - return ts.isSpreadExpression(node) + return ts.isSpreadElement(node) ? visitSpanOfSpreads : visitSpanOfNonSpreads; } @@ -47004,7 +48250,7 @@ var ts; : ts.createIdentifier("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 && node.name.text === "target") { + if (node.keywordToken === 94 && node.name.escapedText === "target") { if (hierarchyFacts & 8192) { hierarchyFacts |= 32768; } @@ -47105,8 +48351,7 @@ var ts; return false; } if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { - return currentNode.kind !== 149 - || (ts.getModifierFlags(currentNode) & 32) === 0; + return true; } currentNode = currentNode.parent; } @@ -47148,7 +48393,7 @@ var ts; return false; } var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression.text === "arguments"; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; } } ts.transformES2015 = transformES2015; @@ -47476,7 +48721,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } function visitBinaryExpression(node) { @@ -47542,10 +48787,10 @@ var ts; else if (node.operatorToken.kind === 26) { return visitCommaExpression(node); } - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -47672,10 +48917,10 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -47791,7 +49036,7 @@ var ts; return undefined; } function transformInitializedVariable(node) { - return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); } function transformAndEmitIfStatement(node) { if (containsYield(node)) { @@ -47978,13 +49223,13 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? node.label.text : undefined); + var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); emitBreak(label, node); } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && node.label.text); + var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, node); } @@ -47992,13 +49237,13 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? node.label.text : undefined); + var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); emitBreak(label, node); } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && node.label.text); + var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, node); } @@ -48093,7 +49338,7 @@ var ts; } function transformAndEmitLabeledStatement(node) { if (containsYield(node)) { - beginLabeledBlock(node.label.text); + beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -48103,7 +49348,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(node.label.text); + beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -48158,17 +49403,17 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(node.text)) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_7 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_7, node); - ts.setCommentRange(clone_7, node); - return clone_7; + var clone_6 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -48275,7 +49520,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = variable.name.text; + var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -48339,7 +49584,7 @@ var ts; kind: 3, isScript: false, breakLabel: breakLabel, - continueLabel: continueLabel + continueLabel: continueLabel, }); return breakLabel; } @@ -48363,7 +49608,7 @@ var ts; beginBlock({ kind: 2, isScript: false, - breakLabel: breakLabel + breakLabel: breakLabel, }); return breakLabel; } @@ -48901,7 +50146,7 @@ var ts; return node; } function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); if (token >= 72 && token <= 107) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -48941,9 +50186,10 @@ var ts; var currentSourceFile; var currentModuleInfo; var noSubstitution; + var needUMDDynamicImportHelper; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864)) { return node; } currentSourceFile = node; @@ -48953,6 +50199,7 @@ var ts; var updated = transformModule(node); currentSourceFile = undefined; currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; return ts.aggregateTransformFlags(updated); } function shouldEmitUnderscoreUnderscoreESModule() { @@ -48974,9 +50221,10 @@ var ts; addExportEqualsIfNeeded(statements, false); ts.addRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); } + ts.addEmitHelpers(updated, context.readEmitHelpers()); return updated; } function transformAMDModule(node) { @@ -49069,9 +50317,12 @@ var ts; addExportEqualsIfNeeded(statements, true); ts.addRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } return body; } function addExportEqualsIfNeeded(statements, emitAsReturn) { @@ -49106,14 +50357,49 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 298: + case 290: return visitMergeDeclarationMarker(node); - case 299: + case 291: return visitEndOfDeclarationMarker(node); default: - return node; + return ts.visitEachChild(node, importCallExpressionVisitor, context); } } + function importCallExpressionVisitor(node) { + if (!(node.transformFlags & 67108864)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else { + return ts.visitEachChild(node, importCallExpressionVisitor, context); + } + } + function visitImportCallExpression(node) { + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return transformImportCallExpressionAMD(node); + case ts.ModuleKind.UMD: + return transformImportCallExpressionUMD(node); + case ts.ModuleKind.CommonJS: + default: + return transformImportCallExpressionCommonJS(node); + } + } + function transformImportCallExpressionUMD(node) { + needUMDDynamicImportHelper = true; + return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); + } + function transformImportCallExpressionAMD(node) { + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + } + function transformImportCallExpressionCommonJS(node) { + return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); + } function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); @@ -49204,11 +50490,7 @@ var ts; return ts.singleOrMany(statements); } else { - return ts.setTextRange(ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ])), node); + return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } function visitExportAssignment(node) { @@ -49229,10 +50511,10 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, node.parameters, undefined, node.body), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49246,10 +50528,10 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, node.heritageClauses, node.members), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49286,7 +50568,7 @@ var ts; } } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49299,10 +50581,10 @@ var ts; } function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(node, undefined, context, 0, false, createExportExpression); + return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), undefined, context, 0, false, createExportExpression); } else { - return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), node.initializer); + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); } } function visitMergeDeclarationMarker(node) { @@ -49399,7 +50681,7 @@ var ts; } function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -49580,7 +50862,18 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), undefined, [module]); + } + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; })(ts || (ts = {})); var ts; @@ -49612,7 +50905,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; } var id = ts.getOriginalNodeId(node); @@ -49717,7 +51010,7 @@ var ts; if (moduleInfo.exportedNames) { for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { var exportedLocalName = _c[_b]; - if (exportedLocalName.text === "default") { + if (exportedLocalName.escapedText === "default") { continue; } exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); @@ -49734,7 +51027,7 @@ var ts; } for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -49791,7 +51084,7 @@ var ts; var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, true)]))); } @@ -49850,7 +51143,7 @@ var ts; if (node.isExportEquals) { return undefined; } - var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); @@ -49862,10 +51155,10 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); } else { - hoistedStatements = ts.append(hoistedStatements, node); + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -49880,7 +51173,7 @@ var ts; var statements; var name = ts.getLocalName(node); hoistVariableDeclaration(name); - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement)), node))), node)); + statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); @@ -49892,7 +51185,7 @@ var ts; } function visitVariableStatement(node) { if (!shouldHoistVariableDeclarationList(node.declarationList)) { - return ts.visitNode(node, destructuringVisitor, ts.isStatement); + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); } var expressions; var isExportedDeclaration = ts.hasModifier(node, 1); @@ -49940,8 +51233,8 @@ var ts; function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) - ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); } function createExportedVariableAssignment(name, value, location) { return createVariableAssignment(name, value, location, true); @@ -50036,7 +51329,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = decl.name.text; + excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -50050,7 +51343,7 @@ var ts; if (ts.hasModifier(decl, 1)) { var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); - excludeName = exportName.text; + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); } if (decl.name) { statements = appendExportsOfDeclaration(statements, decl, excludeName); @@ -50062,11 +51355,11 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; - if (exportSpecifier.name.text !== excludeName) { + if (exportSpecifier.name.escapedText !== excludeName) { statements = appendExportStatement(statements, exportSpecifier.name, name); } } @@ -50125,32 +51418,32 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 298: + case 290: return visitMergeDeclarationMarker(node); - case 299: + case 291: return visitEndOfDeclarationMarker(node); default: - return destructuringVisitor(node); + return destructuringAndImportCallVisitor(node); } } function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -50175,19 +51468,19 @@ var ts; } } function visitDoStatement(node) { - return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } function visitWhileStatement(node) { - return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitLabeledStatement(node) { return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitWithStatement(node) { - return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitSwitchStatement(node) { - return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); } function visitCaseBlock(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; @@ -50197,7 +51490,7 @@ var ts; return node; } function visitCaseClause(node) { - return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); } function visitDefaultClause(node) { return ts.visitEachChild(node, nestedElementVisitor, context); @@ -50219,29 +51512,35 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } - function destructuringVisitor(node) { + function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 && node.kind === 194) { return visitDestructuringAssignment(node); } - else if (node.transformFlags & 2048) { - return ts.visitEachChild(node, destructuringVisitor, context); + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048) || (node.transformFlags & 67108864)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { return node; } } + function visitImportCallExpression(node) { + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); + } function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { - return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, true); + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, true); } - return ts.visitEachChild(node, destructuringVisitor, context); + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } function hasExportedReferenceInDestructuringTarget(node) { if (ts.isAssignmentExpression(node, true)) { return hasExportedReferenceInDestructuringTarget(node.left); } - else if (ts.isSpreadExpression(node)) { + else if (ts.isSpreadElement(node)) { return hasExportedReferenceInDestructuringTarget(node.expression); } else if (ts.isObjectLiteralExpression(node)) { @@ -50481,6 +51780,7 @@ var ts; (function (ts) { function getModuleTransformer(moduleKind) { switch (moduleKind) { + case ts.ModuleKind.ESNext: case ts.ModuleKind.ES2015: return ts.transformES2015Module; case ts.ModuleKind.System: @@ -50533,7 +51833,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300); + var enabledSyntaxKindFeatures = new Array(292); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -50627,7 +51927,7 @@ var ts; function hoistVariableDeclaration(name) { ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); - var decl = ts.createVariableDeclaration(name); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64); if (!lexicalEnvironmentVariableDeclarations) { lexicalEnvironmentVariableDeclarations = [decl]; } @@ -50853,7 +52153,7 @@ var ts; var writer = ts.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; @@ -50950,10 +52250,10 @@ var ts; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } - function reportIllegalExtends() { + function reportPrivateInBaseOfClassExpression(propertyName) { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleThisError() { @@ -50966,14 +52266,17 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); var shouldUseResolverType = declaration.kind === 146 && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { emitType(type); } else { errorNameNode = declaration.name; - var format = 2 | 1024 | - (shouldUseResolverType ? 4096 : 0); + var format = 4 | + 16384 | + 2048 | + (shouldUseResolverType ? 8192 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -50986,7 +52289,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 2048 | 16384, writer); errorNameNode = undefined; } } @@ -51216,7 +52519,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 2048 | 16384, writer); write(";"); writeLine(); return tempVarName; @@ -51681,7 +52984,7 @@ var ts; if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { tempVarName = baseTypeNode.expression.kind === 95 ? "null" : - emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name @@ -52309,7 +53612,7 @@ var ts; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSourceFile; + var currentSource; var currentSourceText; var sourceMapDir; var sourceMapSourceIndex; @@ -52329,6 +53632,9 @@ var ts; getText: getText, getSourceMappingURL: getSourceMappingURL, }; + function skipSourceTrivia(pos) { + return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); + } function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { if (disabled) { return; @@ -52336,7 +53642,7 @@ var ts; if (sourceMapData) { reset(); } - currentSourceFile = undefined; + currentSource = undefined; currentSourceText = undefined; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; @@ -52379,7 +53685,7 @@ var ts; if (disabled) { return; } - currentSourceFile = undefined; + currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; lastRecordedSourceMapSpan = undefined; @@ -52422,7 +53728,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("beforeSourcemap"); } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); sourceLinePos.line++; sourceLinePos.character++; var emittedLine = writer.getLine(); @@ -52459,12 +53765,21 @@ var ts; if (node) { var emitNode = node.emitNode; var emitFlags = emitNode && emitNode.flags; - var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; - if (node.kind !== 295 + var range = emitNode && emitNode.sourceMapRange; + var _a = range || node, pos = _a.pos, end = _a.end; + var source = range && range.source; + var oldSource = currentSource; + if (source === oldSource) + source = undefined; + if (source) + setSourceFile(source); + if (node.kind !== 287 && (emitFlags & 16) === 0 && pos >= 0) { - emitPos(ts.skipTrivia(currentSourceText, pos)); + emitPos(skipSourceTrivia(pos)); } + if (source) + setSourceFile(oldSource); if (emitFlags & 64) { disabled = true; emitCallback(hint, node); @@ -52473,11 +53788,15 @@ var ts; else { emitCallback(hint, node); } - if (node.kind !== 295 + if (source) + setSourceFile(source); + if (node.kind !== 287 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); } + if (source) + setSourceFile(oldSource); } } function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { @@ -52487,7 +53806,7 @@ var ts; var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128) === 0 && tokenPos >= 0) { emitPos(tokenPos); } @@ -52503,17 +53822,17 @@ var ts; if (disabled) { return; } - currentSourceFile = sourceFile; - currentSourceText = currentSourceFile.text; + currentSource = sourceFile; + currentSourceText = currentSource.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); - sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSource.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSource.text); } } } @@ -52613,9 +53932,9 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295; - var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0; + var isEmittedNode = node.kind !== 287; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { emitLeadingComments(pos, isEmittedNode); } @@ -52906,6 +54225,50 @@ var ts; (function (ts) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getOutputExtension(sourceFile, options) { + if (options.jsx === 1) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + return ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + return ".jsx"; + } + } + return ".js"; + } + function getOriginalSourceFileOrBundle(sourceFileOrBundle) { + if (sourceFileOrBundle.kind === 266) { + return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); + } + return ts.getOriginalSourceFile(sourceFileOrBundle); + } function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -52932,7 +54295,7 @@ var ts; onSetSourceFile: setSourceFile, }); ts.performance.mark("beforePrint"); - ts.forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); transform.dispose(); return { @@ -52952,7 +54315,7 @@ var ts; emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -53348,6 +54711,8 @@ var ts; return emitModuleBlock(node); case 235: return emitCaseBlock(node); + case 236: + return emitNamespaceExportDeclaration(node); case 237: return emitImportEqualsDeclaration(node); case 238: @@ -53427,6 +54792,7 @@ var ts; case 97: case 101: case 99: + case 91: writeTokenNode(node); return; case 177: @@ -53487,9 +54853,9 @@ var ts; return emitJsxElement(node); case 250: return emitJsxSelfClosingElement(node); - case 296: + case 288: return emitPartiallyEmittedExpression(node); - case 297: + case 289: return emitCommaList(node); } } @@ -53566,6 +54932,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -53585,6 +54952,7 @@ var ts; emitModifiers(node, node.modifiers); writeIfPresent(node.asteriskToken, "*"); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -53644,7 +55012,7 @@ var ts; function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); - emitParametersForArrow(node, node.parameters); + emitParameters(node, node.parameters); write(" => "); emit(node.type); } @@ -53732,7 +55100,7 @@ var ts; } else { write("{"); - emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); + emitList(node, elements, 432); write("}"); } } @@ -54404,6 +55772,11 @@ var ts; } write(";"); } + function emitNamespaceExportDeclaration(node) { + write("export as namespace "); + emit(node.name); + write(";"); + } function emitNamedExports(node) { emitNamedImportsOrExports(node); } @@ -54503,6 +55876,9 @@ var ts; (ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (statements.length > 0) { + emitTrailingCommentsOfPosition(statements.pos); + } if (emitAsSingleStatement) { write(" "); emit(statements[0]); @@ -54592,7 +55968,7 @@ var ts; } emit(statement); if (seenPrologueDirectives) { - seenPrologueDirectives.set(statement.expression.text, statement.expression.text); + seenPrologueDirectives.set(statement.expression.text, true); } } } @@ -54636,7 +56012,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 256); + emitList(node, modifiers, 131328); write(" "); } } @@ -54682,11 +56058,24 @@ var ts; function emitParameters(parentNode, parameters) { emitList(parentNode, parameters, 1360); } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos + && !(ts.isArrowFunction(parentNode) && parentNode.type) + && !ts.some(parentNode.decorators) + && !ts.some(parentNode.modifiers) + && !ts.some(parentNode.typeParameters) + && !ts.some(parameter.decorators) + && !ts.some(parameter.modifiers) + && !parameter.dotDotDotToken + && !parameter.questionToken + && !parameter.type + && !parameter.initializer + && ts.isIdentifier(parameter.name); + } function emitParametersForArrow(parentNode, parameters) { - if (parameters && - parameters.length === 1 && - parameters[0].type === undefined && - parameters[0].pos === parentNode.pos) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { emit(parameters[0]); } else { @@ -55001,7 +56390,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeIdentifier(node.text); + return ts.unescapeLeadingUnderscores(node.escapedText); } else if (node.kind === 9 && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -55039,12 +56428,12 @@ var ts; } else { var autoGenerateId = name.autoGenerateId; - return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(makeName(name))); + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } function generateNameCached(node) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); } function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) @@ -55054,8 +56443,8 @@ var ts; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { - var local = node.locals.get(name); - if (local && local.flags & (107455 | 1048576 | 8388608)) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + if (local && local.flags & (107455 | 1048576 | 2097152)) { return false; } } @@ -55091,7 +56480,7 @@ var ts; while (true) { var generatedName = baseName + i; if (isUniqueName(generatedName)) { - generatedNames.set(generatedName, generatedName); + generatedNames.set(generatedName, true); return generatedName; } i++; @@ -55103,8 +56492,8 @@ var ts; } function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); } function generateNameForExportDefault() { @@ -55150,7 +56539,7 @@ var ts; case 2: return makeTempVariableName(268435456); case 3: - return makeUniqueName(ts.unescapeIdentifier(name.text)); + return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -55229,15 +56618,14 @@ var ts; ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 131328] = "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["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; @@ -55270,7 +56658,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var emptyArray = []; var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -55483,9 +56870,9 @@ var ts; 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 start = diagnostic.start, length_6 = 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 _b = ts.getLineAndCharacterOfPosition(file, start + length_6), 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; @@ -55528,6 +56915,7 @@ var ts; 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); + output += ts.sys.newLine; } return output; } @@ -55596,11 +56984,12 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { if (!resolved || resolved.extension !== undefined) { return resolved; } @@ -55612,18 +57001,18 @@ var ts; else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); }; } else { var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } - var filesByName = ts.createFileMap(); - var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; + var filesByName = ts.createMap(); + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); @@ -55648,6 +57037,7 @@ var ts; } } } + var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); moduleResolutionCache = undefined; oldProgram = undefined; program = { @@ -55655,6 +57045,7 @@ var ts; getSourceFile: getSourceFile, getSourceFileByPath: getSourceFileByPath, getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, getOptionsDiagnostics: getOptionsDiagnostics, @@ -55681,6 +57072,9 @@ var ts; ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function getCommonSourceDirectory() { if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); @@ -55699,7 +57093,7 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); @@ -55755,7 +57149,7 @@ var ts; } var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) - : emptyArray; + : ts.emptyArray; if (!result) { ts.Debug.assert(resolutions.length === moduleNames.length); return resolutions; @@ -55840,6 +57234,9 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { oldProgram.structureIsReused = 1; } + if ((oldSourceFile.flags & 524288) !== (newSourceFile.flags & 524288)) { + oldProgram.structureIsReused = 1; + } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { oldProgram.structureIsReused = 1; } @@ -55883,13 +57280,20 @@ var ts; if (oldProgram.structureIsReused !== 2) { return oldProgram.structureIsReused; } + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 1; + } + for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { + var p = _e[_d]; + filesByName.set(p, undefined); + } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { - var modifiedFile = modifiedSourceFiles_2[_d]; + for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { + var modifiedFile = modifiedSourceFiles_2[_f]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -55926,7 +57330,7 @@ var ts; return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); } function isEmitBlocked(emitFileName) { - return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; @@ -55956,7 +57360,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return getSourceFileByPath(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { return filesByName.get(path); @@ -55965,14 +57369,12 @@ var ts; if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } - var allDiagnostics = []; - ts.forEach(program.getSourceFiles(), function (sourceFile) { + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } - ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); - }); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return getDiagnostics(sourceFile, cancellationToken); + })); } function getSyntacticDiagnostics(sourceFile, cancellationToken) { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); @@ -55993,6 +57395,9 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + if (ts.isCheckJsEnabledForFile(sourceFile, options)) { + sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); + } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -56016,13 +57421,13 @@ var ts; function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { - return emptyArray; + return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var bindDiagnostics = sourceFile.bindDiagnostics; - var includeCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); - var checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : []; + var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); @@ -56072,7 +57477,6 @@ var ts; case 186: case 228: case 187: - case 228: case 226: if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -56108,10 +57512,14 @@ var ts; case 232: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 184: - var typeAssertionExpression = node; - diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + case 203: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; + case 202: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 184: + ts.Debug.fail(); } var prevParent = parent; parent = node; @@ -56132,7 +57540,6 @@ var ts; case 186: case 228: case 187: - case 228: if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; @@ -56220,10 +57627,10 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; if (sourceFile) { if (!cache.perFile) { - cache.perFile = ts.createFileMap(); + cache.perFile = ts.createMap(); } cache.perFile.set(sourceFile.path, result); } @@ -56236,15 +57643,10 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); - ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); } function getGlobalDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { processSourceFile(ts.normalizePath(fileName), isDefaultLib); @@ -56279,13 +57681,13 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, false); - if (isJavaScriptFile) { - collectRequireCalls(node); + if ((file.flags & 524288) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(node); } } - file.imports = imports || emptyArray; - file.moduleAugmentations = moduleAugmentations || emptyArray; - file.ambientModuleNames = ambientModules || emptyArray; + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { @@ -56293,7 +57695,7 @@ var ts; case 237: case 244: var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || moduleNameExpr.kind !== 9) { + if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; } if (!moduleNameExpr.text) { @@ -56306,12 +57708,13 @@ var ts; case 233: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { if (file.isDeclarationFile) { - (ambientModules || (ambientModules = [])).push(moduleName.text); + (ambientModules || (ambientModules = [])).push(nameText); } var body = node.body; if (body) { @@ -56324,17 +57727,20 @@ var ts; } } } - function collectRequireCalls(node) { + function collectDynamicImportOrRequireCalls(node) { if (ts.isRequireCall(node, true)) { (imports || (imports = [])).push(node.arguments[0]); } + else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9) { + (imports || (imports = [])).push(node.arguments[0]); + } else { - ts.forEachChild(node, collectRequireCalls); + ts.forEachChild(node, collectDynamicImportOrRequireCalls); } } } function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -56369,7 +57775,7 @@ var ts; } } 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) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -56387,7 +57793,7 @@ var ts; } } function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(path)) { + if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); @@ -56422,12 +57828,13 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { - var existingFile = filesByNameIgnoreCase.get(path); + var pathLowerCase = path.toLowerCase(); + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(path, file); + filesByNameIgnoreCase.set(pathLowerCase, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -56535,7 +57942,7 @@ var ts; modulesWithElidedImports.set(file.path, true); } else if (shouldAddFile) { - var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); } @@ -56578,28 +57985,28 @@ var ts; function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); } if (options.noEmitOnError) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); } if (options.out) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); } if (options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); } } if (options.inlineSourceMap) { if (options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); } if (options.mapRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); } } if (options.paths && options.baseUrl === undefined) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } if (options.paths) { for (var key in options.paths) { @@ -56607,64 +58014,65 @@ var ts; continue; } if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + createDiagnosticForOptionPaths(true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); } - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var subst = _a[_i]; + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); } } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); } } } if (!options.sourceMap && !options.inlineSourceMap) { if (options.inlineSources) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); } if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); } } if (options.out && options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } if (options.mapRoot && !options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); } if (options.declarationDir) { if (!options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); } if (options.out || options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.lib && options.noLib) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; 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)); + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { @@ -56678,7 +58086,7 @@ var ts; } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); @@ -56690,33 +58098,33 @@ var ts; options.mapRoot) { var dir = getCommonSourceDirectory(); if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } if (!options.noEmit && options.allowJs && options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } if (options.jsxFactory) { if (options.reactNamespace) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); } if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); } } else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); } if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); @@ -56724,8 +58132,8 @@ var ts; } function verifyEmitFilePath(emitFileName, emitFilesSeen) { if (emitFileName) { - var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); - if (filesByName.contains(emitFilePath)) { + var emitFilePath = toPath(emitFileName); + if (filesByName.has(emitFilePath)) { var chain_1; if (!options.configFilePath) { chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); @@ -56733,17 +58141,96 @@ var ts; chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } - if (emitFilesSeen.contains(emitFilePath)) { + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + if (emitFilesSeen.has(emitFileKey)) { blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { - emitFilesSeen.set(emitFilePath, true); + emitFilesSeen.set(emitFileKey, true); } } } } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + if (ts.isArrayLiteralExpression(keyProps.initializer) && + keyProps.initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionPathsSyntax() { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + } + return ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2) { + createDiagnosticForOption(true, option1, option2, message, option1, option2); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(false, option1, undefined, message, arg0); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; + if (options.configFile && options.configFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + } + return !!props.length; + } function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } } @@ -56751,14 +58238,14 @@ var ts; function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { - case ts.Extension.Ts: - case ts.Extension.Dts: + case ".ts": + case ".d.ts": return undefined; - case ts.Extension.Tsx: + case ".tsx": return needJsx(); - case ts.Extension.Jsx: + case ".jsx": return needJsx() || needAllowJs(); - case ts.Extension.Js: + case ".js": return needAllowJs(); } function needJsx() { @@ -56769,6 +58256,10 @@ var ts; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; + function checkAllDefined(names) { + ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); + return names; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -56862,11 +58353,12 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES2015, "es2015": ts.ModuleKind.ES2015, + "esnext": ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, }, { name: "lib", @@ -57359,6 +58851,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, { name: "plugins", type: "list", @@ -57429,12 +58927,14 @@ var ts; optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; return optionNameMapCache; } - ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } function parseCustomTypeOption(opt, value, errors) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } @@ -57463,7 +58963,6 @@ var ts; var options = {}; var fileNames = []; var errors = []; - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; parseStrings(commandLine); return { options: options, @@ -57479,12 +58978,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - var short = shortOptionNames.get(s); - if (short !== undefined) { - s = short; - } - var opt = optionNameMap.get(s); + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -57568,36 +59062,234 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } function readConfigFile(fileName, readFile) { - var text = ""; + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; try { text = readFile(fileName); } catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return parseConfigFileTextToJson(fileName, text); + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; } - ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } - try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]); } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; + return _tsconfigRootOptions; + } + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, undefined, undefined); + } + ts.convertToObject = convertToObject; + function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.jsonObject) { + return {}; + } + return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 261) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined" && typeof value !== "undefined") { + result[keyText] = value; + if (jsonConversionNotifier && + (parentOption || knownOptions === knownRootOptions)) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (knownOptions === knownRootOptions) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 86: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95: + reportInvalidOptionValue(!!option); + return null; + case 9: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + var text = valueExpression.text; + if (option && typeof option.type !== "string") { + var customOption = option; + if (!customOption.type.has(text)) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 178: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); + } + case 177: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + if (option) { + reportInvalidOptionValue(true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + } + } + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + typeof option.type === "string" ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = typeof option.type === "string" ? option.type : "string"; + return typeof value === expectedType; } } - ts.parseConfigFileTextToJson = parseConfigFileTextToJson; function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition) { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { @@ -57618,35 +59310,33 @@ var ts; }); } function serializeCompilerOptions(options) { - var result = {}; + var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name in options) { + var _loop_5 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - continue; + return "continue"; } var value = options[name]; var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - result[name] = value; + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + result.set(name, value); } else { if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name] = convertedValue; + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { - result[name] = getNameOfCompilerOptionValue(value, customTypeMap); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } + }; + for (var name in options) { + _loop_5(name); } return result; } @@ -57663,37 +59353,37 @@ var ts; case "object": return {}; default: - return ts.arrayFrom(option.type.keys())[0]; + return option.type.keys().next().value; } } function makePadding(paddingLength) { return Array(paddingLength + 1).join(" "); } function writeConfigurations() { - var categorizedOptions = ts.reduceLeft(ts.filter(ts.optionDeclarations, function (o) { return o.category !== ts.Diagnostics.Command_line_Options && o.category !== ts.Diagnostics.Advanced_Options; }), function (memo, value) { - if (value.category) { - var name = ts.getLocaleSpecificMessage(value.category); - (memo[name] || (memo[name] = [])).push(value); + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); } - return memo; - }, {}); + } var marginLength = 0; var seenKnownKeys = 0; var nameColumn = []; var descriptionColumn = []; - var knownKeysCount = ts.getOwnKeys(configurations.compilerOptions).length; - for (var category in categorizedOptions) { + categorizedOptions.forEach(function (options, category) { if (nameColumn.length !== 0) { nameColumn.push(""); descriptionColumn.push(""); } nameColumn.push("/* " + category + " */"); descriptionColumn.push(""); - for (var _i = 0, _a = categorizedOptions[category]; _i < _a.length; _i++) { - var option = _a[_i]; + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; var optionName = void 0; - if (ts.hasProperty(configurations.compilerOptions, option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(configurations.compilerOptions[option.name]) + ((seenKnownKeys += 1) === knownKeysCount ? "" : ","); + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); } else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; @@ -57702,7 +59392,7 @@ var ts; descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); marginLength = Math.max(optionName.length, marginLength); } - } + }); var tab = makePadding(2); var result = []; result.push("{"); @@ -57710,13 +59400,13 @@ var ts; for (var i = 0; i < nameColumn.length; i++) { var optionName = nameColumn[i]; var description = descriptionColumn[i]; - result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description); + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); } - if (configurations.files && configurations.files.length) { + if (fileNames.length) { result.push(tab + "},"); result.push(tab + "\"files\": ["); - for (var i = 0; i < configurations.files.length; i++) { - result.push("" + tab + tab + JSON.stringify(configurations.files[i]) + (i === configurations.files.length - 1 ? "" : ",")); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); } result.push(tab + "]"); } @@ -57728,169 +59418,250 @@ var ts; } } ts.generateTSConfig = generateTSConfig; - function removeComments(jsonText) { - var output = ""; - var scanner = ts.createScanner(1, false, 0, jsonText); - var token; - while ((token = scanner.scan()) !== 1) { - switch (token) { - case 2: - case 3: - output += scanner.getTokenText().replace(/\S/g, " "); - break; - default: - output += scanner.getTokenText(); - break; - } - } - return output; - } function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - 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); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + setConfigFileInOptions(options, sourceFile); var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typeAcquisition: typeAcquisition, - raw: json, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + compileOnSave: !!raw.compileOnSave }; function getFileNames() { var fileNames; - if (ts.hasProperty(json, "files")) { - if (ts.isArray(json["files"])) { - fileNames = json["files"]; + if (ts.hasProperty(raw, "files")) { + if (ts.isArray(raw["files"])) { + fileNames = raw["files"]; if (fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); } } var includeSpecs; - if (ts.hasProperty(json, "include")) { - if (ts.isArray(json["include"])) { - includeSpecs = json["include"]; + if (ts.hasProperty(raw, "include")) { + if (ts.isArray(raw["include"])) { + includeSpecs = raw["include"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(json, "exclude")) { - if (ts.isArray(json["exclude"])) { - excludeSpecs = json["exclude"]; + if (ts.hasProperty(raw, "exclude")) { + if (ts.isArray(raw["exclude"])) { + excludeSpecs = raw["exclude"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; + var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - excludeSpecs.push(outDir); + specs.push(outDir); } + excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); - if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } return result; } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } } - ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + function parseConfig(json, sourceFile, 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 }; + return { raw: json || convertToObject(sourceFile, errors) }; } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + if (ownConfig.extendedConfigPath) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { 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; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; 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); + if (typeof json.extends !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } - return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - 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")); + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); 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); + 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, extended)); + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return undefined; } } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); 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 }; + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; + return undefined; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); if (typeof result === "boolean" && result) { @@ -57898,7 +59669,6 @@ var ts; } return false; } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -57911,15 +59681,23 @@ var ts; return { options: options, errors: errors }; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultCompilerOptions(configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultTypeAcquisition(configFileName) { var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return options; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; @@ -57928,7 +59706,7 @@ var ts; if (!jsonOptions) { return; } - var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); + var optionNameMap = commandLineOptionsToMap(optionDeclarations); for (var id in jsonOptions) { var opt = optionNameMap.get(id); if (opt) { @@ -57940,28 +59718,41 @@ var ts; } } function convertJsonOption(opt, value, basePath, errors) { - var optType = opt.type; - var expectedType = typeof optType === "string" ? optType : "string"; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); - } - else if (typeof value === expectedType) { - if (typeof optType !== "string") { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (typeof optType !== "string") { return convertJsonOptionOfCustomType(opt, value, errors); } - else { - if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; - } - } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType)); + else if (typeof option.type !== "string") { + return option.type.get(value); } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); @@ -57984,16 +59775,16 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); if (include) { - include = validateSpecs(include, errors, false); + include = validateSpecs(include, errors, false, jsonSourceFile, "include"); } if (exclude) { - exclude = validateSpecs(exclude, errors, true); + exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); @@ -58005,7 +59796,7 @@ var ts; } } if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { var file = _b[_a]; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; @@ -58024,24 +59815,40 @@ var ts; wildcardDirectories: wildcardDirectories }; } - function validateSpecs(specs, errors, allowTrailingRecursion) { + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { var validSpecs = []; for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { var spec = specs_1[_i]; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else { validSpecs.push(spec); } } return validSpecs; + function createDiagnostic(message, spec) { + if (jsonSourceFile && jsonSourceFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isArrayLiteralExpression(property.initializer)) { + for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (ts.isStringLiteral(element) && element.text === spec) { + return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); + } + } + } + } + } + return ts.createCompilerDiagnostic(message, spec); + } } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); @@ -58067,7 +59874,7 @@ var ts; } } } - for (var key in wildcardDirectories) + for (var key in wildcardDirectories) { if (ts.hasProperty(wildcardDirectories, key)) { for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { var recursiveKey = recursiveKeys_1[_a]; @@ -58076,6 +59883,7 @@ var ts; } } } + } } return wildcardDirectories; } @@ -58119,6 +59927,40 @@ var ts; function caseInsensitiveKeyMapper(key) { return key.toLowerCase(); } + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": + return ""; + case "string": + return ""; + case "number": + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -58154,10 +59996,10 @@ var ts; ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); var IndentStyle; (function (IndentStyle) { @@ -58220,80 +60062,77 @@ var ts; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; - ScriptElementKind.keyword = "keyword"; - ScriptElementKind.scriptElement = "script"; - ScriptElementKind.moduleElement = "module"; - ScriptElementKind.classElement = "class"; - ScriptElementKind.localClassElement = "local class"; - ScriptElementKind.interfaceElement = "interface"; - ScriptElementKind.typeElement = "type"; - ScriptElementKind.enumElement = "enum"; - ScriptElementKind.enumMemberElement = "enum member"; - ScriptElementKind.variableElement = "var"; - ScriptElementKind.localVariableElement = "local var"; - ScriptElementKind.functionElement = "function"; - ScriptElementKind.localFunctionElement = "local function"; - ScriptElementKind.memberFunctionElement = "method"; - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; - ScriptElementKind.memberVariableElement = "property"; - ScriptElementKind.constructorImplementationElement = "constructor"; - ScriptElementKind.callSignatureElement = "call"; - ScriptElementKind.indexSignatureElement = "index"; - ScriptElementKind.constructSignatureElement = "construct"; - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; - ScriptElementKind.jsxAttribute = "JSX attribute"; + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; + ScriptElementKind["keyword"] = "keyword"; + ScriptElementKind["scriptElement"] = "script"; + ScriptElementKind["moduleElement"] = "module"; + ScriptElementKind["classElement"] = "class"; + ScriptElementKind["localClassElement"] = "local class"; + ScriptElementKind["interfaceElement"] = "interface"; + ScriptElementKind["typeElement"] = "type"; + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; + ScriptElementKind["variableElement"] = "var"; + ScriptElementKind["localVariableElement"] = "local var"; + ScriptElementKind["functionElement"] = "function"; + ScriptElementKind["localFunctionElement"] = "local function"; + ScriptElementKind["memberFunctionElement"] = "method"; + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; + ScriptElementKind["memberVariableElement"] = "property"; + ScriptElementKind["constructorImplementationElement"] = "constructor"; + ScriptElementKind["callSignatureElement"] = "call"; + ScriptElementKind["indexSignatureElement"] = "index"; + ScriptElementKind["constructSignatureElement"] = "construct"; + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; + ScriptElementKind["jsxAttribute"] = "JSX attribute"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - return ClassificationTypeNames; - }()); - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - ts.ClassificationTypeNames = ClassificationTypeNames; + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); var ClassificationType; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -58325,7 +60164,6 @@ var ts; var ts; (function (ts) { ts.scanner = ts.createScanner(5, true); - ts.emptyArray = []; var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -58359,11 +60197,11 @@ var ts; case 231: case 163: return 2; + case 283: + return node.name === undefined ? 1 | 2 : 2; case 264: case 229: return 1 | 2; - case 232: - return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -58374,6 +60212,7 @@ var ts; else { return 4; } + case 232: case 241: case 242: case 237: @@ -58384,7 +60223,7 @@ var ts; case 265: return 4 | 1; } - return 1 | 2 | 4; + return 7; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { @@ -58392,9 +60231,9 @@ var ts; return 1; } else if (node.parent.kind === 243) { - return 1 | 2 | 4; + return 7; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -58406,6 +60245,10 @@ var ts; else if (isNamespaceReference(node)) { return 4; } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); + return 2; + } else { return 1; } @@ -58420,12 +60263,13 @@ var ts; } return 4; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -58460,10 +60304,19 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 159 || - (node.parent.kind === 201 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 99 && !ts.isPartOfExpression(node)) || - node.kind === 169; + switch (node.kind) { + case 99: + return !ts.isPartOfExpression(node); + case 169: + return true; + } + switch (node.parent.kind) { + case 159: + return true; + case 201: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; } function isCallExpressionTarget(node) { return isCallOrNewExpressionTarget(node, 181); @@ -58483,7 +60336,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 && referenceNode.label.text === labelName) { + if (referenceNode.kind === 222 && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -58551,6 +60404,9 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { + if (node.kind === 283) { + node = node.parent.parent; + } while (true) { node = node.parent; if (!node) { @@ -58576,15 +60432,15 @@ var ts; function getNodeKind(node) { switch (node.kind) { case 265: - return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + return ts.isExternalModule(node) ? "module" : "script"; case 233: - return ts.ScriptElementKind.moduleElement; + return "module"; case 229: case 199: - return ts.ScriptElementKind.classElement; - case 230: return ts.ScriptElementKind.interfaceElement; - case 231: return ts.ScriptElementKind.typeElement; - case 232: return ts.ScriptElementKind.enumElement; + return "class"; + case 230: return "interface"; + case 231: return "type"; + case 232: return "enum"; case 226: return getKindOfVariableDeclaration(node); case 176: @@ -58592,39 +60448,39 @@ var ts; case 187: case 228: case 186: - return ts.ScriptElementKind.functionElement; - case 153: return ts.ScriptElementKind.memberGetAccessorElement; - case 154: return ts.ScriptElementKind.memberSetAccessorElement; + return "function"; + case 153: return "getter"; + case 154: return "setter"; case 151: case 150: - return ts.ScriptElementKind.memberFunctionElement; + return "method"; case 149: case 148: - return ts.ScriptElementKind.memberVariableElement; - case 157: return ts.ScriptElementKind.indexSignatureElement; - case 156: return ts.ScriptElementKind.constructSignatureElement; - case 155: return ts.ScriptElementKind.callSignatureElement; - case 152: return ts.ScriptElementKind.constructorImplementationElement; - case 145: return ts.ScriptElementKind.typeParameterElement; - case 264: return ts.ScriptElementKind.enumMemberElement; - case 146: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + return "property"; + case 157: return "index"; + case 156: return "construct"; + case 155: return "call"; + case 152: return "constructor"; + case 145: return "type parameter"; + case 264: return "enum member"; + case 146: return ts.hasModifier(node, 92) ? "property" : "parameter"; case 237: case 242: case 239: case 246: case 240: - return ts.ScriptElementKind.alias; - case 290: - return ts.ScriptElementKind.typeElement; + return "alias"; + case 283: + return "type"; default: - return ts.ScriptElementKind.unknown; + return ""; } function getKindOfVariableDeclaration(v) { return ts.isConst(v) - ? ts.ScriptElementKind.constElement + ? "const" : ts.isLet(v) - ? ts.ScriptElementKind.letElement - : ts.ScriptElementKind.variableElement; + ? "let" + : "var"; } } ts.getNodeKind = getNodeKind; @@ -58820,7 +60676,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 294 && c.pos <= node.pos && c.end >= node.end) { + if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -58829,27 +60685,22 @@ var ts; } ts.findContainingList = findContainingList; function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); + function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, false, includePrecedingTokenAtEndPosition, false, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); + function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { @@ -58857,21 +60708,21 @@ var ts; } for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; - if (ts.isJSDocNode(child) && !includeJsDocComment) { + if (!includeJsDocComment && ts.isJSDocNode(child)) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); if (start > position) { - continue; + break; } var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { + if (position < end || (position === end && (child.kind === 1 || includeEndPosition))) { current = child; continue outer; } - else if (includeItemAtEndPosition && end === position) { + else if (includePrecedingTokenAtEndPosition && end === position) { var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { return previousToken; } } @@ -58880,7 +60731,7 @@ var ts; } } function findTokenOnLeftOfPosition(file, position) { - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -58906,7 +60757,7 @@ var ts; } } ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { + function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { return find(startNode || sourceFile); function findRightmostToken(n) { if (ts.isToken(n)) { @@ -58924,7 +60775,7 @@ var ts; for (var i = 0; i < children.length; i++) { var child = children[i]; if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { - var start = child.getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 && start === child.end); if (lookInPreviousChild) { @@ -58936,7 +60787,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265); + ts.Debug.assert(startNode !== undefined || n.kind === 265 || ts.isJSDocCommentContainingNode(n)); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -58953,7 +60804,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9) { + if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); if (start < position && position < end) { @@ -58967,7 +60818,7 @@ var ts; } ts.isInString = isInString; function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); if (!token) { return false; } @@ -58990,12 +60841,12 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, false); } return position <= tokenAtPosition.getStart(sourceFile) && (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); @@ -59018,7 +60869,7 @@ var ts; } } function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); function jsDocPrefix(c) { @@ -59027,38 +60878,6 @@ var ts; } } ts.hasDocComment = hasDocComment; - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (ts.isToken(node)) { - switch (node.kind) { - case 104: - case 110: - case 76: - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (jsDoc.tags) { - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } - } - } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; function nodeHasTokens(n) { return n.getWidth() !== 0; } @@ -59066,20 +60885,20 @@ var ts; var flags = ts.getCombinedModifierFlags(node); var result = []; if (flags & 8) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); + result.push("private"); if (flags & 16) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + result.push("protected"); if (flags & 4) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); + result.push("public"); if (flags & 32) - result.push(ts.ScriptElementKindModifier.staticModifier); + result.push("static"); if (flags & 128) - result.push(ts.ScriptElementKindModifier.abstractModifier); + result.push("abstract"); if (flags & 1) - result.push(ts.ScriptElementKindModifier.exportedModifier); + result.push("export"); if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + result.push("declare"); + return result.length > 0 ? result.join(",") : ""; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { @@ -59131,6 +60950,12 @@ var ts; return false; } ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; function compareDataObjects(dst, src) { if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { return false; @@ -59253,7 +61078,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop + reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { if (lineStart) { @@ -59325,7 +61150,7 @@ var ts; else if (flags & 524288) { return ts.SymbolDisplayPartKind.aliasName; } - else if (flags & 8388608) { + else if (flags & 2097152) { return ts.SymbolDisplayPartKind.aliasName; } return ts.SymbolDisplayPartKind.text; @@ -59333,10 +61158,7 @@ var ts; } ts.symbolPart = symbolPart; function displayPart(text, kind) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] - }; + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; } ts.displayPart = displayPart; function spacePart() { @@ -59376,10 +61198,13 @@ var ts; } ts.lineBreakPart = lineBreakPart; function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { @@ -59402,7 +61227,7 @@ var ts; ts.signatureToDisplayParts = signatureToDisplayParts; function getDeclaredName(typeChecker, symbol, location) { if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144) { - return location.text; + return ts.getTextOfIdentifierOrLiteral(location); } var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); return typeChecker.symbolToString(localExportDefaultSymbol || symbol); @@ -59434,38 +61259,9 @@ var ts; } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - var trimmedOutput = outputText.trim(); - 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; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -59478,7 +61274,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -59490,7 +61286,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); @@ -60003,7 +61799,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_7 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -60011,8 +61807,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_7, classification: convertClassification(type) }); + lastEnd = start + length_7; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60366,7 +62162,7 @@ var ts; checkForClassificationCancellation(cancellationToken, kind); if (kind === 71 && !ts.nodeIsMissing(node)) { var identifier = node; - if (classifiableNames.get(identifier.text)) { + if (classifiableNames.has(identifier.escapedText)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); @@ -60383,29 +62179,29 @@ var ts; ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; function getClassificationTypeName(type) { switch (type) { - case 1: return ts.ClassificationTypeNames.comment; - case 2: return ts.ClassificationTypeNames.identifier; - case 3: return ts.ClassificationTypeNames.keyword; - case 4: return ts.ClassificationTypeNames.numericLiteral; - case 5: return ts.ClassificationTypeNames.operator; - case 6: return ts.ClassificationTypeNames.stringLiteral; - case 8: return ts.ClassificationTypeNames.whiteSpace; - case 9: return ts.ClassificationTypeNames.text; - case 10: return ts.ClassificationTypeNames.punctuation; - case 11: return ts.ClassificationTypeNames.className; - case 12: return ts.ClassificationTypeNames.enumName; - case 13: return ts.ClassificationTypeNames.interfaceName; - case 14: return ts.ClassificationTypeNames.moduleName; - case 15: return ts.ClassificationTypeNames.typeParameterName; - case 16: return ts.ClassificationTypeNames.typeAliasName; - case 17: return ts.ClassificationTypeNames.parameterName; - case 18: return ts.ClassificationTypeNames.docCommentTagName; - case 19: return ts.ClassificationTypeNames.jsxOpenTagName; - case 20: return ts.ClassificationTypeNames.jsxCloseTagName; - case 21: return ts.ClassificationTypeNames.jsxSelfClosingTagName; - case 22: return ts.ClassificationTypeNames.jsxAttribute; - case 23: return ts.ClassificationTypeNames.jsxText; - case 24: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + case 1: return "comment"; + case 2: return "identifier"; + case 3: return "keyword"; + case 4: return "number"; + case 5: return "operator"; + case 6: return "string"; + case 8: return "whitespace"; + case 9: return "text"; + case 10: return "punctuation"; + case 11: return "class name"; + case 12: return "enum name"; + case 13: return "interface name"; + case 14: return "module name"; + case 15: return "type parameter name"; + case 16: return "type alias name"; + case 17: return "parameter name"; + case 18: return "doc comment tag name"; + case 19: return "jsx open tag name"; + case 20: return "jsx close tag name"; + case 21: return "jsx self closing tag name"; + case 22: return "jsx attribute"; + case 23: return "jsx text"; + case 24: return "jsx attribute string literal value"; } } function convertClassifications(classifications) { @@ -60465,7 +62261,7 @@ var ts; pushClassification(start, width, 1); continue; } - ts.Debug.assert(ch === 61); + ts.Debug.assert(ch === 124 || ch === 61); classifyDisabledMergeCode(text, start, end); } } @@ -60496,16 +62292,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 286: + case 279: processJSDocParameterTag(tag); break; - case 289: + case 282: processJSDocTemplateTag(tag); break; - case 288: + case 281: processElement(tag.typeExpression); break; - case 287: + case 280: processElement(tag.typeExpression); break; } @@ -60517,20 +62313,20 @@ var ts; } return; function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17); - pos = tag.preParameterName.end; + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17); + pos = tag.name.end; } if (tag.typeExpression) { pushCommentRange(pos, tag.typeExpression.pos - pos); processElement(tag.typeExpression); pos = tag.typeExpression.end; } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17); - pos = tag.postParameterName.end; + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17); + pos = tag.name.end; } } } @@ -60563,7 +62359,7 @@ var ts; } } function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { + if (ts.isJSDoc(node)) { return true; } if (ts.nodeIsMissing(node)) { @@ -60741,14 +62537,9 @@ var ts; PathCompletions.getStringLiteralCompletionEntriesFromModuleNames = getStringLiteralCompletionEntriesFromModuleNames; function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); - var relativeDirectory; - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDirectory = rootDirs_1[_i]; - if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { - relativeDirectory = scriptPath.substr(rootDirectory.length); - break; - } - } + var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + }); return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { @@ -60792,7 +62583,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + result.push(createCompletionEntryForModule(foundFile, "script", span)); }); } var directories = tryGetDirectories(host, baseDirectory); @@ -60800,7 +62591,7 @@ var ts; for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { var directory = directories_2[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + result.push(createCompletionEntryForModule(directoryName, "directory", span)); } } } @@ -60823,7 +62614,7 @@ var ts; var pattern = _a[_i]; for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { var match = _c[_b]; - result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(match, "external module name", span)); } } } @@ -60831,7 +62622,7 @@ var ts; else if (ts.startsWith(path, fragment)) { var entry = paths[path] && paths[path].length === 1 && paths[path][0]; if (entry) { - result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(path, "external module name", span)); } } } @@ -60844,7 +62635,7 @@ var ts; getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { var moduleName = _e[_d]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } return result; } @@ -60871,8 +62662,8 @@ var ts; continue; } var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); + var length_8 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); } return result; } @@ -60884,21 +62675,18 @@ var ts; var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); - var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); if (isNestedModule) { var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { - if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { - return moduleName.substr(moduleNameWithSeperator_1.length); - } - return moduleName; + nonRelativeModuleNames = ts.map(nonRelativeModuleNames, function (nonRelativeModuleName) { + return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); } if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { var visibleModule = _a[_i]; if (!isNestedModule) { - nonRelativeModules.push(visibleModule.moduleName); + nonRelativeModuleNames.push(visibleModule.moduleName); } else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, undefined, ["./*"]); @@ -60907,16 +62695,16 @@ var ts; var f = nestedFiles_1[_b]; f = ts.normalizePath(f); var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); - nonRelativeModules.push(nestedModule); + nonRelativeModuleNames.push(nestedModule); } } } } } - return ts.deduplicate(nonRelativeModules); + return ts.deduplicate(nonRelativeModuleNames); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, false); if (!token) { return undefined; } @@ -60958,7 +62746,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } } else if (host.getDirectories) { @@ -60990,7 +62778,7 @@ var ts; for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { var typeDirectory = directories_3[_i]; typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name", span)); } } } @@ -61061,7 +62849,7 @@ var ts; } } function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + return { name: name, kind: kind, kindModifiers: "", sortText: name, replacementSpan: replacementSpan }; } function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); @@ -61118,6 +62906,12 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var KeywordCompletionFilters; + (function (KeywordCompletionFilters) { + KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); @@ -61129,70 +62923,66 @@ 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, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; - if (requestJsDocTagName) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + if (sourceFile.languageVariant === 1 && + location && location.parent && location.parent.kind === 252) { + var tagName = location.parent.parent.openingElement.tagName; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, + entries: [{ + name: tagName.getFullText(), + kind: "class", + kindModifiers: undefined, + sortText: "0", + }] }; } - if (requestJsDocTag) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagCompletions() }; + if (request) { + var entries_2 = request.kind === "JsDocTagName" + ? ts.JsDoc.getJSDocTagNameCompletions() + : request.kind === "JsDocTag" + ? ts.JsDoc.getJSDocTagCompletions() + : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target)); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 && - location.parent && location.parent.kind === 252) { - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0", - }); - } - else if (!hasFilteredClassMemberKeywords) { - return undefined; - } + if ((!symbols || symbols.length === 0) && keywordFilters === 0) { + return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (hasFilteredClassMemberKeywords) { - ts.addRange(entries, classMemberKeywordCompletions); - } - else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { - ts.addRange(entries, keywordCompletions); + if (keywordFilters !== 0 || !isMemberCompletion) { + ts.addRange(entries, getKeywordCompletions(keywordFilters)); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target) { - var entries = []; - var nameTable = ts.getNameTable(sourceFile); - nameTable.forEach(function (pos, name) { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { if (pos === position) { return; } - if (!uniqueNames.get(name)) { - uniqueNames.set(name, name); - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name), target, true); - if (displayName) { - var entry = { - name: displayName, - kind: ts.ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } + var realName = ts.unescapeLeadingUnderscores(name); + if (uniqueNames.has(realName)) { + return; + } + uniqueNames.set(realName, true); + var displayName = getCompletionEntryDisplayName(realName, target, true); + if (displayName) { + entries.push({ + name: displayName, + kind: "warning", + kindModifiers: "", + sortText: "1" + }); } }); - return entries; } function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { - var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); if (!displayName) { return undefined; } @@ -61211,10 +63001,10 @@ var ts; var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!uniqueNames.get(id)) { + var id = entry.name; + if (!uniqueNames.has(id)) { entries.push(entry); - uniqueNames.set(id, id); + uniqueNames.set(id, true); } } } @@ -61266,9 +63056,9 @@ var ts; 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]; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { @@ -61317,8 +63107,8 @@ var ts; uniques.set(name, true); result.push({ name: name, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, + kindModifiers: "", + kind: "var", sortText: "0" }); } @@ -61327,10 +63117,10 @@ var ts; function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_1 = completionData.location; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_1) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location = completionData.location; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_1, location_1, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -61341,12 +63131,12 @@ var ts; }; } } - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0), function (c) { return c.name === entryName; }); if (keywordCompletion) { return { name: entryName, - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "keyword", + kindModifiers: "", displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, tags: undefined @@ -61357,72 +63147,71 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_2) === entryName ? s : undefined; }); - } - return undefined; + return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - var requestJsDocTagName = false; - var requestJsDocTag = false; + var request; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, false); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64) { - requestJsDocTagName = true; + request = { kind: "JsDocTagName" }; } else { var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); - requestJsDocTag = !(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/)); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + request = { kind: "JsDocTag" }; + } } } - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); + var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - requestJsDocTagName = true; + request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 288: - case 286: - case 287: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267) { + currentToken = ts.getTokenAtPosition(sourceFile, position, true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 284 || + currentToken.parent.name !== currentToken))) { + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } - if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; + if (request) { + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile); + var previousToken = ts.findPrecedingToken(position, sourceFile, undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + var start_4 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, undefined, insideJsDocTagTypeExpression); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } var node = currentToken; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); if (contextToken) { if (isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); @@ -61473,7 +63262,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; - var hasFilteredClassMemberKeywords = false; + var keywordFilters = 0; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -61481,7 +63270,7 @@ var ts; else if (isRightOfOpenTag) { var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 8388608)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 2097152)); })); } else { symbols = tagSymbols; @@ -61504,42 +63293,64 @@ 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, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 277: + case 279: + case 284: + case 280: + case 281: + case 283: + return true; + } + } function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 71 || node.kind === 143 || node.kind === 179) { + var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol && symbol.flags & 8388608) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 | 384)) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isRhsOfImportDeclaration ? + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var symbol_2 = exportedSymbols_1[_i]; + if (isValidAccess(symbol_2)) { + symbols.push(symbol_2); + } } - }); + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 && d.kind !== 233 && d.kind !== 232; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } } function addTypeProperties(type) { - if (type) { - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); } - if (isJavaScriptFile && type.flags & 65536) { - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } + } + if (isJavaScriptFile && type.flags & 65536) { + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); } } } @@ -61554,6 +63365,12 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (tryGetConstructorLikeCompletionContainer(contextToken)) { + isMemberCompletion = false; + isNewIdentifierLocation = true; + keywordFilters = 2; + return true; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { getGetClassLikeCompletionSymbols(classLikeContainer); return true; @@ -61586,10 +63403,64 @@ var ts; scopeNode.kind === 256 || ts.isStatement(scopeNode); } - var symbolMeanings = 793064 | 107455 | 1920 | 8388608; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + var symbolMeanings = 793064 | 107455 | 1920 | 2097152; + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + if (ts.isExportAssignment(location.parent)) { + return true; + } + if (symbol && symbol.flags & 2097152) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + return symbolCanBeReferencedAtTypeLocation(symbol); + } + } + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 && + contextToken.parent.kind === 162; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56: + return parentKind === 149 || + parentKind === 148 || + parentKind === 146 || + parentKind === 226 || + ts.isFunctionLikeKind(parentKind); + case 58: + return parentKind === 231; + case 118: + return parentKind === 202; + } + } + } + function symbolCanBeReferencedAtTypeLocation(symbol) { + symbol = symbol.exportSymbol || symbol; + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & 793064) { + return true; + } + if (symbol.flags & 1536) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); + } + } function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { @@ -61673,9 +63544,9 @@ var ts; if (contextToken.kind === 9 || contextToken.kind === 12 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_3 = contextToken.getStart(); + var start_5 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_3 < position && position < end) { + if (start_5 < position && position < end) { return true; } if (position === end) { @@ -61697,34 +63568,29 @@ var ts; typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 174) { + else { + ts.Debug.assert(objectLikeContainer.kind === 174); isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 146) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 151 || rootDeclaration.parent.kind === 154) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } + if (!ts.isVariableLike(rootDeclaration)) + throw ts.Debug.fail("Root declaration is not variable-like."); + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216; + if (!canGetType && rootDeclaration.kind === 146) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - if (canGetType) { - var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - if (!typeForObject) - return false; - typeMembers = typeChecker.getPropertiesOfType(typeForObject); - existingMembers = objectLikeContainer.elements; + else if (rootDeclaration.parent.kind === 151 || rootDeclaration.parent.kind === 154) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } - else { - ts.Debug.fail("Root declaration is not variable-like."); + if (canGetType) { + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); + existingMembers = objectLikeContainer.elements; } } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -61753,7 +63619,7 @@ var ts; function getGetClassLikeCompletionSymbols(classLikeDeclaration) { isMemberCompletion = true; isNewIdentifierLocation = true; - hasFilteredClassMemberKeywords = true; + keywordFilters = 1; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); if (baseTypeNode || implementsTypeNodes) { @@ -61778,11 +63644,11 @@ var ts; } } var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? - undefined : - ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + ts.emptyArray : + ts.flatMap(implementsTypeNodes || ts.emptyArray, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : - undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + ts.emptyArray, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); } } } @@ -61792,7 +63658,7 @@ var ts; case 17: case 26: var parent = contextToken.parent; - if (parent && (parent.kind === 178 || parent.kind === 174)) { + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; @@ -61817,6 +63683,14 @@ var ts; function isFromClassElementDeclaration(node) { return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); } + function isParameterOfConstructorDeclaration(node) { + return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); + } + function isConstructorParameterCompletion(node) { + return node.parent && + isParameterOfConstructorDeclaration(node.parent) && + (isConstructorParameterCompletionKeyword(node.kind) || ts.isDeclarationName(node)); + } function tryGetClassLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -61826,6 +63700,10 @@ var ts; } break; case 26: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; case 25: case 18: if (ts.isClassLike(location)) { @@ -61840,11 +63718,25 @@ var ts; } } } - if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + if (location && location.kind === 286 && ts.isClassLike(location.parent)) { return location.parent; } return undefined; } + function tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 19: + case 26: + return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + default: + if (isConstructorParameterCompletion(contextToken)) { + return contextToken.parent.parent; + } + } + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61882,19 +63774,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152: - case 161: - case 160: - return false; - default: - return true; - } - } function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { @@ -61903,12 +63782,13 @@ var ts; containingNodeKind === 227 || containingNodeKind === 208 || containingNodeKind === 232 || - isFunction(containingNodeKind) || - containingNodeKind === 229 || - containingNodeKind === 199 || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 230 || containingNodeKind === 175 || - containingNodeKind === 231; + containingNodeKind === 231 || + (ts.isClassLike(contextToken.parent) && + contextToken.parent.typeParameters && + contextToken.parent.typeParameters.end >= contextToken.pos); case 23: return containingNodeKind === 175; case 56: @@ -61917,7 +63797,7 @@ var ts; return containingNodeKind === 175; case 19: return containingNodeKind === 260 || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17: return containingNodeKind === 232 || containingNodeKind === 230 || @@ -61932,7 +63812,7 @@ var ts; containingNodeKind === 199 || containingNodeKind === 230 || containingNodeKind === 231 || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115: return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: @@ -61942,7 +63822,7 @@ var ts; case 114: case 112: case 113: - return containingNodeKind === 146; + return containingNodeKind === 146 && !ts.isConstructorDeclaration(contextToken.parent.parent); case 118: return containingNodeKind === 242 || containingNodeKind === 246 || @@ -61968,6 +63848,13 @@ var ts; isFromClassElementDeclaration(contextToken)) { return false; } + if (isConstructorParameterCompletion(contextToken)) { + if (!ts.isIdentifier(contextToken) || + isConstructorParameterCompletionKeywordText(contextToken.getText()) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61986,7 +63873,10 @@ var ts; case "yield": return true; } - return false; + return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8) { @@ -61996,25 +63886,25 @@ var ts; return false; } function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = ts.createMap(); + var existingImportsOrExports = ts.createUnderscoreEscapedMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; - existingImportsOrExports.set(name.text, true); + existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports.get(e.name); }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); } function filterObjectMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; } - var existingMemberNames = ts.createMap(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; if (m.kind !== 261 && @@ -62031,18 +63921,19 @@ var ts; var existingName = void 0; if (m.kind === 176 && m.propertyName) { if (m.propertyName.kind === 71) { - existingName = m.propertyName.text; + existingName = m.propertyName.escapedText; } } else { - existingName = ts.getNameOfDeclaration(m).text; + var name = ts.getNameOfDeclaration(m); + existingName = ts.getEscapedTextOfIdentifierOrLiteral(name); } existingMemberNames.set(existingName, true); } - return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.escapedName); }); } function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { - var existingMemberNames = ts.createMap(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; if (m.kind !== 149 && @@ -62068,63 +63959,91 @@ var ts; 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); })); + var result = []; + addPropertySymbols(baseSymbols, 8); + addPropertySymbols(implementingTypeSymbols, 24); + return result; + function addPropertySymbols(properties, inValidModifierFlags) { + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; + if (isValidProperty(property, inValidModifierFlags)) { + result.push(property); + } + } + } function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.name) && + return !existingMemberNames.get(propertySymbol.escapedName) && propertySymbol.getDeclarations() && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); } } function filterJsxAttributes(symbols, attributes) { - var seenNames = ts.createMap(); + var seenNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { - seenNames.set(attr.name.text, true); + seenNames.set(attr.name.escapedText, true); } } - return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); + return ts.filter(symbols, function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(typeChecker, symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - if ((symbol.flags & 1920) && (firstCharCode === 39 || firstCharCode === 34)) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + var name = symbol.name; + if (!name) + return undefined; + if (symbol.flags & 1920) { + var firstCharCode = name.charCodeAt(0); + if (firstCharCode === 39 || firstCharCode === 34) { return undefined; } } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks); } function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { + if (performCharacterChecks && !ts.isIdentifierText(name, target)) { return undefined; } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } - if (performCharacterChecks) { - if (!ts.isIdentifierText(name, target)) { - return undefined; - } - } return name; } - var keywordCompletions = []; - for (var i = 72; i <= 142; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, - sortText: "0" - }); + var _keywordCompletions = []; + function getKeywordCompletions(keywordFilter) { + var completions = _keywordCompletions[keywordFilter]; + if (completions) { + return completions; + } + return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); + function generateKeywordCompletions(keywordFilter) { + switch (keywordFilter) { + case 0: + return getAllKeywordCompletions(); + case 1: + return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + case 2: + return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + } + } + function getAllKeywordCompletions() { + var allKeywordsCompletions = []; + for (var i = 72; i <= 142; i++) { + allKeywordsCompletions.push({ + name: ts.tokenToString(i), + kind: "keyword", + kindModifiers: "", + sortText: "0" + }); + } + return allKeywordsCompletions; + } + function getFilteredKeywordCompletions(filterFn) { + return ts.filter(getKeywordCompletions(0), function (entry) { return filterFn(entry.name); }); + } } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -62144,9 +64063,18 @@ var ts; function isClassMemberCompletionKeywordText(text) { return isClassMemberCompletionKeyword(ts.stringToToken(text)); } - var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { - return isClassMemberCompletionKeywordText(entry.name); - }); + function isConstructorParameterCompletionKeyword(kind) { + switch (kind) { + case 114: + case 112: + case 113: + case 131: + return true; + } + } + function isConstructorParameterCompletionKeywordText(text) { + return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); + } function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -62156,6 +64084,34 @@ var ts; kind === 34 || kind === 35; } + function getJsDocTagAtPosition(node, position) { + var jsDoc = getJsDocHavingNode(node).jsDoc; + if (!jsDoc) + return undefined; + for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) { + var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags; + if (!tags || position < pos || position > end) + continue; + for (var i = tags.length - 1; i >= 0; i--) { + var tag = tags[i]; + if (position >= tag.pos) { + return tag; + } + } + } + } + function getJsDocHavingNode(node) { + if (!ts.isToken(node)) + return node; + switch (node.kind) { + case 104: + case 110: + case 76: + return node.parent.parent; + default: + return node.parent; + } + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -62163,17 +64119,26 @@ var ts; var DocumentHighlights; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + var node = ts.getTouchingWord(sourceFile, position, true); + if (node === sourceFile) + return undefined; + ts.Debug.assert(node.parent !== undefined); + if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var end = node.getEnd(); return { fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: ts.HighlightSpanKind.none + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" }; } function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { @@ -62407,7 +64372,7 @@ var ts; case 234: case 265: if (modifierFlag & 128) { - nodes = declaration.members.concat(declaration); + nodes = declaration.members.concat([declaration]); } else { nodes = container.statements; @@ -62428,7 +64393,7 @@ var ts; } } else if (modifierFlag & 128) { - nodes = nodes.concat(container); + nodes = nodes.concat([container]); } break; default: @@ -62620,7 +64585,7 @@ var ts; result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: ts.HighlightSpanKind.reference + kind: "reference" }); i++; continue; @@ -62632,7 +64597,7 @@ var ts; } function isLabeledBy(node, labelName) { for (var owner = node.parent; owner.kind === 222; owner = owner.parent) { - if (owner.label.text === labelName) { + if (owner.label.escapedText === labelName) { return true; } } @@ -62652,7 +64617,7 @@ var ts; function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createFileMap()); + buckets.set(key, bucket = ts.createMap()); } return bucket; } @@ -62660,9 +64625,9 @@ var ts; var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); var sourceFiles = []; - entries.forEachValue(function (key, entry) { + entries.forEach(function (entry, name) { sourceFiles.push({ - name: key, + name: name, refCount: entry.languageServiceRefCount, references: entry.owners.slice(0) }); @@ -62726,7 +64691,7 @@ var ts; entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(path); + bucket.delete(path); } } return { @@ -62788,7 +64753,7 @@ var ts; } function handleDirectImports(exportingModuleSymbol) { var theseDirectImports = getDirectImports(exportingModuleSymbol); - if (theseDirectImports) + if (theseDirectImports) { for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { var direct = theseDirectImports_1[_i]; if (!markSeenDirectImport(direct)) { @@ -62831,6 +64796,7 @@ var ts; break; } } + } } function handleNamespaceImport(importDeclaration, name, isReExport) { if (exportKind === 2) { @@ -62862,28 +64828,30 @@ var ts; var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); ts.Debug.assert(!!(moduleSymbol.flags & 1536)); var directImports = getDirectImports(moduleSymbol); - if (directImports) + if (directImports) { for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { var directImport = directImports_1[_i]; addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); } + } } function getDirectImports(moduleSymbol) { return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); } } function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.name; + var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { importSearches.push([location, symbol]); } - if (directImports) + if (directImports) { for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { var decl = directImports_2[_i]; handleImport(decl); } + } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { if (decl.kind === 237) { @@ -62917,7 +64885,7 @@ var ts; } else { var name = importClause.name; - if (name && (!isForRename || name.text === symbolName(exportSymbol))) { + if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { var defaultImportAlias = checker.getSymbolAtLocation(name); addSearch(name, defaultImportAlias); } @@ -62928,16 +64896,16 @@ var ts; } } function handleNamespaceImportLike(importName) { - if (exportKind === 2 && (!isForRename || importName.text === exportName)) { + if (exportKind === 2 && (!isForRename || importName.escapedText === exportName)) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) + if (namedBindings) { for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var element = _a[_i]; var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).text !== exportName) { + if ((propertyName || name).escapedText !== exportName) { continue; } if (propertyName) { @@ -62953,6 +64921,7 @@ var ts; addSearch(name, localSymbol); } } + } } } function findNamespaceReExports(sourceFileLike, name, checker) { @@ -63074,22 +65043,20 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; - if (symbol.flags & 7340032) { + if (symbol.exportSymbol) { if (parent.kind === 179) { - return symbol.declarations.some(function (d) { return d === parent; }) && parent.parent.kind === 194 + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) ? getSpecialPropertyExport(parent.parent, false) : undefined; } else { - var exportSymbol = symbol.exportSymbol; - ts.Debug.assert(!!exportSymbol); - return exportInfo(exportSymbol, getExportKindForDeclaration(parent)); + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); } } else { - var exportNode = getExportNode(parent); + var exportNode = getExportNode(parent, node); if (exportNode && ts.hasModifier(exportNode, 1)) { - if (exportNode.kind === 237 && exportNode.moduleReference === node) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { if (comingFromExport) { return undefined; } @@ -63100,18 +65067,24 @@ var ts; return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } } - else if (parent.kind === 243) { - var exportingModuleSymbol = parent.symbol.parent; - ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 } }; + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); } - else if (parent.kind === 194) { + else if (ts.isExportAssignment(parent.parent)) { + return getExportAssignmentExport(parent.parent); + } + else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, true); } - else if (parent.parent.kind === 194) { + else if (ts.isBinaryExpression(parent.parent)) { return getSpecialPropertyExport(parent.parent, true); } } + function getExportAssignmentExport(ex) { + var exportingModuleSymbol = ex.symbol.parent; + ts.Debug.assert(!!exportingModuleSymbol); + return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 } }; + } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; switch (ts.getSpecialPropertyAssignmentKind(node)) { @@ -63131,16 +65104,16 @@ var ts; function getImport() { var isImport = isNodeImport(node); if (!isImport) - return; + return undefined; var importedSymbol = checker.getImmediateAliasedSymbol(symbol); - if (importedSymbol) { - importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); - if (importedSymbol.name === "export=") { - importedSymbol = checker.getImmediateAliasedSymbol(importedSymbol); - } - if (symbolName(importedSymbol) === symbol.name) { - return __assign({ kind: 0, symbol: importedSymbol }, isImport); - } + if (!importedSymbol) + return undefined; + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + if (symbolName(importedSymbol) === symbol.escapedName) { + return __assign({ kind: 0, symbol: importedSymbol }, isImport); } } function exportInfo(symbol, kind) { @@ -63152,10 +65125,24 @@ var ts; } } FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; - function getExportNode(parent) { + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152) { + return checker.getImmediateAliasedSymbol(importedSymbol); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { + return decl.expression.symbol; + } + else if (ts.isBinaryExpression(decl)) { + return decl.right.symbol; + } + ts.Debug.fail(); + } + function getExportNode(parent, node) { if (parent.kind === 226) { var p = parent; - return p.parent.kind === 260 ? undefined : p.parent.parent.kind === 208 ? p.parent.parent : undefined; + return p.name !== node ? undefined : + p.parent.kind === 260 ? undefined : p.parent.parent.kind === 208 ? p.parent.parent : undefined; } else { return parent; @@ -63184,25 +65171,26 @@ var ts; } FindAllReferences.getExportInfo = getExportInfo; function symbolName(symbol) { - if (symbol.name !== "default") { - return symbol.name; + if (symbol.escapedName !== "default") { + return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; } var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 && name.text; + return name && name.kind === 71 && name.escapedText; }); } function skipExportSpecifierSymbol(symbol, checker) { - if (symbol.declarations) + if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { return checker.getExportSpecifierLocalTargetSymbol(declaration); } } + } return symbol; } function getContainingModuleSymbol(importer, checker) { @@ -63253,13 +65241,16 @@ var ts; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, false); 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(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265) { + return undefined; + } var checker = program.getTypeChecker(); if (node.parent.kind === 262) { var result_5 = []; @@ -63302,22 +65293,22 @@ var ts; } case "label": { var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: ts.ScriptElementKind.label, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + return { node: node_3, name: node_3.text, kind: "label", displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: ts.ScriptElementKind.keyword, displayParts: [{ text: name_4, kind: ts.ScriptElementKind.keyword }] }; + return { node: node_4, name: name_4, kind: "keyword", displayParts: [{ text: name_4, kind: "keyword" }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: ts.ScriptElementKind.variableElement, displayParts: displayParts_2 }; + return { node: node_5, name: "this", kind: "var", displayParts: displayParts_2 }; } case "string": { var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: ts.ScriptElementKind.variableElement, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + return { node: node_6, name: node_6.text, kind: "var", displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -63349,7 +65340,7 @@ var ts; fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -63360,7 +65351,7 @@ var ts; } else { var textSpan = entry.textSpan, fileName = entry.fileName; - return { textSpan: textSpan, fileName: fileName, kind: ts.ScriptElementKind.unknown, displayParts: [] }; + return { textSpan: textSpan, fileName: fileName, kind: "", displayParts: [] }; } } function implementationKindDisplayParts(node, checker) { @@ -63370,13 +65361,13 @@ var ts; } else if (node.kind === 178) { return { - kind: ts.ScriptElementKind.interfaceElement, + kind: "interface", displayParts: [ts.punctuationPart(19), ts.textPart("object literal"), ts.punctuationPart(20)] }; } else if (node.kind === 199) { return { - kind: ts.ScriptElementKind.localClassElement, + kind: "local class", displayParts: [ts.punctuationPart(19), ts.textPart("anonymous local class"), ts.punctuationPart(20)] }; } @@ -63387,14 +65378,14 @@ var ts; function toHighlightSpan(entry) { if (entry.type === "span") { var fileName_1 = entry.fileName, textSpan = entry.textSpan; - return { fileName: fileName_1, span: { textSpan: textSpan, kind: ts.HighlightSpanKind.reference } }; + return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" } }; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; var writeAccess = isWriteAccess(node); var span = { textSpan: getTextSpan(node), - kind: writeAccess ? ts.HighlightSpanKind.writtenReference : ts.HighlightSpanKind.reference, + kind: writeAccess ? "writtenReference" : "reference", isInString: isInString }; return { fileName: fileName, span: span }; @@ -63410,20 +65401,19 @@ var ts; return ts.createTextSpanFromBounds(start, end); } function isWriteAccess(node) { - if (node.kind === 71 && ts.isDeclarationName(node)) { + if (ts.isAnyDeclarationName(node)) { return true; } var parent = node.parent; - if (parent) { - if (parent.kind === 193 || parent.kind === 192) { + switch (parent && parent.kind) { + case 193: + case 192: return true; - } - else if (parent.kind === 194 && parent.left === node) { - var operator = parent.operatorToken.kind; - return 58 <= operator && operator <= 70; - } + case 194: + return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); + default: + return false; } - return false; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -63468,7 +65458,7 @@ var ts; case 244: return true; case 181: - return ts.isRequireCall(node.parent, false); + return ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent); default: return false; } @@ -63529,7 +65519,7 @@ var ts; symbol = skipPastExportOrImportSpecifier(symbol, node, checker); var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; - var state = createState(sourceFiles, node, checker, cancellationToken, searchMeaning, options, result); + var state = new State(sourceFiles, node.kind === 123, checker, cancellationToken, searchMeaning, options, result); var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); var scope = getSymbolScope(symbol); if (scope) { @@ -63554,51 +65544,59 @@ var ts; } return symbol; } - function createState(sourceFiles, originalLocation, checker, cancellationToken, searchMeaning, options, result) { - var symbolIdToReferences = []; - var inheritsFromCache = ts.createMap(); - var sourceFileToSeenSymbols = []; - var isForConstructor = originalLocation.kind === 123; - var importTracker; - return __assign({}, options, { sourceFiles: sourceFiles, isForConstructor: isForConstructor, checker: checker, cancellationToken: cancellationToken, searchMeaning: searchMeaning, inheritsFromCache: inheritsFromCache, getImportSearches: getImportSearches, createSearch: createSearch, referenceAdder: referenceAdder, addStringOrCommentReference: addStringOrCommentReference, - markSearchedSymbol: markSearchedSymbol, markSeenContainingTypeReference: ts.nodeSeenTracker(), markSeenReExportRHS: ts.nodeSeenTracker() }); - function getImportSearches(exportSymbol, exportInfo) { - if (!importTracker) - importTracker = FindAllReferences.createImportTracker(sourceFiles, checker, cancellationToken); - return importTracker(exportSymbol, exportInfo, options.isForRename); + var State = (function () { + function State(sourceFiles, isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.isForConstructor = isForConstructor; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + this.inheritsFromCache = ts.createMap(); + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + this.sourceFileToSeenSymbols = []; } - function createSearch(location, symbol, comingFrom, searchOptions) { + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + }; + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; - var escapedText = ts.escapeIdentifier(text); - var parents = options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, checker); - return { location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: includes }; - function includes(referenceSymbol) { - return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; - } - } - function referenceAdder(referenceSymbol, searchLocation) { - var symbolId = ts.getSymbolId(referenceSymbol); - var references = symbolIdToReferences[symbolId]; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + return { + location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, + }; + }; + State.prototype.referenceAdder = function (searchSymbol, searchLocation) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; if (!references) { - references = symbolIdToReferences[symbolId] = []; - result.push({ definition: { type: "symbol", symbol: referenceSymbol, node: searchLocation }, references: references }); + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; - } - function addStringOrCommentReference(fileName, textSpan) { - result.push({ + }; + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ definition: undefined, references: [{ type: "span", fileName: fileName, textSpan: textSpan }] }); - } - function markSearchedSymbol(sourceFile, symbol) { + }; + State.prototype.markSearchedSymbol = function (sourceFile, symbol) { var sourceId = ts.getNodeId(sourceFile); var symbolId = ts.getSymbolId(symbol); - var seenSymbols = sourceFileToSeenSymbols[sourceId] || (sourceFileToSeenSymbols[sourceId] = []); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []); return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true); - } - } + }; + return State; + }()); function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; if (singleReferences.length) { @@ -63619,7 +65617,7 @@ var ts; indirectSearch = state.createSearch(exportLocation, exportSymbol, 1); break; case 1: - indirectSearch = state.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1, { text: "default" }); + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1, { text: "default" }); break; case 2: break; @@ -63647,15 +65645,17 @@ var ts; return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && checker.getPropertySymbolOfDestructuringAssignment(location); } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { + function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 176); - return bindingElement && + if (bindingElement && bindingElement.parent.kind === 174 && - !bindingElement.propertyName; + !bindingElement.propertyName) { + return bindingElement; + } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176); + var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); + if (bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } @@ -63670,20 +65670,18 @@ var ts; return undefined; } if (flags & (4 | 8192)) { - var privateDeclaration = ts.find(declarations, function (d) { return !!(ts.getModifierFlags(d) & 8); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8); }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 229); } + return undefined; } - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + if (getObjectBindingElementWithoutPropertyName(symbol)) { return undefined; } if (parent && !((parent.flags & 1536) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } - if ((flags & 134217728 && symbol.checkFlags & 6)) { - return undefined; - } var scope; for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var declaration = declarations_10[_i]; @@ -63698,11 +65696,8 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { 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; @@ -63710,9 +65705,9 @@ var ts; var text = sourceFile.text; var sourceLength = text.length; var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); + var position = text.indexOf(symbolName, container.pos); while (position >= 0) { - if (position > end) + if (position > container.end) break; var endPosition = position + symbolNameLength; if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5)) && @@ -63730,7 +65725,7 @@ var ts; 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); + var node = ts.getTouchingWord(sourceFile, position, false); if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } @@ -63740,7 +65735,7 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; + return node.text.length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && node.text.length === searchSymbolName.length; @@ -63760,10 +65755,10 @@ var ts; return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -63777,15 +65772,15 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments); _i < _a.length; _i++) { + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (!isValidReferencePosition(referenceLocation, search.text)) { - if (!state.implementations && (state.findInStrings && ts.isInString(sourceFile, position) || state.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); } return; @@ -63833,7 +65828,7 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.isForRename && state.markSeenReExportRHS(name)) { + if (!state.options.isForRename && state.markSeenReExportRHS(name)) { addReference(name, referenceSymbol, name, state); } } @@ -63842,7 +65837,7 @@ var ts; addRef(); } } - if (!(referenceLocation === propertyName && state.isForRename)) { + if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 ? 1 : 0; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); ts.Debug.assert(!!exportInfo); @@ -63874,7 +65869,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0) { - if (!state.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename || importOrExport.isNamedImport) { searchForImportedSymbol(symbol, state); } } @@ -63885,13 +65880,13 @@ var ts; function getReferenceForShorthandProperty(_a, search, state) { var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); - if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { + if (!(flags & 33554432) && search.includes(shorthandValueSymbol)) { addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { var addRef = state.referenceAdder(relatedSymbol, searchLocation); - if (state.implementations) { + if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { @@ -63980,15 +65975,16 @@ var ts; addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { - if (parent.body.kind === 207) { - ts.forEachReturnStatement(parent.body, function (returnStatement) { + var body = parent.body; + if (body.kind === 207) { + ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); } }); } - else if (isImplementationExpression(parent.body)) { - addReference(parent.body); + else if (isImplementationExpression(body)) { + addReference(body); } } else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { @@ -64119,7 +66115,7 @@ var ts; 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); + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || node.kind !== 97) { continue; } @@ -64177,7 +66173,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || !ts.isThis(node)) { return; } @@ -64225,7 +66221,7 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + var node_7 = ts.getTouchingWord(sourceFile, position, false); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); } @@ -64264,7 +66260,7 @@ var ts; result.push(rootSymbol); } if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap(), checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); } } return result; @@ -64273,7 +66269,7 @@ var ts; if (!symbol) { return; } - if (previousIterationSymbolsCache.has(symbol.name)) { + if (previousIterationSymbolsCache.has(symbol.escapedName)) { return; } if (symbol.flags & (32 | 64)) { @@ -64296,7 +66292,7 @@ var ts; if (propertySymbol) { result.push.apply(result, checker.getRootSymbols(propertySymbol)); } - previousIterationSymbolsCache.set(symbol.name, symbol); + previousIterationSymbolsCache.set(symbol.escapedName, symbol); getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); } } @@ -64332,7 +66328,7 @@ var ts; return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); return ts.find(result, search.includes); } return undefined; @@ -64346,7 +66342,7 @@ var ts; } return undefined; } - return node.name.text; + return ts.getTextOfIdentifierOrLiteral(node.name); } function getPropertySymbolsFromContextualType(node, checker) { var objectLiteral = node.parent; @@ -64479,7 +66475,6 @@ var ts; if (referenceFile) { return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; } - return undefined; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { @@ -64487,14 +66482,14 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } if (ts.isJumpStatementTarget(node)) { var labelName = node.text; - var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, ts.ScriptElementKind.label, labelName, undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, labelName); + return label ? [createDefinitionInfoFromName(label, "label", labelName, undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -64505,7 +66500,7 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + if (symbol.flags & 2097152 && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = typeChecker.getAliasedSymbol(symbol); if (aliased.declarations) { symbol = aliased; @@ -64532,7 +66527,7 @@ var ts; } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -64677,7 +66672,7 @@ var ts; return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ts.ScriptElementKind.scriptElement, + kind: "script", name: name, containerName: undefined, containerKind: undefined @@ -64754,19 +66749,14 @@ var ts; function getJsDocCommentsFromDeclarations(declarations) { var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getCommentsFromJSDoc(declaration); - if (!comments) { - return; - } - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var comment = comments_3[_i]; - if (comment) { + ts.forEach(ts.getAllJSDocs(declaration), function (doc) { + if (doc.comment) { if (documentationComment.length) { documentationComment.push(ts.lineBreakPart()); } - documentationComment.push(ts.textPart(comment)); + documentationComment.push(ts.textPart(doc.comment)); } - } + }); }); return documentationComment; } @@ -64774,20 +66764,10 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { var tags = []; forEachUnique(declarations, function (declaration) { - var jsDocs = ts.getJSDocs(declaration); - if (!jsDocs) { - return; - } - for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { - var doc = jsDocs_1[_i]; - var tagsForDoc = doc.tags; - if (tagsForDoc) { - tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 284; }).map(function (jsDocTag) { - return { - name: jsDocTag.tagName.text, - text: jsDocTag.comment - }; - })); + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 276) { + tags.push({ name: tag.tagName.text, text: tag.comment }); } } }); @@ -64811,7 +66791,7 @@ var ts; return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword", kindModifiers: "", sortText: "0", }; @@ -64822,18 +66802,39 @@ var ts; return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: "@" + tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword", kindModifiers: "", sortText: "0" }; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter", kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -64868,7 +66869,7 @@ var ts; for (var i = 0; i < parameters.length; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 71 ? - currentName.text : + currentName.escapedText : "param" + i; if (isJavaScriptFile) { docParams += indentationStr + " * @param {any} " + paramName + newLine; @@ -64924,8 +66925,6 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - var safeList; - var EmptySafeList = ts.createMap(); JsTyping.nodeCoreModuleList = [ "buffer", "querystring", "events", "http", "cluster", "zlib", "os", "https", "punycode", "repl", "readline", @@ -64935,58 +66934,53 @@ var ts; "constants", "process", "v8", "timers", "console" ]; var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { - var inferredTypings = ts.createMap(); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 || kind === 2; + var inferredTypings = ts.createMap(); + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMapFromTemplate(result.config) : EmptySafeList; - } var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typeAcquisition.include); - exclude = typeAcquisition.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { var packageJsonPath = ts.combinePaths(searchDir, "package.json"); getTypingNamesFromJson(packageJsonPath, filesToWatch); var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); getTypingNamesFromJson(bowerJsonPath, filesToWatch); var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath); - } + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); getTypingNamesFromSourceFileNames(fileNames); if (unresolvedImports) { - for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { - var moduleId = unresolvedImports_1[_a]; - var typingName = nodeCoreModules.has(moduleId) ? "node" : moduleId; - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); } packageNameToTypingLocation.forEach(function (typingLocation, name) { if (inferredTypings.has(name) && inferredTypings.get(name) === undefined) { inferredTypings.set(name, typingLocation); } }); - for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { - var excludeTypingName = exclude_1[_b]; - inferredTypings.delete(excludeTypingName); + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); } var newTypingNames = []; var cachedTypingPaths = []; @@ -64998,58 +66992,56 @@ var ts; newTypingNames.push(typing); } }); - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!inferredTypings.has(typing)) { - inferredTypings.set(typing, undefined); - } + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); } } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (host.fileExists(jsonPath)) { - filesToWatch.push(jsonPath); - } - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } + if (!host.fileExists(jsonPath)) { + return; } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); } function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return safeList.has(f); })); + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx"); }); if (hasJsxFile) { - mergeTypings(["react"]); + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); } } - function getTypingNamesFromPackagesFolder(packagesFolderPath) { + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { filesToWatch.push(packagesFolderPath); if (!host.directoryExists(packagesFolderPath)) { return; } - var typingNames = []; var fileNames = host.readDirectory(packagesFolderPath, [".json"], undefined, undefined, 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -65057,11 +67049,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; + var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_8.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -65069,15 +67058,18 @@ var ts; if (!packageJson.name) { continue; } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); inferredTypings.set(packageJson.name, absolutePath); } else { - typingNames.push(packageJson.name); + packageNames.push(packageJson.name); } } - mergeTypings(typingNames); + addInferredTypings(packageNames, " Found package names"); } } JsTyping.discoverTypings = discoverTypings; @@ -65090,7 +67082,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { return "continue"; @@ -65122,14 +67114,14 @@ var ts; }; for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_6(sourceFile); } rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; if (decl.kind === 239 || decl.kind === 242 || decl.kind === 237) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); - return importer.name !== imported.name; + return importer.escapedName !== imported.escapedName; } else { return true; @@ -65151,21 +67143,11 @@ var ts; } return true; } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 || - node.kind === 9 || - node.kind === 8) { - return node.text; - } - } - return undefined; - } function tryAddSingleDeclarationName(declaration, containers) { if (declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var text = getTextOfIdentifierOrLiteral(name); + var text = ts.getTextOfIdentifierOrLiteral(name); if (text !== undefined) { containers.unshift(text); } @@ -65180,7 +67162,7 @@ var ts; return true; } function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = getTextOfIdentifierOrLiteral(expression); + var text = ts.getTextOfIdentifierOrLiteral(expression); if (text !== undefined) { if (includeLastPortion) { containers.unshift(text); @@ -65446,7 +67428,7 @@ var ts; default: ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 290) { + if (tag.kind === 283) { addLeafNode(tag); } }); @@ -65538,14 +67520,14 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.getPropertyNameForPropertyNameNode(declName); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { case 186: case 187: case 199: return getFunctionOrClassName(node); - case 290: + case 283: return getJSDocTypedefTagName(node); default: return undefined; @@ -65585,7 +67567,7 @@ var ts; return "()"; case 157: return "[]"; - case 290: + case 283: return getJSDocTypedefTagName(node); default: return ""; @@ -65632,7 +67614,7 @@ var ts; case 233: case 265: case 231: - case 290: + case 283: return true; case 152: case 151: @@ -65717,10 +67699,10 @@ var ts; return ts.getTextOfNode(moduleDeclaration.name); } var result = []; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); while (moduleDeclaration.body && moduleDeclaration.body.kind === 233) { moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } return result.join("."); } @@ -65780,7 +67762,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_13); } @@ -65791,7 +67773,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_14); } @@ -65803,8 +67785,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { - var currentComment = comments_4[_i]; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var currentComment = comments_3[_i]; cancellationToken.throwIfCancellationRequested(); if (currentComment.kind === 2) { if (isFirstSingleLineComment) { @@ -66370,13 +68352,9 @@ var ts; }); } function getFileReference() { - var file = ts.scanner.getTokenValue(); + var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; + return { fileName: fileName, pos: pos, end: pos + fileName.length }; } function recordAmbientExternalModule() { if (!ambientExternalModules) { @@ -66411,7 +68389,14 @@ var ts; var token = ts.scanner.getToken(); if (token === 91) { token = nextToken(); - if (token === 9) { + if (token === 19) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + return true; + } + } + else if (token === 9) { recordModuleName(); return true; } @@ -66660,7 +68645,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } var displayName = ts.stripQuotes(node.text); - return getRenameInfoSuccess(displayName, displayName, ts.ScriptElementKind.variableElement, ts.ScriptElementKindModifier.none, node, sourceFile); + return getRenameInfoSuccess(displayName, displayName, "var", "", node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -66706,7 +68691,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var emptyArray = []; var ArgumentListKind; (function (ArgumentListKind) { ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; @@ -66721,13 +68705,12 @@ var ts; return undefined; } var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); - cancellationToken.throwIfCancellationRequested(); - if (!argumentInfo) { + if (!argumentInfo) return undefined; - } + cancellationToken.throwIfCancellationRequested(); var call = argumentInfo.invocation; var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates); + var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { if (ts.isSourceFileJavaScript(sourceFile)) { @@ -66749,7 +68732,7 @@ var ts; : expression.kind === 179 ? expression.name : undefined; - if (!name || !name.text) { + if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -66776,36 +68759,25 @@ var ts; } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { if (ts.isCallOrNewExpression(node.parent)) { - var callExpression = node.parent; - if (node.kind === 27 || - node.kind === 19) { - var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + var invocation = node.parent; + var list = void 0; + var argumentIndex = void 0; + if (node.kind === 27 || node.kind === 19) { + list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); ts.Debug.assert(list !== undefined); - return { - kind: isTypeArgList ? 0 : 1, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: 0, - argumentCount: getArgumentCount(list) - }; + argumentIndex = 0; } - var listItemInfo = ts.findListItemInfo(node); - if (listItemInfo) { - var list = listItemInfo.list; - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; - var argumentIndex = getArgumentIndex(list, node); - var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - kind: isTypeArgList ? 0 : 1, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + else { + list = ts.findContainingList(node); + if (!list) + return undefined; + argumentIndex = getArgumentIndex(list, node); } - return undefined; + var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 : 1; + var argumentCount = getArgumentCount(list); + ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (node.kind === 13 && node.parent.kind === 183) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -66929,25 +68901,9 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } - function selectBestInvalidOverloadIndex(candidates, argumentCount) { - var maxParamsSignatureIndex = -1; - var maxParams = -1; - for (var i = 0; i < candidates.length; i++) { - var candidate = candidates[i]; - if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { - return i; - } - if (candidate.parameters.length > maxParams) { - maxParams = candidate.parameters.length; - maxParamsSignatureIndex = i; - } - } - return maxParamsSignatureIndex; - } - function createSignatureHelpItems(candidates, bestSignature, argumentListInfo, typeChecker) { - var applicableSpan = argumentListInfo.argumentsSpan; + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0; - var invocation = argumentListInfo.invocation; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, undefined, undefined); @@ -66962,8 +68918,8 @@ var ts; if (isTypeParameterList) { isVariadic = false; prefixDisplayParts.push(ts.punctuationPart(27)); - var typeParameters = candidateSignature.typeParameters; - signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; + var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); @@ -66977,8 +68933,7 @@ var ts; }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19)); - var parameters = candidateSignature.parameters; - signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; + signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); suffixDisplayParts.push(ts.punctuationPart(20)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { @@ -66995,20 +68950,10 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - var argumentIndex = argumentListInfo.argumentIndex; - var argumentCount = argumentListInfo.argumentCount; - var selectedItemIndex = candidates.indexOf(bestSignature); - if (selectedItemIndex < 0) { - selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount); - } ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - items: items, - applicableSpan: applicableSpan, - selectedItemIndex: selectedItemIndex, - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); @@ -67026,7 +68971,7 @@ var ts; }); return { name: typeParameter.symbol.name, - documentation: emptyArray, + documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; @@ -67039,94 +68984,95 @@ var ts; var SymbolDisplay; (function (SymbolDisplay) { function getSymbolKind(typeChecker, symbol, location) { - var flags = symbol.flags; - if (flags & 32) + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32) { return ts.getDeclarationOfKind(symbol, 199) ? - ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + "local class" : "class"; + } if (flags & 384) - return ts.ScriptElementKind.enumElement; + return "enum"; if (flags & 524288) - return ts.ScriptElementKind.typeElement; + return "type"; if (flags & 64) - return ts.ScriptElementKind.interfaceElement; + return "interface"; if (flags & 262144) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter"; var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - if (result === ts.ScriptElementKind.unknown) { + if (result === "") { if (flags & 262144) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter"; if (flags & 8) - return ts.ScriptElementKind.enumMemberElement; - if (flags & 8388608) - return ts.ScriptElementKind.alias; + return "enum member"; + if (flags & 2097152) + return "alias"; if (flags & 1536) - return ts.ScriptElementKind.moduleElement; + return "module"; } return result; } SymbolDisplay.getSymbolKind = getSymbolKind; function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { if (typeChecker.isUndefinedSymbol(symbol)) { - return ts.ScriptElementKind.variableElement; + return "var"; } if (typeChecker.isArgumentsSymbol(symbol)) { - return ts.ScriptElementKind.localVariableElement; + return "local var"; } if (location.kind === 99 && ts.isExpression(location)) { - return ts.ScriptElementKind.parameterElement; + return "parameter"; } - var flags = symbol.flags; + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 3) { if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ts.ScriptElementKind.parameterElement; + return "parameter"; } else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ts.ScriptElementKind.constElement; + return "const"; } else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ts.ScriptElementKind.letElement; + return "let"; } - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + return isLocalVariableOrFunction(symbol) ? "local var" : "var"; } if (flags & 16) - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + return isLocalVariableOrFunction(symbol) ? "local function" : "function"; if (flags & 32768) - return ts.ScriptElementKind.memberGetAccessorElement; + return "getter"; if (flags & 65536) - return ts.ScriptElementKind.memberSetAccessorElement; + return "setter"; if (flags & 8192) - return ts.ScriptElementKind.memberFunctionElement; + return "method"; if (flags & 16384) - return ts.ScriptElementKind.constructorImplementationElement; + return "constructor"; if (flags & 4) { - if (flags & 134217728 && symbol.checkFlags & 6) { + if (flags & 33554432 && symbol.checkFlags & 6) { var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (98308 | 3)) { - return ts.ScriptElementKind.memberVariableElement; + return "property"; } ts.Debug.assert(!!(rootSymbolFlags & 8192)); }); if (!unionPropertyKind) { var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { - return ts.ScriptElementKind.memberFunctionElement; + return "method"; } - return ts.ScriptElementKind.memberVariableElement; + return "property"; } return unionPropertyKind; } if (location.parent && ts.isJsxAttribute(location.parent)) { - return ts.ScriptElementKind.jsxAttribute; + return "JSX attribute"; } - return ts.ScriptElementKind.memberVariableElement; + return "property"; } - return ts.ScriptElementKind.unknown; + return ""; } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) - : ts.ScriptElementKindModifier.none; + : ""; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { @@ -67134,17 +69080,17 @@ var ts; var displayParts = []; var documentation; var tags; - var symbolFlags = symbol.flags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 && ts.isExpression(location); var type; - if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { - if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { - symbolKind = ts.ScriptElementKind.memberVariableElement; + if (symbolKind !== "" || symbolFlags & 32 || symbolFlags & 2097152) { + if (symbolKind === "getter" || symbolKind === "setter") { + symbolKind = "property"; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); if (type) { if (location.parent && location.parent.kind === 179) { var right = location.parent.name; @@ -67175,11 +69121,11 @@ var ts; } if (signature) { if (useConstructSignatures && (symbolFlags & 32)) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor"; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - else if (symbolFlags & 8388608) { - symbolKind = ts.ScriptElementKind.alias; + else if (symbolFlags & 2097152) { + symbolKind = "alias"; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { @@ -67192,13 +69138,13 @@ var ts; addPrefixForAnyFunctionOrVar(symbol, symbolKind); } switch (symbolKind) { - case ts.ScriptElementKind.jsxAttribute: - case ts.ScriptElementKind.memberVariableElement: - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.parameterElement: - case ts.ScriptElementKind.localVariableElement: + case "JSX attribute": + case "property": + case "var": + case "const": + case "let": + case "parameter": + case "local var": displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { @@ -67208,7 +69154,7 @@ var ts; if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } - addSignatureDisplayParts(signature, allSignatures, 8); + addSignatureDisplayParts(signature, allSignatures, 16); break; default: addSignatureDisplayParts(signature, allSignatures); @@ -67216,7 +69162,7 @@ var ts; hasAddedSymbolInfo = true; } } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { var functionDeclaration_1 = location.parent; var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { @@ -67231,7 +69177,7 @@ var ts; signature = allSignatures[0]; } if (functionDeclaration_1.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor"; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { @@ -67246,7 +69192,7 @@ var ts; } if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { if (ts.getDeclarationOfKind(symbol, 199)) { - pushTypePart(ts.ScriptElementKind.localClassElement); + pushTypePart("local class"); } else { displayParts.push(ts.keywordPart(75)); @@ -67271,7 +69217,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); @@ -67318,7 +69264,7 @@ var ts; else if (declaration.kind !== 155 && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64)); } else if (declaration.kind === 231) { addInPrefix(); @@ -67331,7 +69277,7 @@ var ts; } } if (symbolFlags & 8) { - symbolKind = ts.ScriptElementKind.enumMemberElement; + symbolKind = "enum member"; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; if (declaration.kind === 264) { @@ -67344,7 +69290,7 @@ var ts; } } } - if (symbolFlags & 8388608) { + if (symbolFlags & 2097152) { addNewLineIfDisplayPartsExist(); if (symbol.declarations[0].kind === 236) { displayParts.push(ts.keywordPart(84)); @@ -67382,7 +69328,7 @@ var ts; }); } if (!hasAddedSymbolInfo) { - if (symbolKind !== ts.ScriptElementKind.unknown) { + if (symbolKind !== "") { if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); @@ -67391,10 +69337,10 @@ var ts; else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); } - if (symbolKind === ts.ScriptElementKind.memberVariableElement || - symbolKind === ts.ScriptElementKind.jsxAttribute || + if (symbolKind === "property" || + symbolKind === "JSX attribute" || symbolFlags & 3 || - symbolKind === ts.ScriptElementKind.localVariableElement || + symbolKind === "local var" || isThisExpression) { displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); @@ -67413,7 +69359,7 @@ var ts; symbolFlags & 16384 || symbolFlags & 131072 || symbolFlags & 98304 || - symbolKind === ts.ScriptElementKind.memberFunctionElement) { + symbolKind === "method") { var allSignatures = type.getNonNullableType().getCallSignatures(); addSignatureDisplayParts(allSignatures[0], allSignatures); } @@ -67426,7 +69372,7 @@ var ts; if (!documentation) { documentation = symbol.getDocumentationComment(); tags = symbol.getJsDocTags(); - if (documentation.length === 0 && symbol.flags & 4) { + if (documentation.length === 0 && symbolFlags & 4) { if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 265; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -67471,11 +69417,11 @@ var ts; } function pushTypePart(symbolKind) { switch (symbolKind) { - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.functionElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.constructorImplementationElement: + case "var": + case "function": + case "let": + case "const": + case "constructor": displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: @@ -67486,7 +69432,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19)); @@ -67602,8 +69548,8 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); - options = ts.clone(options); - var _loop_5 = function (opt) { + options = ts.cloneCompilerOptions(options); + var _loop_7 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -67619,7 +69565,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_7(opt); } return options; } @@ -67823,11 +69769,7 @@ var ts; break; } } - lastTokenInfo = { - leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia, - token: token - }; + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } function isOnToken() { @@ -67944,7 +69886,8 @@ var ts; FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -68074,9 +70017,9 @@ var ts; } return true; }; + RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); - RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -68104,11 +70047,11 @@ var ts; 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); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71, 3, 75, 84, 91]); - 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.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 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.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); 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)); @@ -68300,6 +70243,9 @@ var ts; Rules.IsOptionDisabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; }; + Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + }; Rules.IsOptionEnabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; }; @@ -68343,8 +70289,8 @@ var ts; Rules.IsConditionalOperatorContext = function (context) { return context.contextNode.kind === 195; }; - Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { - return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); + Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { + return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); }; Rules.IsBraceWrappedContext = function (context) { return context.contextNode.kind === 174 || Rules.IsSingleLineBlockContext(context); @@ -68890,11 +70836,27 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 25, sourceFile, options, rulesProvider, 3); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3); } formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, options, rulesProvider, 4); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 18, sourceFile, options, rulesProvider, 4); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -68908,33 +70870,22 @@ var ts; function formatSelection(start, end, sourceFile, rulesProvider, options) { var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), - end: end + end: end, }; return formatSpan(span, sourceFile, options, rulesProvider, 1); } formatting.formatSelection = formatSelection; - function formatOutermostParent(position, expectedLastToken, sourceFile, options, rulesProvider, requestKind) { - var parent = findOutermostParent(position, expectedLastToken, sourceFile); - if (!parent) { - return []; - } - var span = { - pos: ts.getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile), - end: parent.end - }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; } - function findOutermostParent(position, expectedTokenKind, sourceFile) { - var precedingToken = ts.findPrecedingToken(position, sourceFile); - if (!precedingToken || - precedingToken.kind !== expectedTokenKind || - position !== precedingToken.getEnd()) { - return undefined; - } - var current = precedingToken; + function findOutermostNodeWithinListLevel(node) { + var current = node; while (current && current.parent && - current.parent.end === precedingToken.end && + current.parent.end === node.end && !isListElement(current.parent, current)) { current = current.parent; } @@ -69031,11 +70982,21 @@ var ts; } return 0; } - function formatNode(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); } - formatting.formatNode = formatNode; + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + } function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { var enclosingNode = findEnclosingNode(originalRange, sourceFile); 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); @@ -70177,7 +72138,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, false); if (nextToken && isSeparator(node, nextToken)) { var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); var nextElement = containingList[index + 1]; @@ -70186,7 +72147,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -70254,7 +72215,7 @@ var ts; } var end = after.getEnd(); if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, false); if (nextToken && isSeparator(after, nextToken)) { var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); @@ -70328,7 +72289,7 @@ var ts; }; ChangeTracker.prototype.getChanges = function () { var _this = this; - var changesPerFile = ts.createFileMap(); + var changesPerFile = ts.createMap(); for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { var c = _a[_i]; var changesInFile = changesPerFile.get(c.sourceFile.path); @@ -70338,8 +72299,7 @@ var ts; changesInFile.push(c); } var fileChangesList = []; - changesPerFile.forEachValue(function (path) { - var changesInFile = changesPerFile.get(path); + changesPerFile.forEach(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; var fileTextChanges = { fileName: sourceFile.fileName, textChanges: [] }; for (var _i = 0, _a = ChangeTracker.normalize(changesInFile); _i < _a.length; _i++) { @@ -70407,7 +72367,7 @@ var ts; lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNode(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } textChanges.applyFormatting = applyFormatting; @@ -70581,39 +72541,46 @@ var ts; } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - var results; - var refactorList = []; - refactors.forEach(function (refactor) { - refactorList.push(refactor); + return ts.flatMapIter(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); }); - 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; + function getEditsForRefactor(context, refactorName, actionName) { var refactor = refactors.get(refactorName); - if (!refactor) { - return undefined; - } - var codeActions = refactor.getCodeActions(context); - if (codeActions) { - ts.addRange((result || (result = [])), codeActions); - } - return result; + return refactor && refactor.getEditsForAction(context, actionName); } - refactor_1.getRefactorCodeActions = getRefactorCodeActions; + refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var qualifiedName = ts.getAncestor(token, 143); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + if (!ts.isIdentifier(qualifiedName.left)) { + return undefined; + } + var leftText = qualifiedName.left.getText(sourceFile); + var rightText = qualifiedName.right.getText(sourceFile); + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -70624,7 +72591,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -70663,11 +72630,7 @@ var ts; newNodes.push(newIndexSignatureDeclaration); } function pushAction(result, newNodes, description) { - var newAction = { - description: description, - changes: codefix.newNodesToChanges(newNodes, openBrace, context) - }; - result.push(newAction); + result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -70682,90 +72645,134 @@ var ts; getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { - var sourceFile = context.sourceFile; + var tokenSourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(tokenSourceFile, start, false); if (token.kind !== 71) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent) || token.parent.expression.kind !== 99) { + if (!ts.isPropertyAccessExpression(token.parent)) { return undefined; } - var classMemberDeclaration = ts.getThisContainer(token, false); - if (!ts.isClassElement(classMemberDeclaration)) { - return undefined; + var tokenName = token.getText(tokenSourceFile); + var makeStatic = false; + var classDeclaration; + if (token.parent.expression.kind === 99) { + var containingClassMemberDeclaration = ts.getThisContainer(token, false); + if (!ts.isClassElement(containingClassMemberDeclaration)) { + return undefined; + } + classDeclaration = containingClassMemberDeclaration.parent; + makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32); + } + else { + var checker = context.program.getTypeChecker(); + var leftExpression = token.parent.expression; + var leftExpressionType = checker.getTypeAtLocation(leftExpression); + if (leftExpressionType.flags & 32768) { + var symbol = leftExpressionType.symbol; + if (symbol.flags & 32) { + classDeclaration = symbol.declarations && symbol.declarations[0]; + if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { + makeStatic = true; + } + } + } } - var classDeclaration = classMemberDeclaration.parent; if (!classDeclaration || !ts.isClassLike(classDeclaration)) { return undefined; } - var isStatic = ts.hasModifier(classMemberDeclaration, 32); - return ts.isInJavaScriptFile(sourceFile) ? getActionsForAddMissingMemberInJavaScriptFile() : getActionsForAddMissingMemberInTypeScriptFile(); - function getActionsForAddMissingMemberInJavaScriptFile() { - var memberName = token.getText(); - if (isStatic) { + var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); + var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); + return ts.isInJavaScriptFile(classDeclarationSourceFile) ? + getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : + getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); + function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(false); + if (methodCodeAction) { + actions = [methodCodeAction]; + } + if (makeStatic) { if (classDeclaration.kind === 199) { - return undefined; + return actions; } var className = classDeclaration.name.getText(); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classDeclaration.getEnd(), length: 0 }, - newText: "" + context.newLineCharacter + className + "." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + var initializeStaticAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), + changes: staticInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeStaticAction); + return actions; } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); if (!classConstructor) { - return undefined; + return actions; } - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classConstructor.body.getEnd() - 1, length: 0 }, - newText: "this." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var initializeAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), + changes: propertyInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeAction); + return actions; } } - function getActionsForAddMissingMemberInTypeScriptFile() { + function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(true); + if (methodCodeAction) { + actions = [methodCodeAction]; + } var typeNode; if (token.parent.parent.kind === 194) { var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(binaryExpression.right))); + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } typeNode = typeNode || ts.createKeywordTypeNode(119); - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); - var property = ts.createProperty(undefined, isStatic ? [ts.createToken(115)] : undefined, token.getText(sourceFile), undefined, typeNode, undefined); + var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - propertyChangeTracker.insertNodeAfter(sourceFile, openBrace, property, { suffix: context.newLineCharacter }); - var actions = [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_declaration_for_missing_property_0), [token.getText()]), - changes: propertyChangeTracker.getChanges() - }]; - if (!isStatic) { + propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); + (actions || (actions = [])).push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + changes: propertyChangeTracker.getChanges() + }); + if (!makeStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); + indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_missing_property_0), [token.getText()]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: indexSignatureChangeTracker.getChanges() }); } return actions; } + function getActionForMethodDeclaration(includeTypeScriptSyntax) { + if (token.parent.parent.kind === 181) { + var callExpression = token.parent.parent; + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? + ts.Diagnostics.Declare_method_0 : + ts.Diagnostics.Declare_static_method_0), [tokenName]), + changes: methodDeclarationChangeTracker.getChanges() + }; + } + } } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -70780,10 +72787,11 @@ var ts; }); function getActionsForCorrectSpelling(context) { var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); var checker = context.program.getTypeChecker(); var suggestion; - if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } @@ -70834,7 +72842,7 @@ var ts; function getActionForClassLikeMissingAbstractMember(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -70869,7 +72877,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 99) { return undefined; } @@ -70879,9 +72887,9 @@ var ts; return undefined; } if (superCall.expression && superCall.expression.kind === 181) { - var arguments_1 = superCall.expression.arguments; - for (var i = 0; i < arguments_1.length; i++) { - if (arguments_1[i].expression === token) { + var expressionArguments = superCall.expression.arguments; + for (var i = 0; i < expressionArguments.length; i++) { + if (expressionArguments[i].expression === token) { return undefined; } } @@ -70914,7 +72922,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 123) { return undefined; } @@ -70938,7 +72946,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 && ts.isClassLike(classDeclNode))) { return undefined; @@ -70976,7 +72984,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 71) { return undefined; } @@ -71002,129 +73010,133 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); if (token.kind === 21) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, false); } switch (token.kind) { case 71: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149: case 240: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: return deleteDefault(); } function deleteDefault() { if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + return [deleteNode(token.parent)]; } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + return [deleteNode(token.parent.parent)]; } else { return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = 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); + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); + ts.Debug.assert(previousToken.kind === 27); + ts.Debug.assert(nextToken.kind === 29); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237); + return [deleteNode(importEquals)]; case 242: - var namedImports = token.parent.parent; + var namedImports = parent.parent; if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); + return deleteNamedImportBinding(namedImports); } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 239: - var importClause = token.parent; + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + var start_6 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) })]; } else { - return deleteNode(importClause.name); + 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); - } + return deleteNamedImportBinding(parent); default: return deleteDefault(); } } - function deleteVariableDeclaration(varDecl) { + function deleteNamedImportBinding(namedBindings) { + if (namedBindings.parent.name) { + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, false); + if (previousToken && previousToken.kind === 26) { + return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; + } + return undefined; + } + else { + var importDecl = ts.getAncestor(namedBindings, 238); + return [deleteNode(importDecl)]; + } + } + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, 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); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : 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()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215: - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -71144,16 +73156,55 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], + getCodeActions: getActionsForJSDocTypes + }); + function getActionsForJSDocTypes(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var decl = ts.findAncestor(node, function (n) { return n.kind === 226; }); + if (!decl) + return; + var checker = context.program.getTypeChecker(); + var jsdocType = decl.type; + var original = ts.getTextOfNode(jsdocType); + var type = checker.getTypeFromTypeNode(jsdocType); + var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, undefined, 8))]; + if (jsdocType.kind === 270) { + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048), undefined, 8); + actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); + } + return actions; + } + function createAction(declaration, fileName, original, replacement) { + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), + changes: [{ + fileName: fileName, + textChanges: [{ + span: { start: declaration.getStart(), length: declaration.getWidth() }, + newText: replacement + }] + }], + }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -71253,15 +73304,28 @@ var ts; 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 token = ts.getTokenAtPosition(sourceFile, context.span.start, false); 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 umdSymbol = checker.getSymbolAtLocation(token); + var symbol = void 0; + var symbolName = void 0; + if (umdSymbol.flags & 2097152) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = name; + } + else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { + symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455)); + symbolName = symbol.name; + } + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, symbolName, false, true); } var candidateModules = checker.getAmbientModules(); for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { @@ -71276,15 +73340,16 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, true)); } } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + ts.Debug.assert(name !== "default"); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); } } return symbolIdActionMap.getAllActions(); @@ -71319,16 +73384,13 @@ var ts; } } function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + return ts.getSymbolId(ts.skipAlias(symbol, checker)); } 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) { + function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { var existingDeclarations = getImportDeclarations(moduleSymbol); if (existingDeclarations.length > 0) { return getCodeActionsForExistingImport(existingDeclarations); @@ -71412,10 +73474,10 @@ var ts; var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); var changeTracker = createChangeTracker(); var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) + ? ts.createImportClause(ts.createIdentifier(symbolName), undefined) : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); if (!lastImportDeclaration) { changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); @@ -71423,7 +73485,7 @@ var ts; else { changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -71436,8 +73498,9 @@ var ts; tryGetModuleNameFromRootDirs() || ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; } } function tryGetModuleNameFromBaseUrl() { @@ -71504,43 +73567,90 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { return undefined; } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { 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"))); + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (context.host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); 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 mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } } - catch (e) { } + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory); + } } - return relativeFileName; } } + function getNodeModulePathParts(fullPath) { + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["PackageContent"] = 2] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1; + } + break; + case 1: + packageRootIndex = partEnd; + state = 2; + break; + case 2: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1; + } + else { + state = 2; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDir = rootDirs_1[_i]; var relativeName = getRelativePathIfInDirectory(path, rootDir); if (relativeName !== undefined) { return relativeName; @@ -71561,7 +73671,7 @@ var ts; } function getRelativePath(path, directoryPath) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; } } } @@ -71598,7 +73708,7 @@ var ts; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -71668,7 +73778,7 @@ var ts; codefix.newNodesToChanges = newNodesToChanges; function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.getName()); }); + var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); var newNodes = []; for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { var symbol = missingMembers_1[_i]; @@ -71695,7 +73805,7 @@ var ts; var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); - var optional = !!(symbol.flags & 67108864); + var optional = !!(symbol.flags & 16777216); switch (declaration.kind) { case 153: case 154: @@ -71751,6 +73861,29 @@ var ts; return signatureDeclaration; } } + function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { + var parameters = createDummyParameters(callExpression.arguments.length, undefined, undefined, includeTypeScriptSyntax); + var typeParameters; + if (includeTypeScriptSyntax) { + var typeArgCount = ts.length(callExpression.typeArguments); + for (var i = 0; i < typeArgCount; i++) { + var name = typeArgCount < 8 ? String.fromCharCode(84 + i) : "T" + i; + var typeParameter = ts.createTypeParameterDeclaration(name, undefined, undefined); + (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); + } + } + var newMethod = ts.createMethod(undefined, makeStatic ? [ts.createToken(115)] : undefined, undefined, methodName, undefined, typeParameters, parameters, includeTypeScriptSyntax ? ts.createKeywordTypeNode(119) : undefined, createStubbedMethodBody()); + return newMethod; + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter(undefined, undefined, undefined, names && names[i] || "arg" + i, minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55) : undefined, addAnyType ? ts.createKeywordTypeNode(119) : undefined, undefined); + parameters.push(newParameter); + } + return parameters; + } function createMethodImplementingSignatures(signatures, name, optional, modifiers) { var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; @@ -71766,13 +73899,8 @@ var ts; } } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); - var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.getName(); }); - var parameters = []; - for (var i = 0; i < maxNonRestArgs; i++) { - var anyType = ts.createKeywordTypeNode(119); - var newParameter = ts.createParameter(undefined, undefined, undefined, maxArgsParameterSymbolNames[i], i >= minArgumentCount ? ts.createToken(55) : undefined, anyType, undefined); - parameters.push(newParameter); - } + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, true); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119)); var restParameter = ts.createParameter(undefined, undefined, ts.createToken(24), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", maxNonRestArgs >= minArgumentCount ? ts.createToken(55) : undefined, anyArrayType, undefined); @@ -71802,34 +73930,54 @@ var ts; (function (ts) { var refactor; (function (refactor) { + var actionName = "convert"; var convertFunctionToES6Class = { name: "Convert to ES2015 class", description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getCodeActions: getCodeActions, - isApplicable: isApplicable + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions }; refactor.registerRefactor(convertFunctionToES6Class); - function isApplicable(context) { + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start); + var node = ts.getTokenAtPosition(context.file, start, false); 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; + if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - function getCodeActions(context) { + function getEditsForAction(context, action) { + if (actionName !== action) { + return undefined; + } var start = context.startPosition; var sourceFile = context.file; var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var ctorSymbol = checker.getSymbolAtLocation(token); var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 | 3))) { - return []; + return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -71853,17 +74001,16 @@ var ts; break; } if (!newClassDeclaration) { - return []; + return undefined; } 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() - }]; + return { + edits: changeTracker.getChanges() + }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { @@ -71915,10 +74062,13 @@ var ts; return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186: + case 186: { var functionExpression = assignmentBinaryExpression.right; - return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); - case 187: + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + copyComments(assignmentBinaryExpression, method); + return method; + } + case 187: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; @@ -71929,15 +74079,33 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); - default: + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + copyComments(assignmentBinaryExpression, method); + return method; + } + default: { if (ts.isSourceFileJavaScript(sourceFile)) { return; } - return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } } } } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3) { + pos += 2; + end -= 2; + } + else { + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; if (!initializer || initializer.kind !== 186) { @@ -71950,14 +74118,16 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); } - return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; } 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); + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; } } })(refactor = ts.refactor || (ts.refactor = {})); @@ -71967,7 +74137,7 @@ var ts; ts.servicesVersion = "0.5"; var ruleProvider; function createNode(kind, pos, end, parent) { - var node = kind >= 143 ? new NodeObject(kind, pos, end) : + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; @@ -72012,10 +74182,11 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { + NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var token = ts.scanner.scan(); + ts.Debug.assert(token !== 1); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -72025,7 +74196,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(294, nodes.pos, nodes.end, this); + var list = createNode(286, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -72043,43 +74214,44 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143) { - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; - var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 283 && this.kind <= 293; - var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); - } - children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } - }; - var processNodes = function (nodes) { - if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); - } - children.push(_this.createSyntaxList(nodes)); - pos_3 = nodes.end; - }; - if (this.jsDoc) { - for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - processNode(jsDocComment); - } - } - pos_3 = this.pos; - ts.forEachChild(this, processNode, processNodes); - if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); - } - ts.scanner.setText(undefined); + if (!ts.isNodeKind(this.kind)) { + this._children = ts.emptyArray; + return; } - this._children = children || ts.emptyArray; + if (ts.isJSDocCommentContainingNode(this)) { + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + return; + } + var children = []; + ts.scanner.setText((sourceFile || this.getSourceFile()).text); + var pos = this.pos; + var processNode = function (node) { + pos = _this.addSyntheticNodes(children, pos, node.pos); + children.push(node); + pos = node.end; + }; + var processNodes = function (nodes) { + if (pos < nodes.pos) { + pos = _this.addSyntheticNodes(children, pos, nodes.pos); + } + children.push(_this.createSyntaxList(nodes)); + pos = nodes.end; + }; + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + processNode(jsDocComment); + } + } + pos = this.pos; + ts.forEachChild(this, processNode, processNodes); + if (pos < this.end) { + this.addSyntheticNodes(children, pos, this.end); + } + ts.scanner.setText(undefined); + this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -72101,7 +74273,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 || kid.kind > 293; }); + var child = ts.find(children, function (kid) { return kid.kind < 267 || kid.kind > 285; }); return child.kind < 143 ? child : child.getFirstToken(sourceFile); @@ -72176,11 +74348,21 @@ var ts; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; } SymbolObject.prototype.getFlags = function () { return this.flags; }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedName); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; SymbolObject.prototype.getName = function () { return this.name; }; @@ -72215,6 +74397,13 @@ var ts; function IdentifierObject(_kind, pos, end) { return _super.call(this, pos, end) || this; } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedText); + }, + enumerable: true, + configurable: true + }); return IdentifierObject; }(TokenOrIdentifierObject)); IdentifierObject.prototype.kind = 71; @@ -72346,26 +74535,16 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_9 = ts.getTextOfIdentifierOrLiteral(name); + if (result_9 !== undefined) { + return result_9; } if (name.kind === 144) { var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } - return getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; - } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 || - node.kind === 9 || - node.kind === 8) { - return node.text; + return ts.getTextOfIdentifierOrLiteral(expr); } } return undefined; @@ -72401,7 +74580,6 @@ var ts; case 237: case 246: case 242: - case 237: case 239: case 240: case 153: @@ -72421,8 +74599,9 @@ var ts; ts.forEachChild(decl.name, visit); break; } - if (decl.initializer) + if (decl.initializer) { visit(decl.initializer); + } } case 264: case 149: @@ -72457,6 +74636,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); + var SourceMapSourceObject = (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); function getServicesObjectAllocator() { return { getNodeConstructor: function () { return NodeObject; }, @@ -72466,6 +74656,7 @@ var ts; getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, }; } function toEditorSettings(optionsAsMap) { @@ -72513,9 +74704,8 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = ts.createFileMap(); + this.fileNameToEntry = ts.createMap(); var rootFileNames = host.getScriptFileNames(); for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { var fileName = rootFileNames_1[_i]; @@ -72540,24 +74730,20 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { - return this.fileNameToEntry.contains(path); - }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); + HostCache.prototype.containsEntryByPath = function (path) { + return this.fileNameToEntry.has(path); }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (_path, value) { + this.fileNameToEntry.forEach(function (value) { if (value) { fileNames.push(value.hostFileName); } @@ -72565,11 +74751,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -72764,11 +74950,18 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -72843,7 +75036,15 @@ var ts; return false; } } - return ts.compareDataObjects(program.getCompilerOptions(), hostCache.compilationSettings()); + var currentOptions = program.getCompilerOptions(); + var newOptions = hostCache.compilationSettings(); + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; } } function getProgram() { @@ -72858,7 +75059,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } function getSyntacticDiagnostics(fileName) { synchronizeHostData(); @@ -72893,7 +75096,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -72913,8 +75116,8 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ts.ScriptElementKind.unknown, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "", + kindModifiers: "", textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, @@ -72974,7 +75177,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === "writtenReference", isDefinition: false, isInString: highlightSpan.isInString, }); @@ -73006,12 +75209,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; - function writeFile(fileName, data, writeByteOrderMark) { - outputFiles.push({ - name: fileName, - writeByteOrderMark: writeByteOrderMark, - text: data - }); + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); @@ -73033,7 +75232,7 @@ var ts; } function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, false); if (node === sourceFile) { return; } @@ -73113,7 +75312,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); if (matchKind) { @@ -73173,7 +75372,10 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "}") { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { @@ -73187,27 +75389,13 @@ var ts; function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var span = { start: start, length: end - start }; - var newLineChar = ts.getNewLineOrDefaultFromHost(host); - var allFixes = []; - ts.forEach(ts.deduplicate(errorCodes), function (error) { + var span = ts.createTextSpanFromBounds(start, end); + var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); + var rulesProvider = getRuleProvider(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - var context = { - errorCode: error, - sourceFile: sourceFile, - span: span, - program: program, - newLineCharacter: newLineChar, - host: host, - cancellationToken: cancellationToken, - rulesProvider: getRuleProvider(formatOptions) - }; - var fixes = ts.codefix.getFixes(context); - if (fixes) { - allFixes = allFixes.concat(fixes); - } + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); - return allFixes; } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); @@ -73226,6 +75414,12 @@ var ts; if (ts.isInTemplateString(sourceFile, position)) { return false; } + switch (openingBrace) { + case 39: + case 34: + case 96: + return !ts.isInComment(sourceFile, position); + } return true; } function getTodoComments(fileName, descriptors) { @@ -73234,7 +75428,7 @@ var ts; cancellationToken.throwIfCancellationRequested(); var fileContents = sourceFile.text; var result = []; - if (descriptors.length > 0) { + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { var regExp = getTodoCommentsRegExp(); var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { @@ -73257,11 +75451,7 @@ var ts; continue; } var message = matchArray[2]; - result.push({ - descriptor: descriptor, - message: message, - position: matchPosition - }); + result.push({ descriptor: descriptor, message: message, position: matchPosition }); } } return result; @@ -73285,6 +75475,10 @@ var ts; (char >= 65 && char <= 90) || (char >= 48 && char <= 57); } + function isNodeModulesFile(path) { + var node_modulesFolderName = "/node_modules/"; + return path.indexOf(node_modulesFolderName) !== -1; + } } function getRenameInfo(fileName, position) { synchronizeHostData(); @@ -73308,18 +75502,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); } - function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, - getApplicableRefactors: getApplicableRefactors, - getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -73357,7 +75549,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, - getProgram: getProgram + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, }; } ts.createLanguageService = createLanguageService; @@ -73369,36 +75563,26 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); - walk(sourceFile); - sourceFile.nameTable = nameTable; - function walk(node) { - switch (node.kind) { - case 71: - setNameTable(node.text, node); - break; - case 9: - case 8: - if (ts.isDeclarationName(node) || - node.parent.kind === 248 || - isArgumentOfElementAccessExpression(node) || - ts.isLiteralComputedPropertyDeclarationName(node)) { - setNameTable(node.text, node); - } - break; - default: - ts.forEachChild(node, walk); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - ts.forEachChild(jsDoc, walk); - } - } + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } - } - function setNameTable(text, node) { - nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); - } + ts.forEachChild(node, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 248 || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { @@ -73431,22 +75615,22 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.getTextOfPropertyName(node.name); + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); if (name && contextualType) { - var result_9 = []; + var result_10 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_10.push(symbol); } }); - return result_9; + return result_10; } if (symbol) { - result_9.push(symbol); - return result_9; + result_10.push(symbol); + return result_10; } } return undefined; @@ -73634,23 +75818,8 @@ var ts; } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - try { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - } - catch (e) { - var results = []; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { - var file = _b[_a]; - if (!ts.contains(results, file)) { - results.push(file); - } - } - } - return results; - } + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -73658,9 +75827,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; - CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { - return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); - }; CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { return JSON.parse(this.shimHost.getDirectories(path)); }; @@ -73983,7 +76149,7 @@ 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) { + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" && result.resolvedModule.extension !== ".tsx" && result.resolvedModule.extension !== ".d.ts") { resolvedFileName = undefined; } return { @@ -74043,24 +76209,15 @@ var ts; var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseConfigFileTextToJson(fileName, text); - if (result.error) { - return { - options: {}, - typeAcquisition: {}, - files: [], - raw: {}, - errors: [realizeDiagnostic(result.error, "\r\n")] - }; - } + var result = ts.parseJsonText(fileName, text); var normalizedFileName = ts.normalizeSlashes(fileName); - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); return { options: configFile.options, typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, - errors: realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") }; }); }; @@ -74072,7 +76229,10 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -74118,7 +76278,7 @@ var ts; } }; TypeScriptServicesFactory.prototype.close = function () { - this._shims = []; + ts.clear(this._shims); this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { @@ -74147,7 +76307,7 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.4"; +var toolsVersion = "2.5"; var ts; (function (ts) { var server; @@ -74163,6 +76323,7 @@ var ts; Arguments.LogFile = "--logFile"; Arguments.EnableTelemetry = "--enableTelemetry"; Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.NpmLocation = "--npmLocation"; })(Arguments = server.Arguments || (server.Arguments = {})); function hasArgument(argumentName) { return ts.sys.args.indexOf(argumentName) >= 0; @@ -74188,7 +76349,7 @@ var ts; LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; LogLevel[LogLevel["verbose"] = 3] = "verbose"; })(LogLevel = server.LogLevel || (server.LogLevel = {})); - server.emptyArray = []; + server.emptyArray = createSortedArray(); var Msg; (function (Msg) { Msg.Err = "Err"; @@ -74209,7 +76370,7 @@ var ts; function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), - fileNames: project.getFileNames(true), + fileNames: project.getFileNames(true, true), compilerOptions: project.getCompilerOptions(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, @@ -74266,22 +76427,6 @@ var ts; } } server.mergeMapLikes = mergeMapLikes; - function removeItemFromSet(items, itemToRemove) { - if (items.length === 0) { - return; - } - var index = items.indexOf(itemToRemove); - if (index < 0) { - return; - } - if (index === items.length - 1) { - items.pop(); - } - else { - items[index] = items.pop(); - } - } - server.removeItemFromSet = removeItemFromSet; function toNormalizedPath(fileName) { return ts.normalizePath(fileName); } @@ -74321,11 +76466,46 @@ var ts; return "/dev/null/inferredProject" + counter + "*"; } server.makeInferredProjectName = makeInferredProjectName; - function toSortedReadonlyArray(arr) { - arr.sort(); + function createSortedArray() { + return []; + } + server.createSortedArray = createSortedArray; + function toSortedArray(arr, comparer) { + arr.sort(comparer); return arr; } - server.toSortedReadonlyArray = toSortedReadonlyArray; + server.toSortedArray = toSortedArray; + function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { + compare = compare || ts.compareValues; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = compare(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; var ThrottledOperations = (function () { function ThrottledOperations(host) { this.host = host; @@ -74370,6 +76550,154 @@ var ts; return GcTimer; }()); server.GcTimer = GcTimer; + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = ts.binarySearch(array, insert, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + server.insertSorted = insertSorted; + function removeSorted(array, remove, compare) { + if (!array || array.length === 0) { + return; + } + if (array[0] === remove) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, remove, compare); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + } + server.removeSorted = removeSorted; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var protocol; + (function (protocol) { + var CommandTypes; + (function (CommandTypes) { + CommandTypes["Brace"] = "brace"; + CommandTypes["BraceFull"] = "brace-full"; + CommandTypes["BraceCompletion"] = "braceCompletion"; + CommandTypes["Change"] = "change"; + CommandTypes["Close"] = "close"; + CommandTypes["Completions"] = "completions"; + CommandTypes["CompletionsFull"] = "completions-full"; + CommandTypes["CompletionDetails"] = "completionEntryDetails"; + CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; + CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; + CommandTypes["Configure"] = "configure"; + CommandTypes["Definition"] = "definition"; + CommandTypes["DefinitionFull"] = "definition-full"; + CommandTypes["Implementation"] = "implementation"; + CommandTypes["ImplementationFull"] = "implementation-full"; + CommandTypes["Exit"] = "exit"; + CommandTypes["Format"] = "format"; + CommandTypes["Formatonkey"] = "formatonkey"; + CommandTypes["FormatFull"] = "format-full"; + CommandTypes["FormatonkeyFull"] = "formatonkey-full"; + CommandTypes["FormatRangeFull"] = "formatRange-full"; + CommandTypes["Geterr"] = "geterr"; + CommandTypes["GeterrForProject"] = "geterrForProject"; + CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; + CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; + CommandTypes["NavBar"] = "navbar"; + CommandTypes["NavBarFull"] = "navbar-full"; + CommandTypes["Navto"] = "navto"; + CommandTypes["NavtoFull"] = "navto-full"; + CommandTypes["NavTree"] = "navtree"; + CommandTypes["NavTreeFull"] = "navtree-full"; + CommandTypes["Occurrences"] = "occurrences"; + CommandTypes["DocumentHighlights"] = "documentHighlights"; + CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full"; + CommandTypes["Open"] = "open"; + CommandTypes["Quickinfo"] = "quickinfo"; + CommandTypes["QuickinfoFull"] = "quickinfo-full"; + CommandTypes["References"] = "references"; + CommandTypes["ReferencesFull"] = "references-full"; + CommandTypes["Reload"] = "reload"; + CommandTypes["Rename"] = "rename"; + CommandTypes["RenameInfoFull"] = "rename-full"; + CommandTypes["RenameLocationsFull"] = "renameLocations-full"; + CommandTypes["Saveto"] = "saveto"; + CommandTypes["SignatureHelp"] = "signatureHelp"; + CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; + CommandTypes["TypeDefinition"] = "typeDefinition"; + CommandTypes["ProjectInfo"] = "projectInfo"; + CommandTypes["ReloadProjects"] = "reloadProjects"; + CommandTypes["Unknown"] = "unknown"; + CommandTypes["OpenExternalProject"] = "openExternalProject"; + CommandTypes["OpenExternalProjects"] = "openExternalProjects"; + CommandTypes["CloseExternalProject"] = "closeExternalProject"; + CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList"; + CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; + CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; + CommandTypes["Cleanup"] = "cleanup"; + CommandTypes["OutliningSpans"] = "outliningSpans"; + CommandTypes["TodoComments"] = "todoComments"; + CommandTypes["Indentation"] = "indentation"; + CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; + CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; + CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; + CommandTypes["BreakpointStatement"] = "breakpointStatement"; + CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; + CommandTypes["GetCodeFixes"] = "getCodeFixes"; + CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; + CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; + CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; + CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; + CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; + })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle["None"] = "None"; + IndentStyle["Block"] = "Block"; + IndentStyle["Smart"] = "Smart"; + })(IndentStyle = protocol.IndentStyle || (protocol.IndentStyle = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit["None"] = "None"; + JsxEmit["Preserve"] = "Preserve"; + JsxEmit["ReactNative"] = "ReactNative"; + JsxEmit["React"] = "React"; + })(JsxEmit = protocol.JsxEmit || (protocol.JsxEmit = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind["None"] = "None"; + ModuleKind["CommonJS"] = "CommonJS"; + ModuleKind["AMD"] = "AMD"; + ModuleKind["UMD"] = "UMD"; + ModuleKind["System"] = "System"; + ModuleKind["ES6"] = "ES6"; + ModuleKind["ES2015"] = "ES2015"; + })(ModuleKind = protocol.ModuleKind || (protocol.ModuleKind = {})); + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind["Classic"] = "Classic"; + ModuleResolutionKind["Node"] = "Node"; + })(ModuleResolutionKind = protocol.ModuleResolutionKind || (protocol.ModuleResolutionKind = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind["Crlf"] = "Crlf"; + NewLineKind["Lf"] = "Lf"; + })(NewLineKind = protocol.NewLineKind || (protocol.NewLineKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget["ES3"] = "ES3"; + ScriptTarget["ES5"] = "ES5"; + ScriptTarget["ES6"] = "ES6"; + ScriptTarget["ES2015"] = "ES2015"; + })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); + })(protocol = server.protocol || (server.protocol = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -74433,33 +76761,22 @@ var ts; return ts.createTextSpanFromBounds(start, end); } var index = this.svc.getSnapshot().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); + var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; + var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; + return ts.createTextSpan(absolutePosition, len); }; TextStorage.prototype.lineOffsetToPosition = function (line, offset) { if (!this.svc) { - return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1); + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); } - var index = this.svc.getSnapshot().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); + return this.svc.getSnapshot().index.absolutePositionOfStartOfLine(line) + (offset - 1); }; TextStorage.prototype.positionToLineOffset = function (position) { if (!this.svc) { var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; return { line: line + 1, offset: character + 1 }; } - var index = this.svc.getSnapshot().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return this.svc.getSnapshot().index.positionToLineOffset(position); }; TextStorage.prototype.getFileText = function (tempFileName) { return this.host.readFile(tempFileName || this.fileName) || ""; @@ -74469,7 +76786,7 @@ var ts; }; TextStorage.prototype.switchToScriptVersionCache = function (newText) { if (!this.svc) { - this.svc = server.ScriptVersionCache.fromString(this.host, newText !== undefined ? newText : this.getOrLoadText()); + this.svc = server.ScriptVersionCache.fromString(newText !== undefined ? newText : this.getOrLoadText()); this.svcVersion++; this.text = undefined; } @@ -74566,7 +76883,7 @@ var ts; } break; default: - server.removeItemFromSet(this.containingProjects, project); + ts.unorderedRemoveItem(this.containingProjects, project); break; } }; @@ -74575,7 +76892,7 @@ var ts; var p = _a[_i]; p.removeFile(this, false); } - this.containingProjects.length = 0; + ts.clear(this.containingProjects); }; ScriptInfo.prototype.getDefaultProject = function () { switch (this.containingProjects.length) { @@ -74681,8 +76998,8 @@ var ts; this.host = host; this.project = project; this.cancellationToken = cancellationToken; - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); + this.resolvedModuleNames = ts.createMap(); + this.resolvedTypeReferenceDirectives = ts.createMap(); this.cancellationToken = new ts.ThrottledCancellationToken(cancellationToken, project.projectService.throttleWaitMilliseconds); this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); if (host.trace) { @@ -74693,7 +77010,7 @@ var ts; ? _this.project.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); - if (ts.moduleHasNonRelativeName(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { + if (!ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { var _a = ts.loadModuleFromGlobalCache(moduleName, _this.project.getProjectName(), compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (resolvedModule) { return { resolvedModule: resolvedModule, failedLookupLocations: primaryResult.failedLookupLocations.concat(failedLookupLocations) }; @@ -74705,6 +77022,10 @@ var ts; this.realpath = function (path) { return _this.host.realpath(path); }; } } + LSHost.prototype.dispose = function () { + this.project = undefined; + this.resolveModuleName = undefined; + }; LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { this.filesWithChangedSetOfUnresolvedImports = []; }; @@ -74821,8 +77142,9 @@ var ts; LSHost.prototype.resolvePath = function (path) { return this.host.resolvePath(path); }; - LSHost.prototype.fileExists = function (path) { - return this.host.fileExists(path); + LSHost.prototype.fileExists = function (file) { + var path = ts.toPath(file, this.host.getCurrentDirectory(), this.getCanonicalFileName); + return !this.project.isWatchedMissingFile(path) && this.host.fileExists(file); }; LSHost.prototype.readFile = function (fileName) { return this.host.readFile(fileName); @@ -74830,15 +77152,15 @@ var ts; LSHost.prototype.directoryExists = function (path) { return this.host.directoryExists(path); }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); + LSHost.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + return this.host.readDirectory(path, extensions, exclude, include, depth); }; LSHost.prototype.getDirectories = function (path) { return this.host.getDirectories(path); }; LSHost.prototype.notifyFileRemoved = function (info) { - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); + this.resolvedModuleNames.delete(info.path); + this.resolvedTypeReferenceDirectives.delete(info.path); }; LSHost.prototype.setCompilationSettings = function (opt) { if (ts.changesAffectModuleResolution(this.compilationSettings, opt)) { @@ -74942,7 +77264,7 @@ var ts; this.perProjectCache.set(projectName, { compilerOptions: compilerOptions, typeAcquisition: typeAcquisition, - typings: server.toSortedReadonlyArray(newTypings), + typings: server.toSortedArray(newTypings), unresolvedImports: unresolvedImports, poisoned: false }); @@ -75017,7 +77339,10 @@ var ts; this.ctor = ctor; } AbstractBuilder.prototype.getFileInfos = function () { - return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createFileMap()); + return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createMap()); + }; + AbstractBuilder.prototype.hasFileInfos = function () { + return !!this.fileInfos_doNotAccessDirectly; }; AbstractBuilder.prototype.clear = function () { this.fileInfos_doNotAccessDirectly = undefined; @@ -75035,18 +77360,19 @@ var ts; return fileInfo; }; AbstractBuilder.prototype.getFileInfoPaths = function () { - return this.getFileInfos().getKeys(); + return ts.arrayFrom(this.getFileInfos().keys()); }; AbstractBuilder.prototype.setFileInfo = function (path, info) { this.getFileInfos().set(path, info); }; AbstractBuilder.prototype.removeFileInfo = function (path) { - this.getFileInfos().remove(path); + this.getFileInfos().delete(path); }; AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.getFileInfos().forEachValue(function (_path, value) { return action(value); }); + this.getFileInfos().forEach(action); }; AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + this.ensureFileInfoIfInProject(scriptInfo); var fileInfo = this.getFileInfo(scriptInfo.path); if (!fileInfo) { return false; @@ -75071,7 +77397,20 @@ var ts; _this.project = project; return _this; } + NonModuleBuilder.prototype.ensureFileInfoIfInProject = function (scriptInfo) { + if (this.project.containsScriptInfo(scriptInfo)) { + this.getOrCreateFileInfo(scriptInfo.path); + } + }; NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + var _this = this; + if (this.hasFileInfos()) { + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + } }; NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { var info = this.getOrCreateFileInfo(scriptInfo.path); @@ -75091,50 +77430,25 @@ var ts; __extends(ModuleBuilderFileInfo, _super); function ModuleBuilderFileInfo() { var _this = _super !== null && _super.apply(this, arguments) || this; - _this.references = []; - _this.referencedBy = []; + _this.references = server.createSortedArray(); + _this.referencedBy = server.createSortedArray(); return _this; } ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { - var l = lf.scriptInfo.fileName; - var r = rf.scriptInfo.fileName; - return (l < r ? -1 : (l > r ? 1 : 0)); - }; - ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { - if (array.length === 0) { - array.push(fileInfo); - return; - } - var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (insertIndex < 0) { - array.splice(~insertIndex, 0, fileInfo); - } - }; - ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { - if (!array || array.length === 0) { - return; - } - if (array[0] === fileInfo) { - array.splice(0, 1); - return; - } - var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (removeIndex >= 0) { - array.splice(removeIndex, 1); - } + return ts.compareStrings(lf.scriptInfo.fileName, rf.scriptInfo.fileName); }; ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + server.insertSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); }; ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + server.removeSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); }; ModuleBuilderFileInfo.prototype.removeFileReferences = function () { for (var _i = 0, _a = this.references; _i < _a.length; _i++) { var reference = _a[_i]; reference.removeReferencedBy(this); } - this.references = []; + ts.clear(this.references); }; return ModuleBuilderFileInfo; }(BuilderFileInfo)); @@ -75152,16 +77466,18 @@ var ts; ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { var _this = this; if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return []; + return server.createSortedArray(); } var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); - if (referencedFilePaths.length > 0) { - return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); - } - return []; + return server.toSortedArray(referencedFilePaths.map(function (f) { return _this.getOrCreateFileInfo(f); }), ModuleBuilderFileInfo.compareFileInfos); + }; + ModuleBuilder.prototype.ensureFileInfoIfInProject = function (_scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); }; ModuleBuilder.prototype.onProjectUpdateGraph = function () { - this.ensureProjectDependencyGraphUpToDate(); + if (this.hasFileInfos()) { + this.ensureProjectDependencyGraphUpToDate(); + } }; ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { var _this = this; @@ -75187,31 +77503,9 @@ var ts; } var newReferences = this.getReferencedFileInfos(fileInfo); var oldReferences = fileInfo.references; - var oldIndex = 0; - var newIndex = 0; - while (oldIndex < oldReferences.length && newIndex < newReferences.length) { - var oldReference = oldReferences[oldIndex]; - var newReference = newReferences[newIndex]; - var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); - if (compare < 0) { - oldReference.removeReferencedBy(fileInfo); - oldIndex++; - } - else if (compare > 0) { - newReference.addReferencedBy(fileInfo); - newIndex++; - } - else { - oldIndex++; - newIndex++; - } - } - for (var i = oldIndex; i < oldReferences.length; i++) { - oldReferences[i].removeReferencedBy(fileInfo); - } - for (var i = newIndex; i < newReferences.length; i++) { - newReferences[i].addReferencedBy(fileInfo); - } + server.enumerateInsertsAndDeletes(newReferences, oldReferences, function (newReference) { return newReference.addReferencedBy(fileInfo); }, function (oldReference) { + oldReference.removeReferencedBy(fileInfo); + }, ModuleBuilderFileInfo.compareFileInfos); fileInfo.references = newReferences; fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); }; @@ -75276,12 +77570,6 @@ var ts; ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; ProjectKind[ProjectKind["External"] = 2] = "External"; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); - function remove(items, item) { - var index = items.indexOf(item); - if (index >= 0) { - items.splice(index, 1); - } - } function countEachFileTypes(infos) { var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { @@ -75305,6 +77593,7 @@ var ts; } return result; } + server.countEachFileTypes = countEachFileTypes; function hasOneOrMoreJsAndNoTsFiles(project) { var counts = countEachFileTypes(project.getScriptInfos()); return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; @@ -75321,7 +77610,7 @@ var ts; server.allFilesAreJsOrDts = allFilesAreJsOrDts; var UnresolvedImportsMap = (function () { function UnresolvedImportsMap() { - this.perFileMap = ts.createFileMap(); + this.perFileMap = ts.createMap(); this.version = 0; } UnresolvedImportsMap.prototype.clear = function () { @@ -75332,7 +77621,7 @@ var ts; return this.version; }; UnresolvedImportsMap.prototype.remove = function (path) { - this.perFileMap.remove(path); + this.perFileMap.delete(path); this.version++; }; UnresolvedImportsMap.prototype.get = function (path) { @@ -75354,7 +77643,8 @@ var ts; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; this.rootFiles = []; - this.rootFilesMap = ts.createFileMap(); + this.rootFilesMap = ts.createMap(); + this.missingFilesMap = ts.createMap(); this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); this.languageServiceEnabled = true; this.lastReportedVersion = 0; @@ -75405,7 +77695,10 @@ var ts; this.compilerOptions.noEmitForJsFiles = true; } }; - Project.prototype.getProjectErrors = function () { + Project.prototype.getGlobalProjectErrors = function () { + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }); + }; + Project.prototype.getAllProjectErrors = function () { return this.projectErrors; }; Project.prototype.getLanguageService = function (ensureSynchronized) { @@ -75444,7 +77737,7 @@ var ts; return this.projectName; }; Project.prototype.getExternalFiles = function () { - return []; + return server.emptyArray; }; Project.prototype.getSourceFile = function (path) { if (!this.program) { @@ -75474,7 +77767,15 @@ var ts; this.rootFiles = undefined; this.rootFilesMap = undefined; this.program = undefined; + this.builder = undefined; + this.cachedUnresolvedImportsPerFile = undefined; + this.projectErrors = undefined; + this.lsHost.dispose(); + this.lsHost = undefined; + this.missingFilesMap.forEach(function (fileWatcher) { return fileWatcher.close(); }); + this.missingFilesMap = undefined; this.languageService.dispose(); + this.languageService = undefined; }; Project.prototype.getCompilerOptions = function () { return this.compilerOptions; @@ -75525,7 +77826,7 @@ var ts; } return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); }; - Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries) { + Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries, excludeConfigFiles) { if (!this.program) { return []; } @@ -75547,8 +77848,39 @@ var ts; } result.push(server.asNormalizedPath(f.fileName)); } + if (!excludeConfigFiles) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + result.push(server.asNormalizedPath(configFile.fileName)); + if (configFile.extendedSourceFiles) { + for (var _b = 0, _c = configFile.extendedSourceFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(server.asNormalizedPath(f)); + } + } + } + } return result; }; + Project.prototype.hasConfigFile = function (configFilePath) { + if (this.program && this.languageServiceEnabled) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + if (configFilePath === server.asNormalizedPath(configFile.fileName)) { + return true; + } + if (configFile.extendedSourceFiles) { + for (var _i = 0, _a = configFile.extendedSourceFiles; _i < _a.length; _i++) { + var f = _a[_i]; + if (configFilePath === server.asNormalizedPath(f)) { + return true; + } + } + } + } + } + return false; + }; Project.prototype.getAllEmittableFiles = function () { if (!this.languageServiceEnabled) { return []; @@ -75574,7 +77906,7 @@ var ts; } }; Project.prototype.isRoot = function (info) { - return this.rootFilesMap && this.rootFilesMap.contains(info.path); + return this.rootFilesMap && this.rootFilesMap.has(info.path); }; Project.prototype.addRoot = function (info) { if (!this.isRoot(info)) { @@ -75597,7 +77929,7 @@ var ts; this.markAsDirty(); }; Project.prototype.registerFileUpdate = function (fileName) { - (this.updatedFileNames || (this.updatedFileNames = ts.createMap())).set(fileName, fileName); + (this.updatedFileNames || (this.updatedFileNames = ts.createMap())).set(fileName, true); }; Project.prototype.markAsDirty = function () { this.projectStateVersion++; @@ -75645,7 +77977,7 @@ var ts; var sourceFile = _b[_a]; this.extractUnresolvedImportsFromSourceFile(sourceFile, result); } - this.lastCachedUnresolvedImportsList = server.toSortedReadonlyArray(result); + this.lastCachedUnresolvedImportsList = server.toSortedArray(result); } unresolvedImports = this.lastCachedUnresolvedImportsList; var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); @@ -75672,11 +78004,11 @@ var ts; return true; }; Project.prototype.updateGraphWorker = function () { + var _this = this; var oldProgram = this.program; this.program = this.languageService.getProgram(); - var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { - hasChanges = true; + var hasChanges = !oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2)); + if (hasChanges) { if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; @@ -75689,9 +78021,49 @@ var ts; } } } + var missingFilePaths = this.program.getMissingFilePaths(); + var missingFilePathsSet_1 = ts.arrayToSet(missingFilePaths); + this.missingFilesMap.forEach(function (fileWatcher, missingFilePath) { + if (!missingFilePathsSet_1.has(missingFilePath)) { + _this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + } + }); + var _loop_8 = function (missingFilePath) { + if (!this_1.missingFilesMap.has(missingFilePath)) { + var fileWatcher_1 = this_1.projectService.host.watchFile(missingFilePath, function (_filename, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { + fileWatcher_1.close(); + _this.missingFilesMap.delete(missingFilePath); + _this.markAsDirty(); + _this.updateGraph(); + } + }); + this_1.missingFilesMap.set(missingFilePath, fileWatcher_1); + } + }; + var this_1 = this; + for (var _b = 0, missingFilePaths_1 = missingFilePaths; _b < missingFilePaths_1.length; _b++) { + var missingFilePath = missingFilePaths_1[_b]; + _loop_8(missingFilePath); + } } + var oldExternalFiles = this.externalFiles || server.emptyArray; + this.externalFiles = this.getExternalFiles(); + server.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, function (inserted) { + var scriptInfo = _this.projectService.getOrCreateScriptInfo(inserted, false); + scriptInfo.attachToProject(_this); + }, function (removed) { + var scriptInfoToDetach = _this.projectService.getScriptInfo(removed); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(_this); + } + }); return hasChanges; }; + Project.prototype.isWatchedMissingFile = function (path) { + return this.missingFilesMap.has(path); + }; Project.prototype.getScriptInfoLSHost = function (fileName) { var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); if (scriptInfo) { @@ -75716,7 +78088,7 @@ var ts; var strBuilder = ""; for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { var file = _a[_i]; - strBuilder += file.fileName + "\n"; + strBuilder += "\t" + file.fileName + "\n"; } return strBuilder; }; @@ -75755,13 +78127,13 @@ var ts; this.updatedFileNames = undefined; if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { if (this.projectStructureVersion === this.lastReportedVersion && !updatedFileNames) { - return { info: info, projectErrors: this.projectErrors }; + return { info: info, projectErrors: this.getGlobalProjectErrors() }; } var lastReportedFileNames_1 = this.lastReportedFileNames; - var currentFiles_1 = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var currentFiles_1 = ts.arrayToSet(this.getFileNames()); var added_1 = []; var removed_1 = []; - var updated = ts.arrayFrom(updatedFileNames.keys()); + var updated = updatedFileNames ? ts.arrayFrom(updatedFileNames.keys()) : []; ts.forEachKey(currentFiles_1, function (id) { if (!lastReportedFileNames_1.has(id)) { added_1.push(id); @@ -75774,13 +78146,13 @@ var ts; }); this.lastReportedFileNames = currentFiles_1; this.lastReportedVersion = this.projectStructureVersion; - return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.projectErrors }; + return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() }; } else { var projectFileNames = this.getFileNames(); - this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedFileNames = ts.arrayToSet(projectFileNames); this.lastReportedVersion = this.projectStructureVersion; - return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + return { info: info, files: projectFileNames, projectErrors: this.getGlobalProjectErrors() }; } }; Project.prototype.getReferencedFiles = function (path) { @@ -75829,8 +78201,8 @@ var ts; return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); }; Project.prototype.removeRoot = function (info) { - remove(this.rootFiles, info); - this.rootFilesMap.remove(info.path); + ts.orderedRemoveItem(this.rootFiles, info); + this.rootFilesMap.delete(info.path); }; return Project; }()); @@ -75850,7 +78222,7 @@ var ts; } }; InferredProject.prototype.setCompilerOptions = function (options) { - var newOptions = options ? ts.clone(options) : this.getCompilerOptions(); + var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilerOptions(); if (!newOptions) { return; } @@ -75898,16 +78270,16 @@ var ts; exclude: [] }; }; + InferredProject.newName = (function () { + var nextId = 1; + return function () { + var id = nextId; + nextId++; + return server.makeInferredProjectName(id); + }; + })(); return InferredProject; }(Project)); - InferredProject.newName = (function () { - var nextId = 1; - return function () { - var id = nextId; - nextId++; - return server.makeInferredProjectName(id); - }; - })(); server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); @@ -75944,15 +78316,15 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_6 = function (globalPluginName) { + var _loop_9 = function (globalPluginName) { if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; - this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); }; - var this_1 = this; + var this_2 = this; for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_6(globalPluginName); + _loop_9(globalPluginName); } } }; @@ -76005,19 +78377,17 @@ var ts; return this.typeAcquisition; }; ConfiguredProject.prototype.getExternalFiles = function () { - var items = []; - for (var _i = 0, _a = this.plugins; _i < _a.length; _i++) { - var plugin = _a[_i]; - if (typeof plugin.getExternalFiles === "function") { - try { - items.push.apply(items, plugin.getExternalFiles(this)); - } - catch (e) { - this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); - } + var _this = this; + return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.getExternalFiles !== "function") + return; + try { + return plugin.getExternalFiles(_this); } - } - return items; + catch (e) { + _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + } + })); }; ConfiguredProject.prototype.watchConfigFile = function (callback) { var _this = this; @@ -76068,6 +78438,7 @@ var ts; _super.prototype.close.call(this); if (this.projectFileWatcher) { this.projectFileWatcher.close(); + this.projectFileWatcher = undefined; } if (this.typeRootsWatchers) { for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { @@ -76150,6 +78521,7 @@ var ts; server.ContextEvent = "context"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + server.ProjectInfoTelemetryEvent = "projectInfo"; function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { var map = ts.createMap(); for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { @@ -76235,17 +78607,14 @@ var ts; } server.convertScriptKindName = convertScriptKindName; function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + var result = ts.flatMap(projects, action).sort(comparer); return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; } server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (_) { return undefined; }, - hasMixedContent: function (fileName, extraFileExtensions) { - var mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, function (item) { return item.isMixedContent; }), function (item) { return item.extension; }); - return ts.forEach(mixedContentExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } + hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, @@ -76305,13 +78674,15 @@ var ts; }()); var ProjectService = (function () { function ProjectService(opts) { - this.filenameToScriptInfo = ts.createFileMap(); + this.filenameToScriptInfo = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); this.externalProjects = []; this.inferredProjects = []; this.configuredProjects = []; this.openFiles = []; this.projectToSizeMap = ts.createMap(); + this.safelist = defaultTypeSafeList; + this.seenProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -76458,8 +78829,14 @@ var ts; } else { if (info && (!info.isScriptOpen())) { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); + if (info.containingProjects.length === 0) { + info.stopWatcher(); + this.filenameToScriptInfo.delete(info.path); + } + else { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } } } }; @@ -76467,7 +78844,7 @@ var ts; this.logger.info(info.fileName + " deleted"); info.stopWatcher(); if (!info.isScriptOpen()) { - this.filenameToScriptInfo.remove(info.path); + this.filenameToScriptInfo.delete(info.path); this.lastDeletedFile = info; var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); @@ -76541,15 +78918,15 @@ var ts; project.close(); switch (project.projectKind) { case server.ProjectKind.External: - server.removeItemFromSet(this.externalProjects, project); + ts.unorderedRemoveItem(this.externalProjects, project); this.projectToSizeMap.delete(project.externalProjectName); break; case server.ProjectKind.Configured: - server.removeItemFromSet(this.configuredProjects, project); + ts.unorderedRemoveItem(this.configuredProjects, project); this.projectToSizeMap.delete(project.canonicalConfigFilePath); break; case server.ProjectKind.Inferred: - server.removeItemFromSet(this.inferredProjects, project); + ts.unorderedRemoveItem(this.inferredProjects, project); break; } }; @@ -76603,7 +78980,7 @@ var ts; }; ProjectService.prototype.closeOpenFile = function (info) { info.close(); - server.removeItemFromSet(this.openFiles, info); + ts.unorderedRemoveItem(this.openFiles, info); var projectsToRemove; for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; @@ -76641,9 +79018,21 @@ var ts; } } } - if (info.containingProjects.length === 0) { - this.filenameToScriptInfo.remove(info.path); + if (this.host.fileExists(info.fileName)) { + this.watchClosedScriptInfo(info); } + else { + this.handleDeletedFile(info); + } + }; + ProjectService.prototype.deleteOrphanScriptInfoNotInAnyProject = function () { + var _this = this; + this.filenameToScriptInfo.forEach(function (info) { + if (!info.isScriptOpen() && info.containingProjects.length === 0) { + info.stopWatcher(); + _this.filenameToScriptInfo.delete(info.path); + } + }); }; ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName, projectRootPath) { var searchPath = ts.getDirectoryPath(fileName); @@ -76700,7 +79089,7 @@ var ts; this.logger.info("Open files: "); for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { var rootFile = _a[_i]; - this.logger.info(rootFile.fileName); + this.logger.info("\t" + rootFile.fileName); } this.logger.endGroup(); function printProjects(logger, projects, counter) { @@ -76730,27 +79119,27 @@ var ts; ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { configFilename = ts.normalizePath(configFilename); var configFileContent = this.host.readFile(configFilename); - var errors; - var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); - var config = result.config; - if (result.error) { - var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; - config = sanitizedConfig; - errors = diagnostics.length ? diagnostics : [result.error]; + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 }; } - var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + var errors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { - errors = ts.concatenate(errors, parsedCommandLine.errors); + errors.push.apply(errors, parsedCommandLine.errors); } ts.Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.fileNames.length === 0) { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); return { success: false, configFileErrors: errors }; } var projectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options, - configHasFilesProperty: config["files"] !== undefined, + configHasExtendsProperty: parsedCommandLine.raw["extends"] !== undefined, + configHasFilesProperty: parsedCommandLine.raw["files"] !== undefined, + configHasIncludeProperty: parsedCommandLine.raw["include"] !== undefined, + configHasExcludeProperty: parsedCommandLine.raw["exclude"] !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, compileOnSave: parsedCommandLine.compileOnSave @@ -76787,8 +79176,49 @@ var ts; var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typeAcquisition, undefined); this.externalProjects.push(project); + this.sendProjectTelemetry(project.externalProjectName, project); return project; }; + ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { + if (this.seenProjects.has(projectKey)) { + return; + } + this.seenProjects.set(projectKey, true); + if (!this.eventHandler) + return; + var data = { + projectId: this.host.createHash(projectKey), + fileStats: server.countEachFileTypes(project.getScriptInfos()), + compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilerOptions()), + typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), + extends: projectOptions && projectOptions.configHasExtendsProperty, + files: projectOptions && projectOptions.configHasFilesProperty, + include: projectOptions && projectOptions.configHasIncludeProperty, + exclude: projectOptions && projectOptions.configHasExcludeProperty, + compileOnSave: project.compileOnSaveEnabled, + configFileName: configFileName(), + projectType: project instanceof server.ExternalProject ? "external" : "configured", + languageServiceEnabled: project.languageServiceEnabled, + version: ts.version, + }; + this.eventHandler({ eventName: server.ProjectInfoTelemetryEvent, data: data }); + function configFileName() { + if (!(project instanceof server.ConfiguredProject)) { + return "other"; + } + var configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath(); + var base = ts.getBaseFileName(configFilePath); + return base === "tsconfig.json" || base === "jsconfig.json" ? base : "other"; + } + function convertTypeAcquisition(_a) { + var enable = _a.enable, include = _a.include, exclude = _a.exclude; + return { + enable: enable, + include: include !== undefined && include.length !== 0, + exclude: exclude !== undefined && exclude.length !== 0, + }; + } + }; ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { if (!this.eventHandler) { return; @@ -76810,6 +79240,7 @@ var ts; project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); this.configuredProjects.push(project); + this.sendProjectTelemetry(project.getConfigFilePath(), project, projectOptions); return project; }; ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { @@ -76841,12 +79272,12 @@ var ts; var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); var projectOptions = conversionResult.success ? conversionResult.projectOptions - : { files: [], compilerOptions: {}, typeAcquisition: { enable: false } }; + : { files: [], compilerOptions: {}, configHasExtendsProperty: false, configHasFilesProperty: false, configHasIncludeProperty: false, configHasExcludeProperty: false, typeAcquisition: { enable: false } }; var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); return { success: conversionResult.success, project: project, - errors: project.getProjectErrors() + errors: project.getGlobalProjectErrors() }; }; ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors) { @@ -76964,8 +79395,14 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; + if (!info.hasMixedContent) { + var fileName_2 = info.fileName; + info.setWatcher(this.host.watchFile(fileName_2, function (_) { return _this.onSourceFileChanged(fileName_2); })); + } + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { if (openedByClient || this.host.fileExists(fileName)) { @@ -76977,14 +79414,13 @@ var ts; } } else { - if (!hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); - } + this.watchClosedScriptInfo(info); } } } if (info) { if (openedByClient && !info.isScriptOpen()) { + info.stopWatcher(); info.open(fileContent); if (hasMixedContent) { info.registerFileUpdate(); @@ -77084,6 +79520,7 @@ var ts; } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; var _a; @@ -77096,13 +79533,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_7 = function (proj) { + var _loop_10 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_7(proj); + _loop_10(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -77205,7 +79642,7 @@ var ts; return filename.replace(this.filenameEscapeRegexp, "\\$&"); }; ProjectService.prototype.resetSafeList = function () { - ProjectService.safelist = defaultTypeSafeList; + this.safelist = defaultTypeSafeList; }; ProjectService.prototype.loadSafeList = function (fileName) { var raw = JSON.parse(this.host.readFile(fileName, "utf-8")); @@ -77213,7 +79650,7 @@ var ts; var k = _a[_i]; raw[k].match = new RegExp(raw[k].match, "i"); } - ProjectService.safelist = raw; + this.safelist = raw; }; ProjectService.prototype.applySafeList = function (proj) { var _this = this; @@ -77221,12 +79658,12 @@ var ts; var types = (typeAcquisition && typeAcquisition.include) || []; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); - var _loop_8 = function (name) { - var rule = ProjectService.safelist[name]; + var _loop_11 = function (name) { + var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; if (rule.match.test(root)) { - this_2.logger.info("Excluding files based on rule " + name); + this_3.logger.info("Excluding files based on rule " + name); if (rule.types) { for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { var type = _b[_a]; @@ -77236,7 +79673,7 @@ var ts; } } if (rule.exclude) { - var _loop_9 = function (exclude) { + var _loop_12 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -77259,7 +79696,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_9(exclude); + _loop_12(exclude); } } else { @@ -77275,10 +79712,10 @@ var ts; proj.typeAcquisition.include = types; } }; - var this_2 = this; - for (var _i = 0, _a = Object.keys(ProjectService.safelist); _i < _a.length; _i++) { + var this_3 = this; + for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_8(name); + _loop_11(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); proj.rootFiles = proj.rootFiles.filter(function (_file, index) { return !excludeRegexes.some(function (re) { return re.test(normalizedNames[index]); }); }); @@ -77374,10 +79811,9 @@ var ts; this.refreshInferredProjects(); } }; + ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; }()); - ProjectService.safelist = defaultTypeSafeList; - ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; server.ProjectService = ProjectService; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -77433,14 +79869,17 @@ var ts; source: diag.source }; } - function formatConfigFileDiag(diag) { - return { - start: undefined, - end: undefined, - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), - category: ts.DiagnosticCategory[diag.category].toLowerCase(), - source: diag.source - }; + function convertToLocation(lineAndCharacter) { + return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; + } + function formatConfigFileDiag(diag, includeFileName) { + var start = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start)); + var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)); + var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); + var code = diag.code, source = diag.source; + var category = ts.DiagnosticCategory[diag.category].toLowerCase(); + return includeFileName ? { start: start, end: end, text: text, code: code, category: category, source: source, fileName: diag.file && diag.file.fileName } : + { start: start, end: end, text: text, code: code, category: category, source: source }; } function allEditsBeforePos(edits, pos) { for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { @@ -77451,80 +79890,7 @@ var ts; } return true; } - var CommandNames; - (function (CommandNames) { - CommandNames.Brace = "brace"; - CommandNames.BraceFull = "brace-full"; - CommandNames.BraceCompletion = "braceCompletion"; - CommandNames.Change = "change"; - CommandNames.Close = "close"; - CommandNames.Completions = "completions"; - CommandNames.CompletionsFull = "completions-full"; - CommandNames.CompletionDetails = "completionEntryDetails"; - CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - CommandNames.Configure = "configure"; - CommandNames.Definition = "definition"; - CommandNames.DefinitionFull = "definition-full"; - CommandNames.Exit = "exit"; - CommandNames.Format = "format"; - CommandNames.Formatonkey = "formatonkey"; - CommandNames.FormatFull = "format-full"; - CommandNames.FormatonkeyFull = "formatonkey-full"; - CommandNames.FormatRangeFull = "formatRange-full"; - CommandNames.Geterr = "geterr"; - CommandNames.GeterrForProject = "geterrForProject"; - CommandNames.Implementation = "implementation"; - CommandNames.ImplementationFull = "implementation-full"; - CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - CommandNames.NavBar = "navbar"; - CommandNames.NavBarFull = "navbar-full"; - CommandNames.NavTree = "navtree"; - CommandNames.NavTreeFull = "navtree-full"; - CommandNames.Navto = "navto"; - CommandNames.NavtoFull = "navto-full"; - CommandNames.Occurrences = "occurrences"; - CommandNames.DocumentHighlights = "documentHighlights"; - CommandNames.DocumentHighlightsFull = "documentHighlights-full"; - CommandNames.Open = "open"; - CommandNames.Quickinfo = "quickinfo"; - CommandNames.QuickinfoFull = "quickinfo-full"; - CommandNames.References = "references"; - CommandNames.ReferencesFull = "references-full"; - CommandNames.Reload = "reload"; - CommandNames.Rename = "rename"; - CommandNames.RenameInfoFull = "rename-full"; - CommandNames.RenameLocationsFull = "renameLocations-full"; - CommandNames.Saveto = "saveto"; - CommandNames.SignatureHelp = "signatureHelp"; - CommandNames.SignatureHelpFull = "signatureHelp-full"; - CommandNames.TypeDefinition = "typeDefinition"; - CommandNames.ProjectInfo = "projectInfo"; - CommandNames.ReloadProjects = "reloadProjects"; - CommandNames.Unknown = "unknown"; - CommandNames.OpenExternalProject = "openExternalProject"; - CommandNames.OpenExternalProjects = "openExternalProjects"; - CommandNames.CloseExternalProject = "closeExternalProject"; - CommandNames.SynchronizeProjectList = "synchronizeProjectList"; - CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - CommandNames.Cleanup = "cleanup"; - CommandNames.OutliningSpans = "outliningSpans"; - CommandNames.TodoComments = "todoComments"; - CommandNames.Indentation = "indentation"; - CommandNames.DocCommentTemplate = "docCommentTemplate"; - CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; - CommandNames.BreakpointStatement = "breakpointStatement"; - CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - 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 = {})); + server.CommandNames = server.protocol.CommandTypes; function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); var json = JSON.stringify(msg); @@ -77537,13 +79903,8 @@ var ts; server.formatMessage = formatMessage; var MultistepOperation = (function () { function MultistepOperation(operationHost) { - var _this = this; this.operationHost = operationHost; this.completed = true; - this.next = { - immediate: function (action) { return _this.immediate(action); }, - delay: function (ms, action) { return _this.delay(ms, action); } - }; } MultistepOperation.prototype.startNew = function (action) { this.complete(); @@ -77586,7 +79947,7 @@ var ts; stop = true; } else { - action(this.next); + action(this); } } catch (e) { @@ -77621,19 +79982,19 @@ var ts; var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, - _a[CommandNames.OpenExternalProject] = function (request) { + _a[server.CommandNames.OpenExternalProject] = function (request) { _this.projectService.openExternalProject(request.arguments, false); return _this.requiredResponse(true); }, - _a[CommandNames.OpenExternalProjects] = function (request) { + _a[server.CommandNames.OpenExternalProjects] = function (request) { _this.projectService.openExternalProjects(request.arguments.projects); return _this.requiredResponse(true); }, - _a[CommandNames.CloseExternalProject] = function (request) { + _a[server.CommandNames.CloseExternalProject] = function (request) { _this.projectService.closeExternalProject(request.arguments.projectFileName); return _this.requiredResponse(true); }, - _a[CommandNames.SynchronizeProjectList] = function (request) { + _a[server.CommandNames.SynchronizeProjectList] = function (request) { var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { return _this.requiredResponse(result); @@ -77651,220 +80012,220 @@ var ts; }); return _this.requiredResponse(converted); }, - _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); _this.changeSeq++; return _this.requiredResponse(true); }, - _a[CommandNames.Exit] = function () { + _a[server.CommandNames.Exit] = function () { _this.exit(); return _this.notRequired(); }, - _a[CommandNames.Definition] = function (request) { + _a[server.CommandNames.Definition] = function (request) { return _this.requiredResponse(_this.getDefinition(request.arguments, true)); }, - _a[CommandNames.DefinitionFull] = function (request) { + _a[server.CommandNames.DefinitionFull] = function (request) { return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, - _a[CommandNames.TypeDefinition] = function (request) { + _a[server.CommandNames.TypeDefinition] = function (request) { return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, - _a[CommandNames.Implementation] = function (request) { + _a[server.CommandNames.Implementation] = function (request) { return _this.requiredResponse(_this.getImplementation(request.arguments, true)); }, - _a[CommandNames.ImplementationFull] = function (request) { + _a[server.CommandNames.ImplementationFull] = function (request) { return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, - _a[CommandNames.References] = function (request) { + _a[server.CommandNames.References] = function (request) { return _this.requiredResponse(_this.getReferences(request.arguments, true)); }, - _a[CommandNames.ReferencesFull] = function (request) { + _a[server.CommandNames.ReferencesFull] = function (request) { return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, - _a[CommandNames.Rename] = function (request) { + _a[server.CommandNames.Rename] = function (request) { return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); }, - _a[CommandNames.RenameLocationsFull] = function (request) { + _a[server.CommandNames.RenameLocationsFull] = function (request) { return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); }, - _a[CommandNames.RenameInfoFull] = function (request) { + _a[server.CommandNames.RenameInfoFull] = function (request) { return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, - _a[CommandNames.Open] = function (request) { + _a[server.CommandNames.Open] = function (request) { _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); return _this.notRequired(); }, - _a[CommandNames.Quickinfo] = function (request) { + _a[server.CommandNames.Quickinfo] = function (request) { return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); }, - _a[CommandNames.QuickinfoFull] = function (request) { + _a[server.CommandNames.QuickinfoFull] = function (request) { return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); }, - _a[CommandNames.OutliningSpans] = function (request) { + _a[server.CommandNames.OutliningSpans] = function (request) { return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); }, - _a[CommandNames.TodoComments] = function (request) { + _a[server.CommandNames.TodoComments] = function (request) { return _this.requiredResponse(_this.getTodoComments(request.arguments)); }, - _a[CommandNames.Indentation] = function (request) { + _a[server.CommandNames.Indentation] = function (request) { return _this.requiredResponse(_this.getIndentation(request.arguments)); }, - _a[CommandNames.NameOrDottedNameSpan] = function (request) { + _a[server.CommandNames.NameOrDottedNameSpan] = function (request) { return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); }, - _a[CommandNames.BreakpointStatement] = function (request) { + _a[server.CommandNames.BreakpointStatement] = function (request) { return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); }, - _a[CommandNames.BraceCompletion] = function (request) { + _a[server.CommandNames.BraceCompletion] = function (request) { return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); }, - _a[CommandNames.DocCommentTemplate] = function (request) { + _a[server.CommandNames.DocCommentTemplate] = function (request) { return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, - _a[CommandNames.Format] = function (request) { + _a[server.CommandNames.Format] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, - _a[CommandNames.Formatonkey] = function (request) { + _a[server.CommandNames.Formatonkey] = function (request) { return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); }, - _a[CommandNames.FormatFull] = function (request) { + _a[server.CommandNames.FormatFull] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); }, - _a[CommandNames.FormatonkeyFull] = function (request) { + _a[server.CommandNames.FormatonkeyFull] = function (request) { return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); }, - _a[CommandNames.FormatRangeFull] = function (request) { + _a[server.CommandNames.FormatRangeFull] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, - _a[CommandNames.Completions] = function (request) { + _a[server.CommandNames.Completions] = function (request) { return _this.requiredResponse(_this.getCompletions(request.arguments, true)); }, - _a[CommandNames.CompletionsFull] = function (request) { + _a[server.CommandNames.CompletionsFull] = function (request) { return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, - _a[CommandNames.CompletionDetails] = function (request) { + _a[server.CommandNames.CompletionDetails] = function (request) { return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); }, - _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); }, - _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + _a[server.CommandNames.CompileOnSaveEmitFile] = function (request) { return _this.requiredResponse(_this.emitFile(request.arguments)); }, - _a[CommandNames.SignatureHelp] = function (request) { + _a[server.CommandNames.SignatureHelp] = function (request) { return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); }, - _a[CommandNames.SignatureHelpFull] = function (request) { + _a[server.CommandNames.SignatureHelpFull] = function (request) { return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); }, - _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + _a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); }, - _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + _a[server.CommandNames.EncodedSemanticClassificationsFull] = function (request) { return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); }, - _a[CommandNames.Cleanup] = function () { + _a[server.CommandNames.Cleanup] = function () { _this.cleanup(); return _this.requiredResponse(true); }, - _a[CommandNames.SemanticDiagnosticsSync] = function (request) { + _a[server.CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); }, - _a[CommandNames.SyntacticDiagnosticsSync] = function (request) { + _a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments)); }, - _a[CommandNames.Geterr] = function (request) { + _a[server.CommandNames.Geterr] = function (request) { _this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); }); return _this.notRequired(); }, - _a[CommandNames.GeterrForProject] = function (request) { + _a[server.CommandNames.GeterrForProject] = function (request) { _this.errorCheck.startNew(function (next) { return _this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file); }); return _this.notRequired(); }, - _a[CommandNames.Change] = function (request) { + _a[server.CommandNames.Change] = function (request) { _this.change(request.arguments); return _this.notRequired(); }, - _a[CommandNames.Configure] = function (request) { + _a[server.CommandNames.Configure] = function (request) { _this.projectService.setHostConfiguration(request.arguments); - _this.output(undefined, CommandNames.Configure, request.seq); + _this.output(undefined, server.CommandNames.Configure, request.seq); return _this.notRequired(); }, - _a[CommandNames.Reload] = function (request) { + _a[server.CommandNames.Reload] = function (request) { _this.reload(request.arguments, request.seq); return _this.requiredResponse({ reloadFinished: true }); }, - _a[CommandNames.Saveto] = function (request) { + _a[server.CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); return _this.notRequired(); }, - _a[CommandNames.Close] = function (request) { + _a[server.CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); return _this.notRequired(); }, - _a[CommandNames.Navto] = function (request) { + _a[server.CommandNames.Navto] = function (request) { return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); }, - _a[CommandNames.NavtoFull] = function (request) { + _a[server.CommandNames.NavtoFull] = function (request) { return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, - _a[CommandNames.Brace] = function (request) { + _a[server.CommandNames.Brace] = function (request) { return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); }, - _a[CommandNames.BraceFull] = function (request) { + _a[server.CommandNames.BraceFull] = function (request) { return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, - _a[CommandNames.NavBar] = function (request) { + _a[server.CommandNames.NavBar] = function (request) { return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); }, - _a[CommandNames.NavBarFull] = function (request) { + _a[server.CommandNames.NavBarFull] = function (request) { return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); }, - _a[CommandNames.NavTree] = function (request) { + _a[server.CommandNames.NavTree] = function (request) { return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); }, - _a[CommandNames.NavTreeFull] = function (request) { + _a[server.CommandNames.NavTreeFull] = function (request) { return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, - _a[CommandNames.Occurrences] = function (request) { + _a[server.CommandNames.Occurrences] = function (request) { return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, - _a[CommandNames.DocumentHighlights] = function (request) { + _a[server.CommandNames.DocumentHighlights] = function (request) { return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); }, - _a[CommandNames.DocumentHighlightsFull] = function (request) { + _a[server.CommandNames.DocumentHighlightsFull] = function (request) { return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); }, - _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + _a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) { _this.setCompilerOptionsForInferredProjects(request.arguments); return _this.requiredResponse(true); }, - _a[CommandNames.ProjectInfo] = function (request) { + _a[server.CommandNames.ProjectInfo] = function (request) { return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, - _a[CommandNames.ReloadProjects] = function () { + _a[server.CommandNames.ReloadProjects] = function () { _this.projectService.reloadProjects(); return _this.notRequired(); }, - _a[CommandNames.GetCodeFixes] = function (request) { + _a[server.CommandNames.GetCodeFixes] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); }, - _a[CommandNames.GetCodeFixesFull] = function (request) { + _a[server.CommandNames.GetCodeFixesFull] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); }, - _a[CommandNames.GetSupportedCodeFixes] = function () { + _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, - _a[CommandNames.GetApplicableRefactors] = function (request) { + _a[server.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[server.CommandNames.GetEditsForRefactor] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, true)); }, - _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { - return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + _a[server.CommandNames.GetEditsForRefactorFull] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, false)); }, _a)); this.host = opts.host; @@ -77916,21 +80277,30 @@ var ts; var _this = this; switch (event.eventName) { case server.ContextEvent: - var _a = event.data, project_1 = _a.project, fileName_2 = _a.fileName; - this.projectService.logger.info("got context event, updating diagnostics for " + fileName_2); - this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_2, project: project_1 }], _this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); }); + var _a = event.data, project_1 = _a.project, fileName_3 = _a.fileName; + this.projectService.logger.info("got context event, updating diagnostics for " + fileName_3); + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_3, project: project_1 }], _this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); }); break; case server.ConfigFileDiagEvent: var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); break; - case server.ProjectLanguageServiceStateEvent: + case server.ProjectLanguageServiceStateEvent: { var eventName = "projectLanguageServiceState"; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled }, eventName); break; + } + case server.ProjectInfoTelemetryEvent: { + var eventName = "telemetry"; + this.event({ + telemetryEventName: event.eventName, + payload: event.data, + }, eventName); + break; + } } }; Session.prototype.logError = function (err, cmd) { @@ -77953,7 +80323,7 @@ var ts; this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { - var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); + var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); var ev = { seq: 0, type: "event", @@ -78080,9 +80450,37 @@ var ts; Session.prototype.getProject = function (projectFileName) { return projectFileName && this.projectService.findProject(projectFileName); }; + Session.prototype.getConfigFileAndProject = function (args) { + var project = this.getProject(args.projectFileName); + var file = server.toNormalizedPath(args.file); + return { + configFile: project && project.hasConfigFile(file) && file, + project: project + }; + }; + Session.prototype.getConfigFileDiagnostics = function (configFile, project, includeLinePosition) { + var projectErrors = project.getAllProjectErrors(); + var optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); + var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return diagnostic.file && diagnostic.file.fileName === configFile; }); + return includeLinePosition ? + this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : + ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); }); + }; + Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start)), + endLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length)) + }); }); + }; Session.prototype.getCompilerOptionsDiagnostics = function (args) { var project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), undefined); }; Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { var _this = this; @@ -78195,9 +80593,17 @@ var ts; }); }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + return []; + } return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { + var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; + if (configFile) { + return this.getConfigFileDiagnostics(configFile, project, args.includeLinePosition); + } return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { @@ -78233,14 +80639,14 @@ var ts; this.projectService.setCompilerOptionsForInferredProjects(args.options); }; Session.prototype.getProjectInfo = function (args) { - return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); }; - Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames() : undefined + fileNames: needFileNameList ? project.getFileNames(false, excludeConfigFiles) : undefined }; return projectInfo; }; @@ -78309,21 +80715,22 @@ var ts; }; }); }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; + var locs = []; + for (var _i = 0, fileSpans_1 = fileSpans; _i < fileSpans_1.length; _i++) { + var cur = fileSpans_1[_i]; + var curFileAccum = void 0; + if (locs.length > 0) { + curFileAccum = locs[locs.length - 1]; if (curFileAccum.file !== cur.file) { curFileAccum = undefined; } } if (!curFileAccum) { curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + locs.push(curFileAccum); } curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); + } return { info: renameInfo, locs: locs }; } else { @@ -78536,31 +80943,28 @@ var ts; var formatOptions = this.projectService.getFormatCodeOptions(file); var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var lineInfo = scriptInfo.getLineInfo(args.line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) === " ") { - hasIndent++; - } - else if (lineText.charAt(i) === "\t") { - hasIndent += formatOptions.tabSize; - } - else { - break; - } + var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; + if (lineText && lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) === " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) - }); + else if (lineText.charAt(i) === "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = absolutePosition + i; + edits.push({ + span: ts.createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -78586,14 +80990,13 @@ var ts; return undefined; } if (simplifiedResult) { - return completions.entries.reduce(function (result, entry) { + return ts.mapDefined(completions.entries, function (entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; - result.push({ name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; } - return result; - }, []).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); + }).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } else { return completions; @@ -78603,13 +81006,9 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - return args.entryNames.reduce(function (accum, entryName) { - var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); - if (details) { - accum.push(details); - } - return accum; - }, []); + return ts.mapDefined(args.entryNames, function (entryName) { + return project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + }); }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { var info = this.projectService.getScriptInfo(args.file); @@ -78669,14 +81068,11 @@ var ts; }; Session.prototype.getDiagnostics = function (next, delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var checkList = ts.mapDefined(fileNames, function (uncheckedFileName) { var fileName = server.toNormalizedPath(uncheckedFileName); var project = _this.projectService.getDefaultProjectForFile(fileName, true); - if (project) { - accum.push({ fileName: fileName, project: project }); - } - return accum; - }, []); + return project && { fileName: fileName, project: project }; + }); if (checkList.length > 0) { this.updateErrorCheck(next, checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } @@ -78702,7 +81098,7 @@ var ts; if (project) { this.changeSeq++; if (project.reloadScript(file, tempFileName)) { - this.output(undefined, CommandNames.Reload, reqSeq); + this.output(undefined, server.CommandNames.Reload, reqSeq); } } }; @@ -78857,21 +81253,32 @@ var ts; 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) { + Session.prototype.getEditsForRefactor = 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) { + var result = project.getLanguageService().getEditsForRefactor(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); + if (result === undefined) { return { - actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + edits: [] + }; + } + if (simplifiedResult) { + var file_2 = result.renameFilename; + var location = void 0; + if (file_2 !== undefined && result.renameLocation !== undefined) { + var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(file_2)); + location = renameScriptInfo.positionToLineOffset(result.renameLocation); + } + return { + renameLocation: location, + renameFilename: file_2, + edits: result.edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) }; } else { - return { - actions: result - }; + return result; } }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { @@ -78922,6 +81329,14 @@ var ts; }); }) }; }; + Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { + var _this = this; + var scriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(textChanges.fileName)); + return { + fileName: textChanges.fileName, + textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }; + }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { start: scriptInfo.positionToLineOffset(change.span.start), @@ -78943,7 +81358,7 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { var _this = this; - var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -78956,18 +81371,22 @@ var ts; var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; - if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) + if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { highPriorityFiles.push(fileNameInProject); + } else { var info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isScriptOpen()) { - if (fileNameInProject.indexOf(".d.ts") > 0) + if (fileNameInProject.indexOf(".d.ts") > 0) { veryLowPriorityFiles.push(fileNameInProject); - else + } + else { lowPriorityFiles.push(fileNameInProject); + } } - else + else { mediumPriorityFiles.push(fileNameInProject); + } } } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); @@ -79020,7 +81439,7 @@ var ts; } else { this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); - this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); + this.output(undefined, server.CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; @@ -79059,7 +81478,7 @@ var ts; return; } this.logError(err, message); - this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); + this.output(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); } }; return Session; @@ -79081,32 +81500,25 @@ var ts; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; })(CharRangeSection = server.CharRangeSection || (server.CharRangeSection = {})); - var BaseLineIndexWalker = (function () { - function BaseLineIndexWalker() { - this.goSubtree = true; - this.done = false; - } - BaseLineIndexWalker.prototype.leaf = function (_rangeStart, _rangeLength, _ll) { - }; - return BaseLineIndexWalker; - }()); - var EditWalker = (function (_super) { - __extends(EditWalker, _super); + var EditWalker = (function () { function EditWalker() { - var _this = _super.call(this) || this; - _this.lineIndex = new LineIndex(); - _this.endBranch = []; - _this.state = CharRangeSection.Entire; - _this.initialText = ""; - _this.trailingText = ""; - _this.suppressTrailingText = false; - _this.lineIndex.root = new LineNode(); - _this.startPath = [_this.lineIndex.root]; - _this.stack = [_this.lineIndex.root]; - return _this; + this.goSubtree = true; + this.lineIndex = new LineIndex(); + this.endBranch = []; + this.state = CharRangeSection.Entire; + this.initialText = ""; + this.trailingText = ""; + this.lineIndex.root = new LineNode(); + this.startPath = [this.lineIndex.root]; + this.stack = [this.lineIndex.root]; } - EditWalker.prototype.insertLines = function (insertedText) { - if (this.suppressTrailingText) { + Object.defineProperty(EditWalker.prototype, "done", { + get: function () { return false; }, + enumerable: true, + configurable: true + }); + EditWalker.prototype.insertLines = function (insertedText, suppressTrailingText) { + if (suppressTrailingText) { this.trailingText = ""; } if (insertedText) { @@ -79119,7 +81531,7 @@ var ts; var lines = lm.lines; if (lines.length > 1) { if (lines[lines.length - 1] === "") { - lines.length--; + lines.pop(); } } var branchParent; @@ -79139,20 +81551,18 @@ var ts; if (lastZeroCount) { branchParent.remove(lastZeroCount); } - var insertionNode = this.startPath[this.startPath.length - 2]; var leafNode = this.startPath[this.startPath.length - 1]; - var len = lines.length; - if (len > 0) { + if (lines.length > 0) { leafNode.text = lines[0]; - if (len > 1) { - var insertedNodes = new Array(len - 1); + if (lines.length > 1) { + var insertedNodes = new Array(lines.length - 1); var startNode = leafNode; for (var i = 1; i < lines.length; i++) { insertedNodes[i - 1] = new LineLeaf(lines[i]); } var pathIndex = this.startPath.length - 2; while (pathIndex >= 0) { - insertionNode = this.startPath[pathIndex]; + var insertionNode = this.startPath[pathIndex]; insertedNodes = insertionNode.insertAt(startNode, insertedNodes); pathIndex--; startNode = insertionNode; @@ -79174,6 +81584,7 @@ var ts; } } else { + var insertionNode = this.startPath[this.startPath.length - 2]; insertionNode.remove(leafNode); for (var j = this.startPath.length - 2; j >= 0; j--) { this.startPath[j].updateCounts(); @@ -79185,8 +81596,7 @@ var ts; if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } - this.stack.length--; - return undefined; + this.stack.pop(); }; EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { var currentNode = this.stack[this.stack.length - 1]; @@ -79217,20 +81627,20 @@ var ts; else { child = fresh(lineCollection); currentNode.add(child); - this.startPath[this.startPath.length] = child; + this.startPath.push(child); } break; case CharRangeSection.Entire: if (this.state !== CharRangeSection.End) { child = fresh(lineCollection); currentNode.add(child); - this.startPath[this.startPath.length] = child; + this.startPath.push(child); } else { if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); - this.endBranch[this.endBranch.length] = child; + this.endBranch.push(child); } } break; @@ -79245,7 +81655,7 @@ var ts; if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); - this.endBranch[this.endBranch.length] = child; + this.endBranch.push(child); } } break; @@ -79257,9 +81667,8 @@ var ts; break; } if (this.goSubtree) { - this.stack[this.stack.length] = child; + this.stack.push(child); } - return lineCollection; }; EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { if (this.state === CharRangeSection.Start) { @@ -79274,7 +81683,7 @@ var ts; } }; return EditWalker; - }(BaseLineIndexWalker)); + }()); var TextChange = (function () { function TextChange(pos, deleteLen, insertedText) { this.pos = pos; @@ -79304,10 +81713,10 @@ var ts; return this.currentVersion % ScriptVersionCache.maxVersions; }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { - this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); - if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || - (deleteLen > ScriptVersionCache.changeLengthThreshold) || - (insertedText && (insertedText.length > ScriptVersionCache.changeLengthThreshold))) { + this.changes.push(new TextChange(pos, deleteLen, insertedText)); + if (this.changes.length > ScriptVersionCache.changeNumberThreshold || + deleteLen > ScriptVersionCache.changeLengthThreshold || + insertedText && insertedText.length > ScriptVersionCache.changeLengthThreshold) { this.getSnapshot(); } }; @@ -79320,22 +81729,14 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename) { - var content = this.host.readFile(filename); - if (!content) { - content = ""; - } - this.reload(content); - }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; - var snap = new LineIndexSnapshot(this.currentVersion, this); + var snap = new LineIndexSnapshot(this.currentVersion, this, new LineIndex()); for (var i = 0; i < this.versions.length; i++) { this.versions[i] = undefined; } this.versions[this.currentVersionToIndex()] = snap; - snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); this.minVersion = this.currentVersion; @@ -79348,9 +81749,7 @@ var ts; var change = _a[_i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); } - snap = new LineIndexSnapshot(this.currentVersion + 1, this); - snap.index = snapIndex; - snap.changesSincePreviousVersion = this.changes; + snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes); this.currentVersion = snap.version; this.versions[this.currentVersionToIndex()] = snap; this.changes = []; @@ -79368,7 +81767,7 @@ var ts; var snap = this.versions[this.versionToIndex(i)]; for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) { var textChange = _a[_i]; - textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); + textChangeRanges.push(textChange.getTextChangeRange()); } } return ts.collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges); @@ -79381,27 +81780,27 @@ var ts; return ts.unchangedTextChangeRange; } }; - ScriptVersionCache.fromString = function (host, script) { + ScriptVersionCache.fromString = function (script) { var svc = new ScriptVersionCache(); - var snap = new LineIndexSnapshot(0, svc); + var snap = new LineIndexSnapshot(0, svc, new LineIndex()); svc.versions[svc.currentVersion] = snap; - svc.host = host; - snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); return svc; }; + ScriptVersionCache.changeNumberThreshold = 8; + ScriptVersionCache.changeLengthThreshold = 256; + ScriptVersionCache.maxVersions = 8; return ScriptVersionCache; }()); - ScriptVersionCache.changeNumberThreshold = 8; - ScriptVersionCache.changeLengthThreshold = 256; - ScriptVersionCache.maxVersions = 8; server.ScriptVersionCache = ScriptVersionCache; var LineIndexSnapshot = (function () { - function LineIndexSnapshot(version, cache) { + function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) { + if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; } this.version = version; this.cache = cache; - this.changesSincePreviousVersion = []; + this.index = index; + this.changesSincePreviousVersion = changesSincePreviousVersion; } LineIndexSnapshot.prototype.getText = function (rangeStart, rangeEnd) { return this.index.getText(rangeStart, rangeEnd - rangeStart); @@ -79409,35 +81808,14 @@ var ts; LineIndexSnapshot.prototype.getLength = function () { return this.index.root.charCount(); }; - LineIndexSnapshot.prototype.getLineStartPositions = function () { - var starts = [-1]; - var count = 1; - var pos = 0; - this.index.every(function (ll) { - starts[count] = pos; - count++; - pos += ll.text.length; - return true; - }, 0); - return starts; - }; - LineIndexSnapshot.prototype.getLineMapper = function () { - var _this = this; - return function (line) { - return _this.index.lineNumberToInfo(line).offset; - }; - }; - LineIndexSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { - if (this.version <= scriptVersion) { - return ts.unchangedTextChangeRange; - } - else { - return this.cache.getTextChangesBetweenVersions(scriptVersion, this.version); - } - }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { - return this.getTextChangeRangeSinceVersion(oldSnapshot.version); + if (this.version <= oldSnapshot.version) { + return ts.unchangedTextChangeRange; + } + else { + return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version); + } } }; return LineIndexSnapshot; @@ -79447,21 +81825,24 @@ var ts; function LineIndex() { this.checkEdits = false; } - LineIndex.prototype.charOffsetToLineNumberAndPos = function (charOffset) { - return this.root.charOffsetToLineNumberAndPos(1, charOffset); + LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) { + return this.lineNumberToInfo(oneBasedLine).absolutePosition; }; - LineIndex.prototype.lineNumberToInfo = function (lineNumber) { + LineIndex.prototype.positionToLineOffset = function (position) { + var _a = this.root.charOffsetToLineInfo(1, position), oneBasedLine = _a.oneBasedLine, zeroBasedColumn = _a.zeroBasedColumn; + return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; + }; + LineIndex.prototype.positionToColumnAndLineText = function (position) { + return this.root.charOffsetToLineInfo(1, position); + }; + LineIndex.prototype.lineNumberToInfo = function (oneBasedLine) { var lineCount = this.root.lineCount(); - if (lineNumber <= lineCount) { - var lineInfo = this.root.lineNumberToInfo(lineNumber, 0); - lineInfo.line = lineNumber; - return lineInfo; + if (oneBasedLine <= lineCount) { + var _a = this.root.lineNumberToInfo(oneBasedLine, 0), position = _a.position, leaf = _a.leaf; + return { absolutePosition: position, lineText: leaf && leaf.text }; } else { - return { - line: lineNumber, - offset: this.root.charCount() - }; + return { absolutePosition: this.root.charCount(), lineText: undefined }; } }; LineIndex.prototype.load = function (lines) { @@ -79512,11 +81893,8 @@ var ts; return !walkFns.done; }; LineIndex.prototype.edit = function (pos, deleteLength, newText) { - function editFlat(source, s, dl, nt) { - if (nt === void 0) { nt = ""; } - return source.substring(0, s) + nt + source.substring(s + dl, source.length); - } if (this.root.charCount() === 0) { + ts.Debug.assert(deleteLength === 0); if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; @@ -79525,9 +81903,11 @@ var ts; else { var checkText = void 0; if (this.checkEdits) { - checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText); + var source = this.getText(0, this.root.charCount()); + checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength); } var walker = new EditWalker(); + var suppressTrailingText = false; if (pos >= this.root.charCount()) { pos = this.root.charCount() - 1; var endString = this.getText(pos, 1); @@ -79538,88 +81918,68 @@ var ts; newText = endString; } deleteLength = 0; - walker.suppressTrailingText = true; + suppressTrailingText = true; } else if (deleteLength > 0) { var e = pos + deleteLength; - var lineInfo = this.charOffsetToLineNumberAndPos(e); - if ((lineInfo && (lineInfo.offset === 0))) { - deleteLength += lineInfo.text.length; - if (newText) { - newText = newText + lineInfo.text; - } - else { - newText = lineInfo.text; - } + var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText; + if (zeroBasedColumn === 0) { + deleteLength += lineText.length; + newText = newText ? newText + lineText : lineText; } } - if (pos < this.root.charCount()) { - this.root.walk(pos, deleteLength, walker); - walker.insertLines(newText); - } + this.root.walk(pos, deleteLength, walker); + walker.insertLines(newText, suppressTrailingText); if (this.checkEdits) { - var updatedText = this.getText(0, this.root.charCount()); + var updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength()); ts.Debug.assert(checkText === updatedText, "buffer edit mismatch"); } return walker.lineIndex; } }; LineIndex.buildTreeFromBottom = function (nodes) { - var nodeCount = Math.ceil(nodes.length / lineCollectionCapacity); - var interiorNodes = []; + if (nodes.length < lineCollectionCapacity) { + return new LineNode(nodes); + } + var interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity)); var nodeIndex = 0; - for (var i = 0; i < nodeCount; i++) { - interiorNodes[i] = new LineNode(); - var charCount = 0; - var lineCount = 0; - for (var j = 0; j < lineCollectionCapacity; j++) { - if (nodeIndex < nodes.length) { - interiorNodes[i].add(nodes[nodeIndex]); - charCount += nodes[nodeIndex].charCount(); - lineCount += nodes[nodeIndex].lineCount(); - } - else { - break; - } - nodeIndex++; - } - interiorNodes[i].totalChars = charCount; - interiorNodes[i].totalLines = lineCount; - } - if (interiorNodes.length === 1) { - return interiorNodes[0]; - } - else { - return this.buildTreeFromBottom(interiorNodes); + for (var i = 0; i < interiorNodes.length; i++) { + var end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length); + interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end)); + nodeIndex = end; } + return this.buildTreeFromBottom(interiorNodes); }; LineIndex.linesFromText = function (text) { - var lineStarts = ts.computeLineStarts(text); - if (lineStarts.length === 0) { - return { lines: [], lineMap: lineStarts }; + var lineMap = ts.computeLineStarts(text); + if (lineMap.length === 0) { + return { lines: [], lineMap: lineMap }; } - var lines = new Array(lineStarts.length); - var lc = lineStarts.length - 1; + var lines = new Array(lineMap.length); + var lc = lineMap.length - 1; for (var lmi = 0; lmi < lc; lmi++) { - lines[lmi] = text.substring(lineStarts[lmi], lineStarts[lmi + 1]); + lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]); } - var endText = text.substring(lineStarts[lc]); + var endText = text.substring(lineMap[lc]); if (endText.length > 0) { lines[lc] = endText; } else { - lines.length--; + lines.pop(); } - return { lines: lines, lineMap: lineStarts }; + return { lines: lines, lineMap: lineMap }; }; return LineIndex; }()); server.LineIndex = LineIndex; var LineNode = (function () { - function LineNode() { + function LineNode(children) { + if (children === void 0) { children = []; } + this.children = children; this.totalChars = 0; this.totalLines = 0; - this.children = []; + if (children.length) + this.updateCounts(); } LineNode.prototype.isLeaf = function () { return false; @@ -79656,15 +82016,13 @@ var ts; }; LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) { var childIndex = 0; - var child = this.children[0]; - var childCharCount = child.charCount(); + var childCharCount = this.children[childIndex].charCount(); var adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); adjustedStart -= childCharCount; childIndex++; - child = this.children[childIndex]; - childCharCount = child.charCount(); + childCharCount = this.children[childIndex].charCount(); } if ((adjustedStart + rangeLength) <= childCharCount) { if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, CharRangeSection.Entire)) { @@ -79677,7 +82035,7 @@ var ts; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); childIndex++; - child = this.children[childIndex]; + var child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { @@ -79685,8 +82043,7 @@ var ts; } adjustedLength -= childCharCount; childIndex++; - child = this.children[childIndex]; - childCharCount = child.charCount(); + childCharCount = this.children[childIndex].charCount(); } if (adjustedLength > 0) { if (this.execWalk(0, adjustedLength, walkFns, childIndex, CharRangeSection.End)) { @@ -79703,97 +82060,77 @@ var ts; } } }; - LineNode.prototype.charOffsetToLineNumberAndPos = function (lineNumber, charOffset) { - var childInfo = this.childFromCharOffset(lineNumber, charOffset); + LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { + var childInfo = this.childFromCharOffset(lineNumberAccumulator, relativePosition); if (!childInfo.child) { return { - line: lineNumber, - offset: charOffset, + oneBasedLine: lineNumberAccumulator, + zeroBasedColumn: relativePosition, + lineText: undefined, }; } else if (childInfo.childIndex < this.children.length) { if (childInfo.child.isLeaf()) { return { - line: childInfo.lineNumber, - offset: childInfo.charOffset, - text: (childInfo.child).text, - leaf: (childInfo.child) + oneBasedLine: childInfo.lineNumberAccumulator, + zeroBasedColumn: childInfo.relativePosition, + lineText: childInfo.child.text, }; } else { var lineNode = (childInfo.child); - return lineNode.charOffsetToLineNumberAndPos(childInfo.lineNumber, childInfo.charOffset); + return lineNode.charOffsetToLineInfo(childInfo.lineNumberAccumulator, childInfo.relativePosition); } } else { var lineInfo = this.lineNumberToInfo(this.lineCount(), 0); - return { line: this.lineCount(), offset: lineInfo.leaf.charCount() }; + return { oneBasedLine: this.lineCount(), zeroBasedColumn: lineInfo.leaf.charCount(), lineText: undefined }; } }; - LineNode.prototype.lineNumberToInfo = function (lineNumber, charOffset) { - var childInfo = this.childFromLineNumber(lineNumber, charOffset); + LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { + var childInfo = this.childFromLineNumber(relativeOneBasedLine, positionAccumulator); if (!childInfo.child) { - return { - line: lineNumber, - offset: charOffset - }; + return { position: positionAccumulator, leaf: undefined }; } else if (childInfo.child.isLeaf()) { - return { - line: lineNumber, - offset: childInfo.charOffset, - text: (childInfo.child).text, - leaf: (childInfo.child) - }; + return { position: childInfo.positionAccumulator, leaf: childInfo.child }; } else { var lineNode = (childInfo.child); - return lineNode.lineNumberToInfo(childInfo.relativeLineNumber, childInfo.charOffset); + return lineNode.lineNumberToInfo(childInfo.relativeOneBasedLine, childInfo.positionAccumulator); } }; - LineNode.prototype.childFromLineNumber = function (lineNumber, charOffset) { + LineNode.prototype.childFromLineNumber = function (relativeOneBasedLine, positionAccumulator) { var child; - var relativeLineNumber = lineNumber; var i; - var len; - for (i = 0, len = this.children.length; i < len; i++) { + for (i = 0; i < this.children.length; i++) { child = this.children[i]; var childLineCount = child.lineCount(); - if (childLineCount >= relativeLineNumber) { + if (childLineCount >= relativeOneBasedLine) { break; } else { - relativeLineNumber -= childLineCount; - charOffset += child.charCount(); + relativeOneBasedLine -= childLineCount; + positionAccumulator += child.charCount(); } } - return { - child: child, - childIndex: i, - relativeLineNumber: relativeLineNumber, - charOffset: charOffset - }; + return { child: child, relativeOneBasedLine: relativeOneBasedLine, positionAccumulator: positionAccumulator }; }; - LineNode.prototype.childFromCharOffset = function (lineNumber, charOffset) { + LineNode.prototype.childFromCharOffset = function (lineNumberAccumulator, relativePosition) { var child; var i; var len; for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; - if (child.charCount() > charOffset) { + if (child.charCount() > relativePosition) { break; } else { - charOffset -= child.charCount(); - lineNumber += child.lineCount(); + relativePosition -= child.charCount(); + lineNumberAccumulator += child.lineCount(); } } - return { - child: child, - childIndex: i, - charOffset: charOffset, - lineNumber: lineNumber - }; + return { child: child, childIndex: i, relativePosition: relativePosition, lineNumberAccumulator: lineNumberAccumulator }; }; LineNode.prototype.splitAfter = function (childIndex) { var splitNode; @@ -79819,13 +82156,11 @@ var ts; this.children[i] = this.children[i + 1]; } } - this.children.length--; + this.children.pop(); }; LineNode.prototype.findChildIndex = function (child) { - var childIndex = 0; - var clen = this.children.length; - while ((this.children[childIndex] !== child) && (childIndex < clen)) - childIndex++; + var childIndex = this.children.indexOf(child); + ts.Debug.assert(childIndex !== -1); return childIndex; }; LineNode.prototype.insertAt = function (child, nodes) { @@ -79866,12 +82201,12 @@ var ts; } for (var i = splitNodes.length - 1; i >= 0; i--) { if (splitNodes[i].children.length === 0) { - splitNodes.length--; + splitNodes.pop(); } } } if (shiftNode) { - splitNodes[splitNodes.length] = shiftNode; + splitNodes.push(shiftNode); } this.updateCounts(); for (var i = 0; i < splitNodeCount; i++) { @@ -79881,8 +82216,8 @@ var ts; } }; LineNode.prototype.add = function (collection) { - this.children[this.children.length] = collection; - return (this.children.length < lineCollectionCapacity); + this.children.push(collection); + ts.Debug.assert(this.children.length <= lineCollectionCapacity); }; LineNode.prototype.charCount = function () { return this.totalChars; @@ -79930,13 +82265,15 @@ var ts; process.env.USERPROFILE || (process.env.HOMEDRIVE && process.env.HOMEPATH && ts.normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) || os.tmpdir(); - return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"); + return ts.combinePaths(ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"), ts.versionMajorMinor); } + case "openbsd": + case "freebsd": case "darwin": case "linux": case "android": { var cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin"); - return ts.combinePaths(cacheLocation, "typescript"); + return ts.combinePaths(ts.combinePaths(cacheLocation, "typescript"), ts.versionMajorMinor); } default: ts.Debug.fail("unsupported platform '" + process.platform + "'"); @@ -80016,7 +82353,7 @@ var ts; Logger.prototype.msg = function (s, type) { if (type === void 0) { type = server.Msg.Err; } if (this.fd >= 0 || this.traceToConsole) { - s = s + "\n"; + s = "[" + nowString() + "] " + s + "\n"; var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); if (this.firstInGroup) { s = prefix + s; @@ -80037,13 +82374,18 @@ var ts; }; return Logger; }()); + function nowString() { + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } var NodeTypingsInstaller = (function () { - function NodeTypingsInstaller(telemetryEnabled, logger, host, eventPort, globalTypingsCacheLocation, typingSafeListLocation, newLine) { + function NodeTypingsInstaller(telemetryEnabled, logger, host, eventPort, globalTypingsCacheLocation, typingSafeListLocation, npmLocation, newLine) { var _this = this; this.telemetryEnabled = telemetryEnabled; this.logger = logger; this.globalTypingsCacheLocation = globalTypingsCacheLocation; this.typingSafeListLocation = typingSafeListLocation; + this.npmLocation = npmLocation; this.newLine = newLine; this.installerPidReported = false; this.throttledOperations = new server.ThrottledOperations(host); @@ -80085,18 +82427,19 @@ var ts; if (this.typingSafeListLocation) { args.push(server.Arguments.TypingSafeListLocation, this.typingSafeListLocation); } + if (this.npmLocation) { + args.push(server.Arguments.NpmLocation, this.npmLocation); + } var execArgv = []; - { - for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { - var arg = _a[_i]; - var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); - if (match) { - var currentPort = match[3] !== undefined - ? +match[3] - : match[1] === "debug" ? 5858 : 9229; - execArgv.push("--" + match[1] + "=" + (currentPort + 1)); - break; - } + for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { + var arg = _a[_i]; + var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); + if (match) { + var currentPort = match[3] !== undefined + ? +match[3] + : match[1] === "debug" ? 5858 : 9229; + execArgv.push("--" + match[1] + "=" + (currentPort + 1)); + break; } } this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv }); @@ -80187,10 +82530,10 @@ var ts; __extends(IOSession, _super); function IOSession(options) { var _this = this; - var host = options.host, installerEventPort = options.installerEventPort, globalTypingsCacheLocation = options.globalTypingsCacheLocation, typingSafeListLocation = options.typingSafeListLocation, canUseEvents = options.canUseEvents; + var host = options.host, installerEventPort = options.installerEventPort, globalTypingsCacheLocation = options.globalTypingsCacheLocation, typingSafeListLocation = options.typingSafeListLocation, npmLocation = options.npmLocation, canUseEvents = options.canUseEvents; var typingsInstaller = disableAutomaticTypingAcquisition ? undefined - : new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, host.newLine); + : new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, npmLocation, host.newLine); _this = _super.call(this, { host: host, cancellationToken: cancellationToken, @@ -80285,6 +82628,7 @@ var ts; var watchedFiles = []; var nextFileToCheck = 0; var watchTimer; + return { getModifiedTime: getModifiedTime, poll: poll, startWatchTimer: startWatchTimer, addFile: addFile, removeFile: removeFile }; function getModifiedTime(fileName) { return fs.statSync(fileName).mtime; } @@ -80295,11 +82639,20 @@ var ts; } fs.stat(watchedFile.fileName, function (err, stats) { if (err) { - watchedFile.callback(watchedFile.fileName); + watchedFile.callback(watchedFile.fileName, ts.FileWatcherEventKind.Changed); } - else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) { - watchedFile.mtime = getModifiedTime(watchedFile.fileName); - watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0); + else { + var oldTime = watchedFile.mtime.getTime(); + var newTime = stats.mtime.getTime(); + if (oldTime !== newTime) { + watchedFile.mtime = stats.mtime; + var eventKind = oldTime === 0 + ? ts.FileWatcherEventKind.Created + : newTime === 0 + ? ts.FileWatcherEventKind.Deleted + : ts.FileWatcherEventKind.Changed; + watchedFile.callback(watchedFile.fileName, eventKind); + } } }); } @@ -80326,7 +82679,9 @@ var ts; var file = { fileName: fileName, callback: callback, - mtime: getModifiedTime(fileName) + mtime: sys.fileExists(fileName) + ? getModifiedTime(fileName) + : new Date(0) }; watchedFiles.push(file); if (watchedFiles.length === 1) { @@ -80337,13 +82692,6 @@ var ts; function removeFile(file) { ts.unorderedRemoveItem(watchedFiles, file); } - return { - getModifiedTime: getModifiedTime, - poll: poll, - startWatchTimer: startWatchTimer, - addFile: addFile, - removeFile: removeFile - }; } var pollingWatchedFileSet = createPollingWatchedFileSet(); var pending = []; @@ -80472,7 +82820,8 @@ var ts; if (localeStr) { ts.validateLocaleAndSetLanguage(localeStr, sys); } - var typingSafeListLocation = server.findArgument("--typingSafeListLocation"); + var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); + var npmLocation = server.findArgument(server.Arguments.NpmLocation); var globalPlugins = (server.findArgument("--globalPlugins") || "").split(","); var pluginProbeLocations = (server.findArgument("--pluginProbeLocations") || "").split(","); var allowLocalPluginLoads = server.hasArgument("--allowLocalPluginLoads"); @@ -80488,6 +82837,7 @@ var ts; disableAutomaticTypingAcquisition: disableAutomaticTypingAcquisition, globalTypingsCacheLocation: getGlobalTypingsCacheLocation(), typingSafeListLocation: typingSafeListLocation, + npmLocation: npmLocation, telemetryEnabled: telemetryEnabled, logger: logger, globalPlugins: globalPlugins, @@ -80502,5 +82852,3 @@ 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 643a9e80d06..fce0d53e635 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -17,18 +17,20 @@ declare namespace ts { interface MapLike { [index: string]: T; } - interface Map { + interface ReadonlyMap { get(key: string): T | undefined; has(key: string): boolean; - set(key: string, value: T): this; - delete(key: string): boolean; - clear(): void; forEach(action: (value: T, key: string) => void): void; readonly size: number; keys(): Iterator; values(): Iterator; entries(): Iterator<[string, T]>; } + interface Map extends ReadonlyMap { + set(key: string, value: T): this; + delete(key: string): boolean; + clear(): void; + } interface Iterator { next(): { value: T; @@ -38,23 +40,17 @@ declare namespace ts { done: true; }; } + interface Push { + push(...values: T[]): void; + } type Path = string & { __pathBrand: any; }; - interface FileMap { - get(fileName: Path): T; - set(fileName: Path, value: T): void; - contains(fileName: Path): boolean; - remove(fileName: Path): void; - forEachValue(f: (key: Path, v: T) => void): void; - getKeys(): Path[]; - clear(): void; - } interface TextRange { pos: number; end: number; } - const enum SyntaxKind { + enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, SingleLineCommentTrivia = 2, @@ -325,37 +321,29 @@ declare namespace ts { JSDocTypeExpression = 267, JSDocAllType = 268, JSDocUnknownType = 269, - JSDocArrayType = 270, - JSDocUnionType = 271, - JSDocTupleType = 272, - JSDocNullableType = 273, - JSDocNonNullableType = 274, - JSDocRecordType = 275, - JSDocRecordMember = 276, - JSDocTypeReference = 277, - JSDocOptionalType = 278, - JSDocFunctionType = 279, - JSDocVariadicType = 280, - JSDocConstructorType = 281, - JSDocThisType = 282, - JSDocComment = 283, - JSDocTag = 284, - JSDocAugmentsTag = 285, - JSDocParameterTag = 286, - JSDocReturnTag = 287, - JSDocTypeTag = 288, - JSDocTemplateTag = 289, - JSDocTypedefTag = 290, - JSDocPropertyTag = 291, - JSDocTypeLiteral = 292, - JSDocLiteralType = 293, - SyntaxList = 294, - NotEmittedStatement = 295, - PartiallyEmittedExpression = 296, - CommaListExpression = 297, - MergeDeclarationMarker = 298, - EndOfDeclarationMarker = 299, - Count = 300, + JSDocNullableType = 270, + JSDocNonNullableType = 271, + JSDocOptionalType = 272, + JSDocFunctionType = 273, + JSDocVariadicType = 274, + JSDocComment = 275, + JSDocTag = 276, + JSDocAugmentsTag = 277, + JSDocClassTag = 278, + JSDocParameterTag = 279, + JSDocReturnTag = 280, + JSDocTypeTag = 281, + JSDocTemplateTag = 282, + JSDocTypedefTag = 283, + JSDocPropertyTag = 284, + JSDocTypeLiteral = 285, + SyntaxList = 286, + NotEmittedStatement = 287, + PartiallyEmittedExpression = 288, + CommaListExpression = 289, + MergeDeclarationMarker = 290, + EndOfDeclarationMarker = 291, + Count = 292, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -382,11 +370,11 @@ declare namespace ts { LastBinaryOperator = 70, FirstNode = 143, FirstJSDocNode = 267, - LastJSDocNode = 293, - FirstJSDocTagNode = 283, - LastJSDocTagNode = 293, + LastJSDocNode = 285, + FirstJSDocTagNode = 276, + LastJSDocTagNode = 285, } - const enum NodeFlags { + enum NodeFlags { None = 0, Let = 1, Const = 2, @@ -407,13 +395,14 @@ declare namespace ts { JavaScriptFile = 65536, ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, + JSDoc = 1048576, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 96256, TypeExcludesFlags = 20480, } - const enum ModifierFlags { + enum ModifierFlags { None = 0, Export = 1, Ambient = 2, @@ -433,7 +422,7 @@ declare namespace ts { TypeScriptModifier = 2270, ExportDefault = 513, } - const enum JsxFlags { + enum JsxFlags { None = 0, IntrinsicNamedElement = 1, IntrinsicIndexedElement = 2, @@ -446,7 +435,7 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } - interface NodeArray extends Array, TextRange { + interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } interface Token extends Node { @@ -466,7 +455,7 @@ declare namespace ts { type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { kind: SyntaxKind.Identifier; - text: string; + escapedText: __String; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; } @@ -549,7 +538,7 @@ declare namespace ts { initializer?: Expression; } interface PropertySignature extends TypeElement { - kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; + kind: SyntaxKind.PropertySignature; name: PropertyName; questionToken?: QuestionToken; type?: TypeNode; @@ -587,7 +576,7 @@ declare namespace ts { interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; - name: DeclarationName; + name?: DeclarationName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; @@ -607,13 +596,15 @@ declare namespace ts { } type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; type ArrayBindingElement = BindingElement | OmittedExpression; - interface FunctionLikeDeclaration extends SignatureDeclaration { + interface FunctionLikeDeclarationBase extends SignatureDeclaration { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; body?: Block | Expression; } - interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; @@ -622,12 +613,12 @@ declare namespace ts { kind: SyntaxKind.MethodSignature; name: PropertyName; } - interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; @@ -636,13 +627,13 @@ declare namespace ts { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; } - interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } - interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; @@ -669,6 +660,7 @@ declare namespace ts { interface ConstructorTypeNode extends TypeNode, SignatureDeclaration { kind: SyntaxKind.ConstructorType; } + type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; interface TypeReferenceNode extends TypeNode { kind: SyntaxKind.TypeReference; typeName: EntityName; @@ -746,22 +738,23 @@ declare namespace ts { interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } - interface IncrementExpression extends UnaryExpression { - _incrementExpressionBrand: any; + type IncrementExpression = UpdateExpression; + interface UpdateExpression extends UnaryExpression { + _updateExpressionBrand: any; } type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; - interface PrefixUnaryExpression extends IncrementExpression { + interface PrefixUnaryExpression extends UpdateExpression { kind: SyntaxKind.PrefixUnaryExpression; operator: PrefixUnaryOperator; operand: UnaryExpression; } type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; - interface PostfixUnaryExpression extends IncrementExpression { + interface PostfixUnaryExpression extends UpdateExpression { kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; operator: PostfixUnaryOperator; } - interface LeftHandSideExpression extends IncrementExpression { + interface LeftHandSideExpression extends UpdateExpression { _leftHandSideExpressionBrand: any; } interface MemberExpression extends LeftHandSideExpression { @@ -782,6 +775,9 @@ declare namespace ts { interface SuperExpression extends PrimaryExpression { kind: SyntaxKind.SuperKeyword; } + interface ImportExpression extends PrimaryExpression { + kind: SyntaxKind.ImportKeyword; + } interface DeleteExpression extends UnaryExpression { kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; @@ -858,12 +854,12 @@ declare namespace ts { } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase { kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } - interface ArrowFunction extends Expression, FunctionLikeDeclaration { + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; @@ -959,6 +955,9 @@ declare namespace ts { interface SuperCall extends CallExpression { expression: SuperExpression; } + interface ImportCall extends CallExpression { + expression: ImportExpression; + } interface ExpressionWithTypeArguments extends TypeNode { kind: SyntaxKind.ExpressionWithTypeArguments; parent?: HeritageClause; @@ -1105,6 +1104,7 @@ declare namespace ts { condition?: Expression; incrementor?: Expression; } + type ForInOrOfStatement = ForInStatement | ForOfStatement; interface ForInStatement extends IterationStatement { kind: SyntaxKind.ForInStatement; initializer: ForInitializer; @@ -1178,7 +1178,7 @@ declare namespace ts { variableDeclaration: VariableDeclaration; block: Block; } - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; + type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; @@ -1340,9 +1340,9 @@ declare namespace ts { pos: -1; end: -1; } - interface JSDocTypeExpression extends Node { + interface JSDocTypeExpression extends TypeNode { kind: SyntaxKind.JSDocTypeExpression; - type: JSDocType; + type: TypeNode; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; @@ -1353,72 +1353,33 @@ declare namespace ts { interface JSDocUnknownType extends JSDocType { kind: SyntaxKind.JSDocUnknownType; } - interface JSDocArrayType extends JSDocType { - kind: SyntaxKind.JSDocArrayType; - elementType: JSDocType; - } - interface JSDocUnionType extends JSDocType { - kind: SyntaxKind.JSDocUnionType; - types: NodeArray; - } - interface JSDocTupleType extends JSDocType { - kind: SyntaxKind.JSDocTupleType; - types: NodeArray; - } interface JSDocNonNullableType extends JSDocType { kind: SyntaxKind.JSDocNonNullableType; - type: JSDocType; + type: TypeNode; } interface JSDocNullableType extends JSDocType { kind: SyntaxKind.JSDocNullableType; - type: JSDocType; - } - interface JSDocRecordType extends JSDocType { - kind: SyntaxKind.JSDocRecordType; - literal: TypeLiteralNode; - } - interface JSDocTypeReference extends JSDocType { - kind: SyntaxKind.JSDocTypeReference; - name: EntityName; - typeArguments: NodeArray; + type: TypeNode; } interface JSDocOptionalType extends JSDocType { kind: SyntaxKind.JSDocOptionalType; - type: JSDocType; + type: TypeNode; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { kind: SyntaxKind.JSDocFunctionType; - parameters: NodeArray; - type: JSDocType; } interface JSDocVariadicType extends JSDocType { kind: SyntaxKind.JSDocVariadicType; - type: JSDocType; - } - interface JSDocConstructorType extends JSDocType { - kind: SyntaxKind.JSDocConstructorType; - type: JSDocType; - } - interface JSDocThisType extends JSDocType { - kind: SyntaxKind.JSDocThisType; - type: JSDocType; - } - interface JSDocLiteralType extends JSDocType { - kind: SyntaxKind.JSDocLiteralType; - literal: LiteralTypeNode; - } - type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; - interface JSDocRecordMember extends PropertySignature { - kind: SyntaxKind.JSDocRecordMember; - name: Identifier | StringLiteral | NumericLiteral; - type?: JSDocType; + type: TypeNode; } + type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { + parent: JSDoc; atToken: AtToken; tagName: Identifier; comment: string | undefined; @@ -1430,6 +1391,9 @@ declare namespace ts { kind: SyntaxKind.JSDocAugmentsTag; typeExpression: JSDocTypeExpression; } + interface JSDocClassTag extends JSDocTag { + kind: SyntaxKind.JSDocClassTag; + } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; @@ -1443,31 +1407,32 @@ declare namespace ts { typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; - typeExpression?: JSDocTypeExpression; - jsDocTypeLiteral?: JSDocTypeLiteral; + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } - interface JSDocPropertyTag extends JSDocTag, TypeElement { - kind: SyntaxKind.JSDocPropertyTag; - name: Identifier; + interface JSDocPropertyLikeTag extends JSDocTag, Declaration { + parent: JSDoc; + name: EntityName; typeExpression: JSDocTypeExpression; + isNameFirst: boolean; + isBracketed: boolean; + } + interface JSDocPropertyTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocPropertyTag; + } + interface JSDocParameterTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocParameterTag; } interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; - jsDocPropertyTags?: NodeArray; + jsDocPropertyTags?: ReadonlyArray; jsDocTypeTag?: JSDocTypeTag; + isArrayType?: boolean; } - interface JSDocParameterTag extends JSDocTag { - kind: SyntaxKind.JSDocParameterTag; - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - postParameterName?: Identifier; - parameterName: Identifier; - isBracketed: boolean; - } - const enum FlowFlags { + enum FlowFlags { Unreachable = 1, Start = 2, BranchLabel = 4, @@ -1550,6 +1515,10 @@ declare namespace ts { kind: SyntaxKind.Bundle; sourceFiles: SourceFile[]; } + interface JsonSourceFile extends SourceFile { + jsonObject?: ObjectLiteralExpression; + extendedSourceFiles?: string[]; + } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; getSourceFile(fileName: string): SourceFile; @@ -1558,12 +1527,12 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; fileExists(path: string): boolean; - readFile(path: string): string; + readFile(path: string): string | undefined; } interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray): void; } class OperationCanceledException { } @@ -1620,14 +1589,15 @@ declare 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; getReturnTypeOfSignature(signature: Signature): Type; + getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; @@ -1648,9 +1618,9 @@ declare namespace ts { getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; + isImplementationOfOverload(node: FunctionLike): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; @@ -1712,30 +1682,32 @@ declare namespace ts { clear(): void; trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; - reportIllegalExtends(): void; + reportPrivateInBaseOfClassExpression(propertyName: string): void; } - const enum TypeFormatFlags { + enum TypeFormatFlags { None = 0, WriteArrayAsGenericType = 1, - UseTypeOfFunction = 2, - NoTruncation = 4, - WriteArrowStyleSignature = 8, - WriteOwnNameForAnyLike = 16, - WriteTypeArgumentsOfSignature = 32, - InElementType = 64, - UseFullyQualifiedType = 128, - InFirstTypeArgument = 256, - InTypeAlias = 512, - UseTypeAliasValue = 1024, - SuppressAnyReturnType = 2048, - AddUndefined = 4096, + UseTypeOfFunction = 4, + NoTruncation = 8, + WriteArrowStyleSignature = 16, + WriteOwnNameForAnyLike = 32, + WriteTypeArgumentsOfSignature = 64, + InElementType = 128, + UseFullyQualifiedType = 256, + InFirstTypeArgument = 512, + InTypeAlias = 1024, + UseTypeAliasValue = 2048, + SuppressAnyReturnType = 4096, + AddUndefined = 8192, + WriteClassExpressionAsTypeLiteral = 16384, + InArrayType = 32768, } - const enum SymbolFormatFlags { + enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, } - const enum TypePredicateKind { + enum TypePredicateKind { This = 0, Identifier = 1, } @@ -1752,7 +1724,7 @@ declare namespace ts { parameterIndex: number; } type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; - const enum SymbolFlags { + enum SymbolFlags { None = 0, FunctionScopedVariable = 1, BlockScopedVariable = 2, @@ -1775,13 +1747,11 @@ declare namespace ts { TypeParameter = 262144, TypeAlias = 524288, ExportValue = 1048576, - ExportType = 2097152, - ExportNamespace = 4194304, - Alias = 8388608, - Prototype = 16777216, - ExportStar = 33554432, - Optional = 67108864, - Transient = 134217728, + Alias = 2097152, + Prototype = 4194304, + ExportStar = 8388608, + Optional = 16777216, + Transient = 33554432, Enum = 384, Variable = 3, Value = 107455, @@ -1806,27 +1776,63 @@ declare namespace ts { SetAccessorExcludes = 74687, TypeParameterExcludes = 530920, TypeAliasExcludes = 793064, - AliasExcludes = 8388608, - ModuleMember = 8914931, + AliasExcludes = 2097152, + ModuleMember = 2623475, ExportHasLocal = 944, HasExports = 1952, HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - Export = 7340032, ClassMember = 106500, } interface Symbol { flags: SymbolFlags; - name: string; + escapedName: __String; declarations?: Declaration[]; valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; } - type SymbolTable = Map; - const enum TypeFlags { + enum InternalSymbolName { + Call = "__call", + Constructor = "__constructor", + New = "__new", + Index = "__index", + ExportStar = "__export", + Global = "__global", + Missing = "__missing", + Type = "__type", + Object = "__object", + JSXAttributes = "__jsxAttributes", + Class = "__class", + Function = "__function", + Computed = "__computed", + Resolving = "__resolving__", + ExportEquals = "export=", + Default = "default", + } + type __String = (string & { + __escapedIdentifier: void; + }) | (void & { + __escapedIdentifier: void; + }) | InternalSymbolName; + interface ReadonlyUnderscoreEscapedMap { + get(key: __String): T | undefined; + has(key: __String): boolean; + forEach(action: (value: T, key: __String) => void): void; + readonly size: number; + keys(): Iterator<__String>; + values(): Iterator; + entries(): Iterator<[__String, T]>; + } + interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap { + set(key: __String, value: T): this; + delete(key: __String): boolean; + clear(): void; + } + type SymbolTable = UnderscoreEscapedMap; + enum TypeFlags { Any = 1, String = 2, Number = 4, @@ -1883,7 +1889,7 @@ declare namespace ts { } interface EnumType extends Type { } - const enum ObjectFlags { + enum ObjectFlags { Class = 1, Interface = 2, Reference = 4, @@ -1945,7 +1951,7 @@ declare namespace ts { interface IndexType extends Type { type: TypeVariable | UnionOrIntersectionType; } - const enum SignatureKind { + enum SignatureKind { Call = 0, Construct = 1, } @@ -1954,7 +1960,7 @@ declare namespace ts { typeParameters?: TypeParameter[]; parameters: Symbol[]; } - const enum IndexKind { + enum IndexKind { String = 0, Number = 1, } @@ -1963,6 +1969,24 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } + enum InferencePriority { + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, + } + interface InferenceInfo { + typeParameter: TypeParameter; + candidates: Type[]; + inferredType: Type; + priority: InferencePriority; + topLevel: boolean; + isFixed: boolean; + } + enum InferenceFlags { + InferUnionTypes = 1, + NoDefault = 2, + AnyDefault = 4, + } interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2038,6 +2062,7 @@ declare namespace ts { noImplicitAny?: boolean; noImplicitReturns?: boolean; noImplicitThis?: boolean; + noStrictGenericChecks?: boolean; noUnusedLocals?: boolean; noUnusedParameters?: boolean; noImplicitUseStrict?: boolean; @@ -2066,7 +2091,7 @@ declare namespace ts { traceResolution?: boolean; types?: string[]; typeRoots?: string[]; - [option: string]: CompilerOptionsValue | undefined; + [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { enableAutoDiscovery?: boolean; @@ -2091,14 +2116,15 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, + ESNext = 6, } - const enum JsxEmit { + enum JsxEmit { None = 0, Preserve = 1, React = 2, ReactNative = 3, } - const enum NewLineKind { + enum NewLineKind { CarriageReturnLineFeed = 0, LineFeed = 1, } @@ -2106,15 +2132,16 @@ declare namespace ts { line: number; character: number; } - const enum ScriptKind { + enum ScriptKind { Unknown = 0, JS = 1, JSX = 2, TS = 3, TSX = 4, External = 5, + JSON = 6, } - const enum ScriptTarget { + enum ScriptTarget { ES3 = 0, ES5 = 1, ES2015 = 2, @@ -2123,7 +2150,7 @@ declare namespace ts { ESNext = 5, Latest = 5, } - const enum LanguageVariant { + enum LanguageVariant { Standard = 0, JSX = 1, } @@ -2136,7 +2163,7 @@ declare namespace ts { wildcardDirectories?: MapLike; compileOnSave?: boolean; } - const enum WatchDirectoryFlags { + enum WatchDirectoryFlags { None = 0, Recursive = 1, } @@ -2146,7 +2173,7 @@ declare namespace ts { } interface ModuleResolutionHost { fileExists(fileName: string): boolean; - readFile(fileName: string): string; + readFile(fileName: string): string | undefined; trace?(s: string): void; directoryExists?(directoryName: string): boolean; realpath?(path: string): string; @@ -2161,12 +2188,11 @@ declare namespace ts { extension: Extension; } enum Extension { - Ts = 0, - Tsx = 1, - Dts = 2, - Js = 3, - Jsx = 4, - LastTypeScriptExtension = 2, + Ts = ".ts", + Tsx = ".tsx", + Dts = ".d.ts", + Js = ".js", + Jsx = ".jsx", } interface ResolvedModuleWithFailedLookupLocations { resolvedModule: ResolvedModuleFull | undefined; @@ -2195,7 +2221,15 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string; } - const enum EmitFlags { + interface SourceMapRange extends TextRange { + source?: SourceMapSource; + } + interface SourceMapSource { + fileName: string; + text: string; + skipTrivia?: (pos: number) => number; + } + enum EmitFlags { SingleLine = 1, AdviseOnEmitNode = 2, NoSubstitution = 4, @@ -2231,7 +2265,7 @@ declare namespace ts { readonly text: string; readonly priority?: number; } - const enum EmitHint { + enum EmitHint { SourceFile = 0, Expression = 1, IdentifierName = 2, @@ -2264,7 +2298,7 @@ declare namespace ts { type TransformerFactory = (context: TransformationContext) => Transformer; type Transformer = (node: T) => T; type Visitor = (node: Node) => VisitResult; - type VisitResult = T | T[]; + type VisitResult = T | T[] | undefined; interface Printer { printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; printFile(sourceFile: SourceFile): string; @@ -2292,12 +2326,18 @@ declare namespace ts { } } declare namespace ts { - const version = "2.4.0"; + const versionMajorMinor = "2.5"; + const version: string; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { - type FileWatcherCallback = (fileName: string, removed?: boolean) => void; + enum FileWatcherEventKind { + Created = 0, + Changed = 1, + Deleted = 2, + } + type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; interface WatchedFile { fileName: string; @@ -2309,7 +2349,7 @@ declare namespace ts { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; - readFile(path: string, encoding?: string): string; + readFile(path: string, encoding?: string): string | undefined; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; @@ -2321,7 +2361,7 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; createHash?(data: string): string; getMemoryUsage?(): number; @@ -2340,6 +2380,227 @@ declare namespace ts { function getNodeMajorVersion(): number; let sys: System; } +declare namespace ts { + function getDefaultLibFileName(options: CompilerOptions): string; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + let unchangedTextChangeRange: TextChangeRange; + function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; + function getTypeParameterOwner(d: Declaration): Declaration; + function isParameterPropertyDeclaration(node: Node): boolean; + function getCombinedModifierFlags(node: Node): ModifierFlags; + function getCombinedNodeFlags(node: Node): NodeFlags; + function validateLocaleAndSetLanguage(locale: string, sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + }, errors?: Push): void; + function getOriginalNode(node: Node): Node; + function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function isParseTreeNode(node: Node): boolean; + function getParseTreeNode(node: Node): Node; + function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; + function unescapeLeadingUnderscores(identifier: __String): string; + function unescapeIdentifier(id: string): string; + function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; +} +declare namespace ts { + function isNumericLiteral(node: Node): node is NumericLiteral; + function isStringLiteral(node: Node): node is StringLiteral; + function isJsxText(node: Node): node is JsxText; + function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddle(node: Node): node is TemplateMiddle; + function isTemplateTail(node: Node): node is TemplateTail; + function isIdentifier(node: Node): node is Identifier; + function isQualifiedName(node: Node): node is QualifiedName; + function isComputedPropertyName(node: Node): node is ComputedPropertyName; + function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; + function isParameter(node: Node): node is ParameterDeclaration; + function isDecorator(node: Node): node is Decorator; + function isPropertySignature(node: Node): node is PropertySignature; + function isPropertyDeclaration(node: Node): node is PropertyDeclaration; + function isMethodSignature(node: Node): node is MethodSignature; + function isMethodDeclaration(node: Node): node is MethodDeclaration; + function isConstructorDeclaration(node: Node): node is ConstructorDeclaration; + function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration; + function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration; + function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; + function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; + function isTypePredicateNode(node: Node): node is TypePredicateNode; + function isTypeReferenceNode(node: Node): node is TypeReferenceNode; + function isFunctionTypeNode(node: Node): node is FunctionTypeNode; + function isConstructorTypeNode(node: Node): node is ConstructorTypeNode; + function isTypeQueryNode(node: Node): node is TypeQueryNode; + function isTypeLiteralNode(node: Node): node is TypeLiteralNode; + function isArrayTypeNode(node: Node): node is ArrayTypeNode; + function isTupleTypeNode(node: Node): node is TupleTypeNode; + function isUnionTypeNode(node: Node): node is UnionTypeNode; + function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode; + function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode; + function isThisTypeNode(node: Node): node is ThisTypeNode; + function isTypeOperatorNode(node: Node): node is TypeOperatorNode; + function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; + function isMappedTypeNode(node: Node): node is MappedTypeNode; + function isLiteralTypeNode(node: Node): node is LiteralTypeNode; + function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; + function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; + function isBindingElement(node: Node): node is BindingElement; + function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; + function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; + function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; + function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function isCallExpression(node: Node): node is CallExpression; + function isNewExpression(node: Node): node is NewExpression; + function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; + function isTypeAssertion(node: Node): node is TypeAssertion; + function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; + function skipPartiallyEmittedExpressions(node: Expression): Expression; + function skipPartiallyEmittedExpressions(node: Node): Node; + function isFunctionExpression(node: Node): node is FunctionExpression; + function isArrowFunction(node: Node): node is ArrowFunction; + function isDeleteExpression(node: Node): node is DeleteExpression; + function isTypeOfExpression(node: Node): node is TypeOfExpression; + function isVoidExpression(node: Node): node is VoidExpression; + function isAwaitExpression(node: Node): node is AwaitExpression; + function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression; + function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression; + function isBinaryExpression(node: Node): node is BinaryExpression; + function isConditionalExpression(node: Node): node is ConditionalExpression; + function isTemplateExpression(node: Node): node is TemplateExpression; + function isYieldExpression(node: Node): node is YieldExpression; + function isSpreadElement(node: Node): node is SpreadElement; + function isClassExpression(node: Node): node is ClassExpression; + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isTemplateSpan(node: Node): node is TemplateSpan; + function isSemicolonClassElement(node: Node): node is SemicolonClassElement; + function isBlock(node: Node): node is Block; + function isVariableStatement(node: Node): node is VariableStatement; + function isEmptyStatement(node: Node): node is EmptyStatement; + function isExpressionStatement(node: Node): node is ExpressionStatement; + function isIfStatement(node: Node): node is IfStatement; + function isDoStatement(node: Node): node is DoStatement; + function isWhileStatement(node: Node): node is WhileStatement; + function isForStatement(node: Node): node is ForStatement; + function isForInStatement(node: Node): node is ForInStatement; + function isForOfStatement(node: Node): node is ForOfStatement; + function isContinueStatement(node: Node): node is ContinueStatement; + function isBreakStatement(node: Node): node is BreakStatement; + function isReturnStatement(node: Node): node is ReturnStatement; + function isWithStatement(node: Node): node is WithStatement; + function isSwitchStatement(node: Node): node is SwitchStatement; + function isLabeledStatement(node: Node): node is LabeledStatement; + function isThrowStatement(node: Node): node is ThrowStatement; + function isTryStatement(node: Node): node is TryStatement; + function isDebuggerStatement(node: Node): node is DebuggerStatement; + function isVariableDeclaration(node: Node): node is VariableDeclaration; + function isVariableDeclarationList(node: Node): node is VariableDeclarationList; + function isFunctionDeclaration(node: Node): node is FunctionDeclaration; + function isClassDeclaration(node: Node): node is ClassDeclaration; + function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration; + function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration; + function isEnumDeclaration(node: Node): node is EnumDeclaration; + function isModuleDeclaration(node: Node): node is ModuleDeclaration; + function isModuleBlock(node: Node): node is ModuleBlock; + function isCaseBlock(node: Node): node is CaseBlock; + function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration; + function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; + function isImportDeclaration(node: Node): node is ImportDeclaration; + function isImportClause(node: Node): node is ImportClause; + function isNamespaceImport(node: Node): node is NamespaceImport; + function isNamedImports(node: Node): node is NamedImports; + function isImportSpecifier(node: Node): node is ImportSpecifier; + function isExportAssignment(node: Node): node is ExportAssignment; + function isExportDeclaration(node: Node): node is ExportDeclaration; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; + function isMissingDeclaration(node: Node): node is MissingDeclaration; + function isExternalModuleReference(node: Node): node is ExternalModuleReference; + function isJsxElement(node: Node): node is JsxElement; + function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; + function isJsxOpeningElement(node: Node): node is JsxOpeningElement; + function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxAttribute(node: Node): node is JsxAttribute; + function isJsxAttributes(node: Node): node is JsxAttributes; + function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; + function isJsxExpression(node: Node): node is JsxExpression; + function isCaseClause(node: Node): node is CaseClause; + function isDefaultClause(node: Node): node is DefaultClause; + function isHeritageClause(node: Node): node is HeritageClause; + function isCatchClause(node: Node): node is CatchClause; + function isPropertyAssignment(node: Node): node is PropertyAssignment; + function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; + function isSpreadAssignment(node: Node): node is SpreadAssignment; + function isEnumMember(node: Node): node is EnumMember; + function isSourceFile(node: Node): node is SourceFile; + function isBundle(node: Node): node is Bundle; + function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; + function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; + function isJSDocUnknownType(node: Node): node is JSDocUnknownType; + function isJSDocNullableType(node: Node): node is JSDocNullableType; + function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType; + function isJSDocOptionalType(node: Node): node is JSDocOptionalType; + function isJSDocFunctionType(node: Node): node is JSDocFunctionType; + function isJSDocVariadicType(node: Node): node is JSDocVariadicType; + function isJSDoc(node: Node): node is JSDoc; + function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocParameterTag(node: Node): node is JSDocParameterTag; + function isJSDocReturnTag(node: Node): node is JSDocReturnTag; + function isJSDocTypeTag(node: Node): node is JSDocTypeTag; + function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag; + function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag; + function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; + function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; +} +declare namespace ts { + function isToken(n: Node): boolean; + function isLiteralExpression(node: Node): node is LiteralExpression; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isStringTextContainingNode(node: Node): boolean; + function isModifier(node: Node): node is Modifier; + function isEntityName(node: Node): node is EntityName; + function isPropertyName(node: Node): node is PropertyName; + function isBindingName(node: Node): node is BindingName; + function isFunctionLike(node: Node): node is FunctionLike; + function isClassElement(node: Node): node is ClassElement; + function isClassLike(node: Node): node is ClassLikeDeclaration; + function isAccessor(node: Node): node is AccessorDeclaration; + function isTypeElement(node: Node): node is TypeElement; + function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + function isTypeNode(node: Node): node is TypeNode; + function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; + function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; + function isCallLikeExpression(node: Node): node is CallLikeExpression; + function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; + function isTemplateLiteral(node: Node): node is TemplateLiteral; + function isAssertionExpression(node: Node): node is AssertionExpression; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; + function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; + function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + function isJSDocCommentContainingNode(node: Node): boolean; +} declare namespace ts { interface ErrorCallback { (message: DiagnosticMessage, length: number): void; @@ -2375,9 +2636,9 @@ declare namespace ts { scanRange(start: number, length: number, callback: () => T): T; tryScan(callback: () => T): T; } - function tokenToString(t: SyntaxKind): string; + function tokenToString(t: SyntaxKind): string | undefined; function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; + function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; function isWhiteSpaceLike(ch: number): boolean; function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; @@ -2394,17 +2655,28 @@ declare namespace ts { function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { - function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; - function readConfigFile(fileName: string, readFile: (path: string) => string): { + function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; + function isExternalModule(file: SourceFile): boolean; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic; }; - function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { + function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; 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; + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; + function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -2415,7 +2687,6 @@ declare namespace ts { }; } declare namespace ts { - function moduleHasNonRelativeName(moduleName: string): boolean; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; getCurrentDirectory?: () => string; @@ -2438,44 +2709,7 @@ declare namespace ts { function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; } declare namespace ts { - function getDefaultLibFileName(options: CompilerOptions): string; - function textSpanEnd(span: TextSpan): number; - function textSpanIsEmpty(span: TextSpan): boolean; - function textSpanContainsPosition(span: TextSpan, position: number): boolean; - function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; - function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; - function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; - function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; - function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; - function createTextSpan(start: number, length: number): TextSpan; - function createTextSpanFromBounds(start: number, end: number): TextSpan; - function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; - function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; - function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; - let unchangedTextChangeRange: TextChangeRange; - function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; - function isParameterPropertyDeclaration(node: Node): boolean; - function getCombinedModifierFlags(node: Node): ModifierFlags; - function getCombinedNodeFlags(node: Node): NodeFlags; - function validateLocaleAndSetLanguage(locale: string, sys: { - getExecutingFilePath(): string; - resolvePath(path: string): string; - fileExists(fileName: string): boolean; - readFile(fileName: string): string; - }, errors?: Diagnostic[]): void; - function getOriginalNode(node: Node): Node; - function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; - function isParseTreeNode(node: Node): boolean; - function getParseTreeNode(node: Node): Node; - function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; - function unescapeIdentifier(identifier: string): string; -} -declare namespace ts { - function createNodeArray(elements?: T[], hasTrailingComma?: boolean): NodeArray; + function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; function createLiteral(value: string): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; @@ -2498,36 +2732,36 @@ 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 createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - 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 createParameter(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + function updateParameter(node: ParameterDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | 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 createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createPropertySignature(modifiers: ReadonlyArray | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: ReadonlyArray | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function createProperty(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function updateProperty(node: PropertyDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function createMethodSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, 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; - function createGetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - 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 createMethod(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function updateMethod(node: MethodDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createConstructor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function updateConstructor(node: ConstructorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function createGetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function updateGetAccessor(node: GetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function createSetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function updateSetAccessor(node: SetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, 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 createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, 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 createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | 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; @@ -2535,17 +2769,17 @@ declare namespace ts { 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 createTypeLiteralNode(members: ReadonlyArray): 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 createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): 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 createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray): UnionOrIntersectionTypeNode; function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; @@ -2557,34 +2791,34 @@ declare namespace ts { 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; - function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ArrayBindingElement[]): ArrayBindingPattern; + function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; + function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; + function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; + function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ReadonlyArray): ArrayBindingPattern; function createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; - function createArrayLiteral(elements?: Expression[], multiLine?: boolean): ArrayLiteralExpression; - function updateArrayLiteral(node: ArrayLiteralExpression, elements: Expression[]): ArrayLiteralExpression; - function createObjectLiteral(properties?: ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; - function updateObjectLiteral(node: ObjectLiteralExpression, properties: ObjectLiteralElementLike[]): ObjectLiteralExpression; + function createArrayLiteral(elements?: ReadonlyArray, multiLine?: boolean): ArrayLiteralExpression; + function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; + function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; + function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; function createPropertyAccess(expression: Expression, name: string | Identifier): PropertyAccessExpression; function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - function createCall(expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]): CallExpression; - function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]): CallExpression; - function createNew(expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[] | undefined): NewExpression; - function updateNew(node: NewExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[] | undefined): NewExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; function createParen(expression: Expression): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - function createArrowFunction(modifiers: Modifier[] | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; - function updateArrowFunction(node: ArrowFunction, modifiers: Modifier[] | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: ConciseBody): ArrowFunction; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; function createTypeOf(expression: Expression): TypeOfExpression; @@ -2602,18 +2836,18 @@ declare namespace ts { 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; - function createTemplateExpression(head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; - function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; function createYield(expression?: Expression): YieldExpression; function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function createSpread(expression: Expression): SpreadElement; function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; - function createClassExpression(modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; - function updateClassExpression(node: ClassExpression, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; function createOmittedExpression(): OmittedExpression; - function createExpressionWithTypeArguments(typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; function createAsExpression(expression: Expression, type: TypeNode): AsExpression; function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; @@ -2623,10 +2857,10 @@ declare namespace ts { 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 createBlock(statements: ReadonlyArray, multiLine?: boolean): Block; + function updateBlock(node: Block, statements: ReadonlyArray): Block; + function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement; + function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2661,50 +2895,50 @@ declare namespace ts { 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; - function updateModuleDeclaration(node: ModuleDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; - function createModuleBlock(statements: Statement[]): ModuleBlock; - function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; - function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; - function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createVariableDeclarationList(declarations: ReadonlyArray, flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; + function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function createEnumDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, members: ReadonlyArray): EnumDeclaration; + function updateEnumDeclaration(node: EnumDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, members: ReadonlyArray): EnumDeclaration; + function createModuleDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + function updateModuleDeclaration(node: ModuleDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + function createModuleBlock(statements: ReadonlyArray): ModuleBlock; + function updateModuleBlock(node: ModuleBlock, statements: ReadonlyArray): ModuleBlock; + function createCaseBlock(clauses: ReadonlyArray): CaseBlock; + function updateCaseBlock(node: CaseBlock, clauses: ReadonlyArray): 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; - function updateImportDeclaration(node: ImportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; - function createImportClause(name: Identifier, namedBindings: NamedImportBindings): ImportClause; - function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings): ImportClause; + function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; + function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function createNamespaceImport(name: Identifier): NamespaceImport; function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; - function createNamedImports(elements: ImportSpecifier[]): NamedImports; - function updateNamedImports(node: NamedImports, elements: ImportSpecifier[]): NamedImports; + function createNamedImports(elements: ReadonlyArray): NamedImports; + function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - function createExportAssignment(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; - function updateExportAssignment(node: ExportAssignment, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, expression: Expression): ExportAssignment; - function createExportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; - function updateExportDeclaration(node: ExportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; - function createNamedExports(elements: ExportSpecifier[]): NamedExports; - function updateNamedExports(node: NamedExports, elements: ExportSpecifier[]): NamedExports; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; + function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; + function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; + function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; + function createNamedExports(elements: ReadonlyArray): NamedExports; + function updateNamedExports(node: NamedExports, elements: ReadonlyArray): NamedExports; function createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; function createExternalModuleReference(expression: Expression): ExternalModuleReference; function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; - function createJsxElement(openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement): JsxElement; - function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement): JsxElement; + function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; @@ -2713,18 +2947,18 @@ declare namespace ts { function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; 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 createJsxAttributes(properties: ReadonlyArray): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: ReadonlyArray): 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 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 createCaseClause(expression: Expression, statements: ReadonlyArray): CaseClause; + function updateCaseClause(node: CaseClause, expression: Expression, statements: ReadonlyArray): CaseClause; + function createDefaultClause(statements: ReadonlyArray): DefaultClause; + function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): 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; @@ -2735,15 +2969,17 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: Statement[]): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray): SourceFile; function getMutableClone(node: T): T; 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 createCommaList(elements: ReadonlyArray): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; + function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression; + function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression): Expression; function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; @@ -2761,12 +2997,12 @@ declare namespace ts { function createExternalModuleExport(exportName: Identifier): ExportDeclaration; function disposeEmitNodes(sourceFile: SourceFile): void; function setTextRange(range: T, location: TextRange | undefined): T; - function getEmitFlags(node: Node): EmitFlags | undefined; function setEmitFlags(node: T, emitFlags: EmitFlags): T; - function getSourceMapRange(node: Node): TextRange; - function setSourceMapRange(node: T, range: TextRange | undefined): T; - function getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange | undefined; - function setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange | undefined): T; + function getSourceMapRange(node: Node): SourceMapRange; + function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; + function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; + function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; function getCommentRange(node: Node): TextRange; function setCommentRange(node: T, range: TextRange): T; function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; @@ -2784,14 +3020,6 @@ declare namespace ts { function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; function setOriginalNode(node: T, original: Node | undefined): T; } -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 | 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 { function visitNode(node: T, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; function visitNode(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; @@ -2839,31 +3067,36 @@ declare namespace ts { getText(sourceFile?: SourceFile): string; getFirstToken(sourceFile?: SourceFile): Node; getLastToken(sourceFile?: SourceFile): Node; - forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; + } + interface Identifier { + readonly text: string; } interface Symbol { + readonly name: string; getFlags(): SymbolFlags; + getEscapedName(): __String; getName(): string; - getDeclarations(): Declaration[]; + getDeclarations(): Declaration[] | undefined; getDocumentationComment(): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } 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; } interface Signature { getDeclaration(): SignatureDeclaration; - getTypeParameters(): TypeParameter[]; + getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; @@ -2879,6 +3112,9 @@ declare namespace ts { interface SourceFileLike { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; } + interface SourceMapSource { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } interface IScriptSnapshot { getText(start: number, end: number): string; getLength(): number; @@ -2914,8 +3150,8 @@ declare namespace ts { trace?(s: string): void; error?(s: string): void; useCaseSensitiveFileNames?(): boolean; - readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; - readFile?(path: string, encoding?: string): string; + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile?(path: string, encoding?: string): string | undefined; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; @@ -2963,7 +3199,7 @@ declare 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; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -2974,11 +3210,11 @@ declare namespace ts { } interface ClassifiedSpan { textSpan: TextSpan; - classificationType: string; + classificationType: ClassificationTypeNames; } interface NavigationBarItem { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems: NavigationBarItem[]; @@ -2988,7 +3224,7 @@ declare namespace ts { } interface NavigationTree { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems?: NavigationTree[]; @@ -3017,7 +3253,18 @@ declare namespace ts { interface ApplicableRefactorInfo { name: string; description: string; + inlineable?: boolean; + actions: RefactorActionInfo[]; } + type RefactorActionInfo = { + name: string; + description: string; + }; + type RefactorEditInfo = { + edits: FileTextChanges[]; + renameFilename?: string; + renameLocation?: number; + }; interface TextInsertion { newText: string; caretOffset: number; @@ -3034,35 +3281,35 @@ declare namespace ts { isInString?: true; } interface ImplementationLocation extends DocumentSpan { - kind: string; + kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; } interface DocumentHighlights { fileName: string; highlightSpans: HighlightSpan[]; } - namespace HighlightSpanKind { - const none = "none"; - const definition = "definition"; - const reference = "reference"; - const writtenReference = "writtenReference"; + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference", } interface HighlightSpan { fileName?: string; isInString?: true; textSpan: TextSpan; - kind: string; + kind: HighlightSpanKind; } interface NavigateToItem { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; matchKind: string; isCaseSensitive: boolean; fileName: string; textSpan: TextSpan; containerName: string; - containerKind: string; + containerKind: ScriptElementKind; } enum IndentStyle { None = 0, @@ -3122,9 +3369,9 @@ declare namespace ts { interface DefinitionInfo { fileName: string; textSpan: TextSpan; - kind: string; + kind: ScriptElementKind; name: string; - containerKind: string; + containerKind: ScriptElementKind; containerName: string; } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { @@ -3167,7 +3414,7 @@ declare namespace ts { text?: string; } interface QuickInfo { - kind: string; + kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; @@ -3179,7 +3426,7 @@ declare namespace ts { localizedErrorMessage: string; displayName: string; fullDisplayName: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } @@ -3213,14 +3460,14 @@ declare namespace ts { } interface CompletionEntry { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; sortText: string; replacementSpan?: TextSpan; } interface CompletionEntryDetails { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; @@ -3236,7 +3483,7 @@ declare namespace ts { outputFiles: OutputFile[]; emitSkipped: boolean; } - const enum OutputFileType { + enum OutputFileType { JavaScript = 0, SourceMap = 1, Declaration = 2, @@ -3246,7 +3493,7 @@ declare namespace ts { writeByteOrderMark: boolean; text: string; } - const enum EndOfLineState { + enum EndOfLineState { None = 0, InMultiLineCommentTrivia = 1, InSingleQuoteStringLiteral = 2, @@ -3278,77 +3525,77 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } - namespace ScriptElementKind { - const unknown = ""; - const warning = "warning"; - const keyword = "keyword"; - const scriptElement = "script"; - const moduleElement = "module"; - const classElement = "class"; - const localClassElement = "local class"; - const interfaceElement = "interface"; - const typeElement = "type"; - const enumElement = "enum"; - const enumMemberElement = "enum member"; - const variableElement = "var"; - const localVariableElement = "local var"; - const functionElement = "function"; - const localFunctionElement = "local function"; - const memberFunctionElement = "method"; - const memberGetAccessorElement = "getter"; - const memberSetAccessorElement = "setter"; - const memberVariableElement = "property"; - const constructorImplementationElement = "constructor"; - const callSignatureElement = "call"; - const indexSignatureElement = "index"; - const constructSignatureElement = "construct"; - const parameterElement = "parameter"; - const typeParameterElement = "type parameter"; - const primitiveType = "primitive type"; - const label = "label"; - const alias = "alias"; - const constElement = "const"; - const letElement = "let"; - const directory = "directory"; - const externalModuleName = "external module name"; - const jsxAttribute = "JSX attribute"; + enum ScriptElementKind { + unknown = "", + warning = "warning", + keyword = "keyword", + scriptElement = "script", + moduleElement = "module", + classElement = "class", + localClassElement = "local class", + interfaceElement = "interface", + typeElement = "type", + enumElement = "enum", + enumMemberElement = "enum member", + variableElement = "var", + localVariableElement = "local var", + functionElement = "function", + localFunctionElement = "local function", + memberFunctionElement = "method", + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", + memberVariableElement = "property", + constructorImplementationElement = "constructor", + callSignatureElement = "call", + indexSignatureElement = "index", + constructSignatureElement = "construct", + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", + jsxAttribute = "JSX attribute", } - namespace ScriptElementKindModifier { - const none = ""; - const publicMemberModifier = "public"; - const privateMemberModifier = "private"; - const protectedMemberModifier = "protected"; - const exportedModifier = "export"; - const ambientModifier = "declare"; - const staticModifier = "static"; - const abstractModifier = "abstract"; + enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - static jsxOpenTagName: string; - static jsxCloseTagName: string; - static jsxSelfClosingTagName: string; - static jsxAttribute: string; - static jsxText: string; - static jsxAttributeStringLiteralValue: string; + enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", + punctuation = "punctuation", + 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", } - const enum ClassificationType { + enum ClassificationType { comment = 1, identifier = 2, keyword = 3, @@ -3451,8 +3698,11 @@ declare namespace ts.server { trace?(s: string): void; require?(initialPath: string, moduleName: string): RequireResult; } + interface SortedArray extends Array { + " __sortedArrayBrand": any; + } interface SortedReadonlyArray extends ReadonlyArray { - " __sortedReadonlyArrayBrand": any; + " __sortedArrayBrand": any; } interface TypingInstallerRequest { readonly projectName: string; @@ -3460,9 +3710,9 @@ declare namespace ts.server { } interface DiscoverTypings extends TypingInstallerRequest { readonly fileNames: string[]; - readonly projectRootPath: ts.Path; - readonly compilerOptions: ts.CompilerOptions; - readonly typeAcquisition: ts.TypeAcquisition; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; readonly unresolvedImports: SortedReadonlyArray; readonly cachePath?: string; readonly kind: "discover"; @@ -3486,8 +3736,8 @@ declare namespace ts.server { readonly projectName: string; } interface SetTypings extends ProjectResponse { - readonly typeAcquisition: ts.TypeAcquisition; - readonly compilerOptions: ts.CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; readonly typings: string[]; readonly unresolvedImports: SortedReadonlyArray; readonly kind: ActionSet; @@ -3520,9 +3770,10 @@ declare namespace ts.server { const LogFile = "--logFile"; const EnableTelemetry = "--enableTelemetry"; const TypingSafeListLocation = "--typingSafeListLocation"; + const NpmLocation = "--npmLocation"; } function hasArgument(argumentName: string): boolean; - function findArgument(argumentName: string): string; + function findArgument(argumentName: string): string | undefined; } declare namespace ts.server { enum LogLevel { @@ -3531,7 +3782,7 @@ declare namespace ts.server { requestTime = 2, verbose = 3, } - const emptyArray: ReadonlyArray; + const emptyArray: SortedReadonlyArray; interface Logger { close(): void; hasLevel(level: LogLevel): boolean; @@ -3560,7 +3811,6 @@ declare namespace ts.server { } function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; function mergeMapLikes(target: MapLike, source: MapLike): void; - function removeItemFromSet(items: T[], itemToRemove: T): void; type NormalizedPath = string & { __normalizedPathTag: any; }; @@ -3575,7 +3825,10 @@ declare namespace ts.server { } function createNormalizedPathMap(): NormalizedPathMap; interface ProjectOptions { - configHasFilesProperty?: boolean; + configHasExtendsProperty: boolean; + configHasFilesProperty: boolean; + configHasIncludeProperty: boolean; + configHasExcludeProperty: boolean; files?: string[]; wildcardDirectories?: Map; compilerOptions?: CompilerOptions; @@ -3584,7 +3837,10 @@ declare namespace ts.server { } function isInferredProjectName(name: string): boolean; function makeInferredProjectName(counter: number): string; - function toSortedReadonlyArray(arr: string[]): SortedReadonlyArray; + function createSortedArray(): SortedArray; + function toSortedArray(arr: string[]): SortedArray; + function toSortedArray(arr: T[], comparer: Comparer): SortedArray; + function enumerateInsertsAndDeletes(newItems: SortedReadonlyArray, oldItems: SortedReadonlyArray, inserted: (newItem: T) => void, deleted: (oldItem: T) => void, compare?: Comparer): void; class ThrottledOperations { private readonly host; private pendingTimeouts; @@ -3601,56 +3857,57 @@ declare namespace ts.server { scheduleCollect(): void; private static run(self); } + function insertSorted(array: SortedArray, insert: T, compare: Comparer): void; + function removeSorted(array: SortedArray, remove: T, compare: Comparer): void; } declare namespace ts.server.protocol { - namespace CommandTypes { - type Brace = "brace"; - type BraceCompletion = "braceCompletion"; - type Change = "change"; - type Close = "close"; - type Completions = "completions"; - type CompletionDetails = "completionEntryDetails"; - type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - type Configure = "configure"; - type Definition = "definition"; - type Implementation = "implementation"; - type Exit = "exit"; - type Format = "format"; - type Formatonkey = "formatonkey"; - type Geterr = "geterr"; - type GeterrForProject = "geterrForProject"; - type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - type NavBar = "navbar"; - type Navto = "navto"; - type NavTree = "navtree"; - type NavTreeFull = "navtree-full"; - type Occurrences = "occurrences"; - type DocumentHighlights = "documentHighlights"; - type Open = "open"; - type Quickinfo = "quickinfo"; - type References = "references"; - type Reload = "reload"; - type Rename = "rename"; - type Saveto = "saveto"; - type SignatureHelp = "signatureHelp"; - type TypeDefinition = "typeDefinition"; - type ProjectInfo = "projectInfo"; - type ReloadProjects = "reloadProjects"; - type Unknown = "unknown"; - type OpenExternalProject = "openExternalProject"; - type OpenExternalProjects = "openExternalProjects"; - type CloseExternalProject = "closeExternalProject"; - type TodoComments = "todoComments"; - type Indentation = "indentation"; - type DocCommentTemplate = "docCommentTemplate"; - type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - type GetCodeFixes = "getCodeFixes"; - type GetSupportedCodeFixes = "getSupportedCodeFixes"; - type GetApplicableRefactors = "getApplicableRefactors"; - type GetRefactorCodeActions = "getRefactorCodeActions"; - type GetRefactorCodeActionsFull = "getRefactorCodeActions-full"; + enum CommandTypes { + Brace = "brace", + BraceCompletion = "braceCompletion", + Change = "change", + Close = "close", + Completions = "completions", + CompletionDetails = "completionEntryDetails", + CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", + CompileOnSaveEmitFile = "compileOnSaveEmitFile", + Configure = "configure", + Definition = "definition", + Implementation = "implementation", + Exit = "exit", + Format = "format", + Formatonkey = "formatonkey", + Geterr = "geterr", + GeterrForProject = "geterrForProject", + SemanticDiagnosticsSync = "semanticDiagnosticsSync", + SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", + NavBar = "navbar", + Navto = "navto", + NavTree = "navtree", + NavTreeFull = "navtree-full", + Occurrences = "occurrences", + DocumentHighlights = "documentHighlights", + Open = "open", + Quickinfo = "quickinfo", + References = "references", + Reload = "reload", + Rename = "rename", + Saveto = "saveto", + SignatureHelp = "signatureHelp", + TypeDefinition = "typeDefinition", + ProjectInfo = "projectInfo", + ReloadProjects = "reloadProjects", + Unknown = "unknown", + OpenExternalProject = "openExternalProject", + OpenExternalProjects = "openExternalProjects", + CloseExternalProject = "closeExternalProject", + TodoComments = "todoComments", + Indentation = "indentation", + DocCommentTemplate = "docCommentTemplate", + CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", + GetCodeFixes = "getCodeFixes", + GetSupportedCodeFixes = "getSupportedCodeFixes", + GetApplicableRefactors = "getApplicableRefactors", + GetEditsForRefactor = "getEditsForRefactor", } interface Message { seq: number; @@ -3751,27 +4008,35 @@ declare namespace ts.server.protocol { 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; + interface ApplicableRefactorInfo { + name: string; + description: string; + inlineable?: boolean; + actions: RefactorActionInfo[]; } - type GetRefactorCodeActionsRequestArgs = FileLocationOrRangeRequestArgs & { - refactorName: string; + type RefactorActionInfo = { + name: string; + description: string; }; - type RefactorCodeActions = { - actions: protocol.CodeAction[]; - renameLocation?: number; - }; - interface GetRefactorCodeActionsResponse extends Response { - body: RefactorCodeActions; + interface GetEditsForRefactorRequest extends Request { + command: CommandTypes.GetEditsForRefactor; + arguments: GetEditsForRefactorRequestArgs; } + type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { + refactor: string; + action: string; + }; + interface GetEditsForRefactorResponse extends Response { + body?: RefactorEditInfo; + } + type RefactorEditInfo = { + edits: FileCodeEdits[]; + renameLocation?: Location; + renameFilename?: string; + }; interface CodeFixRequest extends Request { command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; @@ -3855,7 +4120,7 @@ declare namespace ts.server.protocol { arguments: DocumentHighlightsRequestArgs; } interface HighlightSpan extends TextSpan { - kind: string; + kind: HighlightSpanKind; } interface DocumentHighlightsItem { file: string; @@ -3894,7 +4159,7 @@ declare namespace ts.server.protocol { localizedErrorMessage?: string; displayName: string; fullDisplayName: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; } interface SpanGroup { @@ -4014,7 +4279,7 @@ declare namespace ts.server.protocol { command: CommandTypes.Quickinfo; } interface QuickInfoResponseBody { - kind: string; + kind: ScriptElementKind; kindModifiers: string; start: Location; end: Location; @@ -4081,14 +4346,14 @@ declare namespace ts.server.protocol { } interface CompletionEntry { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; sortText: string; replacementSpan?: TextSpan; } interface CompletionEntryDetails { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; @@ -4183,6 +4448,9 @@ declare namespace ts.server.protocol { code?: number; source?: string; } + interface DiagnosticWithFileName extends Diagnostic { + fileName: string; + } interface DiagnosticEventBody { file: string; diagnostics: Diagnostic[]; @@ -4193,7 +4461,7 @@ declare namespace ts.server.protocol { interface ConfigFileDiagnosticEventBody { triggerFile: string; configFile: string; - diagnostics: Diagnostic[]; + diagnostics: DiagnosticWithFileName[]; } interface ConfigFileDiagnosticEvent extends Event { body?: ConfigFileDiagnosticEventBody; @@ -4236,7 +4504,7 @@ declare namespace ts.server.protocol { } interface NavtoItem { name: string; - kind: string; + kind: ScriptElementKind; matchKind?: string; isCaseSensitive?: boolean; kindModifiers?: string; @@ -4244,7 +4512,7 @@ declare namespace ts.server.protocol { start: Location; end: Location; containerName?: string; - containerKind?: string; + containerKind?: ScriptElementKind; } interface NavtoResponse extends Response { body?: NavtoItem[]; @@ -4270,7 +4538,7 @@ declare namespace ts.server.protocol { } interface NavigationBarItem { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers?: string; spans: TextSpan[]; childItems?: NavigationBarItem[]; @@ -4278,7 +4546,7 @@ declare namespace ts.server.protocol { } interface NavigationTree { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems?: NavigationTree[]; @@ -4335,12 +4603,11 @@ declare namespace ts.server.protocol { interface NavTreeResponse extends Response { body?: NavigationTree; } - namespace IndentStyle { - type None = "None"; - type Block = "Block"; - type Smart = "Smart"; + enum IndentStyle { + None = "None", + Block = "Block", + Smart = "Smart", } - type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; interface EditorSettings { baseIndentSize?: number; indentSize?: number; @@ -4433,40 +4700,35 @@ declare namespace ts.server.protocol { typeRoots?: string[]; [option: string]: CompilerOptionsValue | undefined; } - namespace JsxEmit { - type None = "None"; - type Preserve = "Preserve"; - type ReactNative = "ReactNative"; - type React = "React"; + enum JsxEmit { + None = "None", + Preserve = "Preserve", + ReactNative = "ReactNative", + React = "React", } - type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React | JsxEmit.ReactNative; - namespace ModuleKind { - type None = "None"; - type CommonJS = "CommonJS"; - type AMD = "AMD"; - type UMD = "UMD"; - type System = "System"; - type ES6 = "ES6"; - type ES2015 = "ES2015"; + enum ModuleKind { + None = "None", + CommonJS = "CommonJS", + AMD = "AMD", + UMD = "UMD", + System = "System", + ES6 = "ES6", + ES2015 = "ES2015", } - type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; - namespace ModuleResolutionKind { - type Classic = "Classic"; - type Node = "Node"; + enum ModuleResolutionKind { + Classic = "Classic", + Node = "Node", } - type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; - namespace NewLineKind { - type Crlf = "Crlf"; - type Lf = "Lf"; + enum NewLineKind { + Crlf = "Crlf", + Lf = "Lf", } - type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; - namespace ScriptTarget { - type ES3 = "ES3"; - type ES5 = "ES5"; - type ES6 = "ES6"; - type ES2015 = "ES2015"; + enum ScriptTarget { + ES3 = "ES3", + ES5 = "ES5", + ES6 = "ES6", + ES2015 = "ES2015", } - type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; } declare namespace ts.server { interface ServerCancellationToken extends HostCancellationToken { @@ -4481,55 +4743,8 @@ declare namespace ts.server { interface EventSender { event(payload: T, eventName: string): void; } - namespace CommandNames { - const Brace: protocol.CommandTypes.Brace; - const BraceCompletion: protocol.CommandTypes.BraceCompletion; - const Change: protocol.CommandTypes.Change; - const Close: protocol.CommandTypes.Close; - const Completions: protocol.CommandTypes.Completions; - const CompletionDetails: protocol.CommandTypes.CompletionDetails; - const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList; - const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile; - const Configure: protocol.CommandTypes.Configure; - const Definition: protocol.CommandTypes.Definition; - const Exit: protocol.CommandTypes.Exit; - const Format: protocol.CommandTypes.Format; - const Formatonkey: protocol.CommandTypes.Formatonkey; - const Geterr: protocol.CommandTypes.Geterr; - const GeterrForProject: protocol.CommandTypes.GeterrForProject; - const Implementation: protocol.CommandTypes.Implementation; - const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync; - const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync; - const NavBar: protocol.CommandTypes.NavBar; - const NavTree: protocol.CommandTypes.NavTree; - const NavTreeFull: protocol.CommandTypes.NavTreeFull; - const Navto: protocol.CommandTypes.Navto; - const Occurrences: protocol.CommandTypes.Occurrences; - const DocumentHighlights: protocol.CommandTypes.DocumentHighlights; - const Open: protocol.CommandTypes.Open; - const Quickinfo: protocol.CommandTypes.Quickinfo; - const References: protocol.CommandTypes.References; - const Reload: protocol.CommandTypes.Reload; - const Rename: protocol.CommandTypes.Rename; - const Saveto: protocol.CommandTypes.Saveto; - const SignatureHelp: protocol.CommandTypes.SignatureHelp; - const TypeDefinition: protocol.CommandTypes.TypeDefinition; - const ProjectInfo: protocol.CommandTypes.ProjectInfo; - const ReloadProjects: protocol.CommandTypes.ReloadProjects; - const Unknown: protocol.CommandTypes.Unknown; - const OpenExternalProject: protocol.CommandTypes.OpenExternalProject; - const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects; - const CloseExternalProject: protocol.CommandTypes.CloseExternalProject; - const TodoComments: protocol.CommandTypes.TodoComments; - const Indentation: protocol.CommandTypes.Indentation; - const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate; - 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; - } + type CommandNames = protocol.CommandTypes; + const CommandNames: any; function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; interface SessionOptions { host: ServerHost; @@ -4565,7 +4780,7 @@ declare namespace ts.server { private defaultEventHandler(event); logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; - configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; + configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: Diagnostic[]): void; event(info: T, eventName: string): void; output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private semanticCheck(file, project); @@ -4576,6 +4791,9 @@ declare namespace ts.server { private cleanup(); private getEncodedSemanticClassifications(args); private getProject(projectFileName); + private getConfigFileAndProject(args); + private getConfigFileDiagnostics(configFile, project, includeLinePosition); + private convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics); private getCompilerOptionsDiagnostics(args); private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo); private getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition); @@ -4588,7 +4806,7 @@ declare namespace ts.server { private getDocumentHighlights(args, simplifiedResult); private setCompilerOptionsForInferredProjects(args); private getProjectInfo(args); - private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList); + private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles); private getRenameInfo(args); private getProjects(args); private getDefaultProject(args); @@ -4632,10 +4850,11 @@ declare namespace ts.server { private isLocation(locationOrSpan); private extractPositionAndRange(args, scriptInfo); private getApplicableRefactors(args); - private getRefactorCodeActions(args, simplifiedResult); + private getEditsForRefactor(args, simplifiedResult); private getCodeFixes(args, simplifiedResult); private getStartAndEndPosition(args, scriptInfo); private mapCodeAction(codeAction, scriptInfo); + private mapTextChangesToCodeEdits(project, textChanges); private convertTextChangeToCodeEdit(change, scriptInfo); private getBraceMatching(args, simplifiedResult); private getDiagnosticsForProject(next, delay, fileName); @@ -4662,14 +4881,12 @@ declare namespace ts.server { interface LineCollection { charCount(): number; lineCount(): number; - isLeaf(): boolean; + isLeaf(): this is LineLeaf; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; } - interface ILineInfo { - line: number; - offset: number; - text?: string; - leaf?: LineLeaf; + interface AbsolutePositionAndLineText { + absolutePosition: number; + lineText: string | undefined; } enum CharRangeSection { PreStart = 0, @@ -4683,8 +4900,8 @@ declare namespace ts.server { goSubtree: boolean; done: boolean; leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void; - pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): LineCollection; - post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): LineCollection; + pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; + post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): void; } class TextChange { pos: number; @@ -4694,83 +4911,78 @@ declare namespace ts.server { getTextChangeRange(): TextChangeRange; } class ScriptVersionCache { - changes: TextChange[]; - versions: LineIndexSnapshot[]; - minVersion: number; - private host; + private changes; + private readonly versions; + private minVersion; private currentVersion; - static changeNumberThreshold: number; - static changeLengthThreshold: number; - static maxVersions: number; + private static readonly changeNumberThreshold; + private static readonly changeLengthThreshold; + private static readonly maxVersions; private versionToIndex(version); private currentVersionToIndex(); edit(pos: number, deleteLen: number, insertedText?: string): void; latest(): LineIndexSnapshot; latestVersion(): number; - reloadFromFile(filename: string): void; reload(script: string): void; getSnapshot(): LineIndexSnapshot; getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange; - static fromString(host: ServerHost, script: string): ScriptVersionCache; + static fromString(script: string): ScriptVersionCache; } - class LineIndexSnapshot implements ts.IScriptSnapshot { + class LineIndexSnapshot implements IScriptSnapshot { readonly version: number; readonly cache: ScriptVersionCache; - index: LineIndex; - changesSincePreviousVersion: TextChange[]; - constructor(version: number, cache: ScriptVersionCache); + readonly index: LineIndex; + readonly changesSincePreviousVersion: ReadonlyArray; + constructor(version: number, cache: ScriptVersionCache, index: LineIndex, changesSincePreviousVersion?: ReadonlyArray); getText(rangeStart: number, rangeEnd: number): string; getLength(): number; - getLineStartPositions(): number[]; - getLineMapper(): (line: number) => number; - getTextChangeRangeSinceVersion(scriptVersion: number): TextChangeRange; - getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange; + getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; } class LineIndex { root: LineNode; checkEdits: boolean; - charOffsetToLineNumberAndPos(charOffset: number): ILineInfo; - lineNumberToInfo(lineNumber: number): ILineInfo; + absolutePositionOfStartOfLine(oneBasedLine: number): number; + positionToLineOffset(position: number): protocol.Location; + private positionToColumnAndLineText(position); + lineNumberToInfo(oneBasedLine: number): AbsolutePositionAndLineText; load(lines: string[]): void; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; getText(rangeStart: number, rangeLength: number): string; getLength(): number; every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number): boolean; edit(pos: number, deleteLength: number, newText?: string): LineIndex; - static buildTreeFromBottom(nodes: LineCollection[]): LineNode; + private static buildTreeFromBottom(nodes); static linesFromText(text: string): { lines: string[]; lineMap: number[]; }; } class LineNode implements LineCollection { + private readonly children; totalChars: number; totalLines: number; - children: LineCollection[]; + constructor(children?: LineCollection[]); isLeaf(): boolean; updateCounts(): void; - execWalk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker, childIndex: number, nodeType: CharRangeSection): boolean; - skipChild(relativeStart: number, relativeLength: number, childIndex: number, walkFns: ILineIndexWalker, nodeType: CharRangeSection): void; + private execWalk(rangeStart, rangeLength, walkFns, childIndex, nodeType); + private skipChild(relativeStart, relativeLength, childIndex, walkFns, nodeType); walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; - charOffsetToLineNumberAndPos(lineNumber: number, charOffset: number): ILineInfo; - lineNumberToInfo(lineNumber: number, charOffset: number): ILineInfo; - childFromLineNumber(lineNumber: number, charOffset: number): { - child: LineCollection; - childIndex: number; - relativeLineNumber: number; - charOffset: number; + charOffsetToLineInfo(lineNumberAccumulator: number, relativePosition: number): { + oneBasedLine: number; + zeroBasedColumn: number; + lineText: string | undefined; }; - childFromCharOffset(lineNumber: number, charOffset: number): { - child: LineCollection; - childIndex: number; - charOffset: number; - lineNumber: number; + lineNumberToInfo(relativeOneBasedLine: number, positionAccumulator: number): { + position: number; + leaf: LineLeaf | undefined; }; - splitAfter(childIndex: number): LineNode; + private childFromLineNumber(relativeOneBasedLine, positionAccumulator); + private childFromCharOffset(lineNumberAccumulator, relativePosition); + private splitAfter(childIndex); remove(child: LineCollection): void; - findChildIndex(child: LineCollection): number; + private findChildIndex(child); insertAt(child: LineCollection, nodes: LineCollection[]): LineNode[]; - add(collection: LineCollection): boolean; + add(collection: LineCollection): void; charCount(): number; lineCount(): number; } @@ -4814,29 +5026,30 @@ declare namespace ts.server { reload(script: string): void; saveTo(fileName: string): void; reloadFromFile(tempFileName?: NormalizedPath): void; - getLineInfo(line: number): ILineInfo; + getLineInfo(line: number): AbsolutePositionAndLineText; editContent(start: number, end: number, newText: string): void; markContainingProjectsAsDirty(): void; lineToTextSpan(line: number): TextSpan; lineOffsetToPosition(line: number, offset: number): number; - positionToLineOffset(position: number): ILineInfo; + positionToLineOffset(position: number): protocol.Location; isJavaScript(): boolean; } } declare namespace ts.server { - class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost { + class LSHost implements LanguageServiceHost, ModuleResolutionHost { private readonly host; - private readonly project; + private project; private readonly cancellationToken; private compilationSettings; private readonly resolvedModuleNames; private readonly resolvedTypeReferenceDirectives; private readonly getCanonicalFileName; private filesWithChangedSetOfUnresolvedImports; - private readonly resolveModuleName; + private resolveModuleName; readonly trace: (s: string) => void; readonly realpath?: (path: string) => string; constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken); + dispose(): void; startRecordingFilesWithChangedResolutions(): void; finishRecordingFilesWithChangedResolutions(): Path[]; private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult, getResultFileName, logChanges); @@ -4848,20 +5061,20 @@ declare namespace ts.server { resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModuleFull[]; getDefaultLibFileName(): string; - getScriptSnapshot(filename: string): ts.IScriptSnapshot; + getScriptSnapshot(filename: string): IScriptSnapshot; getScriptFileNames(): string[]; getTypeRootsVersion(): number; getScriptKind(fileName: string): ScriptKind; getScriptVersion(filename: string): string; getCurrentDirectory(): string; resolvePath(path: string): string; - fileExists(path: string): boolean; - readFile(fileName: string): string; + fileExists(file: string): boolean; + readFile(fileName: string): string | undefined; directoryExists(path: string): boolean; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getDirectories(path: string): string[]; notifyFileRemoved(info: ScriptInfo): void; - setCompilationSettings(opt: ts.CompilerOptions): void; + setCompilationSettings(opt: CompilerOptions): void; } } declare namespace ts.server { @@ -4913,7 +5126,7 @@ declare namespace ts.server { function allRootFilesAreJsOrDts(project: Project): boolean; function allFilesAreJsOrDts(project: Project): boolean; class UnresolvedImportsMap { - readonly perFileMap: FileMap>; + readonly perFileMap: Map>; private version; clear(): void; getVersion(): number; @@ -4947,11 +5160,13 @@ declare namespace ts.server { private rootFiles; private rootFilesMap; private program; + private externalFiles; + private missingFilesMap; private cachedUnresolvedImportsPerFile; private lastCachedUnresolvedImportsList; protected languageService: LanguageService; languageServiceEnabled: boolean; - protected readonly lsHost: LSHost; + protected lsHost: LSHost; builder: Builder; private updatedFileNames; private lastReportedFileNames; @@ -4965,9 +5180,10 @@ declare namespace ts.server { isJsOnlyProject(): boolean; getCachedUnresolvedImportsPerFile_TestOnly(): UnresolvedImportsMap; static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {}; - constructor(projectName: string, projectKind: ProjectKind, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); + constructor(projectName: string, projectKind: ProjectKind, projectService: ProjectService, documentRegistry: DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); private setInternalCompilerOptionsForEmittingJsFiles(); - getProjectErrors(): Diagnostic[]; + getGlobalProjectErrors(): Diagnostic[]; + getAllProjectErrors(): Diagnostic[]; getLanguageService(ensureSynchronized?: boolean): LanguageService; getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; getProjectVersion(): string; @@ -4976,7 +5192,7 @@ declare namespace ts.server { getProjectName(): string; abstract getProjectRootPath(): string | undefined; abstract getTypeAcquisition(): TypeAcquisition; - getExternalFiles(): string[]; + getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile; updateTypes(): void; close(): void; @@ -4987,7 +5203,8 @@ declare namespace ts.server { getRootScriptInfos(): ScriptInfo[]; getScriptInfos(): ScriptInfo[]; getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput; - getFileNames(excludeFilesFromExternalLibraries?: boolean): NormalizedPath[]; + getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): NormalizedPath[]; + hasConfigFile(configFilePath: NormalizedPath): boolean; getAllEmittableFiles(): string[]; containsScriptInfo(info: ScriptInfo): boolean; containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; @@ -5000,6 +5217,7 @@ declare namespace ts.server { updateGraph(): boolean; private setTypings(typings); private updateGraphWorker(); + isWatchedMissingFile(path: Path): boolean; getScriptInfoLSHost(fileName: string): ScriptInfo; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; @@ -5010,12 +5228,12 @@ declare namespace ts.server { protected removeRoot(info: ScriptInfo): void; } class InferredProject extends Project { - private static newName; + private static readonly newName; private _isJsInferredProject; toggleJsInferredProject(isJsInferredProject: boolean): void; setCompilerOptions(options?: CompilerOptions): void; directoriesWatchedForTsconfig: string[]; - constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions); + constructor(projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions); addRoot(info: ScriptInfo): void; removeRoot(info: ScriptInfo): void; getProjectRootPath(): string; @@ -5033,7 +5251,7 @@ declare namespace ts.server { readonly canonicalConfigFilePath: NormalizedPath; private plugins; openRefCount: number; - constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean); + constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean); getConfigFilePath(): string; enablePlugins(): void; private enablePlugin(pluginConfigEntry, searchPaths); @@ -5042,7 +5260,7 @@ declare namespace ts.server { setProjectErrors(projectErrors: Diagnostic[]): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; getTypeAcquisition(): TypeAcquisition; - getExternalFiles(): string[]; + getExternalFiles(): SortedReadonlyArray; watchConfigFile(callback: (project: ConfiguredProject) => void): void; watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void; watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void; @@ -5058,7 +5276,7 @@ declare namespace ts.server { compileOnSaveEnabled: boolean; private readonly projectFilePath; private typeAcquisition; - constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); + constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); getProjectRootPath(): string; getTypeAcquisition(): TypeAcquisition; setProjectErrors(projectErrors: Diagnostic[]): void; @@ -5070,6 +5288,7 @@ declare namespace ts.server { const ContextEvent = "context"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + const ProjectInfoTelemetryEvent = "projectInfo"; interface ContextEvent { eventName: typeof ContextEvent; data: { @@ -5092,7 +5311,38 @@ declare namespace ts.server { languageServiceEnabled: boolean; }; } - type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent; + interface ProjectInfoTelemetryEvent { + readonly eventName: typeof ProjectInfoTelemetryEvent; + readonly data: ProjectInfoTelemetryEventData; + } + interface ProjectInfoTelemetryEventData { + readonly projectId: string; + readonly fileStats: FileStats; + readonly compilerOptions: CompilerOptions; + readonly extends: boolean | undefined; + readonly files: boolean | undefined; + readonly include: boolean | undefined; + readonly exclude: boolean | undefined; + readonly compileOnSave: boolean; + readonly typeAcquisition: ProjectInfoTypeAcquisitionData; + readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; + readonly projectType: "external" | "configured"; + readonly languageServiceEnabled: boolean; + readonly version: string; + } + interface ProjectInfoTypeAcquisitionData { + readonly enable: boolean; + readonly include: boolean; + readonly exclude: boolean; + } + interface FileStats { + readonly js: number; + readonly jsx: number; + readonly ts: number; + readonly tsx: number; + readonly dts: number; + } + type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent; interface ProjectServiceEventHandler { (event: ProjectServiceEvent): void; } @@ -5144,7 +5394,7 @@ declare namespace ts.server { private readonly directoryWatchers; private readonly throttledOperations; private readonly hostConfiguration; - private static safelist; + private safelist; private changedFiles; readonly toCanonicalFileName: (f: string) => string; lastDeletedFile: ScriptInfo; @@ -5158,6 +5408,7 @@ declare namespace ts.server { readonly globalPlugins: ReadonlyArray; readonly pluginProbeLocations: ReadonlyArray; readonly allowLocalPluginLoads: boolean; + private readonly seenProjects; constructor(opts: ProjectServiceOptions); ensureInferredProjectsUpToDate_TestOnly(): void; getCompilerOptionsForInferredProjects(): CompilerOptions; @@ -5182,6 +5433,7 @@ declare namespace ts.server { private removeProject(project); private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles); private closeOpenFile(info); + private deleteOrphanScriptInfoNotInAnyProject(); private openOrUpdateConfiguredProjectForFile(fileName, projectRootPath?); private findConfigFile(searchPath, projectRootPath?); private printProjects(); @@ -5190,6 +5442,7 @@ declare namespace ts.server { private convertConfigFileContentToProjectOptions(configFilename); private exceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader); private createAndAddExternalProject(projectFileName, files, options, typeAcquisition); + private sendProjectTelemetry(projectKey, project, projectOptions?); private reportConfigFileDiagnostics(configFileName, diagnostics, triggerFile); private createAndAddConfiguredProject(configFileName, projectOptions, configFileErrors, clientFileName?); private watchConfigDirectoryForProject(project, options); @@ -5200,6 +5453,7 @@ declare namespace ts.server { createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject; getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; + watchClosedScriptInfo(info: ScriptInfo): void; getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfoForPath(fileName: Path): ScriptInfo; @@ -5214,7 +5468,7 @@ declare namespace ts.server { private closeConfiguredProject(configFile); closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; openExternalProjects(projects: protocol.ExternalProject[]): void; - private static filenameEscapeRegexp; + private static readonly filenameEscapeRegexp; private static escapeFilenameForRegex(filename); resetSafeList(): void; loadSafeList(fileName: string): void; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 128438ce66a..07c0852235d 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -13,6 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +"use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; @@ -305,37 +306,29 @@ var ts; 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["JSDocNullableType"] = 270] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 59] = "FirstCompoundAssignment"; @@ -362,9 +355,9 @@ var ts; 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[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -388,6 +381,8 @@ var ts; NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -504,18 +499,20 @@ var ts; (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[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -577,13 +574,11 @@ var ts; 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["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -608,14 +603,13 @@ var ts; 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["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "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 = {})); @@ -638,6 +632,25 @@ var ts; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); var NodeCheckFlags; (function (NodeCheckFlags) { NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; @@ -734,6 +747,18 @@ var ts; IndexKind[IndexKind["String"] = 0] = "String"; IndexKind[IndexKind["Number"] = 1] = "Number"; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; + InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { SpecialPropertyAssignmentKind[SpecialPropertyAssignmentKind["None"] = 0] = "None"; @@ -762,6 +787,7 @@ var ts; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); var JsxEmit; (function (JsxEmit) { @@ -783,6 +809,7 @@ var ts; ScriptKind[ScriptKind["TS"] = 3] = "TS"; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -938,12 +965,11 @@ var ts; })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { - Extension[Extension["Ts"] = 0] = "Ts"; - Extension[Extension["Tsx"] = 1] = "Tsx"; - Extension[Extension["Dts"] = 2] = "Dts"; - Extension[Extension["Js"] = 3] = "Js"; - Extension[Extension["Jsx"] = 4] = "Jsx"; - Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; })(Extension = ts.Extension || (ts.Extension = {})); var TransformFlags; (function (TransformFlags) { @@ -976,6 +1002,7 @@ var ts; TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; @@ -1050,13 +1077,14 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; 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[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1127,7 +1155,8 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.0"; + ts.versionMajorMinor = "2.5"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); (function (ts) { var Ternary; @@ -1148,12 +1177,28 @@ var ts; return new MapCtr(); } ts.createMap = createMap; + function createUnderscoreEscapedMap() { + return new MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function createSymbolTable(symbols) { + var result = createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; function createMapFromTemplate(template) { var map = new MapCtr(); - for (var key in template) + for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); } + } return map; } ts.createMapFromTemplate = createMapFromTemplate; @@ -1223,45 +1268,6 @@ var ts; return class_1; }()); } - function createFileMap(keyMapper) { - var files = createMap(); - return { - get: get, - set: set, - contains: contains, - remove: remove, - forEachValue: forEachValueInMap, - getKeys: getKeys, - clear: clear, - }; - function forEachValueInMap(f) { - files.forEach(function (file, key) { - f(key, file); - }); - } - function getKeys() { - return arrayFrom(files.keys()); - } - function get(path) { - return files.get(toKey(path)); - } - function set(path, value) { - files.set(toKey(path), value); - } - function contains(path) { - return files.has(toKey(path)); - } - function remove(path) { - files.delete(toKey(path)); - } - function clear() { - files.clear(); - } - function toKey(path) { - return keyMapper ? keyMapper(path) : path; - } - } - ts.createFileMap = createFileMap; function toPath(fileName, basePath, getCanonicalFileName) { var nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) @@ -1456,6 +1462,10 @@ var ts; array.length = outIndex; } ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; function map(array, f) { var result; if (array) { @@ -1525,6 +1535,19 @@ var ts; return result; } ts.flatMap = flatMap; + function flatMapIter(iter, mapfn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapfn(value); + if (res) + result.push.apply(result, res); + } + return result; + } + ts.flatMapIter = flatMapIter; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1547,6 +1570,18 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapDefined(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } + } + return result; + } + ts.mapDefined = mapDefined; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1740,12 +1775,21 @@ var ts; return to; } ts.append = append; - function addRange(to, from) { + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { if (from === undefined) return to; - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - to = append(to, v); + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + var v = from[i]; + if (v !== undefined) { + to.push(from[i]); + } } return to; } @@ -1768,16 +1812,22 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; function firstOrUndefined(array) { - return array && array.length > 0 - ? array[0] - : undefined; + return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { @@ -1882,10 +1932,11 @@ var ts; ts.getProperty = getProperty; function getOwnKeys(map) { var keys = []; - for (var key in map) + for (var key in map) { if (hasOwnProperty.call(map, key)) { keys.push(key); } + } return keys; } ts.getOwnKeys = getOwnKeys; @@ -1898,15 +1949,6 @@ var ts; var _b; } ts.arrayFrom = arrayFrom; - function convertToArray(iterator, f) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(f(value)); - } - return result; - var _b; - } - ts.convertToArray = convertToArray; function forEachEntry(map, callback) { var iterator = map.entries(); for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { @@ -1945,10 +1987,11 @@ var ts; } for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var arg = args_1[_a]; - for (var p in arg) + for (var p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; } + } } return t; } @@ -1958,18 +2001,20 @@ var ts; return true; if (!left || !right) return false; - for (var key in left) + for (var key in left) { if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } - for (var key in right) + } + for (var key in right) { if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } + } return true; } ts.equalOwnProperties = equalOwnProperties; @@ -1982,6 +2027,10 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToSet(array, makeKey) { + return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2000,14 +2049,16 @@ var ts; ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) + for (var id in second) { if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - for (var id in first) + } + for (var id in first) { if (hasOwnProperty.call(first, id)) { result[id] = first[id]; } + } return result; } ts.extend = extend; @@ -2041,6 +2092,16 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; function noop() { } ts.noop = noop; function notImplemented() { @@ -2358,10 +2419,18 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); + return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function moduleHasNonRelativeName(moduleName) { + return !isExternalModuleNameRelative(moduleName); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2464,7 +2533,7 @@ var ts; var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - directoryComponents.length--; + directoryComponents.pop(); } var joinStartIndex; for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { @@ -2588,7 +2657,7 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsAny(path, extensions) { + function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; if (fileExtensionIs(path, extension)) { @@ -2597,7 +2666,7 @@ var ts; } return false; } - ts.fileExtensionIsAny = fileExtensionIsAny; + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; @@ -2700,7 +2769,7 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -2712,17 +2781,16 @@ var ts; var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } return flatten(results); - function visitDirectory(path, absolutePath) { + function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; files = files.slice().sort(comparer); - directories = directories.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; @@ -2740,13 +2808,20 @@ var ts; var current = files_1[_i]; _loop_1(current); } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + directories = directories.slice().sort(comparer); for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { var current = directories_1[_b]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName); + visitDirectory(name, absoluteName, depth); } } } @@ -2784,7 +2859,7 @@ var ts; return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } function ensureScriptKind(fileName, scriptKind) { - return (scriptKind || getScriptKindFromFileName(fileName)) || 3; + return scriptKind || getScriptKindFromFileName(fileName) || 3; } ts.ensureScriptKind = ensureScriptKind; function getScriptKindFromFileName(fileName) { @@ -2798,6 +2873,8 @@ var ts; return 3; case ".tsx": return 4; + case ".json": + return 6; default: return 0; } @@ -2906,11 +2983,14 @@ var ts; ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; this.declarations = undefined; } - function Type(_checker, flags) { + function Type(checker, flags) { this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } } function Signature() { } @@ -2925,6 +3005,11 @@ var ts; this.parent = undefined; this.original = undefined; } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, getTokenConstructor: function () { return Node; }, @@ -2932,7 +3017,8 @@ var ts; getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, - getSignatureConstructor: function () { return Signature; } + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; var AssertionLevel; (function (AssertionLevel) { @@ -2944,25 +3030,43 @@ var ts; var Debug; (function (Debug) { Debug.currentAssertionLevel = 0; + Debug.isDebugging = false; function shouldAssert(level) { return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo) { + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { - var verboseDebugString = ""; if (verboseDebugInfo) { - verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); } - debugger; - throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; - function fail(message) { - Debug.assert(false, message); + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; } Debug.fail = fail; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; })(Debug = ts.Debug || (ts.Debug = {})); function orderedRemoveItem(array, item) { for (var i = 0; i < array.length; i++) { @@ -3063,7 +3167,7 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; function extensionIsTypeScript(ext) { - return ext <= ts.Extension.LastTypeScriptExtension; + return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } ts.extensionIsTypeScript = extensionIsTypeScript; function extensionFromPath(path) { @@ -3075,21 +3179,7 @@ var ts; } ts.extensionFromPath = extensionFromPath; function tryGetExtensionFromPath(path) { - if (fileExtensionIs(path, ".d.ts")) { - return ts.Extension.Dts; - } - if (fileExtensionIs(path, ".ts")) { - return ts.Extension.Ts; - } - if (fileExtensionIs(path, ".tsx")) { - return ts.Extension.Tsx; - } - if (fileExtensionIs(path, ".js")) { - return ts.Extension.Js; - } - if (fileExtensionIs(path, ".jsx")) { - return ts.Extension.Jsx; - } + return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3099,6 +3189,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -3171,7 +3267,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName); + fileCallback(fileName, FileWatcherEventKind.Changed); } } } @@ -3184,7 +3280,13 @@ var ts; if (platform === "win32" || platform === "win64") { return false; } - return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + return !fileExists(swapCase(__filename)); + } + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); @@ -3257,8 +3359,8 @@ var ts; return { files: [], directories: [] }; } } - function readDirectory(path, extensions, excludes, includes) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -3310,10 +3412,19 @@ var ts; }; } function fileChanged(curr, prev) { - if (+curr.mtime <= +prev.mtime) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { return; } - callback(fileName); + callback(fileName, eventKind); } }, watchDirectory: function (directoryName, callback, recursive) { @@ -3333,9 +3444,7 @@ var ts; } }); }, - resolvePath: function (path) { - return _path.resolve(path); - }, + resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { @@ -3389,6 +3498,7 @@ var ts; realpath: function (path) { return _fs.realpathSync(path); }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { try { require("source-map-support").install(); @@ -3425,7 +3535,7 @@ var ts; getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), - readDirectory: function (path, extensions, excludes, includes) { + readDirectory: function (path, extensions, excludes, includes, _depth) { var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, @@ -3467,913 +3577,5424 @@ var ts; ? 1 : 0; } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } })(ts || (ts = {})); var ts; (function (ts) { + function diag(code, category, key, message) { + return { code: code, category: category, key: key, message: message }; + } ts.Diagnostics = { - Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated_string_literal_1002", message: "Unterminated string literal." }, - Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_1003", message: "Identifier expected." }, - _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "_0_expected_1005", message: "'{0}' expected." }, - A_file_cannot_have_a_reference_to_itself: { code: 1006, category: ts.DiagnosticCategory.Error, key: "A_file_cannot_have_a_reference_to_itself_1006", message: "A file cannot have a reference to itself." }, - Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing_comma_not_allowed_1009", message: "Trailing comma not allowed." }, - Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "Asterisk_Slash_expected_1010", message: "'*/' expected." }, - Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_1012", message: "Unexpected token." }, - A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_last_in_a_parameter_list_1014", message: "A rest parameter must be last in a parameter list." }, - Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: ts.DiagnosticCategory.Error, key: "Parameter_cannot_have_question_mark_and_initializer_1015", message: "Parameter cannot have question mark and initializer." }, - A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: ts.DiagnosticCategory.Error, key: "A_required_parameter_cannot_follow_an_optional_parameter_1016", message: "A required parameter cannot follow an optional parameter." }, - An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: ts.DiagnosticCategory.Error, key: "An_index_signature_cannot_have_a_rest_parameter_1017", message: "An index signature cannot have a rest parameter." }, - An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", message: "An index signature parameter cannot have an accessibility modifier." }, - An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_a_question_mark_1019", message: "An index signature parameter cannot have a question mark." }, - An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_initializer_1020", message: "An index signature parameter cannot have an initializer." }, - An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, - An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, - An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, - readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, - Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, - _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, - _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, - _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_class_element_1031", message: "'{0}' modifier cannot appear on a class element." }, - super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: ts.DiagnosticCategory.Error, key: "super_must_be_followed_by_an_argument_list_or_member_access_1034", message: "'super' must be followed by an argument list or member access." }, - Only_ambient_modules_can_use_quoted_names: { code: 1035, category: ts.DiagnosticCategory.Error, key: "Only_ambient_modules_can_use_quoted_names_1035", message: "Only ambient modules can use quoted names." }, - Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: ts.DiagnosticCategory.Error, key: "Statements_are_not_allowed_in_ambient_contexts_1036", message: "Statements are not allowed in ambient contexts." }, - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", message: "A 'declare' modifier cannot be used in an already ambient context." }, - Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: ts.DiagnosticCategory.Error, key: "Initializers_are_not_allowed_in_ambient_contexts_1039", message: "Initializers are not allowed in ambient contexts." }, - _0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_in_an_ambient_context_1040", message: "'{0}' modifier cannot be used in an ambient context." }, - _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, - _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, - _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, - A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, - A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, - A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, - A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_have_an_initializer_1048", message: "A rest parameter cannot have an initializer." }, - A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_must_have_exactly_one_parameter_1049", message: "A 'set' accessor must have exactly one parameter." }, - A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_an_optional_parameter_1051", message: "A 'set' accessor cannot have an optional parameter." }, - A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, - A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, - A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, - An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, - The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", message: "The return type of an async function must either be a valid promise or must not contain a callable 'then' member." }, - A_promise_must_have_a_then_method: { code: 1059, category: ts.DiagnosticCategory.Error, key: "A_promise_must_have_a_then_method_1059", message: "A promise must have a 'then' method." }, - The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: { code: 1060, category: ts.DiagnosticCategory.Error, key: "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", message: "The first parameter of the 'then' method of a promise must be a callback." }, - Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, - Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, - An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, - In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, - Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, - _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, - _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, - A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, - Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." }, - An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_be_declared_in_an_ambient_context_1086", message: "An accessor cannot be declared in an ambient context." }, - _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", message: "'{0}' modifier cannot appear on a constructor declaration." }, - _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_parameter_1090", message: "'{0}' modifier cannot appear on a parameter." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", message: "Only a single variable declaration is allowed in a 'for...in' statement." }, - Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: ts.DiagnosticCategory.Error, key: "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", message: "Type parameters cannot appear on a constructor declaration." }, - Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: ts.DiagnosticCategory.Error, key: "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", message: "Type annotation cannot appear on a constructor declaration." }, - An_accessor_cannot_have_type_parameters: { code: 1094, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_have_type_parameters_1094", message: "An accessor cannot have type parameters." }, - A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_a_return_type_annotation_1095", message: "A 'set' accessor cannot have a return type annotation." }, - An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_exactly_one_parameter_1096", message: "An index signature must have exactly one parameter." }, - _0_list_cannot_be_empty: { code: 1097, category: ts.DiagnosticCategory.Error, key: "_0_list_cannot_be_empty_1097", message: "'{0}' list cannot be empty." }, - Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type_parameter_list_cannot_be_empty_1098", message: "Type parameter list cannot be empty." }, - Type_argument_list_cannot_be_empty: { code: 1099, category: ts.DiagnosticCategory.Error, key: "Type_argument_list_cannot_be_empty_1099", message: "Type argument list cannot be empty." }, - Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_in_strict_mode_1100", message: "Invalid use of '{0}' in strict mode." }, - with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_strict_mode_1101", message: "'with' statements are not allowed in strict mode." }, - delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", message: "'delete' cannot be called on an identifier in strict mode." }, - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: { code: 1103, category: ts.DiagnosticCategory.Error, key: "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", message: "A 'for-await-of' statement is only allowed within an async function or async generator." }, - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", message: "A 'continue' statement can only be used within an enclosing iteration statement." }, - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", message: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, - Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump_target_cannot_cross_function_boundary_1107", message: "Jump target cannot cross function boundary." }, - A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: ts.DiagnosticCategory.Error, key: "A_return_statement_can_only_be_used_within_a_function_body_1108", message: "A 'return' statement can only be used within a function body." }, - Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." }, - Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." }, - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", message: "A 'default' clause cannot appear more than once in a 'switch' statement." }, - Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'." }, - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", message: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", message: "A 'break' statement can only jump to a label of an enclosing statement." }, - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", message: "An object literal cannot have multiple properties with the same name in strict mode." }, - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", message: "An object literal cannot have multiple get/set accessors with the same name." }, - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", message: "An object literal cannot have property and accessor with the same name." }, - An_export_assignment_cannot_have_modifiers: { code: 1120, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_have_modifiers_1120", message: "An export assignment cannot have modifiers." }, - Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_strict_mode_1121", message: "Octal literals are not allowed in strict mode." }, - A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: ts.DiagnosticCategory.Error, key: "A_tuple_type_element_list_cannot_be_empty_1122", message: "A tuple type element list cannot be empty." }, - Variable_declaration_list_cannot_be_empty: { code: 1123, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_list_cannot_be_empty_1123", message: "Variable declaration list cannot be empty." }, - Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit_expected_1124", message: "Digit expected." }, - Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal_digit_expected_1125", message: "Hexadecimal digit expected." }, - Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected_end_of_text_1126", message: "Unexpected end of text." }, - Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid_character_1127", message: "Invalid character." }, - Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration_or_statement_expected_1128", message: "Declaration or statement expected." }, - Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement_expected_1129", message: "Statement expected." }, - case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "case_or_default_expected_1130", message: "'case' or 'default' expected." }, - Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property_or_signature_expected_1131", message: "Property or signature expected." }, - Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum_member_expected_1132", message: "Enum member expected." }, - Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_expected_1134", message: "Variable declaration expected." }, - Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument_expression_expected_1135", message: "Argument expression expected." }, - Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property_assignment_expected_1136", message: "Property assignment expected." }, - Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression_or_comma_expected_1137", message: "Expression or comma expected." }, - Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter_declaration_expected_1138", message: "Parameter declaration expected." }, - Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type_parameter_declaration_expected_1139", message: "Type parameter declaration expected." }, - Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type_argument_expected_1140", message: "Type argument expected." }, - String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, - Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, - or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, - Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, - File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing." }, - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, - const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized." }, - const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "const_declarations_can_only_be_declared_inside_a_block_1156", message: "'const' declarations can only be declared inside a block." }, - let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "let_declarations_can_only_be_declared_inside_a_block_1157", message: "'let' declarations can only be declared inside a block." }, - Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." }, - Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated_regular_expression_literal_1161", message: "Unterminated regular expression literal." }, - An_object_member_cannot_be_declared_optional: { code: 1162, category: ts.DiagnosticCategory.Error, key: "An_object_member_cannot_be_declared_optional_1162", message: "An object member cannot be declared optional." }, - A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: ts.DiagnosticCategory.Error, key: "A_yield_expression_is_only_allowed_in_a_generator_body_1163", message: "A 'yield' expression is only allowed in a generator body." }, - Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "Computed_property_names_are_not_allowed_in_enums_1164", message: "Computed property names are not allowed in enums." }, - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", message: "A computed property name in an ambient context must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", message: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", message: "A computed property name in a method overload must directly refer to a built-in symbol." }, - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", message: "A computed property name in an interface must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", message: "A computed property name in a type literal must directly refer to a built-in symbol." }, - A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: ts.DiagnosticCategory.Error, key: "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", message: "A comma expression is not allowed in a computed property name." }, - extends_clause_already_seen: { code: 1172, category: ts.DiagnosticCategory.Error, key: "extends_clause_already_seen_1172", message: "'extends' clause already seen." }, - extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "extends_clause_must_precede_implements_clause_1173", message: "'extends' clause must precede 'implements' clause." }, - Classes_can_only_extend_a_single_class: { code: 1174, category: ts.DiagnosticCategory.Error, key: "Classes_can_only_extend_a_single_class_1174", message: "Classes can only extend a single class." }, - implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "implements_clause_already_seen_1175", message: "'implements' clause already seen." }, - Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface_declaration_cannot_have_implements_clause_1176", message: "Interface declaration cannot have 'implements' clause." }, - Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary_digit_expected_1177", message: "Binary digit expected." }, - Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal_digit_expected_1178", message: "Octal digit expected." }, - Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_expected_1179", message: "Unexpected token. '{' expected." }, - Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property_destructuring_pattern_expected_1180", message: "Property destructuring pattern expected." }, - Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array_element_destructuring_pattern_expected_1181", message: "Array element destructuring pattern expected." }, - A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: ts.DiagnosticCategory.Error, key: "A_destructuring_declaration_must_have_an_initializer_1182", message: "A destructuring declaration must have an initializer." }, - An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1183, category: ts.DiagnosticCategory.Error, key: "An_implementation_cannot_be_declared_in_ambient_contexts_1183", message: "An implementation cannot be declared in ambient contexts." }, - Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, - Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, - A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, - The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, - The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, - An_import_declaration_cannot_have_modifiers: { code: 1191, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_cannot_have_modifiers_1191", message: "An import declaration cannot have modifiers." }, - Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, - An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, - Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, - Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, - An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, - Unterminated_Unicode_escape_sequence: { code: 1199, category: ts.DiagnosticCategory.Error, key: "Unterminated_Unicode_escape_sequence_1199", message: "Unterminated Unicode escape sequence." }, - 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." }, - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", message: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." }, - Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", message: "Invalid use of '{0}'. Class definitions are automatically in strict mode." }, - A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, - Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, - Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, - Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, - Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, - Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: ts.DiagnosticCategory.Error, key: "Generators_are_not_allowed_in_an_ambient_context_1221", message: "Generators are not allowed in an ambient context." }, - An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, - _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "_0_tag_already_specified_1223", message: "'{0}' tag already specified." }, - Signature_0_must_have_a_type_predicate: { code: 1224, category: ts.DiagnosticCategory.Error, key: "Signature_0_must_have_a_type_predicate_1224", message: "Signature '{0}' must have a type predicate." }, - Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot_find_parameter_0_1225", message: "Cannot find parameter '{0}'." }, - Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: ts.DiagnosticCategory.Error, key: "Type_predicate_0_is_not_assignable_to_1_1226", message: "Type predicate '{0}' is not assignable to '{1}'." }, - Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: ts.DiagnosticCategory.Error, key: "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", message: "Parameter '{0}' is not in the same position as parameter '{1}'." }, - A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", message: "A type predicate is only allowed in return type position for functions and methods." }, - A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_a_rest_parameter_1229", message: "A type predicate cannot reference a rest parameter." }, - A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", message: "A type predicate cannot reference element '{0}' in a binding pattern." }, - An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_can_only_be_used_in_a_module_1231", message: "An export assignment can only be used in a module." }, - An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", message: "An import declaration can only be used in a namespace or module." }, - An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_can_only_be_used_in_a_module_1233", message: "An export declaration can only be used in a module." }, - An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", message: "An ambient module declaration is only allowed at the top level in a file." }, - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", message: "A namespace declaration is only allowed in a namespace or module." }, - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", message: "The return type of a property decorator function must be either 'void' or 'any'." }, - The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", message: "The return type of a parameter decorator function must be either 'void' or 'any'." }, - Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", message: "Unable to resolve signature of class decorator when called as an expression." }, - Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, - Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, - Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, - _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, - Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, - Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, - An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, - A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, - A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, - A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: { code: 1250, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, - _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, - with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, - await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, - The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, - Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, - Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, - Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, - A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, - An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, - A_default_export_can_only_be_used_in_an_ECMAScript_style_module: { code: 1319, category: ts.DiagnosticCategory.Error, key: "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", message: "A default export can only be used in an ECMAScript-style module." }, - Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1320, category: ts.DiagnosticCategory.Error, key: "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", message: "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1321, category: ts.DiagnosticCategory.Error, key: "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", message: "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1322, category: ts.DiagnosticCategory.Error, key: "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", message: "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member." }, - Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, - Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, - Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, - Circular_definition_of_import_alias_0: { code: 2303, category: ts.DiagnosticCategory.Error, key: "Circular_definition_of_import_alias_0_2303", message: "Circular definition of import alias '{0}'." }, - Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_2304", message: "Cannot find name '{0}'." }, - Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, - File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, - Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, - Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, - An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, - Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, - A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, - An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, - Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, - Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, - Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, - Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_have_1_type_parameter_s_2317", message: "Global type '{0}' must have {1} type parameter(s)." }, - Cannot_find_global_type_0: { code: 2318, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_type_0_2318", message: "Cannot find global type '{0}'." }, - Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: ts.DiagnosticCategory.Error, key: "Named_property_0_of_types_1_and_2_are_not_identical_2319", message: "Named property '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, - Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, - Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, - Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, - Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, - Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: ts.DiagnosticCategory.Error, key: "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", message: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: ts.DiagnosticCategory.Error, key: "Types_of_parameters_0_and_1_are_incompatible_2328", message: "Types of parameters '{0}' and '{1}' are incompatible." }, - Index_signature_is_missing_in_type_0: { code: 2329, category: ts.DiagnosticCategory.Error, key: "Index_signature_is_missing_in_type_0_2329", message: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index_signatures_are_incompatible_2330", message: "Index signatures are incompatible." }, - this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", message: "'this' cannot be referenced in a module or namespace body." }, - this_cannot_be_referenced_in_current_location: { code: 2332, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_current_location_2332", message: "'this' cannot be referenced in current location." }, - this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_constructor_arguments_2333", message: "'this' cannot be referenced in constructor arguments." }, - this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_static_property_initializer_2334", message: "'this' cannot be referenced in a static property initializer." }, - super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_a_derived_class_2335", message: "'super' can only be referenced in a derived class." }, - super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_constructor_arguments_2336", message: "'super' cannot be referenced in constructor arguments." }, - Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: ts.DiagnosticCategory.Error, key: "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", message: "Super calls are not permitted outside constructors or in nested functions inside constructors." }, - super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: ts.DiagnosticCategory.Error, key: "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", message: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." }, - Property_0_does_not_exist_on_type_1: { code: 2339, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_2339", message: "Property '{0}' does not exist on type '{1}'." }, - Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, - Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, - An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, - 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}'." }, - 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." }, - Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, - Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, - Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, - Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, - The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, - The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter." }, - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, - Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, - Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, - Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'." }, - A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", message: "A parameter property is only allowed in a constructor implementation." }, - A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_of_an_array_type_2370", message: "A rest parameter must be of an array type." }, - A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", message: "A parameter initializer is only allowed in a function or constructor implementation." }, - Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: ts.DiagnosticCategory.Error, key: "Parameter_0_cannot_be_referenced_in_its_initializer_2372", message: "Parameter '{0}' cannot be referenced in its initializer." }, - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: ts.DiagnosticCategory.Error, key: "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", message: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, - Duplicate_string_index_signature: { code: 2374, category: ts.DiagnosticCategory.Error, key: "Duplicate_string_index_signature_2374", message: "Duplicate string index signature." }, - Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, - Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, - Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, - get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, - A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, - Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, - Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, - Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, - Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, - Function_overload_must_be_static: { code: 2387, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_be_static_2387", message: "Function overload must be static." }, - Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_not_be_static_2388", message: "Function overload must not be static." }, - Function_implementation_name_must_be_0: { code: 2389, category: ts.DiagnosticCategory.Error, key: "Function_implementation_name_must_be_0_2389", message: "Function implementation name must be '{0}'." }, - Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor_implementation_is_missing_2390", message: "Constructor implementation is missing." }, - Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: ts.DiagnosticCategory.Error, key: "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", message: "Function implementation is missing or not immediately following the declaration." }, - Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: ts.DiagnosticCategory.Error, key: "Multiple_constructor_implementations_are_not_allowed_2392", message: "Multiple constructor implementations are not allowed." }, - Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate_function_implementation_2393", message: "Duplicate function implementation." }, - Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, - Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, - Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, - Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, - Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, - Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, - Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", message: "Expression resolves to '_super' that compiler uses to capture base class reference." }, - Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, - The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, - The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, - Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, - Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class." }, - The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, - Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, - Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, - Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, - Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'." }, - Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, - A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, - Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'." }, - All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, - Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'." }, - In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, - A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged." }, - A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged." }, - Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", message: "Ambient modules cannot be nested in other modules or namespaces." }, - Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient_module_declaration_cannot_specify_relative_module_name_2436", message: "Ambient module declaration cannot specify relative module name." }, - Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name." }, - Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'." }, - Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", message: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." }, - Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." }, - Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types_have_separate_declarations_of_a_private_property_0_2442", message: "Types have separate declarations of a private property '{0}'." }, - Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", message: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." }, - Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", message: "Property '{0}' is protected in type '{1}' but public in type '{2}'." }, - Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", message: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, - The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, - Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - Class_0_used_before_its_declaration: { code: 2449, category: ts.DiagnosticCategory.Error, key: "Class_0_used_before_its_declaration_2449", message: "Class '{0}' used before its declaration." }, - Enum_0_used_before_its_declaration: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Enum_0_used_before_its_declaration_2450", message: "Enum '{0}' used before its declaration." }, - Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, - An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, - The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, - Variable_0_is_used_before_being_assigned: { code: 2454, category: ts.DiagnosticCategory.Error, key: "Variable_0_is_used_before_being_assigned_2454", message: "Variable '{0}' is used before being assigned." }, - Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", message: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, - Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type_alias_0_circularly_references_itself_2456", message: "Type alias '{0}' circularly references itself." }, - Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'." }, - An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An_AMD_module_cannot_have_multiple_name_assignments_2458", message: "An AMD module cannot have multiple name assignments." }, - Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, - Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, - Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern." }, - A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, - A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, - this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, - super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_a_computed_property_name_2466", message: "'super' cannot be referenced in a computed property name." }, - A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", message: "A computed property name cannot reference a type parameter from its containing type." }, - Cannot_find_global_value_0: { code: 2468, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_value_0_2468", message: "Cannot find global value '{0}'." }, - The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: ts.DiagnosticCategory.Error, key: "The_0_operator_cannot_be_applied_to_type_symbol_2469", message: "The '{0}' operator cannot be applied to type 'symbol'." }, - Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: ts.DiagnosticCategory.Error, key: "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", message: "'Symbol' reference does not refer to the global Symbol constructor object." }, - A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", message: "A computed property name of the form '{0}' must be of type 'symbol'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", message: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." }, - Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: ts.DiagnosticCategory.Error, key: "Enum_declarations_must_all_be_const_or_non_const_2473", message: "Enum declarations must all be const or non-const." }, - In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: ts.DiagnosticCategory.Error, key: "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", message: "In 'const' enum declarations member initializer must be constant expression." }, - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: ts.DiagnosticCategory.Error, key: "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", message: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." }, - A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: ts.DiagnosticCategory.Error, key: "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", message: "A const enum member can only be accessed using a string literal." }, - const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", message: "'const' enum member initializer was evaluated to a non-finite value." }, - const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", message: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, - Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_const_enum_1_2479", message: "Property '{0}' does not exist on 'const' enum '{1}'." }, - let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", message: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." }, - Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, - The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, - Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'." }, - The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, - An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, - The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", message: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." }, - Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause." }, - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", message: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." }, - Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", message: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." }, - Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_2495", message: "Type '{0}' is not an array type or a string type." }, - The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", message: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." }, - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: ts.DiagnosticCategory.Error, key: "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", message: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." }, - Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: ts.DiagnosticCategory.Error, key: "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", message: "Module '{0}' uses 'export =' and cannot be used with 'export *'." }, - An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", message: "An interface can only extend an identifier/qualified-name with optional type arguments." }, - A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", message: "A class can only implement an identifier/qualified-name with optional type arguments." }, - A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, - _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, - Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: { code: 2504, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", message: "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator." }, - A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, - _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, - Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, - No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: ts.DiagnosticCategory.Error, key: "No_base_constructor_has_the_specified_number_of_type_arguments_2508", message: "No base constructor has the specified number of type arguments." }, - Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, - Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, - Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, - Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, - Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, - Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, - All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, - Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, - A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, - An_async_iterator_must_have_a_next_method: { code: 2519, category: ts.DiagnosticCategory.Error, key: "An_async_iterator_must_have_a_next_method_2519", message: "An async iterator must have a 'next()' method." }, - Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, - Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, - yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, - await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, - A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, - A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, - Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, - Object_is_possibly_null: { code: 2531, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_2531", message: "Object is possibly 'null'." }, - Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, - Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, - A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, - Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, - Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, - Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, - Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, - The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, - Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, - Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, - Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, - A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, - The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: { code: 2547, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", message: "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property." }, - Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { 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." }, - Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'." }, - JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", message: "JSX element type '{0}' does not have any construct or call signatures." }, - JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", message: "JSX element type '{0}' is not a constructor function for JSX elements." }, - Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", message: "Property '{0}' of JSX spread attribute is not assignable to target property." }, - JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property." }, - The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property." }, - JSX_spread_child_must_be_an_array_type: { code: 2609, category: ts.DiagnosticCategory.Error, key: "JSX_spread_child_must_be_an_array_type_2609", message: "JSX spread child must be an array type." }, - Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: { code: 2649, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", message: "Cannot augment module '{0}' with value exports because it resolves to a non-module entity." }, - Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React." }, - A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", message: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." }, - Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", message: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, - Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", message: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." }, - Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, - Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, - JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element." }, - Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'." }, - super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, - super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, - Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", message: "Cannot export '{0}'. Only local declarations can be exported from a module." }, - Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, - Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, - Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, - Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, - Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, - Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, - export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, - Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, - Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, - Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, - Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, - Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, - Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, - Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, - Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, - A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: { code: 2677, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", message: "A type predicate's type must be assignable to its parameter's type." }, - Type_0_is_not_comparable_to_type_1: { code: 2678, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_comparable_to_type_1_2678", message: "Type '{0}' is not comparable to type '{1}'." }, - A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: { code: 2679, category: ts.DiagnosticCategory.Error, key: "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", message: "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'." }, - A_this_parameter_must_be_the_first_parameter: { code: 2680, category: ts.DiagnosticCategory.Error, key: "A_this_parameter_must_be_the_first_parameter_2680", message: "A 'this' parameter must be the first parameter." }, - A_constructor_cannot_have_a_this_parameter: { code: 2681, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_have_a_this_parameter_2681", message: "A constructor cannot have a 'this' parameter." }, - get_and_set_accessor_must_have_the_same_this_type: { code: 2682, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_this_type_2682", message: "'get' and 'set' accessor must have the same 'this' type." }, - this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, - The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, - The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, - All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, - Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, - Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, - Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, - The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, - Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, - Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: { code: 2699, category: ts.DiagnosticCategory.Error, key: "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", message: "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'." }, - Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, - The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, - The_operand_of_a_delete_operator_must_be_a_property_reference: { code: 2703, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", message: "The operand of a delete operator must be a property reference." }, - The_operand_of_a_delete_operator_cannot_be_a_read_only_property: { code: 2704, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", message: "The operand of a delete operator cannot be a read-only property." }, - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: { code: 2705, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", message: "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option." }, - Required_type_parameters_may_not_follow_optional_type_parameters: { code: 2706, category: ts.DiagnosticCategory.Error, key: "Required_type_parameters_may_not_follow_optional_type_parameters_2706", message: "Required type parameters may not follow optional type parameters." }, - Generic_type_0_requires_between_1_and_2_type_arguments: { code: 2707, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_between_1_and_2_type_arguments_2707", message: "Generic type '{0}' requires between {1} and {2} type arguments." }, - Cannot_use_namespace_0_as_a_value: { code: 2708, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_value_2708", message: "Cannot use namespace '{0}' as a value." }, - Cannot_use_namespace_0_as_a_type: { code: 2709, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_type_2709", message: "Cannot use namespace '{0}' as a type." }, - _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: { code: 2710, category: ts.DiagnosticCategory.Error, key: "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", message: "'{0}' are specified twice. The attribute named '{0}' will be overwritten." }, - Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, - Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, - Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", message: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", message: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", message: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", message: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", message: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", message: "Type parameter '{0}' of exported function has or is using private name '{1}'." }, - Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", message: "Implements clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "'extends' clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "'extends' clause of exported interface '{0}' has or is using private name '{1}'." }, - Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", message: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." }, - Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", message: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." }, - Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_private_name_1_4025", message: "Exported variable '{0}' has or is using private name '{1}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", message: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", message: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", message: "Public static property '{0}' of exported class has or is using private name '{1}'." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", message: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", message: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", message: "Public property '{0}' of exported class has or is using private name '{1}'." }, - Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", message: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." }, - Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", message: "Property '{0}' of exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", message: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", message: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", message: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", message: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", message: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", message: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", message: "Return type of public static property getter from exported class has or is using private name '{0}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", message: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", message: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", message: "Return type of public property getter from exported class has or is using private name '{0}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", message: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", message: "Return type of constructor signature from exported interface has or is using private name '{0}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", message: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", message: "Return type of call signature from exported interface has or is using private name '{0}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", message: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", message: "Return type of index signature from exported interface has or is using private name '{0}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", message: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", message: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", message: "Return type of public static method from exported class has or is using private name '{0}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", message: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", message: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", message: "Return type of public method from exported class has or is using private name '{0}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", message: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", message: "Return type of method from exported interface has or is using private name '{0}'." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", message: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", message: "Return type of exported function has or is using name '{0}' from private module '{1}'." }, - Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", message: "Return type of exported function has or is using private name '{0}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", message: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", message: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", message: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", message: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", message: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", message: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", message: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", message: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", message: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", message: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", message: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, - Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, - Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced: { code: 4093, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced_4093", message: "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced." }, - The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, - Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, - File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, - Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}." }, - Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, - Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "Unknown compiler option '{0}'." }, - Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_requires_a_value_of_type_1_5024", message: "Compiler option '{0}' requires a value of type {1}." }, - Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}." }, - Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", message: "Option 'project' cannot be mixed with source files on a command line." }, - Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher." }, - Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", message: "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." }, - Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, - Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, - A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, - Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, - Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, - Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'." }, - The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'." }, - Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, - Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, - Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character." }, - Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character." }, - Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, - Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, - File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, - Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, - Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, - Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, - Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, - Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", message: "Specify the location where debugger should locate TypeScript files instead of source locations." }, - Watch_input_files: { code: 6005, category: ts.DiagnosticCategory.Message, key: "Watch_input_files_6005", message: "Watch input files." }, - Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect_output_structure_to_the_directory_6006", message: "Redirect output structure to the directory." }, - Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: ts.DiagnosticCategory.Message, key: "Do_not_erase_const_enum_declarations_in_generated_code_6007", message: "Do not erase const enum declarations in generated code." }, - Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, - Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, - Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, - Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, - Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'." }, - Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'." }, - Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, - Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, - Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", message: "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'." }, - Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" }, - options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" }, - file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" }, - Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples_Colon_0_6026", message: "Examples: {0}" }, - Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options_Colon_6027", message: "Options:" }, - Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version_0_6029", message: "Version {0}" }, - Insert_command_line_options_and_files_from_a_file: { code: 6030, category: ts.DiagnosticCategory.Message, key: "Insert_command_line_options_and_files_from_a_file_6030", message: "Insert command line options and files from a file." }, - File_change_detected_Starting_incremental_compilation: { code: 6032, category: ts.DiagnosticCategory.Message, key: "File_change_detected_Starting_incremental_compilation_6032", message: "File change detected. Starting incremental compilation..." }, - KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND_6034", message: "KIND" }, - FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE_6035", message: "FILE" }, - VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, - LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, - DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, - STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, - FILE_OR_DIRECTORY: { code: 6040, category: ts.DiagnosticCategory.Message, key: "FILE_OR_DIRECTORY_6040", message: "FILE OR DIRECTORY" }, - Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, - Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, - Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, - Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}." }, - Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, - Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, - Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." }, - Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted_locale_file_0_6051", message: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", message: "Raise error on expressions and declarations with an implied 'any' type." }, - File_0_not_found: { code: 6053, category: ts.DiagnosticCategory.Error, key: "File_0_not_found_6053", message: "File '{0}' not found." }, - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: ts.DiagnosticCategory.Error, key: "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", message: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, - Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: ts.DiagnosticCategory.Message, key: "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", message: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, - Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", message: "Do not emit declarations for code that has an '@internal' annotation." }, - Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: ts.DiagnosticCategory.Message, key: "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", message: "Specify the root directory of input files. Use to control the output directory structure with --outDir." }, - File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", message: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, - Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", message: "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, - NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, - Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, - Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, - Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, - Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, - Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: { code: 6069, category: ts.DiagnosticCategory.Message, key: "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", message: "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)." }, - Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, - Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, - Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context (experimental)." }, - Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, - Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, - Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, - Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, - Specify_library_files_to_be_included_in_the_compilation_Colon: { code: 6079, category: ts.DiagnosticCategory.Message, key: "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", message: "Specify library files to be included in the compilation: " }, - Specify_JSX_code_generation_Colon_preserve_react_native_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", message: "Specify JSX code generation: 'preserve', 'react-native', or 'react'." }, - File_0_has_an_unsupported_extension_so_skipping_it: { code: 6081, category: ts.DiagnosticCategory.Message, key: "File_0_has_an_unsupported_extension_so_skipping_it_6081", message: "File '{0}' has an unsupported extension, so skipping it." }, - Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, - Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, - Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", message: "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit" }, - Enable_tracing_of_the_name_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_name_resolution_process_6085", message: "Enable tracing of the name resolution process." }, - Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, - Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, - Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, - Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, - Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, - paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, - Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, - Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, - Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, - Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", message: "Loading module as file / folder, candidate module location '{0}', target file type '{1}'." }, - File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, - File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, - Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, - Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, - package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, - Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, - Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, - Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, - Expected_type_of_0_field_in_package_json_to_be_string_got_1: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", message: "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'." }, - baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'." }, - rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'." }, - Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'." }, - Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'." }, - Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'." }, - Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed." }, - Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, - Enable_strict_null_checks: { code: 6113, category: ts.DiagnosticCategory.Message, key: "Enable_strict_null_checks_6113", message: "Enable strict null checks." }, - Unknown_option_excludes_Did_you_mean_exclude: { code: 6114, category: ts.DiagnosticCategory.Error, key: "Unknown_option_excludes_Did_you_mean_exclude_6114", message: "Unknown option 'excludes'. Did you mean 'exclude'?" }, - Raise_error_on_this_expressions_with_an_implied_any_type: { code: 6115, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_this_expressions_with_an_implied_any_type_6115", message: "Raise error on 'this' expressions with an implied 'any' type." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_2: { code: 6116, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========" }, - Resolving_using_primary_search_paths: { code: 6117, category: ts.DiagnosticCategory.Message, key: "Resolving_using_primary_search_paths_6117", message: "Resolving using primary search paths..." }, - Resolving_from_node_modules_folder: { code: 6118, category: ts.DiagnosticCategory.Message, key: "Resolving_from_node_modules_folder_6118", message: "Resolving from node_modules folder..." }, - Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: { code: 6119, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", message: "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========" }, - Type_reference_directive_0_was_not_resolved: { code: 6120, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_not_resolved_6120", message: "======== Type reference directive '{0}' was not resolved. ========" }, - Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'." }, - Root_directory_cannot_be_determined_skipping_primary_search_paths: { code: 6122, category: ts.DiagnosticCategory.Message, key: "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", message: "Root directory cannot be determined, skipping primary search paths." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: { code: 6123, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========" }, - Type_declaration_files_to_be_included_in_compilation: { code: 6124, category: ts.DiagnosticCategory.Message, key: "Type_declaration_files_to_be_included_in_compilation_6124", message: "Type declaration files to be included in compilation." }, - Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'." }, - Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: { code: 6126, category: ts.DiagnosticCategory.Message, key: "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", message: "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder." }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: { code: 6127, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", message: "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========" }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, - The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, - Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'." }, - Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, - File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it." }, - _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - 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}'." }, - Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file." }, - Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, - Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, - Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, - Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, - Resolution_for_module_0_was_found_in_cache: { code: 6147, category: ts.DiagnosticCategory.Message, key: "Resolution_for_module_0_was_found_in_cache_6147", message: "Resolution for module '{0}' was found in cache." }, - Directory_0_does_not_exist_skipping_all_lookups_in_it: { code: 6148, category: ts.DiagnosticCategory.Message, key: "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", message: "Directory '{0}' does not exist, skipping all lookups in it." }, - Show_diagnostic_information: { code: 6149, category: ts.DiagnosticCategory.Message, key: "Show_diagnostic_information_6149", message: "Show diagnostic information." }, - Show_verbose_diagnostic_information: { code: 6150, category: ts.DiagnosticCategory.Message, key: "Show_verbose_diagnostic_information_6150", message: "Show verbose diagnostic information." }, - Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: { code: 6151, category: ts.DiagnosticCategory.Message, key: "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", message: "Emit a single file with source maps instead of having a separate file." }, - Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: { code: 6152, category: ts.DiagnosticCategory.Message, key: "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", message: "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set." }, - Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: { code: 6153, category: ts.DiagnosticCategory.Message, key: "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", message: "Transpile each file as a separate module (similar to 'ts.transpileModule')." }, - Print_names_of_generated_files_part_of_the_compilation: { code: 6154, category: ts.DiagnosticCategory.Message, key: "Print_names_of_generated_files_part_of_the_compilation_6154", message: "Print names of generated files part of the compilation." }, - Print_names_of_files_part_of_the_compilation: { code: 6155, category: ts.DiagnosticCategory.Message, key: "Print_names_of_files_part_of_the_compilation_6155", message: "Print names of files part of the compilation." }, - The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: { code: 6156, category: ts.DiagnosticCategory.Message, key: "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", message: "The locale used when displaying messages to the user (e.g. 'en-us')" }, - Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: { code: 6157, category: ts.DiagnosticCategory.Message, key: "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", message: "Do not generate custom helper functions like '__extends' in compiled output." }, - Do_not_include_the_default_library_file_lib_d_ts: { code: 6158, category: ts.DiagnosticCategory.Message, key: "Do_not_include_the_default_library_file_lib_d_ts_6158", message: "Do not include the default library file (lib.d.ts)." }, - Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: { code: 6159, category: ts.DiagnosticCategory.Message, key: "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", message: "Do not add triple-slash references or imported modules to the list of compiled files." }, - Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: { code: 6160, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", message: "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files." }, - List_of_folders_to_include_type_definitions_from: { code: 6161, category: ts.DiagnosticCategory.Message, key: "List_of_folders_to_include_type_definitions_from_6161", message: "List of folders to include type definitions from." }, - Disable_size_limitations_on_JavaScript_projects: { code: 6162, category: ts.DiagnosticCategory.Message, key: "Disable_size_limitations_on_JavaScript_projects_6162", message: "Disable size limitations on JavaScript projects." }, - The_character_set_of_the_input_files: { code: 6163, category: ts.DiagnosticCategory.Message, key: "The_character_set_of_the_input_files_6163", message: "The character set of the input files." }, - Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: { code: 6164, category: ts.DiagnosticCategory.Message, key: "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", message: "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files." }, - Do_not_truncate_error_messages: { code: 6165, category: ts.DiagnosticCategory.Message, key: "Do_not_truncate_error_messages_6165", message: "Do not truncate error messages." }, - Output_directory_for_generated_declaration_files: { code: 6166, category: ts.DiagnosticCategory.Message, key: "Output_directory_for_generated_declaration_files_6166", message: "Output directory for generated declaration files." }, - A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: { code: 6167, category: ts.DiagnosticCategory.Message, key: "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", message: "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'." }, - List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: { code: 6168, category: ts.DiagnosticCategory.Message, key: "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", message: "List of root folders whose combined content represents the structure of the project at runtime." }, - Show_all_compiler_options: { code: 6169, category: ts.DiagnosticCategory.Message, key: "Show_all_compiler_options_6169", message: "Show all compiler options." }, - Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: { code: 6170, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", message: "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file" }, - Command_line_Options: { code: 6171, category: ts.DiagnosticCategory.Message, key: "Command_line_Options_6171", message: "Command-line Options" }, - Basic_Options: { code: 6172, category: ts.DiagnosticCategory.Message, key: "Basic_Options_6172", message: "Basic Options" }, - Strict_Type_Checking_Options: { code: 6173, category: ts.DiagnosticCategory.Message, key: "Strict_Type_Checking_Options_6173", message: "Strict Type-Checking Options" }, - Module_Resolution_Options: { code: 6174, category: ts.DiagnosticCategory.Message, key: "Module_Resolution_Options_6174", message: "Module Resolution Options" }, - Source_Map_Options: { code: 6175, category: ts.DiagnosticCategory.Message, key: "Source_Map_Options_6175", message: "Source Map Options" }, - Additional_Checks: { code: 6176, category: ts.DiagnosticCategory.Message, key: "Additional_Checks_6176", message: "Additional Checks" }, - Experimental_Options: { code: 6177, category: ts.DiagnosticCategory.Message, key: "Experimental_Options_6177", message: "Experimental Options" }, - Advanced_Options: { code: 6178, category: ts.DiagnosticCategory.Message, key: "Advanced_Options_6178", message: "Advanced Options" }, - Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: { code: 6179, category: ts.DiagnosticCategory.Message, key: "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", message: "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'." }, - 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." }, - new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: ts.DiagnosticCategory.Error, key: "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", message: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, - _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, - Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, - Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, - Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, - Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, - Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, - Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", message: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." }, - _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: { code: 7023, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", message: "'{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." }, - 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: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "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." }, - Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, - JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists." }, - Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, - Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, - Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, - Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, - Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, - Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: { code: 7035, category: ts.DiagnosticCategory.Error, key: "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", message: "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`" }, - You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, - You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, - import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, - export_can_only_be_used_in_a_ts_file: { code: 8003, category: ts.DiagnosticCategory.Error, key: "export_can_only_be_used_in_a_ts_file_8003", message: "'export=' can only be used in a .ts file." }, - type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: ts.DiagnosticCategory.Error, key: "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", message: "'type parameter declarations' can only be used in a .ts file." }, - implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: ts.DiagnosticCategory.Error, key: "implements_clauses_can_only_be_used_in_a_ts_file_8005", message: "'implements clauses' can only be used in a .ts file." }, - interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: ts.DiagnosticCategory.Error, key: "interface_declarations_can_only_be_used_in_a_ts_file_8006", message: "'interface declarations' can only be used in a .ts file." }, - module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: ts.DiagnosticCategory.Error, key: "module_declarations_can_only_be_used_in_a_ts_file_8007", message: "'module declarations' can only be used in a .ts file." }, - type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: ts.DiagnosticCategory.Error, key: "type_aliases_can_only_be_used_in_a_ts_file_8008", message: "'type aliases' can only be used in a .ts file." }, - _0_can_only_be_used_in_a_ts_file: { code: 8009, category: ts.DiagnosticCategory.Error, key: "_0_can_only_be_used_in_a_ts_file_8009", message: "'{0}' can only be used in a .ts file." }, - types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, - type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, - parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, - type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, - Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, - JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, - JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, - Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, - JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "JSX attribute expected." }, - Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, - A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'." }, - An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, - super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, - super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, - _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: { code: 17012, category: ts.DiagnosticCategory.Error, key: "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", message: "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" }, - Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: { code: 17013, category: ts.DiagnosticCategory.Error, key: "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", message: "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." }, - Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, - The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, - No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, - Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, - Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, - Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'." }, - Remove_declaration_for_Colon_0: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_declaration_for_Colon_0_90004", message: "Remove declaration for: '{0}'." }, - Implement_interface_0: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_0_90006", message: "Implement interface '{0}'." }, - Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class." }, - Add_this_to_unresolved_variable: { code: 90008, category: ts.DiagnosticCategory.Message, key: "Add_this_to_unresolved_variable_90008", message: "Add 'this.' to unresolved variable." }, - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig." }, - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, - Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}." }, - Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}." }, - Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}." }, - Add_declaration_for_missing_property_0: { code: 90016, category: ts.DiagnosticCategory.Message, key: "Add_declaration_for_missing_property_0_90016", message: "Add declaration for missing property '{0}'." }, - Add_index_signature_for_missing_property_0: { code: 90017, category: ts.DiagnosticCategory.Message, key: "Add_index_signature_for_missing_property_0_90017", message: "Add index signature for missing property '{0}'." }, - Disable_checking_for_this_file: { code: 90018, category: ts.DiagnosticCategory.Message, key: "Disable_checking_for_this_file_90018", message: "Disable checking for this file." }, - 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." }, + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), + A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), + A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), + A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), + A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "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: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "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: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "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: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "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: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), + Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "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: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _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: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{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."), + 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), }; })(ts || (ts = {})); var ts; +(function (ts) { + ts.emptyArray = []; + ts.emptyMap = ts.createMap(); + ts.externalHelpersModuleNameText = "tslib"; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + function findDeclaration(symbol, predicate) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + if (predicate(declaration)) { + return declaration; + } + } + } + return undefined; + } + ts.findDeclaration = findDeclaration; + var stringWriter = createSingleLineStringWriter(); + var stringWriterAcquired = false; + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + string: function () { return str; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function usingSingleLineStringWriter(action) { + try { + ts.Debug.assert(!stringWriterAcquired); + stringWriterAcquired = true; + action(stringWriter); + return stringWriter.string(); + } + finally { + stringWriter.clear(); + stringWriterAcquired = false; + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + 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]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || + ts.forEachChild(node, containsParseError); + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072; + } + node.flags |= 262144; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 265) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 207: + case 235: + case 214: + case 215: + case 216: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getStartPosOfNode(node) { + return node.pos; + } + ts.getStartPosOfNode = getStartPosOfNode; + function isDefined(value) { + return value !== undefined; + } + ts.isDefined = isDefined; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + return sourceText.length - 1; + } + else { + var start = lineStarts[lineIndex]; + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); + } + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); + } + if (node.kind === 286 && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceFile.text; + return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function getTextOfNodeFromSourceText(sourceText, node) { + if (nodeIsMissing(node)) { + return ""; + } + return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile) { + if (!nodeIsSynthesized(node) && node.parent) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + switch (node.kind) { + case 9: + return '"' + escapeText(node.text) + '"'; + case 13: + return "`" + escapeText(node.text) + "`"; + case 14: + return "`" + escapeText(node.text) + "${"; + case 15: + return "}" + escapeText(node.text) + "${"; + case 16: + return "}" + escapeText(node.text) + "`"; + case 8: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + function escapeIdentifier(identifier) { + return identifier; + } + ts.escapeIdentifier = escapeIdentifier; + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 226 && node.parent.kind === 260; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return node && node.kind === 233 && + (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + return node && node.kind === 233 && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 265 || + node.kind === 233 || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + if (!node || !isAmbientModule(node)) { + return false; + } + switch (node.parent.kind) { + case 265: + return ts.isExternalModule(node.parent); + case 234: + return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules; + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 265: + case 235: + case 260: + case 233: + case 214: + case 215: + case 216: + case 152: + case 151: + case 153: + case 154: + case 228: + case 186: + case 187: + return true; + case 207: + return parentNode && !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function getEnclosingBlockScopeContainer(node) { + var current = node.parent; + while (current) { + if (isBlockScope(current, current.parent)) { + return current; + } + current = current.parent; + } + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + function declarationNameToString(name) { + return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 71: + return name.escapedText; + case 9: + case 8: + return escapeLeadingUnderscores(name.text); + case 144: + if (isStringOrNumericLiteral(name.expression)) { + return escapeLeadingUnderscores(name.expression.text); + } + } + return undefined; + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 71: + return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); + case 143: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 179: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, true, sourceFile.languageVariant, sourceFile.text, undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 207) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 265: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); + if (pos_1 === sourceFile.text.length) { + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + case 226: + case 176: + case 229: + case 199: + case 230: + case 233: + case 232: + case 264: + case 228: + case 186: + case 151: + case 153: + case 154: + case 231: + errorNode = node.name; + break; + case 187: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var pos = nodeIsMissing(errorNode) + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isConstEnumDeclaration(node) { + return node.kind === 232 && isConst(node); + } + ts.isConstEnumDeclaration = isConstEnumDeclaration; + function isConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2) + || !!(ts.getCombinedModifierFlags(node) & 2048); + } + ts.isConst = isConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 181 && n.expression.kind === 97; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 181 && n.expression.kind === 91; + } + ts.isImportCall = isImportCall; + function isPrologueDirective(node) { + return node.kind === 210 + && node.expression.kind === 9; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getLeadingCommentRangesOfNodeFromText(node, text) { + return ts.getLeadingCommentRanges(text, node.pos); + } + ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 146 || + node.kind === 145 || + node.kind === 186 || + node.kind === 187 || + node.kind === 185) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + getLeadingCommentRangesOfNodeFromText(node, text); + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 42 && + text.charCodeAt(comment.pos + 3) !== 47; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (158 <= node.kind && node.kind <= 173) { + return true; + } + switch (node.kind) { + case 119: + case 133: + case 136: + case 122: + case 137: + case 139: + case 130: + return true; + case 105: + return node.parent.kind !== 190; + case 201: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 71: + if (node.parent.kind === 143 && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 179 && node.parent.name === node) { + node = node.parent; + } + ts.Debug.assert(node.kind === 71 || node.kind === 143 || node.kind === 179, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 143: + case 179: + case 99: + var parent = node.parent; + if (parent.kind === 162) { + return false; + } + if (158 <= parent.kind && parent.kind <= 173) { + return true; + } + switch (parent.kind) { + case 201: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 145: + return node === parent.constraint; + case 149: + case 148: + case 146: + case 226: + return node === parent.type; + case 228: + case 186: + case 187: + case 152: + case 151: + case 150: + case 153: + case 154: + return node === parent.type; + case 155: + case 156: + case 157: + return node === parent.type; + case 184: + return node === parent.type; + case 181: + case 182: + return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + case 183: + return false; + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 219: + return visitor(node); + case 235: + case 207: + case 211: + case 212: + case 213: + case 214: + case 215: + case 216: + case 220: + case 221: + case 257: + case 258: + case 222: + case 224: + case 260: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 197: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 232: + case 230: + case 233: + case 231: + case 229: + case 199: + return; + default: + if (ts.isFunctionLike(node)) { + var name = node.name; + if (name && name.kind === 144) { + traverse(name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 164) { + return node.elementType; + } + else if (node && node.kind === 159) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 176: + case 264: + case 146: + case 261: + case 149: + case 148: + case 262: + case 226: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 151: + case 150: + case 152: + case 153: + case 154: + case 228: + case 186: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 222) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 207 && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 151 && node.parent.kind === 178; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 151 && + (node.parent.kind === 178 || + node.parent.kind === 199); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return ts.filter(objectLiteral.properties, function (property) { + if (property.kind === 261) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (key2 && key2 === propName); + } + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getContainingFunction(node) { + while (true) { + node = node.parent; + if (!node || ts.isFunctionLike(node)) { + return node; + } + } + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || ts.isClassLike(node)) { + return node; + } + } + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 144: + if (ts.isClassLike(node.parent.parent)) { + return node; + } + node = node.parent; + break; + case 147: + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + node = node.parent; + } + break; + case 187: + if (!includeArrowFunctions) { + continue; + } + case 228: + case 186: + case 233: + case 149: + case 148: + case 151: + case 150: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 232: + case 265: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, false); + if (container) { + switch (container.kind) { + case 152: + case 228: + case 186: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 144: + node = node.parent; + break; + case 228: + case 186: + case 187: + if (!stopOnFunctions) { + continue; + } + case 149: + case 148: + case 151: + case 150: + case 152: + case 153: + case 154: + return node; + case 147: + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 186 || func.kind === 187) { + var prev = func; + var parent = func.parent; + while (parent.kind === 185) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 181 && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 179 || kind === 180) + && node.expression.kind === 97; + } + ts.isSuperProperty = isSuperProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 159: + return node.typeName; + case 201: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 71: + case 143: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + if (node.kind === 183) { + return node.tag; + } + else if (ts.isJsxOpeningLikeElement(node)) { + return node.tagName; + } + return node.expression; + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node) { + switch (node.kind) { + case 229: + return true; + case 149: + return node.parent.kind === 229; + case 153: + case 154: + case 151: + return node.body !== undefined + && node.parent.kind === 229; + case 146: + return node.parent.body !== undefined + && (node.parent.kind === 152 + || node.parent.kind === 151 + || node.parent.kind === 154) + && node.parent.parent.kind === 229; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node) { + return node.decorators !== undefined + && nodeCanBeDecorated(node); + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 229: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 151: + case 154: + return ts.forEach(node.parameters, nodeIsDecorated); + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 251 || + parent.kind === 250 || + parent.kind === 252) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isPartOfExpression(node) { + switch (node.kind) { + case 97: + case 95: + case 101: + case 86: + case 12: + case 177: + case 178: + case 179: + case 180: + case 181: + case 182: + case 183: + case 202: + case 184: + case 203: + case 185: + case 186: + case 199: + case 187: + case 190: + case 188: + case 189: + case 192: + case 193: + case 194: + case 195: + case 198: + case 196: + case 13: + case 200: + case 249: + case 250: + case 197: + case 191: + case 204: + return true; + case 143: + while (node.parent.kind === 143) { + node = node.parent; + } + return node.parent.kind === 162 || isJSXTagName(node); + case 71: + if (node.parent.kind === 162 || isJSXTagName(node)) { + return true; + } + case 8: + case 9: + case 99: + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 264: + case 261: + case 176: + return parent.initializer === node; + case 210: + case 211: + case 212: + case 213: + case 219: + case 220: + case 221: + case 257: + case 223: + return parent.expression === node; + case 214: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215: + case 216: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + forInStatement.expression === node; + case 184: + case 202: + return node === parent.expression; + case 205: + return node === parent.expression; + case 144: + return node === parent.expression; + case 147: + case 256: + case 255: + case 263: + return true; + case 201: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + if (isPartOfExpression(parent)) { + return true; + } + } + } + return false; + } + ts.isPartOfExpression = isPartOfExpression; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 237 && node.moduleReference.kind === 248; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 237 && node.moduleReference.kind !== 248; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJavaScript(file) { + return isInJavaScriptFile(file); + } + ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isInJavaScriptFile(node) { + return node && !!(node.flags & 65536); + } + ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJSDoc(node) { + return node && !!(node.flags & 1048576); + } + ts.isInJSDoc = isInJSDoc; + function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + if (callExpression.kind !== 181) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 71 || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteral || arg.kind === 9 || arg.kind === 13; + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 || charCode === 34; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionOrClassExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 226) { + var declaration = s.valueDeclaration; + return declaration.initializer && (declaration.initializer.kind === 186 || declaration.initializer.kind === 199); + } + return false; + } + ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + function getSpecialPropertyAssignmentKind(expression) { + if (!isInJavaScriptFile(expression)) { + return 0; + } + var expr = expression; + if (expr.operatorToken.kind !== 58 || expr.left.kind !== 179) { + return 0; + } + var lhs = expr.left; + if (lhs.expression.kind === 71) { + var lhsId = lhs.expression; + if (lhsId.escapedText === "exports") { + return 1; + } + else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { + return 2; + } + else { + return 5; + } + } + else if (lhs.expression.kind === 99) { + return 4; + } + else if (lhs.expression.kind === 179) { + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 71) { + var innerPropertyAccessIdentifier = innerPropertyAccess.expression; + if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { + return 1; + } + if (innerPropertyAccess.name.escapedText === "prototype") { + return 3; + } + } + } + return 0; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getExternalModuleName(node) { + if (node.kind === 238) { + return node.moduleSpecifier; + } + if (node.kind === 237) { + var reference = node.moduleReference; + if (reference.kind === 248) { + return reference.expression; + } + } + if (node.kind === 244) { + return node.moduleSpecifier; + } + if (node.kind === 233 && node.name.kind === 9) { + return node.name; + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + if (node.kind === 237) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240) { + return importClause.namedBindings; + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 238 + && node.importClause + && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 146: + case 151: + case 150: + case 262: + case 261: + case 149: + case 148: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + return node.kind === 273 && + node.parameters.length > 0 && + node.parameters[0].name && + node.parameters[0].name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } + function getAllJSDocs(node) { + if (ts.isJSDocTypedefTag(node)) { + return [node.parent]; + } + return getJSDocCommentsAndTags(node); + } + ts.getAllJSDocs = getAllJSDocs; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getJSDocCommentsAndTags(node) { + var result; + getJSDocCommentsAndTagsWorker(node); + return result || ts.emptyArray; + function getJSDocCommentsAndTagsWorker(node) { + var parent = node.parent; + var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === 208; + var isVariableOfVariableDeclarationStatement = isVariableLike(node) && + parent.parent.kind === 208; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : + undefined; + if (variableStatementNode) { + getJSDocCommentsAndTagsWorker(variableStatementNode); + } + var isSourceOfAssignmentExpressionStatement = parent && parent.parent && + parent.kind === 194 && + parent.operatorToken.kind === 58 && + parent.parent.kind === 210; + if (isSourceOfAssignmentExpressionStatement) { + getJSDocCommentsAndTagsWorker(parent.parent); + } + var isModuleDeclaration = node.kind === 233 && + parent && parent.kind === 233; + var isPropertyAssignmentExpression = parent && parent.kind === 261; + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocCommentsAndTagsWorker(parent); + } + if (node.kind === 146) { + result = ts.addRange(result, getJSDocParameterTags(node)); + } + if (isVariableLike(node) && node.initializer) { + result = ts.addRange(result, node.initializer.jsDoc); + } + result = ts.addRange(result, node.jsDoc); + } + } + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + ts.Debug.assert(node.parent.kind === 275); + var func = node.parent.parent; + if (!ts.isFunctionLike(func)) { + return undefined; + } + var parameter = ts.find(func.parameters, function (p) { + return p.name.kind === 71 && p.name.escapedText === name; + }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281); + if (!tag && node.kind === 146) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function hasRestParameter(s) { + return isRestParameter(ts.lastOrUndefined(s.parameters)); + } + ts.hasRestParameter = hasRestParameter; + function hasDeclaredRestParameter(s) { + return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); + } + ts.hasDeclaredRestParameter = hasDeclaredRestParameter; + function isRestParameter(node) { + if (isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 274 || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { + return true; + } + } + return isDeclaredRestParam(node); + } + ts.isRestParameter = isRestParameter; + function isDeclaredRestParam(node) { + 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) { + switch (parent.kind) { + case 194: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 58 ? 1 : 2 : + 0; + case 192: + case 193: + var unaryOperator = parent.operator; + return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; + case 215: + case 216: + return parent.initializer === node ? 1 : 0; + case 185: + case 177: + case 198: + node = parent; + break; + case 262: + if (parent.name !== node) { + return 0; + } + node = parent.parent; + break; + case 261: + if (parent.name === node) { + return 0; + } + node = parent.parent; + break; + default: + return 0; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0; + } + ts.isAssignmentTarget = isAssignmentTarget; + function isDeleteTarget(node) { + if (node.kind !== 179 && node.kind !== 180) { + return false; + } + node = node.parent; + while (node && node.kind === 185) { + node = node.parent; + } + return node && node.kind === 188; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + function isInAmbientContext(node) { + while (node) { + if (hasModifier(node, 2) || (node.kind === 265 && node.isDeclarationFile)) { + return true; + } + node = node.parent; + } + return false; + } + ts.isInAmbientContext = isInAmbientContext; + function isDeclarationName(name) { + switch (name.kind) { + case 71: + case 9: + case 8: + return ts.isDeclaration(name.parent) && name.parent.name === name; + default: + return false; + } + } + ts.isDeclarationName = isDeclarationName; + function isAnyDeclarationName(name) { + switch (name.kind) { + case 71: + case 9: + case 8: + if (ts.isDeclaration(name.parent)) { + return name.parent.name === name; + } + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + default: + return false; + } + } + ts.isAnyDeclarationName = isAnyDeclarationName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 9 || node.kind === 8) && + node.parent.kind === 144 && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 149: + case 148: + case 151: + case 150: + case 153: + case 154: + case 264: + case 261: + case 179: + return parent.name === node; + case 143: + if (parent.right === node) { + while (parent.kind === 143) { + parent = parent.parent; + } + return parent.kind === 162; + } + return false; + case 176: + case 242: + return parent.propertyName === node; + case 246: + case 253: + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + function isAliasSymbolDeclaration(node) { + return node.kind === 237 || + node.kind === 236 || + node.kind === 239 && !!node.name || + node.kind === 240 || + node.kind === 242 || + node.kind === 246 || + node.kind === 243 && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + return isEntityNameExpression(node.expression); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getClassExtendsHeritageClauseElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 85); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 108); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 85); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function getFileReferenceFromReferencePath(comment, commentRange) { + var simpleReferenceRegEx = /^\/\/\/\s*/gim; + if (simpleReferenceRegEx.test(comment)) { + if (isNoDefaultLibRegEx.test(comment)) { + return { isNoDefaultLib: true }; + } + else { + var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); + var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; + return { + fileReference: { + pos: pos, + end: pos + match[3].length, + fileName: match[3] + }, + isNoDefaultLib: false, + isTypeReferenceDirective: !!refLibResult + }; + } + return { + diagnosticMessage: ts.Diagnostics.Invalid_reference_directive_syntax, + isNoDefaultLib: false + }; + } + } + return undefined; + } + ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; + function isKeyword(token) { + return 72 <= token && token <= 142; + } + ts.isKeyword = isKeyword; + function isTrivia(token) { + 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: + case 186: + case 151: + if (node.asteriskToken) { + flags |= 1; + } + case 187: + if (hasModifier(node, 256)) { + flags |= 2; + } + break; + } + if (!node.body) { + flags |= 4; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 228: + case 186: + case 187: + case 151: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 + || kind === 8; + } + ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 144 && + !isStringOrNumericLiteral(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + if (name.kind === 71) { + return name.escapedText; + } + if (name.kind === 9 || name.kind === 8) { + return escapeLeadingUnderscores(name.text); + } + if (name.kind === 144) { + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + var rightHandSideName = nameExpression.name.escapedText; + return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + } + else if (nameExpression.kind === 9 || nameExpression.kind === 8) { + return escapeLeadingUnderscores(nameExpression.text); + } + } + return undefined; + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return ts.unescapeLeadingUnderscores(node.escapedText); + } + if (node.kind === 9 || + node.kind === 8) { + return node.text; + } + } + return undefined; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return node.escapedText; + } + if (node.kind === 9 || + node.kind === 8) { + return escapeLeadingUnderscores(node.text); + } + } + return undefined; + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isESSymbolIdentifier(node) { + return node.kind === 71 && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 146; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 176) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 152 + || kind === 186 + || kind === 228 + || kind === 187 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 233 + || kind === 265; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(node) { + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + function getOriginalSourceFiles(sourceFiles) { + return ts.sameMap(sourceFiles, getOriginalSourceFile); + } + ts.getOriginalSourceFiles = getOriginalSourceFiles; + 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; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 182: + return hasArguments ? 0 : 1; + case 192: + case 189: + case 190: + case 188: + case 191: + case 195: + case 197: + return 1; + case 194: + switch (operator) { + case 40: + case 58: + case 59: + case 60: + case 62: + case 61: + case 63: + case 64: + case 65: + case 66: + case 67: + case 68: + case 70: + case 69: + return 1; + } + } + return 0; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 194) { + return expression.operatorToken.kind; + } + else if (expression.kind === 192 || expression.kind === 193) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 99: + case 97: + case 71: + case 95: + case 101: + case 86: + case 8: + case 9: + case 177: + case 178: + case 186: + case 187: + case 199: + case 249: + case 250: + case 12: + case 13: + case 196: + case 185: + case 200: + return 19; + case 183: + case 179: + case 180: + return 18; + case 182: + return hasArguments ? 18 : 17; + case 181: + return 17; + case 193: + return 16; + case 192: + case 189: + case 190: + case 188: + case 191: + return 15; + case 194: + switch (operatorKind) { + case 51: + case 52: + return 15; + case 40: + case 39: + case 41: + case 42: + return 14; + case 37: + case 38: + return 13; + case 45: + case 46: + case 47: + return 12; + case 27: + case 30: + case 29: + case 31: + case 92: + case 93: + return 11; + case 32: + case 34: + case 33: + case 35: + return 10; + case 48: + return 9; + case 50: + return 8; + case 49: + return 7; + case 53: + return 6; + case 54: + return 5; + case 58: + case 59: + case 60: + case 62: + case 61: + case 63: + case 64: + case 65: + case 66: + case 67: + case 68: + case 70: + case 69: + return 3; + case 26: + return 0; + default: + return -1; + } + case 195: + return 4; + case 197: + return 2; + case 198: + return 1; + case 289: + return 0; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var diagnosticsModified = false; + var modificationCount = 0; + return { + add: add, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + getModificationCount: getModificationCount, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function getModificationCount() { + return modificationCount; + } + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + } + } + else { + diagnostics = nonFileDiagnostics; + } + diagnostics.push(diagnostic); + diagnosticsModified = true; + modificationCount++; + } + function getGlobalDiagnostics() { + sortAndDeduplicate(); + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + sortAndDeduplicate(); + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var allDiagnostics = []; + function pushDiagnostic(d) { + allDiagnostics.push(d); + } + ts.forEach(nonFileDiagnostics, pushDiagnostic); + fileDiagnostics.forEach(function (diagnostics) { + ts.forEach(diagnostics, pushDiagnostic); + }); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } + function sortAndDeduplicate() { + if (!diagnosticsModified) { + return; + } + diagnosticsModified = false; + nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); + fileDiagnostics.forEach(function (diagnostics, key) { + fileDiagnostics.set(key, ts.sortAndDeduplicateDiagnostics(diagnostics)); + }); + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\0": "\\0", + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" + }); + function escapeString(s) { + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c) { + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.substr(0, 1); + return ch.toLowerCase() === ch; + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s) { + s = escapeString(s); + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function write(s) { + if (s && s.length) { + if (lineStart) { + output += getIndentString(indent); + lineStart = false; + } + output += s; + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + if (lineStart) { + lineStart = false; + } + output += s; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + } + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + function writeTextOfNode(text, node) { + write(getTextOfNodeFromSourceText(text, node)); + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeTextOfNode: writeTextOfNode, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount + 1; }, + getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + reset: reset + }; + } + ts.createTextWriter = createTextWriter; + function getResolvedExternalModuleName(host, file) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + function getExternalModuleNameFromPath(host, fileName) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); + return ts.removeFileExtension(relativePath); + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(sourceFile, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(sourceFile, host) { + var options = host.getCompilerOptions(); + var outputDir = options.declarationDir || options.outDir; + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { + var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.forEach(node.members, function (member) { + if (member.kind === 152 && nodeIsPresent(member.body)) { + return member; + } + }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 71 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 99; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 153) { + getAccessor = accessor; + } + else if (accessor.kind === 154) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if ((member.kind === 153 || member.kind === 154) + && hasModifier(member, 32) === hasModifier(accessor, 32)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 153 && !getAccessor) { + getAccessor = member; + } + if (member.kind === 154 && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + function getEffectiveTypeAnnotationNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocType(node); + } + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getEffectiveReturnTypeNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocReturnType(node); + } + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getEffectiveTypeParameterDeclarations(node) { + if (node.typeParameters) { + return node.typeParameters; + } + if (isInJavaScriptFile(node)) { + var templateTag = getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.write(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.write(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.write(" "); + } + } + } + ts.emitComments = emitComments; + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + } + } + else { + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedComment(comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + writer.rawWrite(indentSizeSpaceString); + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + writer.rawWrite(""); + } + } + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + writer.write(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + writer.write(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + writer.writeLiteral(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9) { + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return (getModifierFlags(node) & flags) !== 0; + } + ts.hasModifier = hasModifier; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912) { + return node.modifierFlagsCache & ~536870912; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) { + flags |= 1; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 115: return 32; + case 114: return 4; + case 113: return 16; + case 112: return 8; + case 117: return 128; + case 84: return 1; + case 124: return 2; + case 76: return 2048; + case 79: return 512; + case 120: return 256; + case 131: return 64; + } + return 0; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 54 + || token === 53 + || token === 51; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 58 && token <= 70; + } + ts.isAssignmentOperator = isAssignmentOperator; + function tryGetClassExtendingExpressionWithTypeArguments(node) { + if (node.kind === 201 && + node.parent.token === 85 && + ts.isClassLike(node.parent.parent)) { + return node.parent.parent; + } + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 58 + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, true)) { + var kind = node.left.kind; + return kind === 178 + || kind === 177; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 71) { + return true; + } + else if (ts.isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } + } + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isExpressionWithTypeArgumentsInClassImplementsClause(node) { + return node.kind === 201 + && isEntityNameExpression(node.expression) + && node.parent + && node.parent.token === 108 + && node.parent.parent + && ts.isClassLike(node.parent.parent); + } + ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; + function isEntityNameExpression(node) { + return node.kind === 71 || + node.kind === 179 && isEntityNameExpression(node.expression); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 143 && node.parent.right === node) || + (node.parent.kind === 179 && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 178 && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 177 && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); + } + function tryExtractTypeScriptExtension(fileName) { + return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options) { + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; + } + if (ts.sys) { + return ts.sys.newLine; + } + return carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + function isSimpleExpression(node) { + return isSimpleExpressionWorker(node, 0); + } + ts.isSimpleExpression = isSimpleExpression; + function isSimpleExpressionWorker(node, depth) { + if (depth <= 5) { + var kind = node.kind; + if (kind === 9 + || kind === 8 + || kind === 12 + || kind === 13 + || kind === 71 + || kind === 99 + || kind === 97 + || kind === 101 + || kind === 86 + || kind === 95) { + return true; + } + else if (kind === 179) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 180) { + return isSimpleExpressionWorker(node.expression, depth + 1) + && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + } + else if (kind === 192 + || kind === 193) { + return isSimpleExpressionWorker(node.operand, depth + 1); + } + else if (kind === 194) { + return node.operatorToken.kind !== 40 + && isSimpleExpressionWorker(node.left, depth + 1) + && isSimpleExpressionWorker(node.right, depth + 1); + } + else if (kind === 195) { + return isSimpleExpressionWorker(node.condition, depth + 1) + && isSimpleExpressionWorker(node.whenTrue, depth + 1) + && isSimpleExpressionWorker(node.whenFalse, depth + 1); + } + else if (kind === 190 + || kind === 189 + || kind === 188) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 177) { + return node.elements.length === 0; + } + else if (kind === 178) { + return node.properties.length === 0; + } + else if (kind === 181) { + if (!isSimpleExpressionWorker(node.expression, depth + 1)) { + return false; + } + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (!isSimpleExpressionWorker(argument, depth + 1)) { + return false; + } + } + return true; + } + } + return false; + } + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, true); + } + ts.formatObjectFlags = formatObjectFlags; + function getRangePos(range) { + return range ? range.pos : -1; + } + ts.getRangePos = getRangePos; + function getRangeEnd(range) { + return range ? range.end : -1; + } + ts.getRangeEnd = getRangeEnd; + function movePos(pos, value) { + return ts.positionIsSynthesized(pos) ? -1 : pos + value; + } + ts.movePos = movePos; + function createRange(pos, end) { + return { pos: pos, end: end }; + } + ts.createRange = createRange; + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + function collapseRangeToStart(range) { + return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); + } + ts.collapseRangeToStart = collapseRangeToStart; + function collapseRangeToEnd(range) { + return isCollapsedRange(range) ? range : moveRangePos(range, range.end); + } + ts.collapseRangeToEnd = collapseRangeToEnd; + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 232: + case 233: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isMergedWithClass(node) { + if (node.symbol) { + for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 229 && declaration !== node) { + return true; + } + } + } + return false; + } + ts.isMergedWithClass = isMergedWithClass; + function isFirstDeclarationOfKind(node, kind) { + return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; + } + ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; + function isWatchSet(options) { + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 ? 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 & 4194304) { + 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; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 5: + return "lib.esnext.full.d.ts"; + case 4: + return "lib.es2017.full.d.ts"; + case 3: + return "lib.es2016.full.d.ts"; + case 2: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + var overlapStart = Math.max(span.start, other.start); + var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + return overlapStart < overlapEnd; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlapStart = Math.max(span1.start, span2.start); + var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (overlapStart < overlapEnd) { + return createTextSpanFromBounds(overlapStart, overlapEnd); + } + return undefined; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + var end = start + length; + return start <= textSpanEnd(span) && end >= span.start; + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var intersectStart = Math.max(span1.start, span2.start); + var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (intersectStart <= intersectEnd) { + return createTextSpanFromBounds(intersectStart, intersectEnd); + } + return undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 145) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 176 || ts.isBindingPattern(node))) { + node = node.parent; + } + return node; + } + function getCombinedModifierFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = ts.getModifierFlags(node); + if (node.kind === 226) { + node = node.parent; + } + if (node && node.kind === 227) { + flags |= ts.getModifierFlags(node); + node = node.parent; + } + if (node && node.kind === 208) { + flags |= ts.getModifierFlags(node); + } + return flags; + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 226) { + node = node.parent; + } + if (node && node.kind === 227) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 208) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, undefined, errors); + } + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + function isParseTreeNode(node) { + return (node.flags & 8) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function unescapeIdentifier(id) { + return id; + } + ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { + return declaration.name.right; + } + if (declaration.kind === 194) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; +})(ts || (ts = {})); +(function (ts) { + function isNumericLiteral(node) { + return node.kind === 8; + } + ts.isNumericLiteral = isNumericLiteral; + function isStringLiteral(node) { + return node.kind === 9; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 10; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 12; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 13; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isTemplateHead(node) { + return node.kind === 14; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 15; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 16; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 71; + } + ts.isIdentifier = isIdentifier; + function isQualifiedName(node) { + return node.kind === 143; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 144; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isTypeParameterDeclaration(node) { + return node.kind === 145; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 146; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 147; + } + ts.isDecorator = isDecorator; + function isPropertySignature(node) { + return node.kind === 148; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 149; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 150; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 151; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 152; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 153; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 154; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 155; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 156; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 157; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isTypePredicateNode(node) { + return node.kind === 158; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 159; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 160; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 161; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 162; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 163; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 164; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 165; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 166; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 167; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 168; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 169; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 170; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 171; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 172; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 173; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isObjectBindingPattern(node) { + return node.kind === 174; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 175; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 176; + } + ts.isBindingElement = isBindingElement; + function isArrayLiteralExpression(node) { + return node.kind === 177; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 178; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 179; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 180; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 181; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 182; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 183; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 184; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 185; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 186; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 187; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 188; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 191; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 190; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 191; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 192; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 193; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 194; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 195; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 196; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 197; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 198; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 199; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 200; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 201; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 202; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 203; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 204; + } + ts.isMetaProperty = isMetaProperty; + function isTemplateSpan(node) { + return node.kind === 205; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 206; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + function isBlock(node) { + return node.kind === 207; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 208; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 209; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 210; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 211; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 212; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 213; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 214; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 215; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 216; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 217; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 218; + } + ts.isBreakStatement = isBreakStatement; + function isReturnStatement(node) { + return node.kind === 219; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 220; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 221; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 222; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 223; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 224; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 225; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 226; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 227; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 228; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 229; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 230; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 231; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 232; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 233; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 234; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 235; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 236; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 237; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 239; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 240; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 241; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 242; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 244; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 245; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 246; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 247; + } + ts.isMissingDeclaration = isMissingDeclaration; + function isExternalModuleReference(node) { + return node.kind === 248; + } + ts.isExternalModuleReference = isExternalModuleReference; + function isJsxElement(node) { + return node.kind === 249; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 250; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 251; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 252; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxAttribute(node) { + return node.kind === 253; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 254; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 255; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 256; + } + ts.isJsxExpression = isJsxExpression; + function isCaseClause(node) { + return node.kind === 257; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 258; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 259; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 260; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 261; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 262; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 263; + } + ts.isSpreadAssignment = isSpreadAssignment; + function isEnumMember(node) { + return node.kind === 264; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 265; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 266; + } + ts.isBundle = isBundle; + function isJSDocTypeExpression(node) { + return node.kind === 267; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 268; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 269; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 270; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 271; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 272; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 273; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 274; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 275; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 277; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocParameterTag(node) { + return node.kind === 279; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 280; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 281; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 282; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 283; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 284; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 284 || node.kind === 279; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 285; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; +})(ts || (ts = {})); +(function (ts) { + function isSyntaxList(n) { + return n.kind === 286; + } + ts.isSyntaxList = isSyntaxList; + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + function isNodeKind(kind) { + return kind >= 143; + } + ts.isNodeKind = isNodeKind; + function isToken(n) { + return n.kind >= 0 && n.kind <= 142; + } + ts.isToken = isToken; + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 13; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 13 <= kind && kind <= 16; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 15 + || kind === 16; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isStringTextContainingNode(node) { + switch (node.kind) { + case 9: + case 14: + case 15: + case 16: + case 13: + return true; + default: + return false; + } + } + ts.isStringTextContainingNode = isStringTextContainingNode; + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && node.autoGenerateKind > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifierKind(token) { + switch (token) { + case 117: + case 120: + case 76: + case 124: + case 79: + case 84: + case 114: + case 112: + case 113: + case 131: + case 115: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 143 + || kind === 71; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 71 + || kind === 9 + || kind === 8 + || kind === 144; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 71 + || kind === 174 + || kind === 175; + } + ts.isBindingName = isBindingName; + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 152: + case 186: + case 228: + case 187: + case 151: + case 150: + case 153: + case 154: + case 155: + case 156: + case 157: + case 160: + case 273: + case 161: + return true; + } + return false; + } + ts.isFunctionLikeKind = isFunctionLikeKind; + function isClassElement(node) { + var kind = node.kind; + return kind === 152 + || kind === 149 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 157 + || kind === 206 + || kind === 247; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 229 || node.kind === 199); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 153 || node.kind === 154); + } + ts.isAccessor = isAccessor; + 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 + || kind === 262 + || kind === 263 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 247; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNodeKind(kind) { + return (kind >= 158 && kind <= 173) + || kind === 119 + || kind === 133 + || kind === 134 + || kind === 122 + || kind === 136 + || kind === 137 + || kind === 99 + || kind === 105 + || kind === 139 + || kind === 95 + || kind === 130 + || kind === 201; + } + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 175 + || kind === 174; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 177 + || kind === 178; + } + ts.isAssignmentPattern = isAssignmentPattern; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 176 + || kind === 200; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 226: + case 146: + case 176: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 174: + case 178: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 175: + case 177: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 179 + || kind === 143; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 251: + case 250: + case 181: + case 182: + case 183: + case 147: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 196 + || kind === 13; + } + ts.isTemplateLiteral = isTemplateLiteral; + function isLeftHandSideExpressionKind(kind) { + return kind === 179 + || kind === 180 + || kind === 182 + || kind === 181 + || kind === 249 + || kind === 250 + || kind === 183 + || kind === 177 + || kind === 185 + || kind === 178 + || kind === 199 + || kind === 186 + || kind === 71 + || kind === 12 + || kind === 8 + || kind === 9 + || kind === 13 + || kind === 196 + || kind === 86 + || kind === 95 + || kind === 99 + || kind === 101 + || kind === 97 + || kind === 91 + || kind === 203 + || kind === 204; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 192 + || kind === 193 + || kind === 188 + || kind === 189 + || kind === 190 + || kind === 191 + || kind === 184 + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 195 + || kind === 197 + || kind === 187 + || kind === 194 + || kind === 198 + || kind === 202 + || kind === 200 + || kind === 289 + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 184 + || kind === 202; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 214: + case 215: + case 216: + case 212: + case 213: + return true; + case 222: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + function isForInOrOfStatement(node) { + return node.kind === 215 || node.kind === 216; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isModuleBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233 + || kind === 71; + } + ts.isModuleBody = isModuleBody; + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233; + } + ts.isNamespaceBody = isNamespaceBody; + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 71 + || kind === 233; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 241 + || kind === 240; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isModuleOrEnumDeclaration(node) { + return node.kind === 233 || node.kind === 232; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 187 + || kind === 176 + || kind === 229 + || kind === 199 + || kind === 152 + || kind === 232 + || kind === 264 + || kind === 246 + || kind === 228 + || kind === 186 + || kind === 153 + || kind === 239 + || kind === 237 + || kind === 242 + || kind === 230 + || kind === 253 + || kind === 151 + || kind === 150 + || kind === 233 + || kind === 236 + || kind === 240 + || kind === 146 + || kind === 261 + || kind === 149 + || kind === 148 + || kind === 154 + || kind === 262 + || kind === 231 + || kind === 145 + || kind === 226 + || kind === 283; + } + function isDeclarationStatementKind(kind) { + return kind === 228 + || kind === 247 + || kind === 229 + || kind === 230 + || kind === 231 + || kind === 232 + || kind === 233 + || kind === 238 + || kind === 237 + || kind === 244 + || kind === 243 + || kind === 236; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 218 + || kind === 217 + || kind === 225 + || kind === 212 + || kind === 210 + || kind === 209 + || kind === 215 + || kind === 216 + || kind === 214 + || kind === 211 + || kind === 222 + || kind === 219 + || kind === 221 + || kind === 223 + || kind === 224 + || kind === 208 + || kind === 213 + || kind === 220 + || kind === 287 + || kind === 291 + || kind === 290; + } + function isDeclaration(node) { + if (node.kind === 145) { + return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 207; + } + ts.isStatement = isStatement; + function isModuleReference(node) { + var kind = node.kind; + return kind === 248 + || kind === 143 + || kind === 71; + } + ts.isModuleReference = isModuleReference; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 99 + || kind === 71 + || kind === 179; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 249 + || kind === 256 + || kind === 250 + || kind === 10; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 253 + || kind === 255; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 + || kind === 256; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 251 + || kind === 250; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 257 + || kind === 258; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isJSDocNode(node) { + return node.kind >= 267 && node.kind <= 285; + } + ts.isJSDocNode = isJSDocNode; + function isJSDocCommentContainingNode(node) { + return node.kind === 275 || isJSDocTag(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + function isJSDocTag(node) { + return node.kind >= 276 && node.kind <= 285; + } + ts.isJSDocTag = isJSDocTag; +})(ts || (ts = {})); +var ts; (function (ts) { function tokenIsIdentifierOrKeyword(token) { return token >= 71; @@ -4588,12 +9209,19 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; - function computePositionOfLineAndCharacter(lineStarts, line, character) { + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { ts.Debug.assert(line >= 0 && line < lineStarts.length); - return lineStarts[line] + character; + var res = lineStarts[line] + character; + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res < debugText.length); + } + return res; } ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; function getLineStarts(sourceFile) { @@ -4660,6 +9288,7 @@ var ts; case 32: case 47: case 60: + case 124: case 61: case 62: return true; @@ -4721,6 +9350,7 @@ var ts; } break; case 60: + case 124: case 61: case 62: if (isConflictMarkerTrivia(text, pos)) { @@ -4774,10 +9404,10 @@ var ts; } } else { - ts.Debug.assert(ch === 61); + ts.Debug.assert(ch === 124 || ch === 61); while (pos < len) { - var ch_1 = text.charCodeAt(pos); - if (ch_1 === 62 && isConflictMarkerTrivia(text, pos)) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 || currentChar === 62) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { break; } pos++; @@ -5457,13 +10087,13 @@ var ts; pos += 2; var commentClosed = false; while (pos < end) { - var ch_2 = text.charCodeAt(pos); - if (ch_2 === 42 && text.charCodeAt(pos + 1) === 47) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) { pos += 2; commentClosed = true; break; } - if (isLineBreak(ch_2)) { + if (isLineBreak(ch_1)) { precedingLineBreak = true; } pos++; @@ -5618,6 +10248,15 @@ var ts; pos++; return token = 17; case 124: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 54; } @@ -5952,6 +10591,5295 @@ var ts; ts.createScanner = createScanner; })(ts || (ts = {})); var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 265) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 71) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 142) { + return; + } + switch (node.kind) { + case 143: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 145: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 262: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 263: + return visitNode(cbNode, node.expression); + case 146: + case 149: + case 148: + case 261: + case 226: + case 176: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 160: + case 161: + case 155: + case 156: + case 157: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 151: + case 150: + case 152: + case 153: + case 154: + case 186: + case 228: + case 187: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 159: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 158: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 162: + return visitNode(cbNode, node.exprName); + case 163: + return visitNodes(cbNode, cbNodes, node.members); + case 164: + return visitNode(cbNode, node.elementType); + case 165: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 166: + case 167: + return visitNodes(cbNode, cbNodes, node.types); + case 168: + case 170: + return visitNode(cbNode, node.type); + case 171: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 172: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 173: + return visitNode(cbNode, node.literal); + case 174: + case 175: + return visitNodes(cbNode, cbNodes, node.elements); + case 177: + return visitNodes(cbNode, cbNodes, node.elements); + case 178: + return visitNodes(cbNode, cbNodes, node.properties); + case 179: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 180: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 181: + case 182: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 183: + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.template); + case 184: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 185: + return visitNode(cbNode, node.expression); + case 188: + return visitNode(cbNode, node.expression); + case 189: + return visitNode(cbNode, node.expression); + case 190: + return visitNode(cbNode, node.expression); + case 192: + return visitNode(cbNode, node.operand); + case 197: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 191: + return visitNode(cbNode, node.expression); + case 193: + return visitNode(cbNode, node.operand); + case 194: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 202: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 203: + return visitNode(cbNode, node.expression); + case 204: + return visitNode(cbNode, node.name); + case 195: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 198: + return visitNode(cbNode, node.expression); + case 207: + case 234: + return visitNodes(cbNode, cbNodes, node.statements); + case 265: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 208: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 227: + return visitNodes(cbNode, cbNodes, node.declarations); + case 210: + return visitNode(cbNode, node.expression); + case 211: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 212: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 213: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 215: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 216: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 217: + case 218: + return visitNode(cbNode, node.label); + case 219: + return visitNode(cbNode, node.expression); + case 220: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 221: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 235: + return visitNodes(cbNode, cbNodes, node.clauses); + case 257: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 258: + return visitNodes(cbNode, cbNodes, node.statements); + case 222: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 223: + return visitNode(cbNode, node.expression); + case 224: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 260: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 147: + return visitNode(cbNode, node.expression); + case 229: + case 199: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 230: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 231: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 232: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 264: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 233: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 237: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 238: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 239: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 236: + return visitNode(cbNode, node.name); + case 240: + return visitNode(cbNode, node.name); + case 241: + case 245: + return visitNodes(cbNode, cbNodes, node.elements); + case 244: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 242: + case 246: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 243: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 196: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 205: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 144: + return visitNode(cbNode, node.expression); + case 259: + return visitNodes(cbNode, cbNodes, node.types); + case 201: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 248: + return visitNode(cbNode, node.expression); + case 247: + return visitNodes(cbNode, cbNodes, node.decorators); + case 289: + return visitNodes(cbNode, cbNodes, node.elements); + case 249: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 250: + case 251: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.attributes); + case 254: + return visitNodes(cbNode, cbNodes, node.properties); + case 253: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 255: + return visitNode(cbNode, node.expression); + case 256: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 252: + return visitNode(cbNode, node.tagName); + case 267: + return visitNode(cbNode, node.type); + case 271: + return visitNode(cbNode, node.type); + case 270: + return visitNode(cbNode, node.type); + case 272: + return visitNode(cbNode, node.type); + case 273: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 274: + return visitNode(cbNode, node.type); + case 275: + return visitNodes(cbNode, cbNodes, node.tags); + case 279: + case 284: + if (node.isNameFirst) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression); + } + else { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name); + } + case 280: + return visitNode(cbNode, node.typeExpression); + case 281: + return visitNode(cbNode, node.typeExpression); + case 277: + return visitNode(cbNode, node.typeExpression); + case 282: + return visitNodes(cbNode, cbNodes, node.typeParameters); + case 283: + if (node.typeExpression && + node.typeExpression.kind === 267) { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName); + } + else { + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + } + case 285: + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } + return; + case 288: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + newSourceFile.flags |= (sourceFile.flags & 524288); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + var Parser; + (function (Parser) { + var scanner = ts.createScanner(5, true); + var disallowInAndDecoratorContext = 2048 | 8192; + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + var contextFlags; + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + initializeState(sourceText, 2, undefined, 6); + sourceFile = createSourceFile(fileName, 2, 6); + var result = sourceFile; + nextToken(); + if (token() === 1) { + sourceFile.endOfFileToken = parseTokenNode(); + } + else if (token() === 17 || + lookAhead(function () { return token() === 9; })) { + result.jsonObject = parseObjectLiteralExpression(); + sourceFile.endOfFileToken = parseExpectedToken(1, false, ts.Diagnostics.Unexpected_token); + } + else { + parseExpected(17); + } + sourceFile.parseDiagnostics = parseDiagnostics; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 || scriptKind === 6 ? 1 : 0; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + parseErrorBeforeNextFinishedNode = false; + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + scanner.setText(""); + scanner.setOnError(undefined); + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; + nextToken(); + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0, parseStatement); + ts.Debug.assert(token() === 1); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + } + function addJSDocComment(node) { + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; + } + if (!node.jsDoc) { + node.jsDoc = []; + } + node.jsDoc.push(jsDoc); + } + } + return node; + } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind) { + var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048); + } + function setYieldContext(val) { + setContextFlag(val, 4096); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192); + } + function setAwaitContext(val) { + setContextFlag(val, 16384); + } + function doOutsideOfContext(context, func) { + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + setContextFlag(false, contextFlagsToClear); + var result = func(); + setContextFlag(true, contextFlagsToClear); + return result; + } + return func(); + } + function doInsideOfContext(context, func) { + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + setContextFlag(true, contextFlagsToSet); + var result = func(); + setContextFlag(false, contextFlagsToSet); + return result; + } + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 | 16384, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096); + } + function inDisallowInContext() { + return inContext(2048); + } + function inDecoratorContext() { + return inContext(8192); + } + function inAwaitContext() { + return inContext(16384); + } + function parseErrorAtCurrentToken(message, arg0) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + parseErrorAtPosition(start, length, message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + parseErrorBeforeNextFinishedNode = true; + } + function scanError(message, length) { + var pos = scanner.getTextPos(); + parseErrorAtPosition(pos, length || 0, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var saveContextFlags = contextFlags; + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, true); + } + function tryParse(callback) { + return speculationHelper(callback, false); + } + function isIdentifier() { + if (token() === 71) { + return true; + } + if (token() === 116 && inYieldContext()) { + return false; + } + if (token() === 121 && inAwaitContext()) { + return false; + } + return token() > 107; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + if (token() === 25) { + return true; + } + return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 25) { + nextToken(); + } + return true; + } + else { + return parseExpected(25); + } + } + function createNode(kind, pos) { + nodeCount++; + if (!(pos >= 0)) { + pos = scanner.getStartPos(); + } + return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : + kind === 71 ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind, scanner.getStartPos()); + if (kind === 71) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(71); + if (token() !== 71) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName() { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 9 || token() === 8) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 21) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseComputedPropertyName() { + var node = createNode(144); + parseExpected(21); + node.expression = allowInAnd(parseExpression); + parseExpected(22); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + if (token() === 76) { + return nextToken() === 83; + } + if (token() === 84) { + nextToken(); + if (token() === 79) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + } + if (token() === 79) { + return nextTokenCanFollowDefaultKeyword(); + } + if (token() === 115) { + nextToken(); + return canFollowModifier(); + } + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 21 + || token() === 17 + || token() === 39 + || token() === 24 + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 75 || token() === 89 || + token() === 109 || + (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0: + case 1: + case 3: + return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); + case 2: + return token() === 73 || token() === 79; + case 4: + return lookAhead(isTypeMemberStart); + case 5: + return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); + case 6: + return token() === 21 || isLiteralPropertyName(); + case 12: + return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); + case 17: + return isLiteralPropertyName(); + case 9: + return token() === 21 || token() === 24 || isLiteralPropertyName(); + case 7: + if (token() === 17) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8: + return isIdentifierOrPattern(); + case 10: + return token() === 26 || token() === 24 || isIdentifierOrPattern(); + case 18: + return isIdentifier(); + case 11: + case 15: + return token() === 26 || token() === 24 || isStartOfExpression(); + case 16: + return isStartOfParameter(); + case 19: + case 20: + return token() === 26 || isStartOfType(); + case 21: + return isHeritageClause(); + case 22: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; + case 14: + return true; + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 17); + if (nextToken() === 18) { + var next = nextToken(); + return next === 26 || next === 17 || next === 85 || next === 108; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 108 || + token() === 85) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function isListTerminator(kind) { + if (token() === 1) { + return true; + } + switch (kind) { + case 1: + case 2: + case 4: + case 5: + case 6: + case 12: + case 9: + case 22: + return token() === 18; + case 3: + return token() === 18 || token() === 73 || token() === 79; + case 7: + return token() === 17 || token() === 85 || token() === 108; + case 8: + return isVariableDeclaratorListTerminator(); + case 18: + return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; + case 11: + return token() === 20 || token() === 25; + case 15: + case 20: + case 10: + return token() === 22; + case 16: + case 17: + return token() === 20 || token() === 22; + case 19: + return token() !== 26; + case 21: + return token() === 17 || token() === 18; + case 13: + return token() === 29 || token() === 41; + case 14: + return token() === 27 && lookAhead(nextTokenIsSlash); + } + } + function isVariableDeclaratorListTerminator() { + if (canParseSemicolon()) { + return true; + } + if (isInOrOfKeyword(token())) { + return true; + } + if (token() === 36) { + return true; + } + return false; + } + function isInSomeParsingContext() { + for (var kind = 0; kind < 23; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + while (!isListTerminator(kind)) { + if (isListElement(kind, false)) { + var element = parseListElement(kind, parseElement); + result.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + if (ts.nodeIsMissing(node)) { + return undefined; + } + if (node.intersectsChange) { + return undefined; + } + if (ts.containsParseError(node)) { + return undefined; + } + var nodeContextFlags = node.flags & 96256; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5: + return isReusableClassMember(node); + case 2: + return isReusableSwitchClause(node); + case 0: + case 1: + case 3: + return isReusableStatement(node); + case 6: + return isReusableEnumMember(node); + case 4: + return isReusableTypeMember(node); + case 8: + return isReusableVariableDeclaration(node); + case 16: + return isReusableParameter(node); + case 17: + return false; + case 21: + case 18: + case 20: + case 19: + case 11: + case 12: + case 7: + case 13: + case 14: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 152: + case 157: + case 153: + case 154: + case 149: + case 206: + return true; + case 151: + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 71 && + methodDeclaration.name.originalKeywordKind === 123; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 257: + case 258: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 228: + case 208: + case 207: + case 211: + case 210: + case 223: + case 219: + case 221: + case 218: + case 217: + case 215: + case 216: + case 214: + case 213: + case 220: + case 209: + case 224: + case 222: + case 212: + case 225: + case 238: + case 237: + case 244: + case 243: + case 233: + case 229: + case 230: + case 232: + case 231: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 264; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 156: + case 150: + case 157: + case 148: + case 155: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 226) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.initializer === undefined; + } + function isReusableParameter(node) { + if (node.kind !== 146) { + return false; + } + var parameter = node; + return parameter.initializer === undefined; + } + function abortParsingListOrMoveToNextToken(kind) { + parseErrorAtCurrentToken(parsingContextErrors(kind)); + if (isInSomeParsingContext()) { + return true; + } + nextToken(); + return false; + } + function parsingContextErrors(context) { + switch (context) { + case 0: return ts.Diagnostics.Declaration_or_statement_expected; + case 1: return ts.Diagnostics.Declaration_or_statement_expected; + case 2: return ts.Diagnostics.case_or_default_expected; + case 3: return ts.Diagnostics.Statement_expected; + case 17: + case 4: return ts.Diagnostics.Property_or_signature_expected; + case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 6: return ts.Diagnostics.Enum_member_expected; + case 7: return ts.Diagnostics.Expression_expected; + case 8: return ts.Diagnostics.Variable_declaration_expected; + case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; + case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; + case 11: return ts.Diagnostics.Argument_expression_expected; + case 12: return ts.Diagnostics.Property_assignment_expected; + case 15: return ts.Diagnostics.Expression_or_comma_expected; + case 16: return ts.Diagnostics.Parameter_declaration_expected; + case 18: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_argument_expected; + case 20: return ts.Diagnostics.Type_expected; + case 21: return ts.Diagnostics.Unexpected_token_expected; + case 22: return ts.Diagnostics.Identifier_expected; + case 13: return ts.Diagnostics.Identifier_expected; + case 14: return ts.Diagnostics.Identifier_expected; + } + } + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + var commaStart = -1; + while (true) { + if (isListElement(kind, false)) { + var startPos = scanner.getStartPos(); + result.push(parseListElement(kind, parseElement)); + commaStart = scanner.getTokenPos(); + if (parseOptional(26)) { + continue; + } + commaStart = -1; + if (isListTerminator(kind)) { + break; + } + parseExpected(26); + if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + } + if (startPos === scanner.getStartPos()) { + nextToken(); + } + continue; + } + if (isListTerminator(kind)) { + break; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + if (commaStart >= 0) { + result.hasTrailingComma = true; + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + return createNodeArray(); + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(23)) { + if (token() === 27) { + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(143, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(196); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); + var templateSpans = createNodeArray(); + do { + templateSpans.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); + templateSpans.end = getNodeEnd(); + template.templateSpans = templateSpans; + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(205); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 18) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + var text = scanner.getTokenValue(); + node.text = text; + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + if (node.kind === 8) { + node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + } + nextToken(); + finishNode(node); + return node; + } + function parseTypeReference() { + var node = createNode(159); + node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(158, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(169); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType() { + var result = createNode(268); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + nextToken(); + if (token() === 26 || + token() === 18 || + token() === 20 || + token() === 29 || + token() === 58 || + token() === 49) { + var result = createNode(269, pos); + return finishNode(result); + } + else { + var result = createNode(270, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNode(273); + nextToken(); + fillSignature(56, 4 | 32, result); + return finishNode(result); + } + var node = createNode(159); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(146); + if (token() === 99 || token() === 94) { + parameter.name = parseIdentifierName(); + parseExpected(56); + } + parameter.type = parseType(); + return finishNode(parameter); + } + function parseJSDocNodeWithType(kind) { + var result = createNode(kind); + nextToken(); + result.type = parseType(); + return finishNode(result); + } + function parseTypeQuery() { + var node = createNode(162); + parseExpected(103); + node.exprName = parseEntityName(true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + if (parseOptional(85)) { + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(58)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 27) { + return parseBracketedList(18, parseTypeParameter, 27, 29); + } + } + function parseParameterType() { + if (parseOptional(56)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter() { + return token() === 24 || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 57 || isStartOfType(); + } + function parseParameter() { + var node = createNode(146); + if (token() === 99) { + node.name = createIdentifier(true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + nextToken(); + } + node.questionToken = parseOptionalToken(55); + node.type = parseParameterType(); + node.initializer = parseBindingElementInitializer(true); + return addJSDocComment(finishNode(node)); + } + function parseBindingElementInitializer(inParameter) { + return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); + } + function parseParameterInitializer() { + return parseInitializer(true); + } + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32)) { + signature.typeParameters = parseTypeParameters(); + } + signature.parameters = parseParameterList(flags); + var returnTokenRequired = returnToken === 36; + if (returnTokenRequired) { + parseExpected(returnToken); + signature.type = parseTypeOrTypePredicate(); + } + else if (parseOptional(returnToken)) { + signature.type = parseTypeOrTypePredicate(); + } + else if (flags & 4) { + var start = scanner.getTokenPos(); + var length_1 = scanner.getTextPos() - start; + var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); + if (backwardToken) { + signature.type = parseTypeOrTypePredicate(); + parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); + } + } + } + function parseParameterList(flags) { + if (parseExpected(19)) { + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + if (!parseExpected(20) && (flags & 8)) { + return undefined; + } + return result; + } + return (flags & 8) ? undefined : createMissingList(); + } + function parseTypeMemberSemicolon() { + if (parseOptional(26)) { + return; + } + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNode(kind); + if (kind === 156) { + parseExpected(94); + } + fillSignature(56, 4, node); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(node)); + } + function isIndexSignature() { + if (token() !== 21) { + return false; + } + return lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + nextToken(); + if (token() === 24 || token() === 22) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + nextToken(); + } + if (token() === 56 || token() === 26) { + return true; + } + if (token() !== 55) { + return false; + } + nextToken(); + return token() === 56 || token() === 26 || token() === 22; + } + function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { + var node = createNode(157, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.parameters = parseBracketedList(16, parseParameter, 21, 22); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(fullStart, modifiers) { + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (token() === 19 || token() === 27) { + var method = createNode(150, fullStart); + method.modifiers = modifiers; + method.name = name; + method.questionToken = questionToken; + fillSignature(56, 4, method); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(method)); + } + else { + var property = createNode(148, fullStart); + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + if (token() === 58) { + property.initializer = parseNonParameterInitializer(); + } + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(property)); + } + } + function isTypeMemberStart() { + if (token() === 19 || token() === 27) { + return true; + } + var idToken; + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + if (token() === 21) { + return true; + } + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + if (idToken) { + return token() === 19 || + token() === 27 || + token() === 55 || + token() === 56 || + token() === 26 || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 19 || token() === 27) { + return parseSignatureMember(155); + } + if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(156); + } + var fullStart = getNodePos(); + var modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 19 || token() === 27; + } + function parseTypeLiteral() { + var node = createNode(163); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(17)) { + members = parseList(4, parseTypeMember); + parseExpected(18); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 131) { + nextToken(); + } + return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; + } + function parseMappedTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + parseExpected(92); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(172); + parseExpected(17); + node.readonlyToken = parseOptionalToken(131); + parseExpected(21); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(22); + node.questionToken = parseOptionalToken(55); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(18); + return finishNode(node); + } + function parseTupleType() { + var node = createNode(165); + node.elementTypes = parseBracketedList(20, parseType, 21, 22); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(168); + parseExpected(19); + node.type = parseType(); + parseExpected(20); + return finishNode(node); + } + function parseFunctionOrConstructorType(kind) { + var node = createNode(kind); + if (kind === 161) { + parseExpected(94); + } + fillSignature(36, 4, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 23 ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(173); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8; + } + function parseNonArrayType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 139: + case 130: + case 134: + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 39: + return parseJSDocAllType(); + case 55: + return parseJSDocUnknownOrNullableType(); + case 89: + return parseJSDocFunctionType(); + case 24: + return parseJSDocNodeWithType(274); + case 51: + return parseJSDocNodeWithType(271); + case 9: + case 8: + case 101: + case 86: + return parseLiteralTypeNode(); + case 38: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + case 105: + case 95: + return parseTokenNode(); + case 99: { + var thisKeyword = parseThisTypeNode(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 103: + return parseTypeQuery(); + case 17: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 21: + return parseTupleType(); + case 19: + return parseParenthesizedType(); + default: + return parseTypeReference(); + } + } + function isStartOfType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 105: + case 139: + case 95: + case 99: + case 103: + case 130: + case 17: + case 21: + case 27: + case 49: + case 48: + case 94: + case 9: + case 8: + case 101: + case 86: + case 134: + return true; + case 38: + return lookAhead(nextTokenIsNumericLiteral); + case 19: + return lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 20 || isStartOfParameter() || isStartOfType(); + } + function parseJSDocPostfixTypeOrHigher() { + var type = parseNonArrayType(); + var kind = getKind(token()); + if (!kind) + return type; + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + function getKind(tokenKind) { + switch (tokenKind) { + case 58: + return contextFlags & 1048576 ? 272 : undefined; + case 51: + return 271; + case 55: + return 270; + } + } + } + function parseArrayTypeOrHigher() { + var type = parseJSDocPostfixTypeOrHigher(); + while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { + if (isStartOfType()) { + var node = createNode(171, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22); + type = finishNode(node); + } + else { + var node = createNode(164, type.pos); + node.elementType = type; + parseExpected(22); + type = finishNode(node); + } + } + return type; + } + function parseTypeOperator(operator) { + var node = createNode(170); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 127: + return parseTypeOperator(127); + } + return parseArrayTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = createNodeArray([type], type.pos); + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + types.end = getNodeEnd(); + var node = createNode(kind, type.pos); + node.types = types; + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + } + function isStartOfFunctionType() { + if (token() === 27) { + return true; + } + return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + parseModifiers(); + } + if (isIdentifier() || token() === 99) { + nextToken(); + return true; + } + if (token() === 21 || token() === 17) { + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 20 || token() === 24) { + return true; + } + if (skipParameterStart()) { + if (token() === 56 || token() === 26 || + token() === 55 || token() === 58) { + return true; + } + if (token() === 20) { + nextToken(); + if (token() === 36) { + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(158, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + return doOutsideOfContext(20480, parseTypeWorker); + } + function parseTypeWorker() { + if (isStartOfFunctionType()) { + return parseFunctionOrConstructorType(160); + } + if (token() === 94) { + return parseFunctionOrConstructorType(161); + } + return parseUnionTypeOrHigher(); + } + function parseTypeAnnotation() { + return parseOptional(56) ? parseType() : undefined; + } + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 99: + case 97: + case 95: + case 101: + case 86: + case 8: + case 9: + case 13: + case 14: + case 19: + case 21: + case 17: + case 89: + case 75: + case 94: + case 41: + case 63: + case 71: + return true; + case 91: + return lookAhead(nextTokenIsOpenParenOrLessThan); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 43: + case 44: + case 27: + case 121: + case 116: + return true; + default: + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + return token() !== 17 && + token() !== 89 && + token() !== 75 && + token() !== 57 && + isStartOfExpression(); + } + function parseExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(26))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return expr; + } + function parseInitializer(inParameter) { + if (token() !== 58) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { + return undefined; + } + } + parseExpected(58); + return parseAssignmentExpressionOrHigher(); + } + function parseAssignmentExpressionOrHigher() { + if (isYieldExpression()) { + return parseYieldExpression(); + } + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + var expr = parseBinaryExpressionOrHigher(0); + if (expr.kind === 71 && token() === 36) { + return parseSimpleArrowFunctionExpression(expr); + } + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 116) { + if (inYieldContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(197); + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 39 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(39); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(187, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(187, identifier.pos); + } + var parameter = createNode(146, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos); + node.parameters.end = parameter.end; + node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(!!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0) { + return undefined; + } + var arrowFunction = triState === 1 + ? parseParenthesizedArrowFunctionExpressionHead(true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + return undefined; + } + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 36 || lastToken === 17) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return addJSDocComment(finishNode(arrowFunction)); + } + function isParenthesizedArrowFunctionExpression() { + if (token() === 19 || token() === 27 || token() === 120) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 36) { + return 1; + } + return 0; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0; + } + if (token() !== 19 && token() !== 27) { + return 0; + } + } + var first = token(); + var second = nextToken(); + if (first === 19) { + if (second === 20) { + var third = nextToken(); + switch (third) { + case 36: + case 56: + case 17: + return 1; + default: + return 0; + } + } + if (second === 21 || second === 17) { + return 2; + } + if (second === 24) { + return 1; + } + if (!isIdentifier()) { + return 0; + } + if (nextToken() === 56) { + return 1; + } + return 2; + } + else { + ts.Debug.assert(first === 27); + if (!isIdentifier()) { + return 0; + } + if (sourceFile.languageVariant === 1) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 85) { + var fourth = nextToken(); + switch (fourth) { + case 58: + case 29: + return false; + default: + return true; + } + } + else if (third === 26) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1; + } + return 0; + } + return 2; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + if (token() === 120) { + var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); + if (isUnParenthesizedAsyncArrowFunction === 1) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak() || token() === 36) { + return 0; + } + var expr = parseBinaryExpressionOrHigher(0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { + return 1; + } + } + return 0; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNode(187); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + if (!node.parameters) { + return undefined; + } + if (!allowAmbiguity && token() !== 36 && token() !== 17) { + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 17) { + return parseFunctionBlock(isAsync ? 2 : 0); + } + if (token() !== 25 && + token() !== 89 && + token() !== 75 && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + return parseFunctionBlock(16 | (isAsync ? 2 : 0)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + var questionToken = parseOptionalToken(55); + if (!questionToken) { + return leftOperand; + } + var node = createNode(195, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); + node.whenFalse = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 92 || t === 142; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + reScanGreaterToken(); + var newPrecedence = getBinaryOperatorPrecedence(); + var consumeCurrentOperator = token() === 40 ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 92 && inDisallowInContext()) { + break; + } + if (token() === 118) { + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 92) { + return false; + } + return getBinaryOperatorPrecedence() > 0; + } + function getBinaryOperatorPrecedence() { + switch (token()) { + case 54: + return 1; + case 53: + return 2; + case 49: + return 3; + case 50: + return 4; + case 48: + return 5; + case 32: + case 33: + case 34: + case 35: + return 6; + case 27: + case 29: + case 30: + case 31: + case 93: + case 92: + case 118: + return 7; + case 45: + case 46: + case 47: + return 8; + case 37: + case 38: + return 9; + case 39: + case 41: + case 42: + return 10; + case 40: + return 11; + } + return -1; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(194, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(202, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(188); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(189); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(190); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 121) { + if (inAwaitContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(191); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseUnaryExpressionOrHigher() { + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 40 ? + parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + updateExpression; + } + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 40) { + var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + if (simpleUnaryExpression.kind === 184) { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + function parseSimpleUnaryExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + return parsePrefixUnaryExpression(); + case 80: + return parseDeleteExpression(); + case 103: + return parseTypeOfExpression(); + case 105: + return parseVoidExpression(); + case 27: + return parseTypeAssertion(); + case 121: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + default: + return parseUpdateExpression(); + } + } + function isUpdateExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 121: + return false; + case 27: + if (sourceFile.languageVariant !== 1) { + return false; + } + default: + return true; + } + } + function parseUpdateExpression() { + if (token() === 43 || token() === 44) { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + return parseJsxElementOrSelfClosingElement(true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(193, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + var expression; + if (token() === 91 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + sourceFile.flags |= 524288; + expression = parseTokenNode(); + } + else { + expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 19 || token() === 23 || token() === 21) { + return expression; + } + var node = createNode(179, expression.pos); + node.expression = expression; + parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(true); + return finishNode(node); + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 71) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 99) { + return true; + } + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + function parseJsxElementOrSelfClosingElement(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + var result; + if (opening.kind === 251) { + var node = createNode(249, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement.tagName); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 250); + result = opening; + } + if (inExpressionContext && token() === 27) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(194, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(26, false, undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(10, scanner.getStartPos()); + node.containsOnlyWhiteSpaces = currentToken === 11; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild() { + switch (token()) { + case 10: + case 11: + return parseJsxText(); + case 17: + return parseJsxExpression(false); + case 27: + return parseJsxElementOrSelfClosingElement(false); + } + ts.Debug.fail("Unknown JSX child kind " + token()); + } + function parseJsxChildren(openingTagName) { + var result = createNodeArray(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14; + while (true) { + currentToken = scanner.reScanJsxToken(); + if (token() === 28) { + break; + } + else if (token() === 1) { + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + break; + } + else if (token() === 7) { + break; + } + var child = parseJsxChild(); + if (child) { + result.push(child); + } + } + result.end = scanner.getTokenPos(); + parsingContext = saveParsingContext; + return result; + } + function parseJsxAttributes() { + var jsxAttributes = createNode(254); + jsxAttributes.properties = parseList(13, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(27); + var tagName = parseJsxElementName(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 29) { + node = createNode(251, fullStart); + scanJsxText(); + } + else { + parseExpected(41); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + node = createNode(250, fullStart); + } + node.tagName = tagName; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + var expression = token() === 99 ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(23)) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(256); + parseExpected(17); + if (token() !== 18) { + node.dotDotDotToken = parseOptionalToken(24); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(18); + } + else { + parseExpected(18, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 17) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(253); + node.name = parseIdentifierName(); + if (token() === 58) { + switch (scanJsxAttributeValue()) { + case 9: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(255); + parseExpected(17); + parseExpected(24); + node.expression = parseExpression(); + parseExpected(18); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(252); + parseExpected(28); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(184); + parseExpected(27); + node.type = parseType(); + parseExpected(29); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(23); + if (dotToken) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 51 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(203, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + if (!inDecoratorContext() && parseOptional(21)) { + var indexedAccess = createNode(180, expression.pos); + indexedAccess.expression = expression; + if (token() !== 22) { + indexedAccess.argumentExpression = allowInAnd(parseExpression); + if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { + var literal = indexedAccess.argumentExpression; + literal.text = internIdentifier(literal.text); + } + } + parseExpected(22); + expression = finishNode(indexedAccess); + continue; + } + if (token() === 13 || token() === 14) { + var tagExpression = createNode(183, expression.pos); + tagExpression.tag = expression; + tagExpression.template = token() === 13 + ? parseLiteralNode() + : parseTemplateExpression(); + expression = finishNode(tagExpression); + continue; + } + return expression; + } + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 27) { + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 19) { + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(19); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(20); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(27)) { + return undefined; + } + var typeArguments = parseDelimitedList(19, parseType); + if (!parseExpected(29)) { + return undefined; + } + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 19: + case 23: + case 20: + case 22: + case 56: + case 25: + case 55: + case 32: + case 34: + case 33: + case 35: + case 53: + case 54: + case 50: + case 48: + case 49: + case 18: + case 1: + return true; + case 26: + case 17: + default: + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8: + case 9: + case 13: + return parseLiteralNode(); + case 99: + case 97: + case 95: + case 101: + case 86: + return parseTokenNode(); + case 19: + return parseParenthesizedExpression(); + case 21: + return parseArrayLiteralExpression(); + case 17: + return parseObjectLiteralExpression(); + case 120: + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 75: + return parseClassExpression(); + case 89: + return parseFunctionExpression(); + case 94: + return parseNewExpression(); + case 41: + case 63: + if (reScanSlashToken() === 12) { + return parseLiteralNode(); + } + break; + case 14: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNode(185); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + return addJSDocComment(finishNode(node)); + } + function parseSpreadElement() { + var node = createNode(198); + parseExpected(24); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 24 ? parseSpreadElement() : + token() === 26 ? createNode(200) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(177); + parseExpected(21); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); + parseExpected(22); + return finishNode(node); + } + function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + } + else if (parseContextualModifier(135)) { + return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + } + return undefined; + } + function parseObjectLiteralElement() { + var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(24); + if (dotDotDotToken) { + var spreadElement = createNode(263, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + var asteriskToken = parseOptionalToken(39); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + } + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); + if (isShorthandPropertyAssignment) { + var shorthandDeclaration = createNode(262, fullStart); + shorthandDeclaration.name = propertyName; + shorthandDeclaration.questionToken = questionToken; + var equalsToken = parseOptionalToken(58); + if (equalsToken) { + shorthandDeclaration.equalsToken = equalsToken; + shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return addJSDocComment(finishNode(shorthandDeclaration)); + } + else { + var propertyAssignment = createNode(261, fullStart); + propertyAssignment.modifiers = modifiers; + propertyAssignment.name = propertyName; + propertyAssignment.questionToken = questionToken; + parseExpected(56); + propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + return addJSDocComment(finishNode(propertyAssignment)); + } + } + function parseObjectLiteralExpression() { + var node = createNode(178); + parseExpected(17); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); + parseExpected(18); + return finishNode(node); + } + function parseFunctionExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var node = createNode(186); + node.modifiers = parseModifiers(); + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return addJSDocComment(finishNode(node)); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpression() { + var fullStart = scanner.getStartPos(); + parseExpected(94); + if (parseOptional(23)) { + var node_1 = createNode(204, fullStart); + node_1.keywordToken = 94; + node_1.name = parseIdentifierName(); + return finishNode(node_1); + } + var node = createNode(182, fullStart); + node.expression = parseMemberExpressionOrHigher(); + node.typeArguments = tryParse(parseTypeArgumentsInExpression); + if (node.typeArguments || token() === 19) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(207); + if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2)); + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var block = parseBlock(!!(flags & 16), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(209); + parseExpected(25); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(211); + parseExpected(90); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(82) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(212); + parseExpected(81); + node.statement = parseStatement(); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + parseOptional(25); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(213); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(88); + var awaitToken = parseOptionalToken(121); + parseExpected(19); + var initializer = undefined; + if (token() !== 25) { + if (token() === 104 || token() === 110 || token() === 76) { + initializer = parseVariableDeclarationList(true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(142) : parseOptional(142)) { + var forOfStatement = createNode(216, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(20); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(92)) { + var forInStatement = createNode(215, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(20); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(214, pos); + forStatement.initializer = initializer; + parseExpected(25); + if (token() !== 25 && token() !== 20) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(25); + if (token() !== 20) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(20); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 218 ? 72 : 77); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(219); + parseExpected(96); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(220); + parseExpected(107); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(257); + parseExpected(73); + node.expression = allowInAnd(parseExpression); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(258); + parseExpected(79); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 73 ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(221); + parseExpected(98); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + var caseBlock = createNode(235, scanner.getStartPos()); + parseExpected(17); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(18); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + var node = createNode(223); + parseExpected(100); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + function parseTryStatement() { + var node = createNode(224); + parseExpected(102); + node.tryBlock = parseBlock(false); + node.catchClause = token() === 74 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 87) { + parseExpected(87); + node.finallyBlock = parseBlock(false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(260); + parseExpected(74); + if (parseExpected(19)) { + result.variableDeclaration = parseVariableDeclaration(); + } + parseExpected(20); + result.block = parseBlock(false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(225); + parseExpected(78); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + var fullStart = scanner.getStartPos(); + var expression = allowInAnd(parseExpression); + if (expression.kind === 71 && parseOptional(56)) { + var labeledStatement = createNode(222, fullStart); + labeledStatement.label = expression; + labeledStatement.statement = parseStatement(); + return addJSDocComment(finishNode(labeledStatement)); + } + else { + var expressionStatement = createNode(210, fullStart); + expressionStatement.expression = expression; + parseSemicolon(); + return addJSDocComment(finishNode(expressionStatement)); + } + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 75 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 89 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 104: + case 110: + case 76: + case 89: + case 75: + case 83: + return true; + case 109: + case 138: + return nextTokenIsIdentifierOnSameLine(); + case 128: + case 129: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 117: + case 120: + case 124: + case 112: + case 113: + case 114: + case 131: + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 141: + nextToken(); + return token() === 17 || token() === 71 || token() === 84; + case 91: + nextToken(); + return token() === 9 || token() === 39 || + token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); + case 84: + nextToken(); + if (token() === 58 || token() === 39 || + token() === 17 || token() === 79 || + token() === 118) { + return true; + } + continue; + case 115: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 57: + case 25: + case 17: + case 104: + case 110: + case 89: + case 75: + case 83: + case 90: + case 81: + case 106: + case 88: + case 77: + case 72: + case 96: + case 107: + case 98: + case 100: + case 102: + case 78: + case 74: + case 87: + return true; + case 91: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + case 76: + case 84: + return isStartOfDeclaration(); + case 120: + case 124: + case 109: + case 128: + case 129: + case 138: + case 141: + return true; + case 114: + case 112: + case 113: + case 115: + case 131: + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 17 || token() === 21; + } + function isLetDeclaration() { + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 25: + return parseEmptyStatement(); + case 17: + return parseBlock(false); + case 104: + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 110: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; + case 89: + return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); + case 75: + return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); + case 90: + return parseIfStatement(); + case 81: + return parseDoStatement(); + case 106: + return parseWhileStatement(); + case 88: + return parseForOrForInOrForOfStatement(); + case 77: + return parseBreakOrContinueStatement(217); + case 72: + return parseBreakOrContinueStatement(218); + case 96: + return parseReturnStatement(); + case 107: + return parseWithStatement(); + case 98: + return parseSwitchStatement(); + case 100: + return parseThrowStatement(); + case 102: + case 74: + case 87: + return parseTryStatement(); + case 78: + return parseDebuggerStatement(); + case 57: + return parseDeclaration(); + case 120: + case 109: + case 138: + case 128: + case 129: + case 124: + case 76: + case 83: + case 84: + case 91: + case 112: + case 113: + case 114: + case 117: + case 115: + case 131: + case 141: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function parseDeclaration() { + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + switch (token()) { + case 104: + case 110: + case 76: + return parseVariableStatement(fullStart, decorators, modifiers); + case 89: + return parseFunctionDeclaration(fullStart, decorators, modifiers); + case 75: + return parseClassDeclaration(fullStart, decorators, modifiers); + case 109: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 138: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 83: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 141: + case 128: + case 129: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 91: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 84: + nextToken(); + switch (token()) { + case 79: + case 58: + return parseExportAssignment(fullStart, decorators, modifiers); + case 118: + return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + default: + return parseExportDeclaration(fullStart, decorators, modifiers); + } + default: + if (decorators || modifiers) { + var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + node.modifiers = modifiers; + return finishNode(node); + } + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 17 && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + function parseArrayBindingElement() { + if (token() === 26) { + return createNode(200); + } + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 56) { + node.name = propertyName; + } + else { + parseExpected(56); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(174); + parseExpected(17); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(18); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(175); + parseExpected(21); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(22); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 17 || token() === 21 || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 21) { + return parseArrayBindingPattern(); + } + if (token() === 17) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclaration() { + var node = createNode(226); + node.name = parseIdentifierOrPattern(); + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(false); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(227); + switch (token()) { + case 104: + break; + case 110: + node.flags |= 1; + break; + case 76: + node.flags |= 2; + break; + default: + ts.Debug.fail(); + } + nextToken(); + if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 20; + } + function parseVariableStatement(fullStart, decorators, modifiers) { + var node = createNode(208, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.declarationList = parseVariableDeclarationList(false); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseFunctionDeclaration(fullStart, decorators, modifiers) { + var node = createNode(228, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseConstructorDeclaration(pos, decorators, modifiers) { + var node = createNode(152, pos); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(123); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { + var method = createNode(151, fullStart); + method.decorators = decorators; + method.modifiers = modifiers; + method.asteriskToken = asteriskToken; + method.name = name; + method.questionToken = questionToken; + var isGenerator = asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(method, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, method); + method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return addJSDocComment(finishNode(method)); + } + function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { + var property = createNode(149, fullStart); + property.decorators = decorators; + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + property.initializer = ts.hasModifier(property, 32) + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); + parseSemicolon(); + return addJSDocComment(finishNode(property)); + } + function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + var asteriskToken = parseOptionalToken(39); + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + } + else { + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + } + } + function parseNonParameterInitializer() { + return parseInitializer(false); + } + function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.name = parsePropertyName(); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0); + return addJSDocComment(finishNode(node)); + } + function isClassMemberModifier(idToken) { + switch (idToken) { + case 114: + case 112: + case 113: + case 115: + case 131: + return true; + default: + return false; + } + } + function isClassMemberStart() { + var idToken; + if (token() === 57) { + return true; + } + while (ts.isModifierKind(token())) { + idToken = token(); + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 39) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + if (token() === 21) { + return true; + } + if (idToken !== undefined) { + if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { + return true; + } + switch (token()) { + case 19: + case 27: + case 56: + case 58: + case 55: + return true; + default: + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var decorators; + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(57)) { + break; + } + var decorator = createNode(147, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } + } + if (decorators) { + decorators.end = getNodeEnd(); + } + return decorators; + } + function parseModifiers(permitInvalidConstAsModifier) { + var modifiers; + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 76 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + if (!modifiers) { + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); + } + } + if (modifiers) { + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 120) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseClassElement() { + if (token() === 25) { + var result = createNode(206); + nextToken(); + return finishNode(result); + } + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(true); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + if (token() === 123) { + return parseConstructorDeclaration(fullStart, decorators, modifiers); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + } + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8 || + token() === 39 || + token() === 21) { + return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + } + if (decorators || modifiers) { + var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + } + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + } + function parseClassDeclaration(fullStart, decorators, modifiers) { + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + } + function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(75); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(17)) { + node.members = parseClassMembers(); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseNameOfClassDeclarationOrExpression() { + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + if (isHeritageClause()) { + return parseList(21, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + if (tok === 85 || tok === 108) { + var node = createNode(259); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); + } + return undefined; + } + function parseExpressionWithTypeArguments() { + var node = createNode(201); + node.expression = parseLeftHandSideExpressionOrHigher(); + if (token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function isHeritageClause() { + return token() === 85 || token() === 108; + } + function parseClassMembers() { + return parseList(5, parseClassElement); + } + function parseInterfaceDeclaration(fullStart, decorators, modifiers) { + var node = createNode(230, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(109); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return addJSDocComment(finishNode(node)); + } + function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { + var node = createNode(231, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(138); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(58); + node.type = parseType(); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseEnumMember() { + var node = createNode(264, scanner.getStartPos()); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseNonParameterInitializer); + return addJSDocComment(finishNode(node)); + } + function parseEnumDeclaration(fullStart, decorators, modifiers) { + var node = createNode(232, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(83); + node.name = parseIdentifier(); + if (parseExpected(17)) { + node.members = parseDelimitedList(6, parseEnumMember); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseModuleBlock() { + var node = createNode(234, scanner.getStartPos()); + if (parseExpected(17)) { + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { + var node = createNode(233, fullStart); + var namespaceFlag = flags & 16; + node.decorators = decorators; + node.modifiers = modifiers; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(23) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + : parseModuleBlock(); + return addJSDocComment(finishNode(node)); + } + function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { + var node = createNode(233, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (token() === 141) { + node.name = parseIdentifier(); + node.flags |= 512; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 17) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(fullStart, decorators, modifiers) { + var flags = 0; + if (token() === 141) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(129)) { + flags |= 16; + } + else { + parseExpected(128); + if (token() === 9) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + } + return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + } + function isExternalModuleReference() { + return token() === 132 && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 19; + } + function nextTokenIsSlash() { + return nextToken() === 41; + } + function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { + var exportDeclaration = createNode(236, fullStart); + exportDeclaration.decorators = decorators; + exportDeclaration.modifiers = modifiers; + parseExpected(118); + parseExpected(129); + exportDeclaration.name = parseIdentifier(); + parseSemicolon(); + return finishNode(exportDeclaration); + } + function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + parseExpected(91); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 26 && token() !== 140) { + return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + } + } + var importDeclaration = createNode(238, fullStart); + importDeclaration.decorators = decorators; + importDeclaration.modifiers = modifiers; + if (identifier || + token() === 39 || + token() === 17) { + importDeclaration.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(140); + } + importDeclaration.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(importDeclaration); + } + function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { + var importEqualsDeclaration = createNode(237, fullStart); + importEqualsDeclaration.decorators = decorators; + importEqualsDeclaration.modifiers = modifiers; + importEqualsDeclaration.name = identifier; + parseExpected(58); + importEqualsDeclaration.moduleReference = parseModuleReference(); + parseSemicolon(); + return addJSDocComment(finishNode(importEqualsDeclaration)); + } + function parseImportClause(identifier, fullStart) { + var importClause = createNode(239, fullStart); + if (identifier) { + importClause.name = identifier; + } + if (!importClause.name || + parseOptional(26)) { + importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(false); + } + function parseExternalModuleReference() { + var node = createNode(248); + parseExpected(132); + parseExpected(19); + node.expression = parseModuleSpecifier(); + parseExpected(20); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 9) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + return parseExpression(); + } + } + function parseNamespaceImport() { + var namespaceImport = createNode(240); + parseExpected(39); + parseExpected(118); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(246); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(242); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 118) { + node.propertyName = identifierName; + parseExpected(118); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 242 && checkIdentifierIsKeyword) { + parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(fullStart, decorators, modifiers) { + var node = createNode(244, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(39)) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(245); + if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(fullStart, decorators, modifiers) { + var node = createNode(243, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(58)) { + node.isExportEquals = true; + } + else { + parseExpected(79); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function processReferenceComments(sourceFile) { + var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); + var referencedFiles = []; + var typeReferenceDirectives = []; + var amdDependencies = []; + var amdModuleName; + var checkJsDirective = undefined; + while (true) { + var kind = triviaScanner.scan(); + if (kind !== 2) { + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); + if (referencePathMatchResult) { + var fileReference = referencePathMatchResult.fileReference; + sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + if (fileReference) { + if (referencePathMatchResult.isTypeReferenceDirective) { + typeReferenceDirectives.push(fileReference); + } + else { + referencedFiles.push(fileReference); + } + } + if (diagnosticMessage) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + } + } + else { + var amdModuleNameRegEx = /^\/\/\/\s*= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + var tags; + var comments = []; + var result; + if (!isJsDocStart(content, start)) { + return result; + } + scanner.scanRange(start + 3, length - 5, function () { + var advanceToken = true; + var state = 1; + var margin = undefined; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5) { + nextJSDocToken(); + } + if (token() === 4) { + state = 0; + indent = 0; + nextJSDocToken(); + } + while (token() !== 1) { + switch (token()) { + case 57: + if (state === 0 || state === 1) { + removeTrailingNewlines(comments); + parseTag(indent); + state = 0; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 39: + var asterisk = scanner.getTokenText(); + if (state === 1 || state === 2) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 71: + pushComment(scanner.getTokenText()); + state = 2; + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break; + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { + nextJSDocToken(); + } + else { + advanceToken = true; + } + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42; + } + function createJSDocComment() { + var result = createNode(275, start); + result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function skipWhitespace() { + while (token() === 5 || token() === 4) { + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return; + } + var tag; + if (tagName) { + switch (tagName.escapedText) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + tag = parseParameterOrPropertyTag(atToken, tagName, 1); + break; + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; + } + } + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + } + function parseTagComments(indent) { + var comments = []; + var state = 0; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 57 && token() !== 1) { + switch (token()) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 57: + break; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 39: + if (state === 0) { + state = 1; + indent += scanner.getTokenText().length; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (token() === 57) { + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { + var result = createNode(276, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); + } + else { + tags.push(tag); + } + tags.end = tag.end; + } + function tryParseTypeExpression() { + return tryParse(function () { + skipWhitespace(); + if (token() !== 17) { + return undefined; + } + return parseJSDocTypeExpression(); + }); + } + function parseBracketNameInPropertyAndParamTag() { + var isBracketed = parseOptional(21); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + if (parseOptionalToken(58)) { + parseExpression(); + } + parseExpected(22); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 134: + return true; + case 164: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(atToken, tagName, target) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespace(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 ? + createNode(279, atToken.pos) : + createNode(284, atToken.pos); + var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { + if (!children) { + children = []; + } + children.push(child); + } + if (children) { + jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(280, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(281, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(277, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } + function parseClassTag(atToken, tagName) { + var tag = createNode(278, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var typedefTag = createNode(283, atToken.pos); + typedefTag.atToken = atToken; + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (true) { + if (rightNode.kind === 71 || !rightNode.body) { + typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; + break; + } + rightNode = rightNode.body; + } + } + skipWhitespace(); + typedefTag.typeExpression = typeExpression; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var alreadyHasTypeTag = false; + var start_3 = scanner.getStartPos(); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(285, start_3); + } + if (child.kind === 281) { + if (alreadyHasTypeTag) { + break; + } + else { + jsdocTypeLiteral.jsDocTypeTag = child; + alreadyHasTypeTag = true; + } + } + else { + if (!jsdocTypeLiteral.jsDocPropertyTags) { + jsdocTypeLiteral.jsDocPropertyTags = []; + } + jsdocTypeLiteral.jsDocPropertyTags.push(child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + } + } + return finishNode(typedefTag); + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23)) { + var jsDocNamespaceNode = createNode(233, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && flags & 4) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildParameterOrPropertyTag(target, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + nextJSDocToken(); + switch (token()) { + case 57: + if (canParseTag) { + var child = tryParseChildTag(target); + if (child && child.kind === 279 && + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4: + canParseTag = true; + seenAsterisk = false; + break; + case 39: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 71: + canParseTag = false; + break; + case 1: + return false; + } + } + } + function tryParseChildTag(target) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getStartPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return false; + } + switch (tagName.escapedText) { + case "type": + return target === 0 && parseTypeTag(atToken, tagName); + case "prop": + case "property": + return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + case "arg": + case "argument": + case "param": + return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + } + return false; + } + function parseTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var typeParameters = createNodeArray(); + while (true) { + var name = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(145, name.pos); + typeParameter.name = name; + finishNode(typeParameter); + typeParameters.push(typeParameter); + if (token() === 26) { + nextJSDocToken(); + skipWhitespace(); + } + else { + break; + } + } + var result = createNode(282, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + finishNode(result); + typeParameters.end = result.end; + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + while (parseOptional(23)) { + var name = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(createIfMissing) { + if (createIfMissing === void 0) { createIfMissing = false; } + if (!ts.tokenIsIdentifierOrKeyword(token())) { + if (createIfMissing) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); + return undefined; + } + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(71, pos); + result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); + } + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + forEachChild(jsDocComment, visitNode, visitArray); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 9: + case 8: + case 71: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + element.pos = Math.min(element.pos, changeRangeNewEnd); + if (element.end >= changeRangeOldEnd) { + element.end += delta; + } + else { + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + checkNodePositions(child, aggressiveChecks); + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; + visitNode(node); + } + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + var maxLookahead = 1; + var start = changeRange.span.start; + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } + else { + ts.Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1; + return { + currentNode: function (position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = undefined; + currentArrayIndex = -1; + current = undefined; + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode, visitArray); + return true; + } + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ @@ -6043,11 +15971,12 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES2015, "es2015": ts.ModuleKind.ES2015, + "esnext": ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, }, { name: "lib", @@ -6540,6 +16469,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, { name: "plugins", type: "list", @@ -6610,12 +16545,14 @@ var ts; optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; return optionNameMapCache; } - ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } function parseCustomTypeOption(opt, value, errors) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } @@ -6644,7 +16581,6 @@ var ts; var options = {}; var fileNames = []; var errors = []; - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; parseStrings(commandLine); return { options: options, @@ -6660,12 +16596,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - var short = shortOptionNames.get(s); - if (short !== undefined) { - s = short; - } - var opt = optionNameMap.get(s); + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -6749,36 +16680,234 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } function readConfigFile(fileName, readFile) { - var text = ""; + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; try { text = readFile(fileName); } catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return parseConfigFileTextToJson(fileName, text); + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; } - ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } - try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]); } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; + return _tsconfigRootOptions; + } + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, undefined, undefined); + } + ts.convertToObject = convertToObject; + function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.jsonObject) { + return {}; + } + return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 261) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined" && typeof value !== "undefined") { + result[keyText] = value; + if (jsonConversionNotifier && + (parentOption || knownOptions === knownRootOptions)) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (knownOptions === knownRootOptions) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 86: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95: + reportInvalidOptionValue(!!option); + return null; + case 9: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + var text = valueExpression.text; + if (option && typeof option.type !== "string") { + var customOption = option; + if (!customOption.type.has(text)) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 178: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); + } + case 177: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + if (option) { + reportInvalidOptionValue(true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + } + } + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + typeof option.type === "string" ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = typeof option.type === "string" ? option.type : "string"; + return typeof value === expectedType; } } - ts.parseConfigFileTextToJson = parseConfigFileTextToJson; function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition) { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { @@ -6799,35 +16928,33 @@ var ts; }); } function serializeCompilerOptions(options) { - var result = {}; + var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name in options) { + var _loop_3 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - continue; + return "continue"; } var value = options[name]; var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - result[name] = value; + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + result.set(name, value); } else { if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name] = convertedValue; + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { - result[name] = getNameOfCompilerOptionValue(value, customTypeMap); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } + }; + for (var name in options) { + _loop_3(name); } return result; } @@ -6844,37 +16971,37 @@ var ts; case "object": return {}; default: - return ts.arrayFrom(option.type.keys())[0]; + return option.type.keys().next().value; } } function makePadding(paddingLength) { return Array(paddingLength + 1).join(" "); } function writeConfigurations() { - var categorizedOptions = ts.reduceLeft(ts.filter(ts.optionDeclarations, function (o) { return o.category !== ts.Diagnostics.Command_line_Options && o.category !== ts.Diagnostics.Advanced_Options; }), function (memo, value) { - if (value.category) { - var name = ts.getLocaleSpecificMessage(value.category); - (memo[name] || (memo[name] = [])).push(value); + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); } - return memo; - }, {}); + } var marginLength = 0; var seenKnownKeys = 0; var nameColumn = []; var descriptionColumn = []; - var knownKeysCount = ts.getOwnKeys(configurations.compilerOptions).length; - for (var category in categorizedOptions) { + categorizedOptions.forEach(function (options, category) { if (nameColumn.length !== 0) { nameColumn.push(""); descriptionColumn.push(""); } nameColumn.push("/* " + category + " */"); descriptionColumn.push(""); - for (var _i = 0, _a = categorizedOptions[category]; _i < _a.length; _i++) { - var option = _a[_i]; + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; var optionName = void 0; - if (ts.hasProperty(configurations.compilerOptions, option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(configurations.compilerOptions[option.name]) + ((seenKnownKeys += 1) === knownKeysCount ? "" : ","); + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); } else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; @@ -6883,7 +17010,7 @@ var ts; descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); marginLength = Math.max(optionName.length, marginLength); } - } + }); var tab = makePadding(2); var result = []; result.push("{"); @@ -6891,13 +17018,13 @@ var ts; for (var i = 0; i < nameColumn.length; i++) { var optionName = nameColumn[i]; var description = descriptionColumn[i]; - result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description); + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); } - if (configurations.files && configurations.files.length) { + if (fileNames.length) { result.push(tab + "},"); result.push(tab + "\"files\": ["); - for (var i = 0; i < configurations.files.length; i++) { - result.push("" + tab + tab + JSON.stringify(configurations.files[i]) + (i === configurations.files.length - 1 ? "" : ",")); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); } result.push(tab + "]"); } @@ -6909,169 +17036,250 @@ var ts; } } ts.generateTSConfig = generateTSConfig; - function removeComments(jsonText) { - var output = ""; - var scanner = ts.createScanner(1, false, 0, jsonText); - var token; - while ((token = scanner.scan()) !== 1) { - switch (token) { - case 2: - case 3: - output += scanner.getTokenText().replace(/\S/g, " "); - break; - default: - output += scanner.getTokenText(); - break; - } - } - return output; - } function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - 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); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + setConfigFileInOptions(options, sourceFile); var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typeAcquisition: typeAcquisition, - raw: json, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + compileOnSave: !!raw.compileOnSave }; function getFileNames() { var fileNames; - if (ts.hasProperty(json, "files")) { - if (ts.isArray(json["files"])) { - fileNames = json["files"]; + if (ts.hasProperty(raw, "files")) { + if (ts.isArray(raw["files"])) { + fileNames = raw["files"]; if (fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); } } var includeSpecs; - if (ts.hasProperty(json, "include")) { - if (ts.isArray(json["include"])) { - includeSpecs = json["include"]; + if (ts.hasProperty(raw, "include")) { + if (ts.isArray(raw["include"])) { + includeSpecs = raw["include"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(json, "exclude")) { - if (ts.isArray(json["exclude"])) { - excludeSpecs = json["exclude"]; + if (ts.hasProperty(raw, "exclude")) { + if (ts.isArray(raw["exclude"])) { + excludeSpecs = raw["exclude"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; + var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - excludeSpecs.push(outDir); + specs.push(outDir); } + excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); - if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } return result; } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } } - ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + function parseConfig(json, sourceFile, 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 }; + return { raw: json || convertToObject(sourceFile, errors) }; } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + if (ownConfig.extendedConfigPath) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { 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; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; 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); + if (typeof json.extends !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } - return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - 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")); + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); 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); + 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, extended)); + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return undefined; } } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); 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 }; + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; + return undefined; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); if (typeof result === "boolean" && result) { @@ -7079,7 +17287,6 @@ var ts; } return false; } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -7092,15 +17299,23 @@ var ts; return { options: options, errors: errors }; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultCompilerOptions(configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultTypeAcquisition(configFileName) { var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return options; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; @@ -7109,7 +17324,7 @@ var ts; if (!jsonOptions) { return; } - var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); + var optionNameMap = commandLineOptionsToMap(optionDeclarations); for (var id in jsonOptions) { var opt = optionNameMap.get(id); if (opt) { @@ -7121,28 +17336,41 @@ var ts; } } function convertJsonOption(opt, value, basePath, errors) { - var optType = opt.type; - var expectedType = typeof optType === "string" ? optType : "string"; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); - } - else if (typeof value === expectedType) { - if (typeof optType !== "string") { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (typeof optType !== "string") { return convertJsonOptionOfCustomType(opt, value, errors); } - else { - if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; - } - } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType)); + else if (typeof option.type !== "string") { + return option.type.get(value); } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); @@ -7165,16 +17393,16 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); if (include) { - include = validateSpecs(include, errors, false); + include = validateSpecs(include, errors, false, jsonSourceFile, "include"); } if (exclude) { - exclude = validateSpecs(exclude, errors, true); + exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); @@ -7186,7 +17414,7 @@ var ts; } } if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { var file = _b[_a]; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; @@ -7205,24 +17433,40 @@ var ts; wildcardDirectories: wildcardDirectories }; } - function validateSpecs(specs, errors, allowTrailingRecursion) { + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { var validSpecs = []; for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { var spec = specs_1[_i]; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else { validSpecs.push(spec); } } return validSpecs; + function createDiagnostic(message, spec) { + if (jsonSourceFile && jsonSourceFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isArrayLiteralExpression(property.initializer)) { + for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (ts.isStringLiteral(element) && element.text === spec) { + return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); + } + } + } + } + } + return ts.createCompilerDiagnostic(message, spec); + } } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); @@ -7248,7 +17492,7 @@ var ts; } } } - for (var key in wildcardDirectories) + for (var key in wildcardDirectories) { if (ts.hasProperty(wildcardDirectories, key)) { for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { var recursiveKey = recursiveKeys_1[_a]; @@ -7257,6 +17501,7 @@ var ts; } } } + } } return wildcardDirectories; } @@ -7300,6 +17545,40 @@ var ts; function caseInsensitiveKeyMapper(key) { return key.toLowerCase(); } + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": + return ""; + case "string": + return ""; + case "number": + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -7330,10 +17609,6 @@ var ts; failedLookupLocations: failedLookupLocations }; } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); @@ -7400,11 +17675,7 @@ var ts; var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: traceEnabled - }; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -7511,7 +17782,7 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createFileMap(); + var directoryToModuleNameMap = ts.createMap(); var moduleNameToDirectoryMap = ts.createMap(); return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { @@ -7524,7 +17795,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (!moduleHasNonRelativeName(nonRelativeModuleName)) { + if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { return undefined; } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); @@ -7535,14 +17806,14 @@ var ts; return perModuleNameCache; } function createPerModuleNameCache() { - var directoryPathMap = ts.createFileMap(); + var directoryPathMap = ts.createMap(); return { get: get, set: set }; function get(directory) { return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); } function set(directory, result) { var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); - if (directoryPathMap.contains(path)) { + if (directoryPathMap.has(path)) { return; } directoryPathMap.set(path, result); @@ -7551,7 +17822,7 @@ var ts; var current = path; while (true) { var parent = ts.getDirectoryPath(current); - if (parent === current || directoryPathMap.contains(parent)) { + if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); @@ -7635,7 +17906,7 @@ var ts; } ts.resolveModuleName = resolveModuleName; function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); } else { @@ -7730,10 +18001,12 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } - var tsExtension = ts.tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); - return path_1 && { path: path_1, extension: tsExtension }; + if (path_1 !== undefined) { + return { path: path_1, extension: extension }; + } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); }); @@ -7774,7 +18047,7 @@ var ts; if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } @@ -7855,14 +18128,14 @@ var ts; } switch (extensions) { case Extensions.DtsOnly: - return tryExtension(".d.ts", ts.Extension.Dts); + return tryExtension(".d.ts"); case Extensions.TypeScript: - return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); case Extensions.JavaScript: - return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + return tryExtension(".js") || tryExtension(".jsx"); } - function tryExtension(ext, extension) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + function tryExtension(extension) { + var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); return path && { path: path, extension: extension }; } } @@ -7932,11 +18205,11 @@ var ts; function extensionIsOk(extensions, extension) { switch (extensions) { case Extensions.JavaScript: - return extension === ts.Extension.Js || extension === ts.Extension.Jsx; + return extension === ".js" || extension === ".jsx"; case Extensions.TypeScript: - return extension === ts.Extension.Ts || extension === ts.Extension.Tsx || extension === ts.Extension.Dts; + return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; case Extensions.DtsOnly: - return extension === ts.Extension.Dts; + return extension === ".d.ts"; } } function pathToPackageJson(directory) { @@ -7988,9 +18261,10 @@ var ts; return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); } } + var mangledScopedPackageSeparator = "__"; function mangleScopedPackage(moduleName, state) { if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, "__"); + var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== moduleName) { var mangled = replaceSlash.slice(1); if (state.traceEnabled) { @@ -8001,6 +18275,16 @@ var ts; } return moduleName; } + function getPackageNameFromAtTypesDirectory(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -8023,7 +18307,7 @@ var ts; return { value: resolvedUsingSettings }; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { @@ -8076,3913 +18360,22091 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.externalHelpersModuleNameText = "tslib"; - function getDeclarationOfKind(symbol, kind) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { - var declaration = declarations_1[_i]; - if (declaration.kind === kind) { - return declaration; + 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; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2; + } + else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { + return 0; + } + else if (node.kind === 234) { + var state_1 = 0; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0: + return false; + case 2: + state_1 = 2; + return false; + case 1: + state_1 = 1; + return true; } - } + }); + return state_1; } - return undefined; - } - ts.getDeclarationOfKind = getDeclarationOfKind; - function findDeclaration(symbol, predicate) { - var declarations = symbol.declarations; - if (declarations) { - for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { - var declaration = declarations_2[_i]; - if (predicate(declaration)) { - return declaration; - } - } + else if (node.kind === 233) { + var body = node.body; + return body ? getModuleInstanceState(body) : 1; } - return undefined; - } - ts.findDeclaration = findDeclaration; - var stringWriters = []; - function getSingleLineStringWriter() { - if (stringWriters.length === 0) { - var str_1 = ""; - var writeText = function (text) { return str_1 += text; }; - return { - string: function () { return str_1; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { return str_1 = ""; }, - trackSymbol: ts.noop, - reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop - }; - } - return stringWriters.pop(); - } - ts.getSingleLineStringWriter = getSingleLineStringWriter; - function releaseStringWriter(writer) { - writer.clear(); - stringWriters.push(writer); - } - ts.releaseStringWriter = releaseStringWriter; - function getFullWidth(node) { - return node.end - node.pos; - } - ts.getFullWidth = getFullWidth; - function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText)); - } - ts.hasResolvedModule = hasResolvedModule; - function getResolvedModule(sourceFile, moduleNameText) { - return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined; - } - ts.getResolvedModule = getResolvedModule; - function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { - if (!sourceFile.resolvedModules) { - sourceFile.resolvedModules = ts.createMap(); - } - sourceFile.resolvedModules.set(moduleNameText, resolvedModule); - } - ts.setResolvedModule = setResolvedModule; - function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { - if (!sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); - } - sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); - } - ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; - function moduleResolutionIsEqualTo(oldResolution, newResolution) { - return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && - oldResolution.extension === newResolution.extension && - oldResolution.resolvedFileName === newResolution.resolvedFileName; - } - ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; - function typeDirectiveIsEqualTo(oldResolution, newResolution) { - return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; - } - ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; - function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { - 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]); - var changed = oldResolution - ? !newResolution || !comparer(oldResolution, newResolution) - : newResolution; - if (changed) { - return true; - } - } - return false; - } - ts.hasChangesInResolutions = hasChangesInResolutions; - function containsParseError(node) { - aggregateChildData(node); - return (node.flags & 131072) !== 0; - } - ts.containsParseError = containsParseError; - function aggregateChildData(node) { - if (!(node.flags & 262144)) { - var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || - ts.forEachChild(node, containsParseError); - if (thisNodeOrAnySubNodesHasError) { - node.flags |= 131072; - } - node.flags |= 262144; - } - } - function getSourceFileOfNode(node) { - while (node && node.kind !== 265) { - node = node.parent; - } - return node; - } - ts.getSourceFileOfNode = getSourceFileOfNode; - function isStatementWithLocals(node) { - switch (node.kind) { - case 207: - case 235: - case 214: - case 215: - case 216: - return true; - } - return false; - } - ts.isStatementWithLocals = isStatementWithLocals; - function getStartPositionOfLine(line, sourceFile) { - ts.Debug.assert(line >= 0); - return ts.getLineStarts(sourceFile)[line]; - } - ts.getStartPositionOfLine = getStartPositionOfLine; - function nodePosToString(node) { - var file = getSourceFileOfNode(node); - var loc = ts.getLineAndCharacterOfPosition(file, node.pos); - return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; - } - ts.nodePosToString = nodePosToString; - function getStartPosOfNode(node) { - return node.pos; - } - ts.getStartPosOfNode = getStartPosOfNode; - function isDefined(value) { - return value !== undefined; - } - ts.isDefined = isDefined; - function getEndLinePosition(line, sourceFile) { - ts.Debug.assert(line >= 0); - var lineStarts = ts.getLineStarts(sourceFile); - var lineIndex = line; - var sourceText = sourceFile.text; - if (lineIndex + 1 === lineStarts.length) { - return sourceText.length - 1; + else if (node.kind === 71 && node.isInJSDocNamespace) { + return 0; } else { - var start = lineStarts[lineIndex]; - var pos = lineStarts[lineIndex + 1] - 1; - ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); - while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { - pos--; + return 1; + } + } + 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"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + var emitFlags; + var inStrictMode; + var symbolCount = 0; + var Symbol; + var classifiableNames; + var unreachableFlow = { flags: 1 }; + var reportedUnreachableFlow = { flags: 1 }; + var subtreeTransformFlags = 0; + var skipTransformFlagAggregation; + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; } - return pos; + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0; + subtreeTransformFlags = 0; } - } - ts.getEndLinePosition = getEndLinePosition; - function nodeIsMissing(node) { - if (node === undefined) { - return true; - } - return node.pos === node.end && node.pos >= 0 && node.kind !== 1; - } - ts.nodeIsMissing = nodeIsMissing; - function nodeIsPresent(node) { - return !nodeIsMissing(node); - } - ts.nodeIsPresent = nodeIsPresent; - function isToken(n) { - return n.kind >= 0 && n.kind <= 142; - } - ts.isToken = isToken; - function getTokenPosOfNode(node, sourceFile, includeJsDoc) { - if (nodeIsMissing(node)) { - return node.pos; - } - if (isJSDocNode(node)) { - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); - } - if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { - return getTokenPosOfNode(node.jsDoc[0]); - } - if (node.kind === 294 && node._children.length > 0) { - return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); - } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); - } - ts.getTokenPosOfNode = getTokenPosOfNode; - function isJSDocNode(node) { - return node.kind >= 267 && node.kind <= 293; - } - ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 283 && node.kind <= 293; - } - ts.isJSDocTag = isJSDocTag; - function getNonDecoratorTokenPosOfNode(node, sourceFile) { - if (nodeIsMissing(node) || !node.decorators) { - return getTokenPosOfNode(node, sourceFile); - } - return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); - } - ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; - function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { - if (includeTrivia === void 0) { includeTrivia = false; } - if (nodeIsMissing(node)) { - return ""; - } - var text = sourceFile.text; - return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); - } - ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; - function getTextOfNodeFromSourceText(sourceText, node) { - if (nodeIsMissing(node)) { - return ""; - } - return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); - } - ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; - function getTextOfNode(node, includeTrivia) { - if (includeTrivia === void 0) { includeTrivia = false; } - return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); - } - ts.getTextOfNode = getTextOfNode; - function getLiteralText(node, sourceFile) { - if (!nodeIsSynthesized(node) && node.parent) { - return getSourceTextOfNodeFromSourceFile(sourceFile, node); - } - var escapeText = ts.getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; - switch (node.kind) { - case 9: - return '"' + escapeText(node.text) + '"'; - case 13: - return "`" + escapeText(node.text) + "`"; - case 14: - return "`" + escapeText(node.text) + "${"; - case 15: - return "}" + escapeText(node.text) + "${"; - case 16: - return "}" + escapeText(node.text) + "`"; - case 8: - return node.text; - } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); - } - ts.getLiteralText = getLiteralText; - 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; - } - ts.escapeIdentifier = escapeIdentifier; - function makeIdentifierFromModuleName(moduleName) { - return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); - } - ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; - function isBlockOrCatchScoped(declaration) { - return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || - isCatchClauseVariableDeclarationOrBindingElement(declaration); - } - ts.isBlockOrCatchScoped = isBlockOrCatchScoped; - function isCatchClauseVariableDeclarationOrBindingElement(declaration) { - var node = getRootDeclaration(declaration); - return node.kind === 226 && node.parent.kind === 260; - } - ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; - function isAmbientModule(node) { - return node && node.kind === 233 && - (node.name.kind === 9 || isGlobalScopeAugmentation(node)); - } - ts.isAmbientModule = isAmbientModule; - function isShorthandAmbientModuleSymbol(moduleSymbol) { - return isShorthandAmbientModule(moduleSymbol.valueDeclaration); - } - ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; - function isShorthandAmbientModule(node) { - return node && node.kind === 233 && (!node.body); - } - function isBlockScopedContainerTopLevel(node) { - return node.kind === 265 || - node.kind === 233 || - isFunctionLike(node); - } - ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; - function isGlobalScopeAugmentation(module) { - return !!(module.flags & 512); - } - ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; - function isExternalModuleAugmentation(node) { - if (!node || !isAmbientModule(node)) { - return false; - } - switch (node.parent.kind) { - case 265: - return ts.isExternalModule(node.parent); - case 234: - return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); - } - return false; - } - ts.isExternalModuleAugmentation = isExternalModuleAugmentation; - function isEffectiveExternalModule(node, compilerOptions) { - return ts.isExternalModule(node) || compilerOptions.isolatedModules; - } - ts.isEffectiveExternalModule = isEffectiveExternalModule; - function isBlockScope(node, parentNode) { - switch (node.kind) { - case 265: - case 235: - case 260: - case 233: - case 214: - case 215: - case 216: - case 152: - case 151: - case 153: - case 154: - case 228: - case 186: - case 187: - return true; - case 207: - return parentNode && !isFunctionLike(parentNode); - } - return false; - } - ts.isBlockScope = isBlockScope; - function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } - } - ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; - function declarationNameToString(name) { - return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); - } - ts.declarationNameToString = declarationNameToString; - function getNameFromIndexInfo(info) { - return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; - } - ts.getNameFromIndexInfo = getNameFromIndexInfo; - function getTextOfPropertyName(name) { - switch (name.kind) { - case 71: - return name.text; - case 9: - case 8: - return name.text; - case 144: - if (isStringOrNumericLiteral(name.expression)) { - return name.expression.text; - } - } - return undefined; - } - ts.getTextOfPropertyName = getTextOfPropertyName; - function entityNameToString(name) { - switch (name.kind) { - case 71: - return getFullWidth(name) === 0 ? ts.unescapeIdentifier(name.text) : getTextOfNode(name); - case 143: - return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 179: - return entityNameToString(name.expression) + "." + entityNameToString(name.name); - } - } - ts.entityNameToString = entityNameToString; - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { - var sourceFile = getSourceFileOfNode(node); - return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); - } - ts.createDiagnosticForNode = createDiagnosticForNode; - function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { - var span = getErrorSpanForNode(sourceFile, node); - return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); - } - ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeFromMessageChain(node, messageChain) { - var sourceFile = getSourceFileOfNode(node); - var span = getErrorSpanForNode(sourceFile, node); - return { - file: sourceFile, - start: span.start, - length: span.length, - code: messageChain.code, - category: messageChain.category, - messageText: messageChain.next ? messageChain : messageChain.messageText - }; - } - ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; - function getSpanOfTokenAtPosition(sourceFile, pos) { - var scanner = ts.createScanner(sourceFile.languageVersion, true, sourceFile.languageVariant, sourceFile.text, undefined, pos); - scanner.scan(); - var start = scanner.getTokenPos(); - return ts.createTextSpanFromBounds(start, scanner.getTextPos()); - } - ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; - function getErrorSpanForArrowFunction(sourceFile, node) { - var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 207) { - var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; - var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; - if (startLine < endLine) { - return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); - } - } - return ts.createTextSpanFromBounds(pos, node.end); - } - function getErrorSpanForNode(sourceFile, node) { - var errorNode = node; - switch (node.kind) { - case 265: - var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); - if (pos_1 === sourceFile.text.length) { - return ts.createTextSpan(0, 0); - } - return getSpanOfTokenAtPosition(sourceFile, pos_1); - case 226: - case 176: - case 229: - case 199: - case 230: - case 233: - case 232: - case 264: - case 228: - case 186: - case 151: - case 153: - case 154: - case 231: - errorNode = node.name; - break; - case 187: - return getErrorSpanForArrowFunction(sourceFile, node); - } - if (errorNode === undefined) { - return getSpanOfTokenAtPosition(sourceFile, node.pos); - } - var pos = nodeIsMissing(errorNode) - ? errorNode.pos - : ts.skipTrivia(sourceFile.text, errorNode.pos); - return ts.createTextSpanFromBounds(pos, errorNode.end); - } - ts.getErrorSpanForNode = getErrorSpanForNode; - function isExternalOrCommonJsModule(file) { - return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; - } - ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isConstEnumDeclaration(node) { - return node.kind === 232 && isConst(node); - } - ts.isConstEnumDeclaration = isConstEnumDeclaration; - function isConst(node) { - return !!(ts.getCombinedNodeFlags(node) & 2) - || !!(ts.getCombinedModifierFlags(node) & 2048); - } - ts.isConst = isConst; - function isLet(node) { - return !!(ts.getCombinedNodeFlags(node) & 1); - } - ts.isLet = isLet; - function isSuperCall(n) { - return n.kind === 181 && n.expression.kind === 97; - } - ts.isSuperCall = isSuperCall; - function isPrologueDirective(node) { - return node.kind === 210 - && node.expression.kind === 9; - } - ts.isPrologueDirective = isPrologueDirective; - function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { - return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); - } - ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; - function getLeadingCommentRangesOfNodeFromText(node, text) { - return ts.getLeadingCommentRanges(text, node.pos); - } - ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; - function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 146 || - node.kind === 145 || - node.kind === 186 || - node.kind === 187) ? - ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : - getLeadingCommentRangesOfNodeFromText(node, text); - return ts.filter(commentRanges, function (comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 42 && - text.charCodeAt(comment.pos + 3) !== 47; - }); - } - ts.getJSDocCommentRanges = getJSDocCommentRanges; - ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; - ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; - function isPartOfTypeNode(node) { - if (158 <= node.kind && node.kind <= 173) { - return true; - } - switch (node.kind) { - case 119: - case 133: - case 136: - case 122: - case 137: - case 139: - case 130: - return true; - case 105: - return node.parent.kind !== 190; - case 201: - return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 71: - if (node.parent.kind === 143 && node.parent.right === node) { - node = node.parent; - } - else if (node.parent.kind === 179 && node.parent.name === node) { - node = node.parent; - } - ts.Debug.assert(node.kind === 71 || node.kind === 143 || node.kind === 179, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); - case 143: - case 179: - case 99: - var parent = node.parent; - if (parent.kind === 162) { - return false; - } - if (158 <= parent.kind && parent.kind <= 173) { - return true; - } - switch (parent.kind) { - case 201: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 145: - return node === parent.constraint; - case 149: - case 148: - case 146: - case 226: - return node === parent.type; - case 228: - case 186: - case 187: - case 152: - case 151: - case 150: - case 153: - case 154: - return node === parent.type; - case 155: - case 156: - case 157: - return node === parent.type; - case 184: - return node === parent.type; - case 181: - case 182: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; - case 183: - return false; - } - } - return false; - } - ts.isPartOfTypeNode = isPartOfTypeNode; - function isChildOfNodeWithKind(node, kind) { - while (node) { - if (node.kind === kind) { + return bindSourceFile; + function bindInStrictMode(file, opts) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { return true; } - node = node.parent; - } - return false; - } - ts.isChildOfNodeWithKind = isChildOfNodeWithKind; - function isPrefixUnaryExpression(node) { - return node.kind === 192; - } - ts.isPrefixUnaryExpression = isPrefixUnaryExpression; - function forEachReturnStatement(body, visitor) { - return traverse(body); - function traverse(node) { - switch (node.kind) { - case 219: - return visitor(node); - case 235: - case 207: - case 211: - case 212: - case 213: - case 214: - case 215: - case 216: - case 220: - case 221: - case 257: - case 258: - case 222: - case 224: - case 260: - return ts.forEachChild(node, traverse); + else { + return !!file.externalModuleIndicator; } } - } - ts.forEachReturnStatement = forEachReturnStatement; - function forEachYieldExpression(body, visitor) { - return traverse(body); - function traverse(node) { - switch (node.kind) { - case 197: - visitor(node); - var operand = node.expression; - if (operand) { - traverse(operand); + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & 6240 && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 107455) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { + symbol.valueDeclaration = node; + } + } + } + function getDeclarationName(node) { + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 144) { + var nameExpression = name.expression; + if (ts.isStringOrNumericLiteral(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); } - return; - case 232: - case 230: - case 233: - case 231: + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + } + return ts.getEscapedTextOfIdentifierOrLiteral(name); + } + switch (node.kind) { + case 152: + return "__constructor"; + case 160: + case 155: + return "__call"; + case 161: + case 156: + return "__new"; + case 157: + return "__index"; + case 244: + return "__export"; + case 243: + return node.isExportEquals ? "export=" : "default"; + case 194: + if (ts.getSpecialPropertyAssignmentKind(node) === 2) { + return "export="; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 228: case 229: - case 199: - return; - default: - if (isFunctionLike(node)) { - var name = node.name; - if (name && name.kind === 144) { - traverse(name.expression); - return; + return (ts.hasModifier(node, 512) ? "default" : undefined); + case 273: + return (ts.isJSDocConstructSignature(node) ? "__new" : "__call"); + case 146: + ts.Debug.assert(node.parent.kind === 273); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "arg" + index; + case 283: + var parentNode = node.parent && node.parent.parent; + var nameFromParentNode = void 0; + if (parentNode && parentNode.kind === 208) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (ts.isIdentifier(nameIdentifier)) { + nameFromParentNode = nameIdentifier.escapedText; + } } } - else if (!isPartOfTypeNode(node)) { - ts.forEachChild(node, traverse); - } + return nameFromParentNode; } } - } - ts.forEachYieldExpression = forEachYieldExpression; - function getRestParameterElementType(node) { - if (node && node.kind === 164) { - return node.elementType; + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); } - else if (node && node.kind === 159) { - return ts.singleOrUndefined(node.typeArguments); + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512); + var name = isDefaultExport && parent ? "default" : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0, "__missing"); + } + else { + symbol = symbolTable.get(name); + if (includes & 788448) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + symbolTable.set(name, symbol = createSymbol(0, name)); + } + else { + if (node.name) { + node.name.parent = node; + } + var message_1 = symbol.flags & 2 + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + symbol = createSymbol(0, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; } - else { + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; + if (symbolFlags & 2097152) { + if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + else { + if (node.kind === 283) + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var isJSDocTypedefInJSDocNamespace = node.kind === 283 && + node.name && + node.name.kind === 71 && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { + var exportKind = symbolFlags & 107455 ? 1048576 : 0; + var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + } + function bindContainer(node, containerFlags) { + var saveContainer = container; + var savedBlockScopeContainer = blockScopeContainer; + if (containerFlags & 1) { + container = blockScopeContainer = node; + if (containerFlags & 32) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); + if (isIIFE) { + currentReturnTarget = createBranchLabel(); + } + else { + currentFlow = { flags: 2 }; + if (containerFlags & (16 | 128)) { + currentFlow.container = node; + } + currentReturnTarget = undefined; + } + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + node.flags &= ~1408; + if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { + node.flags |= 128; + if (hasExplicitReturn) + node.flags |= 256; + } + if (node.kind === 265) { + node.flags |= emitFlags; + } + if (isIIFE) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + } + else { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; + } + else { + bindChildren(node); + } + container = saveContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var nodeArrayFlags = 0; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912; + } + nodes.transformFlags = nodeArrayFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (node.jsDoc) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + if (checkUnreachable(node)) { + bindEachChild(node); + return; + } + switch (node.kind) { + case 213: + bindWhileStatement(node); + break; + case 212: + bindDoStatement(node); + break; + case 214: + bindForStatement(node); + break; + case 215: + case 216: + bindForInOrForOfStatement(node); + break; + case 211: + bindIfStatement(node); + break; + case 219: + case 223: + bindReturnOrThrow(node); + break; + case 218: + case 217: + bindBreakOrContinueStatement(node); + break; + case 224: + bindTryStatement(node); + break; + case 221: + bindSwitchStatement(node); + break; + case 235: + bindCaseBlock(node); + break; + case 257: + bindCaseClause(node); + break; + case 222: + bindLabeledStatement(node); + break; + case 192: + bindPrefixUnaryExpressionFlow(node); + break; + case 193: + bindPostfixUnaryExpressionFlow(node); + break; + case 194: + bindBinaryExpressionFlow(node); + break; + case 188: + bindDeleteExpressionFlow(node); + break; + case 195: + bindConditionalExpressionFlow(node); + break; + case 226: + bindVariableDeclarationFlow(node); + break; + case 181: + bindCallExpressionFlow(node); + break; + case 275: + bindJSDocComment(node); + break; + case 283: + bindJSDocTypedefTag(node); + break; + default: + bindEachChild(node); + break; + } + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 71: + case 99: + case 179: + return isNarrowableReference(expr); + case 181: + return hasNarrowableArgument(expr); + case 185: + return isNarrowingExpression(expr.expression); + case 194: + return isNarrowingBinaryExpression(expr); + case 192: + return expr.operator === 51 && isNarrowingExpression(expr.operand); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 71 || + expr.kind === 99 || + expr.kind === 97 || + expr.kind === 179 && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 179 && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 58: + return isNarrowableReference(expr.left); + case 32: + case 33: + case 34: + case 35: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 93: + return isNarrowableOperand(expr.left); + case 26: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 185: + return isNarrowableOperand(expr.expression); + case 194: + switch (expr.operatorToken.kind) { + case 58: + return isNarrowableOperand(expr.left); + case 26: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + flow.flags |= flow.flags & 512 ? 1024 : 512; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1) { + return antecedent; + } + if (!expression) { + return flags & 32 ? antecedent : unreachableFlow; + } + if (expression.kind === 101 && flags & 64 || + expression.kind === 86 && flags & 32) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: flags, + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent + }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 16, + antecedent: antecedent, + node: node + }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256, + antecedent: antecedent, + node: node + }; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 211: + case 213: + case 212: + return parent.expression === node; + case 214: + case 195: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 185) { + node = node.expression; + } + else if (node.kind === 192 && node.operator === 51) { + node = node.operand; + } + else { + return node.kind === 194 && (node.operatorToken.kind === 53 || + node.operatorToken.kind === 54); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 185 || + node.parent.kind === 192 && + node.parent.operator === 51) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 222 + ? ts.lastOrUndefined(activeLabels) + : undefined; + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 216) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 227) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 219) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } return undefined; } - } - ts.getRestParameterElementType = getRestParameterElementType; - function isVariableLike(node) { - if (node) { + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 218 ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + if (!(currentFlow.flags & 1)) { + if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1)) { + var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + } + if (!node.statement || node.statement.kind !== 212) { + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 194 && node.operatorToken.kind === 58) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 177) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 198) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 178) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 261) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 262) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 263) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 53) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 51) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 43 || node.operator === 44) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 43 || node.operator === 44) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 53 || operator === 54) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 58 && node.left.kind === 180) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 179) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocComment(node) { + ts.forEachChild(node, function (n) { + if (n.kind !== 283) { + bind(n); + } + }); + } + function bindJSDocTypedefTag(node) { + ts.forEachChild(node, function (n) { + if (node.fullName && n === node.name && node.fullName.kind !== 71) { + return; + } + bind(n); + }); + } + function bindCallExpressionFlow(node) { + var expr = node.expression; + while (expr.kind === 185) { + expr = expr.expression; + } + if (expr.kind === 186 || expr.kind === 187) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 179) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { switch (node.kind) { - case 176: - case 264: - case 146: - case 261: - case 149: - case 148: - case 262: - case 226: - return true; - } - } - return false; - } - ts.isVariableLike = isVariableLike; - function isAccessor(node) { - return node && (node.kind === 153 || node.kind === 154); - } - ts.isAccessor = isAccessor; - function isClassLike(node) { - return node && (node.kind === 229 || node.kind === 199); - } - ts.isClassLike = isClassLike; - function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); - } - ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { - switch (kind) { - case 152: - case 186: - case 228: - case 187: - case 151: - case 150: - case 153: - case 154: - case 155: - case 156: - case 157: - case 160: - case 161: - return true; - } - 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: - case 150: - case 152: - case 153: - case 154: - case 228: - case 186: - return true; - } - return false; - } - ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; - function isIterationStatement(node, lookInLabeledStatements) { - switch (node.kind) { - case 214: - case 215: - case 216: - case 212: - case 213: - return true; - case 222: - return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); - } - return false; - } - ts.isIterationStatement = isIterationStatement; - function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { - while (true) { - if (beforeUnwrapLabelCallback) { - beforeUnwrapLabelCallback(node); - } - if (node.statement.kind !== 222) { - return node.statement; - } - node = node.statement; - } - } - ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; - function isFunctionBlock(node) { - return node && node.kind === 207 && isFunctionLike(node.parent); - } - ts.isFunctionBlock = isFunctionBlock; - function isObjectLiteralMethod(node) { - return node && node.kind === 151 && node.parent.kind === 178; - } - ts.isObjectLiteralMethod = isObjectLiteralMethod; - function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 151 && - (node.parent.kind === 178 || - node.parent.kind === 199); - } - ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; - function isIdentifierTypePredicate(predicate) { - return predicate && predicate.kind === 1; - } - ts.isIdentifierTypePredicate = isIdentifierTypePredicate; - function isThisTypePredicate(predicate) { - return predicate && predicate.kind === 0; - } - ts.isThisTypePredicate = isThisTypePredicate; - function getContainingFunction(node) { - while (true) { - node = node.parent; - if (!node || isFunctionLike(node)) { - return node; - } - } - } - ts.getContainingFunction = getContainingFunction; - function getContainingClass(node) { - while (true) { - node = node.parent; - if (!node || isClassLike(node)) { - return node; - } - } - } - ts.getContainingClass = getContainingClass; - function getThisContainer(node, includeArrowFunctions) { - while (true) { - node = node.parent; - if (!node) { - return undefined; - } - switch (node.kind) { - case 144: - if (isClassLike(node.parent.parent)) { - return node; - } - node = node.parent; - break; - case 147: - if (node.parent.kind === 146 && isClassElement(node.parent.parent)) { - node = node.parent.parent; - } - else if (isClassElement(node.parent)) { - node = node.parent; - } - break; - case 187: - if (!includeArrowFunctions) { - continue; - } - case 228: - case 186: + case 199: + case 229: + case 232: + case 178: + case 163: + case 285: + case 254: + return 1; + case 230: + return 1 | 64; case 233: - case 149: - case 148: + case 231: + case 172: + return 1 | 32; + case 265: + return 1 | 4 | 32; case 151: - case 150: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 152: + case 228: + case 150: case 153: case 154: case 155: + case 273: + case 160: case 156: case 157: - case 232: - case 265: - return node; - } - } - } - ts.getThisContainer = getThisContainer; - function getNewTargetContainer(node) { - var container = getThisContainer(node, false); - if (container) { - switch (container.kind) { - case 152: - case 228: - case 186: - return container; - } - } - return undefined; - } - ts.getNewTargetContainer = getNewTargetContainer; - function getSuperContainer(node, stopOnFunctions) { - while (true) { - node = node.parent; - if (!node) { - return node; - } - switch (node.kind) { - case 144: - node = node.parent; - break; - case 228: + case 161: + return 1 | 4 | 32 | 8; case 186: case 187: - if (!stopOnFunctions) { - continue; - } + return 1 | 4 | 32 | 8 | 16; + case 234: + return 4; case 149: - case 148: + return node.initializer ? 4 : 0; + case 260: + case 214: + case 215: + case 216: + case 235: + return 2; + case 207: + return ts.isFunctionLike(node.parent) ? 0 : 2; + } + return 0; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + case 233: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 265: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 199: + case 229: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 232: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 163: + case 285: + case 178: + case 230: + case 254: + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 160: + case 161: + case 155: + case 156: + case 157: case 151: case 150: case 152: case 153: case 154: - return node; - case 147: - if (node.parent.kind === 146 && isClassElement(node.parent.parent)) { - node = node.parent.parent; + case 228: + case 186: + case 187: + case 273: + case 231: + case 172: + return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 265 ? node : node.body; + if (body && (body.kind === 265 || body.kind === 234)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 244 || stat.kind === 243) { + return true; } - else if (isClassElement(node.parent)) { - node = node.parent; + } + } + return false; + } + function setExportContextFlag(node) { + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 32; + } + else { + node.flags &= ~32; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isExternalModuleAugmentation(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 9) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } } + var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); + if (pattern) { + (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); + } + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0) { + if (node.symbol.flags & (16 | 32 | 256)) { + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2; + if (node.symbol.constEnumOnlyModule === undefined) { + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); + return state; + } + function bindFunctionOrConstructorType(node) { + var symbol = createSymbol(131072, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072); + var typeLiteralSymbol = createSymbol(2048, "__type"); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, 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.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263 || prop.name.kind !== 71) { + continue; + } + var identifier = prop.name; + var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 + ? 1 + : 2; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 && existingKind === 1) { + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096, "__object"); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 233: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 265: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2, 107455); + } + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 108 && + node.originalKeywordKind <= 116 && + !ts.isIdentifierName(node) && + !ts.isInAmbientContext(node)) { + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + if (inStrictMode && node.expression.kind === 71) { + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 71) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2) { + if (blockScopeContainer.kind !== 265 && + blockScopeContainer.kind !== 233 && + !ts.isFunctionLike(blockScopeContainer)) { + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 4) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + if (inStrictMode) { + if (node.operator === 43 || node.operator === 44) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + if (ts.isInJavaScriptFile(node)) + bindJSDocTypedefTagIfAny(node); + bindWorker(node); + if (node.kind > 142) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } + inStrictMode = saveInStrictMode; + } + function bindJSDocTypedefTagIfAny(node) { + if (!node.jsDoc) { + return; + } + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (!jsDoc.tags) { + continue; + } + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.kind === 283) { + var savedParent = parent; + parent = jsDoc; + bind(tag); + parent = savedParent; + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + case 71: + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 283) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288, 793064); + break; + } + case 99: + if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 179: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + break; + case 194: + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1: + bindExportsPropertyAssignment(node); + break; + case 2: + bindModuleExportsAssignment(node); + break; + case 3: + bindPrototypePropertyAssignment(node); + break; + case 4: + bindThisPropertyAssignment(node); + break; + case 5: + bindStaticPropertyAssignment(node); + break; + case 0: + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 260: + return checkStrictModeCatchClause(node); + case 188: + return checkStrictModeDeleteExpression(node); + case 8: + return checkStrictModeNumericLiteral(node); + case 193: + return checkStrictModePostfixUnaryExpression(node); + case 192: + return checkStrictModePrefixUnaryExpression(node); + case 220: + return checkStrictModeWithStatement(node); + case 169: + seenThisKeyword = true; + return; + case 158: + return checkTypePredicate(node); + case 145: + return declareSymbolAndAddToSymbolTable(node, 262144, 530920); + case 146: + return bindParameter(node); + case 226: + return bindVariableDeclarationOrBindingElement(node); + case 176: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 149: + case 148: + return bindPropertyWorker(node); + case 261: + case 262: + return bindPropertyOrMethodOrAccessor(node, 4, 0); + case 264: + return bindPropertyOrMethodOrAccessor(node, 8, 900095); + case 155: + case 156: + case 157: + return declareSymbolAndAddToSymbolTable(node, 131072, 0); + case 151: + case 150: + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 16777216 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + case 228: + return bindFunctionDeclaration(node); + case 152: + return declareSymbolAndAddToSymbolTable(node, 16384, 0); + case 153: + return bindPropertyOrMethodOrAccessor(node, 32768, 41919); + case 154: + return bindPropertyOrMethodOrAccessor(node, 65536, 74687); + case 160: + case 273: + case 161: + return bindFunctionOrConstructorType(node); + case 163: + case 285: + case 172: + return bindAnonymousTypeWorker(node); + case 178: + return bindObjectLiteralExpression(node); + case 186: + case 187: + return bindFunctionExpression(node); + case 181: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + case 199: + case 229: + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 230: + return bindBlockScopedDeclaration(node, 64, 792968); + case 231: + return bindBlockScopedDeclaration(node, 524288, 793064); + case 232: + return bindEnumDeclaration(node); + case 233: + return bindModuleDeclaration(node); + case 254: + return bindJsxAttributes(node); + case 253: + return bindJsxAttribute(node, 4, 0); + case 237: + case 240: + case 242: + case 246: + return declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + case 236: + return bindNamespaceExportDeclaration(node); + case 239: + return bindImportClause(node); + case 244: + return bindExportDeclaration(node); + case 243: + return bindExportAssignment(node); + case 265: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 207: + if (!ts.isFunctionLike(node.parent)) { + return; + } + case 234: + return updateStrictModeStatementList(node.statements); + case 279: + if (node.parent.kind !== 285) { + break; + } + case 284: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 ? + 4 | 16777216 : + 4; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0); + case 283: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71) { + return bindBlockScopedDeclaration(node, 524288, 793064); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048, "__type"); + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 71) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 169) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 2097152, getDeclarationName(node)); + } + else { + var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) + ? 2097152 + : 4; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 2097152 | 32 | 16); + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + if (node.parent.kind !== 265) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152, 2097152); + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); + } + else if (!node.exportClause) { + declareSymbol(container.symbol.exports, container.symbol, node, 8388608, 0); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152, 2097152); + } + } + function setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } + } + } + function bindExportsPropertyAssignment(node) { + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 1048576, 0); + } + function isExportsOrModuleExportsOrAlias(node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + isNameOfExportsOrModuleExportsAliasDeclaration(node); + } + function isNameOfExportsOrModuleExportsAliasDeclaration(node) { + if (ts.isIdentifier(node)) { + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); + } + return false; + } + function isExportsOrModuleExportsOrAliasOrAssignment(node) { + return isExportsOrModuleExportsOrAlias(node) || + (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); + } + function bindModuleExportsAssignment(node) { + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + setCommonJsModuleIndicator(node); + return; + } + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node, 4 | 1048576 | 512, 0); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var container = ts.getThisContainer(node, false); + switch (container.kind) { + case 228: + case 186: + container.symbol.members = container.symbol.members || ts.createSymbolTable(); + declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); + break; + case 152: + case 149: + case 151: + case 153: + case 154: + var containingClass = container.parent; + var symbolTable = ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4, 0, true); break; } } - } - ts.getSuperContainer = getSuperContainer; - function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 186 || func.kind === 187) { - var prev = func; - var parent = func.parent; - while (parent.kind === 185) { - prev = parent; - parent = parent.parent; + function bindPrototypePropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, true); + } + function bindStaticPropertyAssignment(node) { + var leftSideOfAssignment = node.left; + var target = leftSideOfAssignment.expression; + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + bindExportsPropertyAssignment(node); } - if (parent.kind === 181 && parent.expression === prev) { - return parent; + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, false); } } - } - ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; - function isSuperProperty(node) { - var kind = node.kind; - return (kind === 179 || kind === 180) - && node.expression.kind === 97; - } - ts.isSuperProperty = isSuperProperty; - function getEntityNameFromTypeNode(node) { - switch (node.kind) { - case 159: - case 277: - return node.typeName; - case 201: - return isEntityNameExpression(node.expression) - ? node.expression - : undefined; - case 71: - case 143: - return node; + function lookupSymbolForName(name) { + return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); } - return undefined; - } - ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; - function isCallLikeExpression(node) { - switch (node.kind) { - case 251: - case 250: - case 181: - case 182: - case 183: - case 147: - return true; - default: + function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { + var targetSymbol = lookupSymbolForName(functionName); + if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { + targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + } + if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { + return; + } + var symbolTable = isPrototypeProperty ? + (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : + (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); + declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); + } + function bindCallExpression(node) { + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 229) { + bindBlockScopedDeclaration(node, 32, 899519); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class"; + bindAnonymousDeclaration(node, 32, bindingName); + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + var prototypeSymbol = createSymbol(4 | 4194304, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isConst(node) + ? bindBlockScopedDeclaration(node, 128, 899967) + : bindBlockScopedDeclaration(node, 256, 899327); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + declareSymbolAndAddToSymbolTable(node, 1, 107455); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 107454); + } + } + } + function bindParameter(node) { + if (inStrictMode && !ts.isInAmbientContext(node)) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1, 107455); + } + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 16777216 : 0), 0); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16, 106927); + } + else { + declareSymbolAndAddToSymbolTable(node, 16, 106927); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function"; + return bindAnonymousDeclaration(node, 16, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed") + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1)) { return false; + } + if (currentFlow === unreachableFlow) { + var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || + node.kind === 229 || + (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 208 || + ts.getCombinedNodeFlags(node.declarationList) & 3 || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + } + return true; } } - 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; - } - else if (isJsxOpeningLikeElement(node)) { - return node.tagName; - } - return node.expression; - } - ts.getInvokedExpression = getInvokedExpression; - function nodeCanBeDecorated(node) { - switch (node.kind) { + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 181: + return computeCallExpression(node, subtreeFlags); + case 182: + return computeNewExpression(node, subtreeFlags); + case 233: + return computeModuleDeclaration(node, subtreeFlags); + case 185: + return computeParenthesizedExpression(node, subtreeFlags); + case 194: + return computeBinaryExpression(node, subtreeFlags); + case 210: + return computeExpressionStatement(node, subtreeFlags); + case 146: + return computeParameter(node, subtreeFlags); + case 187: + return computeArrowFunction(node, subtreeFlags); + case 186: + return computeFunctionExpression(node, subtreeFlags); + case 228: + return computeFunctionDeclaration(node, subtreeFlags); + case 226: + return computeVariableDeclaration(node, subtreeFlags); + case 227: + return computeVariableDeclarationList(node, subtreeFlags); + case 208: + return computeVariableStatement(node, subtreeFlags); + case 222: + return computeLabeledStatement(node, subtreeFlags); case 229: - return true; + return computeClassDeclaration(node, subtreeFlags); + case 199: + return computeClassExpression(node, subtreeFlags); + case 259: + return computeHeritageClause(node, subtreeFlags); + case 260: + return computeCatchClause(node, subtreeFlags); + case 201: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 152: + return computeConstructor(node, subtreeFlags); case 149: - return node.parent.kind === 229; + return computePropertyDeclaration(node, subtreeFlags); + case 151: + return computeMethod(node, subtreeFlags); case 153: case 154: - case 151: - return node.body !== undefined - && node.parent.kind === 229; - case 146: - return node.parent.body !== undefined - && (node.parent.kind === 152 - || node.parent.kind === 151 - || node.parent.kind === 154) - && node.parent.parent.kind === 229; - } - return false; - } - ts.nodeCanBeDecorated = nodeCanBeDecorated; - function nodeIsDecorated(node) { - return node.decorators !== undefined - && nodeCanBeDecorated(node); - } - ts.nodeIsDecorated = nodeIsDecorated; - function nodeOrChildIsDecorated(node) { - return nodeIsDecorated(node) || childIsDecorated(node); - } - ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; - function childIsDecorated(node) { - switch (node.kind) { - case 229: - return ts.forEach(node.members, nodeOrChildIsDecorated); - case 151: - case 154: - return ts.forEach(node.parameters, nodeIsDecorated); + return computeAccessor(node, subtreeFlags); + case 237: + return computeImportEquals(node, subtreeFlags); + case 179: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); } } - ts.childIsDecorated = childIsDecorated; - function isJSXTagName(node) { - var parent = node.parent; - if (parent.kind === 251 || - parent.kind === 250 || - parent.kind === 252) { - return parent.tagName === node; + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (node.typeArguments) { + transformFlags |= 3; } - return false; + if (subtreeFlags & 524288 + || isSuperOrSuperProperty(expression, expressionKind)) { + transformFlags |= 192; + } + if (expression.kind === 91) { + transformFlags |= 67108864; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; } - ts.isJSXTagName = isJSXTagName; - function isPartOfExpression(node) { - switch (node.kind) { - case 99: + function isSuperOrSuperProperty(node, kind) { + switch (kind) { case 97: - case 95: - case 101: - case 86: - case 12: - case 177: - case 178: + return true; case 179: case 180: - case 181: - case 182: - case 183: - case 202: - case 184: - case 203: - case 185: - case 186: - case 199: - case 187: - case 190: - case 188: - case 189: - case 192: - case 193: - case 194: - case 195: - case 198: - case 196: - case 13: - case 200: - case 249: - case 250: - case 197: - case 191: - case 204: - return true; - case 143: - while (node.parent.kind === 143) { - node = node.parent; - } - return node.parent.kind === 162 || isJSXTagName(node); - case 71: - if (node.parent.kind === 162 || isJSXTagName(node)) { - return true; - } - case 8: - case 9: - case 99: - var parent = node.parent; - switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 264: - case 261: - case 176: - return parent.initializer === node; - case 210: - case 211: - case 212: - case 213: - case 219: - case 220: - case 221: - case 257: - case 223: - case 221: - return parent.expression === node; - case 214: - var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || - forStatement.condition === node || - forStatement.incrementor === node; - case 215: - case 216: - var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || - forInStatement.expression === node; - case 184: - case 202: - return node === parent.expression; - case 205: - return node === parent.expression; - case 144: - return node === parent.expression; - case 147: - case 256: - case 255: - case 263: - return true; - case 201: - return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); - default: - if (isPartOfExpression(parent)) { - return true; - } - } + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 97; } return false; } - ts.isPartOfExpression = isPartOfExpression; + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3; + } + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537396545; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 58 && leftKind === 178) { + transformFlags |= 8 | 192 | 3072; + } + else if (operatorTokenKind === 58 && leftKind === 177) { + transformFlags |= 192 | 3072; + } + else if (operatorTokenKind === 40 + || operatorTokenKind === 62) { + transformFlags |= 32; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + if (node.questionToken + || node.type + || subtreeFlags & 4096 + || ts.isThisIdentifier(name)) { + transformFlags |= 3; + } + if (modifierFlags & 92) { + transformFlags |= 3 | 262144; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { + transformFlags |= 192 | 131072; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + if (expressionKind === 202 + || expressionKind === 184) { + transformFlags |= 3; + } + if (expressionTransformFlags & 1024) { + transformFlags |= 1024; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 192; + if ((subtreeFlags & 274432) + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~539358529; + } + function computeClassExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (subtreeFlags & 274432 + || node.typeParameters) { + transformFlags |= 3; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~539358529; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 85: + transformFlags |= 192; + break; + case 108: + transformFlags |= 3; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~537920833; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.typeArguments) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computeMethod(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.typeParameters + || node.type + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.decorators + || ts.hasModifier(node, 2270) + || node.type + || !node.body) { + transformFlags |= 3; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601015617; + } + function computePropertyDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags | 3; + if (node.initializer) { + transformFlags |= 8192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2)) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags | 33554432; + if (modifierFlags & 2270 + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (modifierFlags & 256) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601281857; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= node.asteriskToken ? 8 : 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 163840) { + transformFlags |= 192; + } + if (node.asteriskToken) { + transformFlags |= 768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601281857; + } + function computeArrowFunction(node, subtreeFlags) { + var transformFlags = subtreeFlags | 192; + if (ts.hasModifier(node, 2270) + || node.typeParameters + || node.type) { + transformFlags |= 3; + } + if (ts.hasModifier(node, 256)) { + transformFlags |= 16; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (subtreeFlags & 16384) { + transformFlags |= 32768; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~601249089; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (expressionKind === 97) { + transformFlags |= 16384; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 | 8388608; + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + if (node.type) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + if (modifierFlags & 2) { + transformFlags = 3; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 8388608) { + transformFlags |= 192; + } + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (subtreeFlags & 4194304 + && ts.isIterationStatement(node, true)) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.expression.transformFlags & 1024) { + transformFlags |= 192; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~536872257; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~574674241; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 33554432; + if (subtreeFlags & 8388608) { + transformFlags |= 192; + } + if (node.flags & 3) { + transformFlags |= 192 | 4194304; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~546309441; + } + function computeOther(node, kind, subtreeFlags) { + var transformFlags = subtreeFlags; + var excludeFlags = 536872257; + switch (kind) { + case 120: + case 191: + transformFlags |= 8 | 16; + break; + case 114: + case 112: + case 113: + case 117: + case 124: + case 76: + case 232: + case 264: + case 184: + case 202: + case 203: + case 131: + transformFlags |= 3; + break; + case 249: + case 250: + case 251: + case 10: + case 252: + case 253: + case 254: + case 255: + case 256: + transformFlags |= 4; + break; + case 13: + case 14: + case 15: + case 16: + case 196: + case 183: + case 262: + case 115: + case 204: + transformFlags |= 192; + break; + case 9: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192; + } + break; + case 8: + if (node.numericLiteralFlags & 48) { + transformFlags |= 192; + } + break; + case 216: + if (node.awaitModifier) { + transformFlags |= 8; + } + transformFlags |= 192; + break; + case 197: + transformFlags |= 8 | 192 | 16777216; + break; + case 119: + case 133: + case 130: + case 134: + case 136: + case 122: + case 137: + case 105: + case 145: + case 148: + case 150: + case 155: + case 156: + case 157: + case 158: + case 159: + case 160: + case 161: + case 162: + case 163: + case 164: + case 165: + case 166: + case 167: + case 168: + case 230: + case 231: + case 169: + case 170: + case 171: + case 172: + case 173: + case 236: + transformFlags = 3; + excludeFlags = -3; + break; + case 144: + transformFlags |= 2097152; + if (subtreeFlags & 16384) { + transformFlags |= 65536; + } + break; + case 198: + transformFlags |= 192 | 524288; + break; + case 263: + transformFlags |= 8 | 1048576; + break; + case 97: + transformFlags |= 192; + break; + case 99: + transformFlags |= 16384; + break; + case 174: + transformFlags |= 192 | 8388608; + if (subtreeFlags & 524288) { + transformFlags |= 8 | 1048576; + } + excludeFlags = 537396545; + break; + case 175: + transformFlags |= 192 | 8388608; + excludeFlags = 537396545; + break; + case 176: + transformFlags |= 192; + if (node.dotDotDotToken) { + transformFlags |= 524288; + } + break; + case 147: + transformFlags |= 3 | 4096; + break; + case 178: + excludeFlags = 540087617; + if (subtreeFlags & 2097152) { + transformFlags |= 192; + } + if (subtreeFlags & 65536) { + transformFlags |= 16384; + } + if (subtreeFlags & 1048576) { + transformFlags |= 8; + } + break; + case 177: + case 182: + excludeFlags = 537396545; + if (subtreeFlags & 524288) { + transformFlags |= 192; + } + break; + case 212: + case 213: + case 214: + case 215: + if (subtreeFlags & 4194304) { + transformFlags |= 192; + } + break; + case 265: + if (subtreeFlags & 32768) { + transformFlags |= 192; + } + break; + case 219: + case 217: + case 218: + transformFlags |= 33554432; + break; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~excludeFlags; + } + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 158 && kind <= 173) { + return -3; + } + switch (kind) { + case 181: + case 182: + case 177: + return 537396545; + case 233: + return 574674241; + case 146: + return 536872257; + case 187: + return 601249089; + case 186: + case 228: + return 601281857; + case 227: + return 546309441; + case 229: + case 199: + return 539358529; + case 152: + return 601015617; + case 151: + case 153: + case 154: + return 601015617; + case 119: + case 133: + case 130: + case 136: + case 134: + case 122: + case 137: + case 105: + case 145: + case 148: + case 150: + case 155: + case 156: + case 157: + case 230: + case 231: + return -3; + case 178: + return 540087617; + case 260: + return 537920833; + case 174: + case 175: + return 537396545; + default: + return 536872257; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + } +})(ts || (ts = {})); +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || (preserveConstEnums && moduleState === 2); } ts.isInstantiatedModule = isInstantiatedModule; - function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind === 248; - } - ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; - function getExternalModuleImportEqualsDeclarationExpression(node) { - ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); - return node.moduleReference.expression; - } - ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; - function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 237 && node.moduleReference.kind !== 248; - } - ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; - function isSourceFileJavaScript(file) { - return isInJavaScriptFile(file); - } - ts.isSourceFileJavaScript = isSourceFileJavaScript; - function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536); - } - ts.isInJavaScriptFile = isInJavaScriptFile; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 181) { - return false; - } - var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 || expression.text !== "require") { - return false; - } - if (args.length !== 1) { - return false; - } - var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 || arg.kind === 13; - } - ts.isRequireCall = isRequireCall; - function isSingleOrDoubleQuote(charCode) { - return charCode === 39 || charCode === 34; - } - ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; - function isDeclarationOfFunctionOrClassExpression(s) { - if (s.valueDeclaration && s.valueDeclaration.kind === 226) { - var declaration = s.valueDeclaration; - return declaration.initializer && (declaration.initializer.kind === 186 || declaration.initializer.kind === 199); - } - return false; - } - ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; - function getRightMostAssignedExpression(node) { - while (isAssignmentExpression(node, true)) { - node = node.right; - } - return node; - } - ts.getRightMostAssignedExpression = getRightMostAssignedExpression; - function isExportsIdentifier(node) { - return isIdentifier(node) && node.text === "exports"; - } - ts.isExportsIdentifier = isExportsIdentifier; - function isModuleExportsPropertyAccessExpression(node) { - return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports"; - } - ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; - function getSpecialPropertyAssignmentKind(expression) { - if (!isInJavaScriptFile(expression)) { - return 0; - } - var expr = expression; - if (expr.operatorToken.kind !== 58 || expr.left.kind !== 179) { - return 0; - } - var lhs = expr.left; - if (lhs.expression.kind === 71) { - var lhsId = lhs.expression; - if (lhsId.text === "exports") { - return 1; - } - else if (lhsId.text === "module" && lhs.name.text === "exports") { - return 2; - } - else { - return 5; - } - } - else if (lhs.expression.kind === 99) { - return 4; - } - else if (lhs.expression.kind === 179) { - var innerPropertyAccess = lhs.expression; - if (innerPropertyAccess.expression.kind === 71) { - var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { - return 1; + function createTypeChecker(host, produceDiagnostics) { + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var symbolInstantiationDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); + var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; + var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; + var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; + var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4, "arguments"); + var apparentArgumentCount; + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { + parameter = ts.getParseTreeNode(parameter, ts.isParameter); + ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (node) { + node = ts.getParseTreeNode(node, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : unknownType; + }, + getParameterType: getTypeAtPosition, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (node) { + node = ts.getParseTreeNode(node, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : unknownType; + }, + getPropertySymbolOfDestructuringAssignment: function (location) { + location = ts.getParseTreeNode(location, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, + symbolToString: function (symbol, enclosingDeclaration, meaning) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (node) { + node = ts.getParseTreeNode(node, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { + node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + apparentArgumentCount = theArgumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; + apparentArgumentCount = undefined; + return res; + }, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (node, propertyName) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); + return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + }, + getSignatureFromDeclaration: function (declaration) { + declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: function (symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + links.immediateTarget = getTargetOfAliasDeclaration(node, true); } - if (innerPropertyAccess.name.text === "prototype") { - return 3; - } - } - } - return 0; - } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; - function getExternalModuleName(node) { - if (node.kind === 238) { - return node.moduleSpecifier; - } - if (node.kind === 237) { - var reference = node.moduleReference; - if (reference.kind === 248) { - return reference.expression; - } - } - if (node.kind === 244) { - return node.moduleSpecifier; - } - if (node.kind === 233 && node.name.kind === 9) { - return node.name; - } - } - ts.getExternalModuleName = getExternalModuleName; - function getNamespaceDeclarationNode(node) { - if (node.kind === 237) { - return node; - } - var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240) { - return importClause.namedBindings; - } - } - ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; - function isDefaultImport(node) { - return node.kind === 238 - && node.importClause - && !!node.importClause.name; - } - ts.isDefaultImport = isDefaultImport; - function hasQuestionToken(node) { - if (node) { - switch (node.kind) { - case 146: - case 151: - case 150: - case 262: - case 261: - case 149: - case 148: - return node.questionToken !== undefined; - } - } - return false; - } - ts.hasQuestionToken = hasQuestionToken; - function isJSDocConstructSignature(node) { - return node.kind === 279 && - node.parameters.length > 0 && - node.parameters[0].type.kind === 281; - } - ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getCommentsFromJSDoc(node) { - return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); - } - ts.getCommentsFromJSDoc = getCommentsFromJSDoc; - function hasJSDocParameterTags(node) { - var parameterTags = getJSDocTags(node, 286); - return parameterTags && parameterTags.length > 0; - } - ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getJSDocTags(node, kind) { - var docs = getJSDocs(node); - if (docs) { - var result = []; - for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { - var doc = docs_1[_i]; - if (doc.kind === 286) { - if (doc.kind === kind) { - result.push(doc); + return links.immediateTarget; + }, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getAmbientModules: getAmbientModules, + getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { + node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; + }, + getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + isOptionalParameter: function (node) { + node = ts.getParseTreeNode(node, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + return tryFindAmbientModule(moduleName, false); + }, + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + resolveNameAtLocation: function (location, name, meaning) { + location = ts.getParseTreeNode(location); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, undefined, ts.escapeLeadingUnderscores(name)); + }, + }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var unknownSymbol = createSymbol(4, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); + var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); + var unknownType = createIntrinsicType(1, "unknown"); + var undefinedType = createIntrinsicType(2048, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); + var nullType = createIntrinsicType(4096, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); + var stringType = createIntrinsicType(2, "string"); + var numberType = createIntrinsicType(4, "number"); + var trueType = createIntrinsicType(128, "true"); + var falseType = createIntrinsicType(128, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512, "symbol"); + var voidType = createIntrinsicType(1024, "void"); + var neverType = createIntrinsicType(8192, "never"); + var silentNeverType = createIntrinsicType(8192, "never"); + var nonPrimitiveType = createIntrinsicType(16777216, "object"); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + anyFunctionType.flags |= 8388608; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, undefined, 0, false, false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var enumNumberIndexInfo = createIndexInfo(stringType, true); + var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); + var globals = ts.createSymbolTable(); + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredJsxElementClassType; + var deferredJsxElementType; + var deferredJsxStatelessElementType; + var deferredNodes; + var deferredUnusedIdentifierNodes; + var flowLoopStart = 0; + var flowLoopCount = 0; + var visitedFlowCount = 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 = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var visitedFlowNodes = []; + var visitedFlowTypes = []; + var potentialThisCollisions = []; + 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, + "boolean": 4, + "symbol": 8, + "undefined": 16384, + "object": 16, + "function": 32 + }); + var typeofNEFacts = ts.createMapFromTemplate({ + "string": 128, + "number": 256, + "boolean": 512, + "symbol": 1024, + "undefined": 131072, + "object": 2048, + "function": 4096 + }); + var typeofTypesByName = ts.createMapFromTemplate({ + "string": stringType, + "number": numberType, + "boolean": booleanType, + "symbol": esSymbolType, + "undefined": undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var _jsxElementPropertiesName; + var _hasComputedJsxElementPropertiesName = false; + var _jsxElementChildrenPropertyName; + var _hasComputedJsxElementChildrenPropertyName = false; + var jsxTypes = ts.createUnderscoreEscapedMap(); + var JsxNames = { + JSX: "JSX", + IntrinsicElements: "IntrinsicElements", + ElementClass: "ElementClass", + ElementAttributesPropertyNameContainer: "ElementAttributesProperty", + ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" + }; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + 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.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + initializeTypeChecker(); + return checker; + function getJsxNamespace() { + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; } } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function error(location, message, arg0, arg1, arg2) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + diagnostics.add(diagnostic); + } + function createSymbol(flags, name) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432, name)); + symbol.checkFlags = 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2) + result |= 107455; + if (flags & 1) + result |= 107454; + if (flags & 4) + result |= 0; + if (flags & 8) + result |= 900095; + if (flags & 16) + result |= 106927; + if (flags & 32) + result |= 899519; + if (flags & 64) + result |= 792968; + if (flags & 256) + result |= 899327; + if (flags & 128) + result |= 899967; + if (flags & 512) + result |= 106639; + if (flags & 8192) + result |= 99263; + if (flags & 32768) + result |= 41919; + if (flags & 65536) + result |= 74687; + if (flags & 262144) + result |= 530920; + if (flags & 524288) + result |= 793064; + if (flags & 2097152) + result |= 2097152; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations.slice(0); + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024) { + 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + ts.forEach(target.declarations, function (node) { + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + } + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + } else { - var tags = doc.tags; - if (tags) { - result.push.apply(result, ts.filter(tags, function (tag) { return tag.kind === kind; })); + if (!(targetSymbol.flags & 33554432)) { + targetSymbol = cloneSymbol(targetSymbol); + target.set(id, targetSymbol); + } + mergeSymbol(targetSymbol, sourceSymbol); + } + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); + if (!mainModule) { + return; + } + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920) { + mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function getObjectFlags(type) { + return type.flags & 32768 ? type.objectFlags : 0; + } + function isGlobalSourceFile(node) { + return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152) { + var target = resolveAlias(symbol); + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + } + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + ts.isInAmbientContext(declaration)) { + return true; + } + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + } + if (declaration.pos <= usage.pos) { + if (declaration.kind === 176) { + var errorBindingElement = ts.getAncestor(usage, 176); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); + } + else if (declaration.kind === 226) { + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + return true; + } + if (usage.parent.kind === 246) { + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 208: + case 214: + case 216: + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 149 && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.getModifierFlags(current.parent) & 32) { + if (declaration.kind === 151) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + }); + } + } + 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; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + loop: while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + 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 !== 275) { + useResult = result.flags & 262144 + ? lastLocation === location.type || + lastLocation.kind === 146 || + lastLocation.kind === 145 + : false; + } + if (meaning & 107455 && result.flags & 1) { + useResult = + lastLocation.kind === 146 || + (lastLocation === location.type && + result.valueDeclaration.kind === 146); + } + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 265: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + case 233: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 265 || ts.isAmbientModule(location)) { + if (result = moduleExports.get("default")) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 && + ts.getDeclarationOfKind(moduleExport, 246)) { + break; + } + } + if (result = lookup(moduleExports, name, meaning & 2623475)) { + break loop; + } + break; + case 232: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { + break loop; + } + break; + case 149: + case 148: + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 107455)) { + propertyWithInvalidInitializer = location; + } + } + } + break; + case 229: + case 199: + case 230: + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + result = undefined; + break; + } + if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 199 && meaning & 32) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 144: + grandparent = location.parent.parent; + if (ts.isClassLike(grandparent) || grandparent.kind === 230) { + 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; + } + } + break; + case 151: + case 150: + case 152: + case 153: + case 154: + case 228: + case 187: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 186: + if (meaning & 3 && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 147: + if (location.parent && location.parent.kind === 146) { + location = location.parent; + } + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (result && nameNotFoundMessage && noUnusedIdentifiers) { + result.isReferenced = true; + } + if (!result) { + result = lookup(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + if (errorLocation && + (meaning & 2 || + ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + if (result && isInExternalModule && (meaning & 107455) === 107455) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 236) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } } return result; } - } - function getFirstJSDocTag(node, kind) { - return node && ts.firstOrUndefined(getJSDocTags(node, kind)); - } - function getJSDocs(node) { - var cache = node.jsDocCache; - if (!cache) { - getJSDocsWorker(node); - node.jsDocCache = cache; + function diagnosticName(nameArg) { + return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } - return cache; - function getJSDocsWorker(node) { - var parent = node.parent; - var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && - parent.initializer === node && - parent.parent.parent.kind === 208; - var isVariableOfVariableDeclarationStatement = isVariableLike(node) && - parent.parent.kind === 208; - var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : - isVariableOfVariableDeclarationStatement ? parent.parent : - undefined; - if (variableStatementNode) { - getJSDocsWorker(variableStatementNode); + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 145 && decl.parent === container) { + return true; + } } - var isSourceOfAssignmentExpressionStatement = parent && parent.parent && - parent.kind === 194 && - parent.operatorToken.kind === 58 && - parent.parent.kind === 210; - if (isSourceOfAssignmentExpressionStatement) { - getJSDocsWorker(parent.parent); - } - var isModuleDeclaration = node.kind === 233 && - parent && parent.kind === 233; - var isPropertyAssignmentExpression = parent && parent.kind === 261; - if (isModuleDeclaration || isPropertyAssignmentExpression) { - getJSDocsWorker(parent); - } - if (node.kind === 146) { - cache = ts.concatenate(cache, getJSDocParameterTags(node)); - } - if (isVariableLike(node) && node.initializer) { - cache = ts.concatenate(cache, node.initializer.jsDoc); - } - cache = ts.concatenate(cache, node.jsDoc); - } - } - ts.getJSDocs = getJSDocs; - function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } - var func = param.parent; - var tags = getJSDocTags(func, 286); - if (!param.name) { - var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 286; }); - if (paramTags && 0 <= i && i < paramTags.length) { - return [paramTags[i]]; - } - } - else if (param.name.kind === 71) { - var name_1 = param.name.text; - return ts.filter(tags, function (tag) { return tag.kind === 286 && tag.parameterName.text === name_1; }); - } - else { - return undefined; - } - } - ts.getJSDocParameterTags = getJSDocParameterTags; - function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 288); - if (!tag && node.kind === 146) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } - } - return tag && tag.typeExpression && tag.typeExpression.type; - } - ts.getJSDocType = getJSDocType; - function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285); - } - ts.getJSDocAugmentsTag = getJSDocAugmentsTag; - function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 287); - } - ts.getJSDocReturnTag = getJSDocReturnTag; - function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 289); - } - ts.getJSDocTemplateTag = getJSDocTemplateTag; - function hasRestParameter(s) { - return isRestParameter(ts.lastOrUndefined(s.parameters)); - } - ts.hasRestParameter = hasRestParameter; - function hasDeclaredRestParameter(s) { - return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); - } - ts.hasDeclaredRestParameter = hasDeclaredRestParameter; - function isRestParameter(node) { - if (node && (node.flags & 65536)) { - if (node.type && node.type.kind === 280 || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 280; })) { - return true; - } - } - return isDeclaredRestParam(node); - } - ts.isRestParameter = isRestParameter; - function isDeclaredRestParam(node) { - 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) { - switch (parent.kind) { - case 194: - var binaryOperator = parent.operatorToken.kind; - return isAssignmentOperator(binaryOperator) && parent.left === node ? - binaryOperator === 58 ? 1 : 2 : - 0; - case 192: - case 193: - var unaryOperator = parent.operator; - return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; - case 215: - case 216: - return parent.initializer === node ? 1 : 0; - case 185: - case 177: - case 198: - node = parent; - break; - case 262: - if (parent.name !== node) { - return 0; - } - node = parent.parent; - break; - case 261: - if (parent.name === node) { - return 0; - } - node = parent.parent; - break; - default: - return 0; - } - parent = node.parent; - } - } - ts.getAssignmentTargetKind = getAssignmentTargetKind; - function isAssignmentTarget(node) { - return getAssignmentTargetKind(node) !== 0; - } - ts.isAssignmentTarget = isAssignmentTarget; - function isDeleteTarget(node) { - if (node.kind !== 179 && node.kind !== 180) { return false; } - node = node.parent; - while (node && node.kind === 185) { - node = node.parent; - } - return node && node.kind === 188; - } - ts.isDeleteTarget = isDeleteTarget; - function isNodeDescendantOf(node, ancestor) { - while (node) { - if (node === ancestor) - return true; - node = node.parent; - } - return false; - } - ts.isNodeDescendantOf = isNodeDescendantOf; - function isInAmbientContext(node) { - while (node) { - if (hasModifier(node, 2) || (node.kind === 265 && node.isDeclarationFile)) { - return true; - } - node = node.parent; - } - return false; - } - ts.isInAmbientContext = isInAmbientContext; - function isDeclarationName(name) { - switch (name.kind) { - case 71: - case 9: - case 8: - return isDeclaration(name.parent) && name.parent.name === name; - default: + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if ((errorLocation.kind === 71 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { return false; + } + var container = ts.getThisContainer(errorLocation, true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + if (location === container && !(ts.getModifierFlags(location) & 32)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; } - } - ts.isDeclarationName = isDeclarationName; - function getNameOfDeclaration(declaration) { - if (!declaration) { - return undefined; + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64, true)); + if (isError) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + } + return isError; } - if (declaration.kind === 194) { - var kind = getSpecialPropertyAssignmentKind(declaration); - var lhs = declaration.left; - switch (kind) { - case 0: - case 2: + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 71: + case 179: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 201: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: 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 && - isDeclaration(node.parent.parent); - } - ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; - function isIdentifierName(node) { - var parent = node.parent; - switch (parent.kind) { - case 149: - case 148: - case 151: - case 150: - case 153: - case 154: - case 264: - case 261: - case 179: - return parent.name === node; - case 143: - if (parent.right === node) { - while (parent.kind === 143) { - parent = parent.parent; - } - return parent.kind === 162; - } - return false; - case 176: - case 242: - return parent.propertyName === node; - case 246: - return true; - } - return false; - } - ts.isIdentifierName = isIdentifierName; - function isAliasSymbolDeclaration(node) { - return node.kind === 237 || - node.kind === 236 || - node.kind === 239 && !!node.name || - node.kind === 240 || - node.kind === 242 || - node.kind === 246 || - node.kind === 243 && exportAssignmentIsAlias(node); - } - ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; - function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); - } - ts.exportAssignmentIsAlias = exportAssignmentIsAlias; - function getClassExtendsHeritageClauseElement(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85); - return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; - } - ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; - function getClassImplementsHeritageClauseElements(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 108); - return heritageClause ? heritageClause.types : undefined; - } - ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; - function getInterfaceBaseTypeNodes(node) { - var heritageClause = getHeritageClause(node.heritageClauses, 85); - return heritageClause ? heritageClause.types : undefined; - } - ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; - function getHeritageClause(clauses, kind) { - if (clauses) { - for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { - var clause = clauses_1[_i]; - if (clause.token === kind) { - return clause; - } - } - } - return undefined; - } - ts.getHeritageClause = getHeritageClause; - function tryResolveScriptReference(host, sourceFile, reference) { - if (!host.getCompilerOptions().noResolve) { - var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); - return host.getSourceFile(referenceFileName); - } - } - ts.tryResolveScriptReference = tryResolveScriptReference; - function getAncestor(node, kind) { - while (node) { - if (node.kind === kind) { - return node; - } - node = node.parent; - } - return undefined; - } - ts.getAncestor = getAncestor; - function getFileReferenceFromReferencePath(comment, commentRange) { - var simpleReferenceRegEx = /^\/\/\/\s*/gim; - if (simpleReferenceRegEx.test(comment)) { - if (isNoDefaultLibRegEx.test(comment)) { - return { isNoDefaultLib: true }; - } - else { - var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); - var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); - var match = refMatchResult || refLibResult; - if (match) { - var pos = commentRange.pos + match[1].length + match[2].length; - return { - fileReference: { - pos: pos, - end: pos + match[3].length, - fileName: match[3] - }, - isNoDefaultLib: false, - isTypeReferenceDirective: !!refLibResult - }; - } - return { - diagnosticMessage: ts.Diagnostics.Invalid_reference_directive_syntax, - isNoDefaultLib: false - }; - } - } - return undefined; - } - ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; - function isKeyword(token) { - return 72 <= token && token <= 142; - } - ts.isKeyword = isKeyword; - function isTrivia(token) { - 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: - case 186: - case 151: - if (node.asteriskToken) { - flags |= 1; - } - case 187: - if (hasModifier(node, 256)) { - flags |= 2; - } - break; - } - if (!node.body) { - flags |= 4; - } - return flags; - } - ts.getFunctionFlags = getFunctionFlags; - function isAsyncFunction(node) { - switch (node.kind) { - case 228: - case 186: - case 187: - case 151: - return node.body !== undefined - && node.asteriskToken === undefined - && hasModifier(node, 256); - } - return false; - } - ts.isAsyncFunction = isAsyncFunction; - function isNumericLiteral(node) { - return node.kind === 8; - } - ts.isNumericLiteral = isNumericLiteral; - function isStringOrNumericLiteral(node) { - var kind = node.kind; - return kind === 9 - || kind === 8; - } - ts.isStringOrNumericLiteral = isStringOrNumericLiteral; - function hasDynamicName(declaration) { - var name = getNameOfDeclaration(declaration); - return name && isDynamicName(name); - } - ts.hasDynamicName = hasDynamicName; - function isDynamicName(name) { - return name.kind === 144 && - !isStringOrNumericLiteral(name.expression) && - !isWellKnownSymbolSyntactically(name.expression); - } - ts.isDynamicName = isDynamicName; - function isWellKnownSymbolSyntactically(node) { - return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); - } - ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; - function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 || name.kind === 9 || name.kind === 8 || name.kind === 146) { - return name.text; - } - if (name.kind === 144) { - var nameExpression = name.expression; - if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.text; - return getPropertyNameForKnownSymbolName(rightHandSideName); - } - else if (nameExpression.kind === 9 || nameExpression.kind === 8) { - return nameExpression.text; - } - } - return undefined; - } - ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; - function getPropertyNameForKnownSymbolName(symbolName) { - return "__@" + symbolName; - } - ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; - function isESSymbolIdentifier(node) { - return node.kind === 71 && node.text === "Symbol"; - } - ts.isESSymbolIdentifier = isESSymbolIdentifier; - function isPushOrUnshiftIdentifier(node) { - return node.text === "push" || node.text === "unshift"; - } - ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; - function isModifierKind(token) { - switch (token) { - case 117: - case 120: - case 76: - case 124: - case 79: - case 84: - case 114: - case 112: - case 113: - case 131: - case 115: - return true; - } - return false; - } - ts.isModifierKind = isModifierKind; - function isParameterDeclaration(node) { - var root = getRootDeclaration(node); - return root.kind === 146; - } - ts.isParameterDeclaration = isParameterDeclaration; - function getRootDeclaration(node) { - while (node.kind === 176) { - node = node.parent.parent; - } - return node; - } - ts.getRootDeclaration = getRootDeclaration; - function nodeStartsNewLexicalEnvironment(node) { - var kind = node.kind; - return kind === 152 - || kind === 186 - || kind === 228 - || kind === 187 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 233 - || kind === 265; - } - ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; - function nodeIsSynthesized(node) { - return ts.positionIsSynthesized(node.pos) - || ts.positionIsSynthesized(node.end); - } - ts.nodeIsSynthesized = nodeIsSynthesized; - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile)); - } - return getOriginalSourceFile(sourceFileOrBundle); - } - ts.getOriginalSourceFileOrBundle = getOriginalSourceFileOrBundle; - function getOriginalSourceFile(sourceFile) { - return ts.getParseTreeNode(sourceFile, isSourceFile) || sourceFile; - } - function getOriginalSourceFiles(sourceFiles) { - return ts.sameMap(sourceFiles, getOriginalSourceFile); - } - ts.getOriginalSourceFiles = getOriginalSourceFiles; - function getOriginalNodeId(node) { - node = ts.getOriginalNode(node); - 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; - return getOperatorAssociativity(expression.kind, operator, hasArguments); - } - ts.getExpressionAssociativity = getExpressionAssociativity; - function getOperatorAssociativity(kind, operator, hasArguments) { - switch (kind) { - case 182: - return hasArguments ? 0 : 1; - case 192: - case 189: - case 190: - case 188: - case 191: - case 195: - case 197: - return 1; - case 194: - switch (operator) { - case 40: - case 58: - case 59: - case 60: - case 62: - case 61: - case 63: - case 64: - case 65: - case 66: - case 67: - case 68: - case 70: - case 69: - return 1; - } - } - return 0; - } - ts.getOperatorAssociativity = getOperatorAssociativity; - function getExpressionPrecedence(expression) { - var operator = getOperator(expression); - var hasArguments = expression.kind === 182 && expression.arguments !== undefined; - return getOperatorPrecedence(expression.kind, operator, hasArguments); - } - ts.getExpressionPrecedence = getExpressionPrecedence; - function getOperator(expression) { - if (expression.kind === 194) { - return expression.operatorToken.kind; - } - else if (expression.kind === 192 || expression.kind === 193) { - return expression.operator; - } - else { - return expression.kind; - } - } - ts.getOperator = getOperator; - function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { - switch (nodeKind) { - case 99: - case 97: - case 71: - case 95: - case 101: - case 86: - case 8: - case 9: - case 177: - case 178: - case 186: - case 187: - case 199: - case 249: - case 250: - case 12: - case 13: - case 196: - case 185: - case 200: - return 19; - case 183: - case 179: - case 180: - return 18; - case 182: - return hasArguments ? 18 : 17; - case 181: - return 17; - case 193: - return 16; - case 192: - case 189: - case 190: - case 188: - case 191: - return 15; - case 194: - switch (operatorKind) { - case 51: - case 52: - return 15; - case 40: - case 39: - case 41: - case 42: - return 14; - case 37: - case 38: - return 13; - case 45: - case 46: - case 47: - return 12; - case 27: - case 30: - case 29: - case 31: - case 92: - case 93: - return 11; - case 32: - case 34: - case 33: - case 35: - return 10; - case 48: - return 9; - case 50: - return 8; - case 49: - return 7; - case 53: - return 6; - case 54: - return 5; - case 58: - case 59: - case 60: - case 62: - case 61: - case 63: - case 64: - case 65: - case 66: - case 67: - case 68: - case 70: - case 69: - return 3; - case 26: - return 0; - default: - return -1; - } - case 195: - return 4; - case 197: - return 2; - case 198: - return 1; - case 297: - return 0; - default: - return -1; - } - } - ts.getOperatorPrecedence = getOperatorPrecedence; - function createDiagnosticCollection() { - var nonFileDiagnostics = []; - var fileDiagnostics = ts.createMap(); - var diagnosticsModified = false; - var modificationCount = 0; - return { - add: add, - getGlobalDiagnostics: getGlobalDiagnostics, - getDiagnostics: getDiagnostics, - getModificationCount: getModificationCount, - reattachFileDiagnostics: reattachFileDiagnostics - }; - function getModificationCount() { - return modificationCount; - } - function reattachFileDiagnostics(newFile) { - ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); - } - function add(diagnostic) { - var diagnostics; - if (diagnostic.file) { - diagnostics = fileDiagnostics.get(diagnostic.file.fileName); - if (!diagnostics) { - diagnostics = []; - fileDiagnostics.set(diagnostic.file.fileName, diagnostics); - } - } - else { - diagnostics = nonFileDiagnostics; - } - diagnostics.push(diagnostic); - diagnosticsModified = true; - modificationCount++; - } - function getGlobalDiagnostics() { - sortAndDeduplicate(); - return nonFileDiagnostics; - } - function getDiagnostics(fileName) { - sortAndDeduplicate(); - if (fileName) { - return fileDiagnostics.get(fileName) || []; - } - var allDiagnostics = []; - function pushDiagnostic(d) { - allDiagnostics.push(d); - } - ts.forEach(nonFileDiagnostics, pushDiagnostic); - fileDiagnostics.forEach(function (diagnostics) { - ts.forEach(diagnostics, pushDiagnostic); - }); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); - } - function sortAndDeduplicate() { - if (!diagnosticsModified) { - return; - } - diagnosticsModified = false; - nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); - fileDiagnostics.forEach(function (diagnostics, key) { - fileDiagnostics.set(key, ts.sortAndDeduplicateDiagnostics(diagnostics)); - }); - } - } - ts.createDiagnosticCollection = createDiagnosticCollection; - var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - var escapedCharsMap = ts.createMapFromTemplate({ - "\0": "\\0", - "\t": "\\t", - "\v": "\\v", - "\f": "\\f", - "\b": "\\b", - "\r": "\\r", - "\n": "\\n", - "\\": "\\\\", - "\"": "\\\"", - "\u2028": "\\u2028", - "\u2029": "\\u2029", - "\u0085": "\\u0085" - }); - function escapeString(s) { - return s.replace(escapedCharsRegExp, getReplacement); - } - ts.escapeString = escapeString; - function getReplacement(c) { - return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); - } - function isIntrinsicJsxName(name) { - var ch = name.substr(0, 1); - return ch.toLowerCase() === ch; - } - ts.isIntrinsicJsxName = isIntrinsicJsxName; - function get16BitUnicodeEscapeSequence(charCode) { - var hexCharCode = charCode.toString(16).toUpperCase(); - var paddedHexCode = ("0000" + hexCharCode).slice(-4); - return "\\u" + paddedHexCode; - } - var nonAsciiCharacters = /[^\u0000-\u007F]/g; - function escapeNonAsciiString(s) { - s = escapeString(s); - return nonAsciiCharacters.test(s) ? - s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : - s; - } - ts.escapeNonAsciiString = escapeNonAsciiString; - var indentStrings = ["", " "]; - function getIndentString(level) { - if (indentStrings[level] === undefined) { - indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; - } - return indentStrings[level]; - } - ts.getIndentString = getIndentString; - function getIndentSize() { - return indentStrings[1].length; - } - ts.getIndentSize = getIndentSize; - function createTextWriter(newLine) { - var output; - var indent; - var lineStart; - var lineCount; - var linePos; - function write(s) { - if (s && s.length) { - if (lineStart) { - output += getIndentString(indent); - lineStart = false; - } - output += s; - } - } - function reset() { - output = ""; - indent = 0; - lineStart = true; - lineCount = 0; - linePos = 0; - } - function rawWrite(s) { - if (s !== undefined) { - if (lineStart) { - lineStart = false; - } - output += s; - } - } - function writeLiteral(s) { - if (s && s.length) { - write(s); - var lineStartsOfS = ts.computeLineStarts(s); - if (lineStartsOfS.length > 1) { - lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); - } - } - } - function writeLine() { - if (!lineStart) { - output += newLine; - lineCount++; - linePos = output.length; - lineStart = true; - } - } - function writeTextOfNode(text, node) { - write(getTextOfNodeFromSourceText(text, node)); - } - reset(); - return { - write: write, - rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, - writeLiteral: writeLiteral, - writeLine: writeLine, - increaseIndent: function () { indent++; }, - decreaseIndent: function () { indent--; }, - getIndent: function () { return indent; }, - getTextPos: function () { return output.length; }, - getLine: function () { return lineCount + 1; }, - getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, - getText: function () { return output; }, - isAtStartOfLine: function () { return lineStart; }, - reset: reset - }; - } - ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); - } - ts.getResolvedExternalModuleName = getResolvedExternalModuleName; - function getExternalModuleNameFromDeclaration(host, resolver, declaration) { - var file = resolver.getExternalModuleFileFromDeclaration(declaration); - if (!file || file.isDeclarationFile) { - return undefined; - } - return getResolvedExternalModuleName(host, file); - } - ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; - function getExternalModuleNameFromPath(host, fileName) { - var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); - var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); - var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); - return ts.removeFileExtension(relativePath); - } - ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { - var compilerOptions = host.getCompilerOptions(); - var emitOutputFilePathWithoutExtension; - if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); - } - else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); - } - return emitOutputFilePathWithoutExtension + extension; - } - ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { - var options = host.getCompilerOptions(); - var outputDir = options.declarationDir || options.outDir; - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } - ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getSourceFilesToEmit(host, targetSourceFile) { - var options = host.getCompilerOptions(); - var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; - if (options.outFile || options.out) { - var moduleKind = ts.getEmitModuleKind(options); - var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; - return ts.filter(host.getSourceFiles(), function (sourceFile) { - return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); - }); - } - else { - var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; - return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); - } - } - ts.getSourceFilesToEmit = getSourceFilesToEmit; - function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); - } - ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { - var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); - var options = host.getCompilerOptions(); - if (options.outFile || options.out) { - if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); - } - } - else { - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); - } - } - } - ts.forEachEmittedFile = forEachEmittedFile; - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } - function getOutputExtension(sourceFile, options) { - if (options.jsx === 1) { - if (isSourceFileJavaScript(sourceFile)) { - if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { - return ".jsx"; - } - } - else if (sourceFile.languageVariant === 1) { - return ".jsx"; - } - } - return ".js"; - } - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; - sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; - return ts.combinePaths(newDirPath, sourceFilePath); - } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; - function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { - host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); - }, sourceFiles); - } - ts.writeFile = writeFile; - function getLineOfLocalPosition(currentSourceFile, pos) { - return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; - } - ts.getLineOfLocalPosition = getLineOfLocalPosition; - function getLineOfLocalPositionFromLineMap(lineMap, pos) { - return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; - } - ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; - function getFirstConstructorWithBody(node) { - return ts.forEach(node.members, function (member) { - if (member.kind === 152 && nodeIsPresent(member.body)) { - return member; - } - }); - } - ts.getFirstConstructorWithBody = getFirstConstructorWithBody; - function getSetAccessorTypeAnnotationNode(accessor) { - if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); - return accessor.parameters[hasThis ? 1 : 0].type; - } - } - ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; - function getThisParameter(signature) { - if (signature.parameters.length) { - var thisParameter = signature.parameters[0]; - if (parameterIsThisKeyword(thisParameter)) { - return thisParameter; - } - } - } - ts.getThisParameter = getThisParameter; - function parameterIsThisKeyword(parameter) { - return isThisIdentifier(parameter.name); - } - ts.parameterIsThisKeyword = parameterIsThisKeyword; - function isThisIdentifier(node) { - return node && node.kind === 71 && identifierIsThisKeyword(node); - } - ts.isThisIdentifier = isThisIdentifier; - function identifierIsThisKeyword(id) { - return id.originalKeywordKind === 99; - } - ts.identifierIsThisKeyword = identifierIsThisKeyword; - function getAllAccessorDeclarations(declarations, accessor) { - var firstAccessor; - var secondAccessor; - var getAccessor; - var setAccessor; - if (hasDynamicName(accessor)) { - firstAccessor = accessor; - if (accessor.kind === 153) { - getAccessor = accessor; - } - else if (accessor.kind === 154) { - setAccessor = accessor; - } - else { - ts.Debug.fail("Accessor has wrong kind"); - } - } - else { - ts.forEach(declarations, function (member) { - if ((member.kind === 153 || member.kind === 154) - && hasModifier(member, 32) === hasModifier(accessor, 32)) { - var memberName = getPropertyNameForPropertyNameNode(member.name); - var accessorName = getPropertyNameForPropertyNameNode(accessor.name); - if (memberName === accessorName) { - if (!firstAccessor) { - firstAccessor = member; - } - else if (!secondAccessor) { - secondAccessor = member; - } - if (member.kind === 153 && !getAccessor) { - getAccessor = member; - } - if (member.kind === 154 && !setAccessor) { - setAccessor = member; + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; } } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; } - }); - } - return { - firstAccessor: firstAccessor, - secondAccessor: secondAccessor, - getAccessor: getAccessor, - setAccessor: setAccessor - }; - } - ts.getAllAccessorDeclarations = getAllAccessorDeclarations; - function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { - emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); - } - ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; - function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { - if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && - getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { - writer.writeLine(); - } - } - ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; - function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { - if (pos !== commentPos && - getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { - writer.writeLine(); - } - } - ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; - function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { - if (comments && comments.length > 0) { - if (leadingSeparator) { - writer.write(" "); } - var emitInterveningSeparator = false; - for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { - var comment = comments_1[_i]; - if (emitInterveningSeparator) { - writer.write(" "); - emitInterveningSeparator = false; + return false; + } + 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, ts.unescapeLeadingUnderscores(name)); + return true; } - writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); + 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, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (107455 & ~1024 & ~793064)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (793064 & ~1024 & ~107455)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); + 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(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 32) { + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 256) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + } + } + function isSameScopeDescendentOf(initial, parent, stopAt) { + return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + if (ts.isAliasSymbolDeclaration(node)) { + if (node.kind === 237) { + return node; + } + return ts.findAncestor(node, ts.isImportDeclaration); + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 248) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; } else { - emitInterveningSeparator = true; + var exportValue = moduleSymbol.exports.get("export="); + exportDefaultSymbol = exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") + : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + } + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (793064 | 1920)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } } - if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + } + return symbol; + } } } - } - ts.emitComments = emitComments; - function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { - var leadingComments; - var currentDetachedCommentInfo; - if (removeComments) { - if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : + resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); + } + function getTargetOfExportAssignment(node, dontResolveAlias) { + return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + switch (node.kind) { + case 237: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 239: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 240: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 242: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 246: + return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); + case 243: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 236: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); } } - else { - leadingComments = ts.getLeadingCommentRanges(text, node.pos); + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 107455 | 793064 | 1920; } + return symbol && (symbol.flags & (2097152 | excludes)) === 2097152; } - if (leadingComments) { - var detachedComments = []; - var lastComment = void 0; - for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { - var comment = leadingComments_1[_i]; - if (lastComment) { - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); - var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); - if (commentLine >= lastCommentLine + 2) { + function resolveSymbol(symbol, dontResolveAlias) { + var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); + return shouldResolve ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + if (node.kind === 243) { + checkExpressionCached(node.expression); + } + else if (node.kind === 246) { + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + checkExpressionCached(node.moduleReference); + } + } + } + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (entityName.kind === 71 || entityName.parent.kind === 143) { + return resolveEntityName(entityName, 1920, false, dontResolveAlias); + } + else { + ts.Debug.assert(entityName.parent.kind === 237); + return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol) { + return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + } + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var symbol; + if (name.kind === 71) { + var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + if (!symbol) { + return undefined; + } + } + else if (name.kind === 143 || name.kind === 179) { + var left = void 0; + if (name.kind === 143) { + left = name.left; + } + else if (name.kind === 179 && + (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { + left = name.expression; + } + else { + return undefined; + } + var right = name.kind === 143 ? name.right : name.name; + var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else if (name.kind === 185) { + return ts.isEntityNameExpression(name.expression) ? + resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : + undefined; + } + else { + ts.Debug.fail("Unknown entity name kind."); + } + 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) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReferenceExpression.kind !== 9 && moduleReferenceExpression.kind !== 13) { + return; + } + var moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === 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(moduleReference, true); + if (ambientModule) { + return ambientModule; + } + var isRelative = ts.isExternalModuleNameRelative(moduleReference); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (noImplicitAny && moduleNotFoundError) { + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return undefined; + } + if (moduleNotFoundError) { + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + } + function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { + 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)); + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=") !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (!symbol) { + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); + } + } + return symbol; + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + function extendExportSymbols(target, source, lookupTable, exportNode) { + source && source.forEach(function (sourceSymbol, id) { + if (id === "default") + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + function visit(symbol) { + if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { + return; + } + visitedSymbols.push(symbol); + var symbols = ts.cloneMap(symbol.exports); + var exportStars = symbol.exports.get("__export"); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent); + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return symbol && (symbol.flags & 1048576) !== 0 + ? getMergedSymbol(symbol.exportSymbol) + : symbol; + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 107455 || symbol.flags & 2097152 && resolveAlias(symbol).flags & 107455); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 152 && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(32768); + type.objectFlags = objectFlags; + type.symbol = symbol; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); + } + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 && + name.charCodeAt(1) === 95 && + name.charCodeAt(2) !== 95 && + name.charCodeAt(2) !== 64; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + if (symbolIsValue(symbol)) { + result.push(symbol); + } + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + if (location.locals && !isGlobalSourceFile(location)) { + if (result = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 265: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + case 233: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + return rightMeaning === 107455 ? 107455 : 1920; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; + function canQualifySymbol(symbolFromSymbolTable, meaning) { + if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { + return true; + } + var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + return !!accessibleParent; + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + } + function trySymbolTable(symbols) { + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; + } + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { + if (!useOnlyExternalAliasing || + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; + } + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + } + }); + } + } + if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + if (!symbolFromSymbolTable) { + return false; + } + if (symbolFromSymbolTable === symbol) { + return true; + } + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 149: + case 151: + case 153: + case 154: + continue; + default: + return false; + } + } + return true; + } + return false; + } + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { + var initialSymbol = symbol; + var meaningToLook = meaning; + while (symbol) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); + if (accessibleSymbolChain) { + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (!hasAccessibleDeclarations) { + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, + }; + } + return hasAccessibleDeclarations; + } + meaningToLook = getQualifiedLeftMeaning(meaning); + symbol = getParentOfSymbol(symbol); + } + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + return { + accessibility: 2, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + return { + accessibility: 1, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 }; + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + return undefined; + } + return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !(ts.getModifierFlags(anyImportSyntax) & 1) && + isDeclarationVisible(anyImportSyntax.parent)) { + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; + } + } + return true; + } + return false; + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + var meaning; + if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning = 107455 | 1048576; + } + else if (entityName.kind === 143 || entityName.kind === 179 || + entityName.parent.kind === 237) { + meaning = 1920; + } + else { + meaning = 793064; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined); + return (symbol && hasVisibleDeclarations(symbol, true)) || { + accessibility: 1, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function writeKeyword(writer, kind) { + writer.writeKeyword(ts.tokenToString(kind)); + } + function writePunctuation(writer, kind) { + writer.writePunctuation(ts.tokenToString(kind)); + } + function writeSpace(writer) { + writer.writeSpace(" "); + } + function symbolToString(symbol, enclosingDeclaration, meaning) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); + }); + } + function signatureToString(signature, enclosingDeclaration, flags, kind) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); + }); + } + function typeToString(type, enclosingDeclaration, flags) { + 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); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3, typeNode, sourceFile, writer); + var result = writer.getText(); + var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; + if (maxLength && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 8) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 256) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 4096) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 64) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + 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) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + } + }; + function createNodeBuilderContext(enclosingDeclaration, flags) { + return { + enclosingDeclaration: enclosingDeclaration, + flags: flags, + encounteredError: false, + symbolStack: undefined + }; + } + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + if (!type) { + context.encounteredError = true; + return undefined; + } + if (type.flags & 1) { + return ts.createKeywordTypeNode(119); + } + if (type.flags & 2) { + return ts.createKeywordTypeNode(136); + } + if (type.flags & 4) { + return ts.createKeywordTypeNode(133); + } + if (type.flags & 8) { + return ts.createKeywordTypeNode(122); + } + 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.setEmitFlags(ts.createLiteral(type.value), 16777216)); + } + if (type.flags & (64)) { + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 128) { + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 1024) { + return ts.createKeywordTypeNode(105); + } + if (type.flags & 2048) { + return ts.createKeywordTypeNode(139); + } + if (type.flags & 4096) { + return ts.createKeywordTypeNode(95); + } + if (type.flags & 8192) { + return ts.createKeywordTypeNode(130); + } + if (type.flags & 512) { + return ts.createKeywordTypeNode(137); + } + if (type.flags & 16777216) { + return ts.createKeywordTypeNode(134); + } + if (type.flags & 16384 && type.isThisType) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + context.encounteredError = true; + } + } + return ts.createThis(); + } + var objectFlags = getObjectFlags(type); + if (objectFlags & 4) { + ts.Debug.assert(!!(type.flags & 32768)); + return typeReferenceToTypeNode(type); + } + if (type.flags & 16384 || objectFlags & 3) { + var name = symbolToName(type.symbol, context, 793064, false); + return ts.createTypeReferenceNode(name, undefined); + } + 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); + } + 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)) { + context.encounteredError = true; + } + return undefined; + } + } + 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, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 524288) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 32768)); + var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; + var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; + 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; + if (symbol) { + if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || + symbol.flags & (384 | 512) || + shouldWriteTypeOfFunctionSymbol()) { + return createTypeQueryNodeFromSymbol(symbol, 107455); + } + else if (ts.contains(context.symbolStack, symbol)) { + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + var entityName = symbolToName(typeAlias, context, 793064, false); + return ts.createTypeReferenceNode(entityName, undefined); + } + else { + return ts.createKeywordTypeNode(119); + } + } + else { + if (!context.symbolStack) { + context.symbolStack = []; + } + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } + } + else { + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 || declaration.parent.kind === 234; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return ts.contains(context.symbolStack, symbol); + } + } + } + function createTypeNodeFromObjectType(type) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + return createMappedTypeNodeFromType(type); + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1); + } + 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.escapedName) ? symbolToName(symbol, context, 793064, false) : ts.createIdentifier(""); + return entityName; + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var qualifiedName = void 0; + if (outerTypeParameters) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + 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 { + qualifiedName = ts.createQualifiedName(namePart, undefined); + } + } + } + } + var entityName = undefined; + var nameIdentifier = symbolToTypeReferenceName(type.symbol); + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); + entityName = qualifiedName; + } + else { + entityName = nameIdentifier; + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.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, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); + } + if (resolvedType.stringIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + var propertyType = getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455, true); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 ? 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, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + typeElements.push(methodDeclaration); + } + } + else { + 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 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 ? 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.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, context); + } + 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, context) { + var name = symbolToName(type.symbol, context, 793064, true); + var constraint = getConstraintFromTypeParameter(type); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function symbolToParameterDeclaration(parameterSymbol, context) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146); + if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { + return ts.createParameter(undefined, undefined, parameterSymbol.isRestParameter ? ts.createToken(24) : undefined, "args", undefined, typeToTypeNodeHelper(anyArrayType, context), undefined); + } + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; + var name = parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216) : + cloneBindingName(parameterDeclaration.name) : + ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55) : undefined; + var parameterType = getTypeOfSymbol(parameterSymbol); + 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, context, meaning, expectsIdentifier) { + var chain; + var isTypeParameter = symbol.flags & 262144; + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, true); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(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 typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { + var parentSymbol = chain[index - 1]; + var typeParameters = void 0; + if (ts.getCheckFlags(symbol) & 1) { + typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); + } + else { + var targetSymbol = getTargetSymbol(parentSymbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + } + } + typeParameterNodes = mapToTypeNodes(typeParameters, context); + } + 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) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var parentSymbol; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); + if (parentChain) { + parentSymbol = parent; + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + return [symbol]; + } + } + } + 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 ts.unescapeLeadingUnderscores(symbol.escapedName); + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + }); + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144)) { + if (t.flags & (128 | 256)) { + 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); + } + } + if (flags & 4096) + result.push(nullType); + if (flags & 2048) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8) { + return "private"; + } + if (flags === 16) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); + if (node.kind === 231) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 234 && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function literalTypeToString(type) { + return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; + } + function getNameOfSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var declaration = symbol.declarations[0]; + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); + } + if (declaration.parent && declaration.parent.kind === 226) { + return ts.declarationNameToString(declaration.parent.name); + } + switch (declaration.kind) { + case 199: + return "(Anonymous class)"; + case 186: + case 187: + return "(Anonymous function)"; + } + } + return ts.unescapeLeadingUnderscores(symbol.escapedName); + } + function getSymbolDisplayBuilder() { + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); + } + function appendPropertyOrElementAccessForSymbol(symbol, writer) { + var symbolName = getNameOfSymbol(symbol); + var firstChar = symbolName.charCodeAt(0); + var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); + if (needsElementAccess) { + writePunctuation(writer, 21); + if (ts.isSingleOrDoubleQuote(firstChar)) { + writer.writeStringLiteral(symbolName); + } + else { + writer.writeSymbol(symbolName, symbol); + } + writePunctuation(writer, 22); + } + else { + writePunctuation(writer, 23); + writer.writeSymbol(symbolName, symbol); + } + } + function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { + var parentSymbol; + function appendParentTypeArgumentsAndSymbolName(symbol) { + if (parentSymbol) { + if (flags & 1) { + if (ts.getCheckFlags(symbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); + } + else { + buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); + } + } + appendPropertyOrElementAccessForSymbol(symbol, writer); + } + else { + appendSymbolNameOnly(symbol, writer); + } + parentSymbol = symbol; + } + writer.trackSymbol(symbol, enclosingDeclaration, meaning); + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); + } + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + } + } + else if (endOfChain || + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(symbol.flags & (2048 | 4096))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + var isTypeParameter = symbol.flags & 262144; + var typeFormatFlag = 256 & typeFlags; + if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { + walkSymbol(symbol, meaning, true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { + var globalFlagsToPass = globalFlags & (32 | 16384); + var inObjectTypeLiteral = false; + return writeType(type, globalFlags); + function writeType(type, flags) { + var nextFlags = flags & ~1024; + if (type.flags & 16793231) { + writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } + else if (type.flags & 16384 && type.isThisType) { + if (inObjectTypeLiteral) { + writer.reportInaccessibleThisError(); + } + writer.writeKeyword("this"); + } + else if (getObjectFlags(type) & 4) { + writeTypeReference(type, nextFlags); + } + 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 & (272 | 16384)) { + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); + } + else if (!(flags & 1024) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); + } + else if (type.flags & 196608) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (getObjectFlags(type) & (16 | 32)) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96) { + writer.writeStringLiteral(literalTypeToString(type)); + } + else if (type.flags & 262144) { + if (flags & 128) { + writePunctuation(writer, 19); + } + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 128); + if (flags & 128) { + writePunctuation(writer, 20); + } + } + else if (type.flags & 524288) { + writeType(type.objectType, 128); + writePunctuation(writer, 21); + writeType(type.indexType, 0); + writePunctuation(writer, 22); + } + else { + writePunctuation(writer, 17); + writeSpace(writer); + writePunctuation(writer, 24); + writeSpace(writer); + writePunctuation(writer, 18); + } + } + function writeTypeList(types, delimiter) { + for (var i = 0; i < types.length; i++) { + if (i > 0) { + if (delimiter !== 26) { + writeSpace(writer); + } + writePunctuation(writer, delimiter); + writeSpace(writer); + } + writeType(types[i], delimiter === 26 ? 0 : 128); + } + } + function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { + if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); + } + if (pos < end) { + writePunctuation(writer, 27); + writeType(typeArguments[pos], 512); + pos++; + while (pos < end) { + writePunctuation(writer, 26); + writeSpace(writer); + writeType(typeArguments[pos], 0); + pos++; + } + writePunctuation(writer, 29); + } + } + function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType && !(flags & 1)) { + writeType(typeArguments[0], 128 | 32768); + writePunctuation(writer, 21); + writePunctuation(writer, 22); + } + else if (type.target.objectFlags & 8) { + writePunctuation(writer, 21); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); + writePunctuation(writer, 22); + } + else if (flags & 16384 && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 199) { + writeAnonymousType(getDeclaredTypeOfClassOrInterface(type.symbol), flags); + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_3 = outerTypeParameters.length; + while (i < length_3) { + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { + writeSymbolTypeReference(parent, typeArguments, start, i, flags); + writePunctuation(writer, 23); + } + } + } + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); + } + } + function writeUnionOrIntersectionType(type, flags) { + if (flags & 128) { + writePunctuation(writer, 19); + } + if (type.flags & 65536) { + writeTypeList(formatUnionTypes(type.types), 49); + } + else { + writeTypeList(type.types, 48); + } + if (flags & 128) { + writePunctuation(writer, 20); + } + } + function writeAnonymousType(type, flags) { + var symbol = type.symbol; + if (symbol) { + if (symbol.flags & 32 && + !getBaseTypeVariableOfClass(symbol) && + !(symbol.valueDeclaration.kind === 199 && flags & 16384) || + symbol.flags & (384 | 512)) { + writeTypeOfSymbol(type, flags); + } + else if (shouldWriteTypeOfFunctionSymbol()) { + writeTypeOfSymbol(type, flags); + } + else if (ts.contains(symbolStack, symbol)) { + var typeAlias = getTypeAliasForTypeLiteral(type); + if (typeAlias) { + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); + } + else { + writeKeyword(writer, 119); + } + } + else { + if (!symbolStack) { + symbolStack = []; + } + var isConstructorObject = type.flags & 32768 && + getObjectFlags(type) & 16 && + type.symbol && type.symbol.flags & 32; + if (isConstructorObject) { + writeLiteralType(type, flags); + } + else { + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } + } + } + else { + writeLiteralType(type, flags); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 || declaration.parent.kind === 234; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + return !!(flags & 4) || + (ts.contains(symbolStack, symbol)); + } + } + } + function writeTypeOfSymbol(type, typeFormatFlags) { + if (typeFormatFlags & 32768) { + writePunctuation(writer, 19); + } + writeKeyword(writer, 103); + writeSpace(writer); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); + if (typeFormatFlags & 32768) { + writePunctuation(writer, 20); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 131); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 16777216) { + writePunctuation(writer, 55); + } + } + function shouldAddParenthesisAroundFunctionType(callSignature, flags) { + if (flags & 128) { + return true; + } + else if (flags & 512) { + var typeParameters = callSignature.target && (flags & 64) ? + callSignature.target.typeParameters : callSignature.typeParameters; + return typeParameters && typeParameters.length !== 0; + } + return false; + } + function writeLiteralType(type, flags) { + if (type.objectFlags & 32) { + if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { + writeMappedType(type); + return; + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + writePunctuation(writer, 17); + writePunctuation(writer, 18); + return; + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); + if (parenthesizeSignature) { + writePunctuation(writer, 19); + } + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); + if (parenthesizeSignature) { + writePunctuation(writer, 20); + } + return; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + if (flags & 128) { + writePunctuation(writer, 19); + } + writeKeyword(writer, 94); + writeSpace(writer); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); + if (flags & 128) { + writePunctuation(writer, 20); + } + return; + } + } + var saveInObjectTypeLiteral = inObjectTypeLiteral; + inObjectTypeLiteral = true; + writePunctuation(writer, 17); + writer.writeLine(); + writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 18); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); + buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + if (globalFlags & 16384) { + if (p.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { + writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + } + } + var t = getTypeOfSymbol(p); + if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { + var signatures = getSignaturesOfType(t, 0); + for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { + var signature = signatures_2[_f]; + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + else { + writePropertyWithModifiers(p); + writePunctuation(writer, 56); + writeSpace(writer); + writeType(t, globalFlags & 16384); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + } + function writeMappedType(type) { + writePunctuation(writer, 17); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 131); + writeSpace(writer); + } + writePunctuation(writer, 21); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 92); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0); + writePunctuation(writer, 22); + if (type.declaration.questionToken) { + writePunctuation(writer, 55); + } + writePunctuation(writer, 56); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0); + writePunctuation(writer, 25); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 18); + } + } + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); + } + } + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { + appendSymbolNameOnly(tp.symbol, writer); + var constraint = getConstraintOfTypeParameter(tp); + if (constraint) { + writeSpace(writer); + writeKeyword(writer, 85); + writeSpace(writer); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); + } + var defaultType = getDefaultFromTypeParameter(tp); + if (defaultType) { + writeSpace(writer); + writePunctuation(writer, 58); + writeSpace(writer); + buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { + writePunctuation(writer, 24); + } + if (parameterNode && ts.isBindingPattern(parameterNode.name)) { + buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + appendSymbolNameOnly(p, writer); + } + if (parameterNode && isOptionalParameter(parameterNode)) { + writePunctuation(writer, 55); + } + writePunctuation(writer, 56); + writeSpace(writer); + var type = getTypeOfSymbol(p); + if (parameterNode && isRequiredInitializedParameter(parameterNode)) { + type = getNullableType(type, 2048); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { + if (bindingPattern.kind === 174) { + writePunctuation(writer, 17); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 18); + } + else if (bindingPattern.kind === 175) { + writePunctuation(writer, 21); + var elements = bindingPattern.elements; + buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (elements && elements.hasTrailingComma) { + writePunctuation(writer, 26); + } + writePunctuation(writer, 22); + } + } + function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isOmittedExpression(bindingElement)) { + return; + } + ts.Debug.assert(bindingElement.kind === 176); + if (bindingElement.propertyName) { + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 56); + writeSpace(writer); + } + if (ts.isBindingPattern(bindingElement.name)) { + buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + if (bindingElement.dotDotDotToken) { + writePunctuation(writer, 24); + } + appendSymbolNameOnly(bindingElement.symbol, writer); + } + } + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27); + buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 29); + } + } + function buildDisplayForCommaSeparatedList(list, writer, action) { + for (var i = 0; i < list.length; i++) { + if (i > 0) { + writePunctuation(writer, 26); + writeSpace(writer); + } + action(list[i]); + } + } + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27); + var flags = 512; + for (var i = 0; i < typeParameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 26); + writeSpace(writer); + flags = 0; + } + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); + } + writePunctuation(writer, 29); + } + } + function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { + writePunctuation(writer, 19); + if (thisParameter) { + buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); + } + for (var i = 0; i < parameters.length; i++) { + if (i > 0 || thisParameter) { + writePunctuation(writer, 26); + writeSpace(writer); + } + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); + } + writePunctuation(writer, 20); + } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 99); + } + writeSpace(writer); + writeKeyword(writer, 126); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + var returnType = getReturnTypeOfSignature(signature); + if (flags & 4096 && isTypeAny(returnType)) { + return; + } + if (flags & 16) { + writeSpace(writer); + writePunctuation(writer, 36); + } + else { + writePunctuation(writer, 56); + } + writeSpace(writer); + if (signature.typePredicate) { + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); + } + else { + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1) { + writeKeyword(writer, 94); + writeSpace(writer); + } + if (signature.target && (flags & 64)) { + buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); + } + else { + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); + } + buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); + } + function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 131); + writeSpace(writer); + } + writePunctuation(writer, 21); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 56); + writeSpace(writer); + switch (kind) { + case 1: + writeKeyword(writer, 133); + break; + case 0: + writeKeyword(writer, 136); + break; + } + writePunctuation(writer, 22); + writePunctuation(writer, 56); + writeSpace(writer); + buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); + writePunctuation(writer, 25); + writer.writeLine(); + } + } + return _displayBuilder || (_displayBuilder = { + buildSymbolDisplay: buildSymbolDisplay, + buildTypeDisplay: buildTypeDisplay, + buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, + buildParameterDisplay: buildParameterDisplay, + buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, + buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, + buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, + buildSignatureDisplay: buildSignatureDisplay, + buildIndexSignatureDisplay: buildIndexSignatureDisplay, + buildReturnTypeDisplay: buildReturnTypeDisplay + }); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 176: + return isDeclarationVisible(node.parent.parent); + case 226: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + return false; + } + case 233: + case 229: + case 230: + case 231: + case 228: + case 232: + case 237: + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + if (!(ts.getCombinedModifierFlags(node) & 1) && + !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { + return isGlobalSourceFile(parent); + } + return isDeclarationVisible(parent); + case 149: + case 148: + case 153: + case 154: + case 151: + case 150: + if (ts.getModifierFlags(node) & (8 | 16)) { + return false; + } + case 152: + case 156: + case 155: + case 157: + case 146: + case 234: + case 160: + case 161: + case 163: + case 159: + case 164: + case 165: + case 166: + case 167: + case 168: + return isDeclarationVisible(node.parent); + case 239: + case 240: + case 242: + return false; + case 145: + case 265: + case 236: + return true; + case 243: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node) { + var exportSymbol; + if (node.parent && node.parent.kind === 243) { + exportSymbol = resolveName(node.parent, node.escapedText, 107455 | 793064 | 1920 | 2097152, ts.Diagnostics.Cannot_find_name_0, node); + } + else if (node.parent.kind === 246) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 2097152); + } + var result = []; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + getNodeLinks(declaration).isVisible = true; + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (!ts.contains(result, resultNode)) { + result.push(resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 | 793064 | 1920, undefined, undefined); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + var length_4 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_4; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + if (propertyName === 0) { + return getSymbolLinks(target).type; + } + if (propertyName === 2) { + return getSymbolLinks(target).declaredType; + } + if (propertyName === 1) { + return target.resolvedBaseConstructorType; + } + if (propertyName === 3) { + return target.resolvedReturnType; + } + ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + } + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 226: + case 227: + case 242: + case 241: + case 240: + case 239: + return false; + default: + return true; + } + }); + return node && node.parent; + } + function getTypeOfPrototypeProperty(prototype) { + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1) !== 0; + } + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); + } + function isComputedNonLiteralName(name) { + return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144); }); + if (source.flags & 8192) { + return emptyObjectType; + } + if (source.flags & 65536) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createSymbolTable(); + var names = ts.createUnderscoreEscapedMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name), true); + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = names.has(prop.escapedName); + var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 | 16); + var isSetOnlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); + if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { + members.set(prop.escapedName, prop); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0); + var numberIndexInfo = getIndexInfoOfType(source, 1); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + if (parentType === unknownType) { + return unknownType; + } + if (!parentType || isTypeAny(parentType)) { + if (declaration.initializer) { + return checkDeclarationInitializer(declaration); + } + return parentType; + } + var type; + if (pattern.kind === 174) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + var name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + var text = ts.getTextOfPropertyName(name); + var declaredType = getTypeOfPropertyOfType(parentType, text); + type = declaredType && getFlowTypeOfReference(declaration, declaredType) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || + getIndexTypeOfType(parentType, 0); + if (!type) { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); + return unknownType; + } + } + } + else { + var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); + if (declaration.dotDotDotToken) { + type = createArrayType(elementType); + } + else { + var propName = "" + ts.indexOf(pattern.elements, declaration); + type = isTupleLikeType(parentType) + ? getTypeOfPropertyOfType(parentType, propName) + : elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + } + return unknownType; + } + } + } + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { + type = getTypeWithFacts(type, 131072); + } + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], true) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 177 && expr.elements.length === 0; + } + function addOptionality(type, optional) { + return strictNullChecks && optional ? getNullableType(type, 2048) : type; + } + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + if (declaration.parent.parent.kind === 215) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 | 262144) ? indexType : stringType; + } + if (declaration.parent.parent.kind === 216) { + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + var declaredType = getTypeFromTypeNode(typeNode); + return addOptionality(declaredType, declaration.questionToken && includeOptionality); + } + if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { + if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 146) { + var func = declaration.parent; + if (func.kind === 154 && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + var type = void 0; + if (declaration.symbol.escapedName === "this") { + type = getContextualThisParameterType(func); + } + else { + type = getContextuallyTypedParameterType(declaration); + } + if (type) { + return addOptionality(type, declaration.questionToken && includeOptionality); + } + } + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, declaration.questionToken && includeOptionality); + } + if (ts.isJsxAttribute(declaration)) { + return trueType; + } + if (declaration.kind === 262) { + return checkIdentifier(declaration.name); + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, false, true); + } + return undefined; + } + function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + 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 : + declaration.kind === 179 ? ts.getAncestor(declaration, 194) : + undefined; + if (!expression) { + return unknownType; + } + if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { + if (ts.getThisContainer(expression, false).kind === 152) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + 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)); + } + } + else if (!jsDocType) { + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } + } + var type = jsDocType || getUnionType(types, true); + return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + } + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return checkDeclarationInitializer(element); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAnyError(element, anyType); + } + return anyType; + } + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var hasComputedProperties = false; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + hasComputedProperties = true; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 | (e.initializer ? 16777216 : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + if (includePatternInType) { + result.pattern = pattern; + } + if (hasComputedProperties) { + result.objectFlags |= 512; + } + return result; + } + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; + } + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + return pattern.kind === 174 + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + var type = getTypeForVariableLikeDeclaration(declaration, true); + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + if (declaration.kind === 261) { + return type; + } + return getWidenedType(type); + } + type = declaration.dotDotDotToken ? anyArrayType : anyType; + if (reportErrors && noImplicitAny) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAnyError(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 146 ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 4194304) { + return links.type = getTypeOfPrototypeProperty(symbol); + } + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return links.type = anyType; + } + if (declaration.kind === 243) { + return links.type = checkExpression(declaration.expression); + } + if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = void 0; + if (declaration.kind === 194 || + declaration.kind === 179 && declaration.parent.kind === 194) { + type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } + else { + type = getWidenedTypeForVariableLikeDeclaration(declaration, true); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function getAnnotatedAccessorType(accessor) { + if (accessor) { + if (accessor.kind === 153) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + } + } + return undefined; + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var getter = ts.getDeclarationOfKind(symbol, 153); + var setter = ts.getDeclarationOfKind(symbol, 154); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return links.type = jsDocType; + } + } + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + var type = void 0; + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + else { + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 153); + error(getter_1, 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, symbolToString(symbol)); + } + } + links.type = type; + } + return links.type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { + links.type = anyType; + } + else { + var type = createObjectType(16, symbol); + if (symbol.flags & 32) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + links.type = strictNullChecks && symbol.flags & 16777216 ? getNullableType(type, 2048) : type; + } + } + } + return links.type; + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getDeclaredTypeOfEnumMember(symbol); + } + return links.type; + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + links.type = targetSymbol.flags & 107455 + ? getTypeOfSymbol(targetSymbol) + : unknownType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbolInstantiationDepth === 100) { + error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); + links.type = unknownType; + } + else { + if (!pushTypeResolution(symbol, 0)) { + return unknownType; + } + symbolInstantiationDepth++; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + symbolInstantiationDepth--; + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + } + return links.type; + } + function reportCircularityError(symbol) { + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (symbol.flags & (3 | 4)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152) { + return getTypeOfAlias(symbol); + } + return unknownType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (getObjectFlags(type) & 4) !== 0 + && type.target === target; + } + function getTargetType(type) { + return getObjectFlags(type) & 4 ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (getObjectFlags(type) & (3 | 4)) { + var target = getTargetType(type); + return target === checkBase || ts.forEach(getBaseTypes(target), check); + } + else if (type.flags & 131072) { + return ts.forEach(type.types, check); + } + } + } + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + if (!typeParameters) { + typeParameters = [tp]; + } + else if (!ts.contains(typeParameters, tp)) { + typeParameters.push(tp); + } + } + return typeParameters; + } + function appendOuterTypeParameters(typeParameters, node) { + while (true) { + node = node.parent; + if (!node) { + return typeParameters; + } + if (node.kind === 229 || node.kind === 199 || + node.kind === 228 || node.kind === 186 || + node.kind === 151 || node.kind === 187) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); + } + } + } + } + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); + return appendOuterTypeParameters(undefined, declaration); + } + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 230 || node.kind === 229 || + node.kind === 199 || node.kind === 231) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } + return result; + } + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { + return true; + } + if (type.flags & 540672) { + var constraint = getBaseConstraintOfType(type); + return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return false; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavaScript = ts.isInJavaScriptFile(location); + return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + } + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & (32768 | 131072)) { + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = unknownType; + } + if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + return type.resolvedBaseConstructorType = unknownType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 | 64)) { + if (type.symbol.flags & 32) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { + 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, typeArgs); + } + else if (baseConstructorType.flags & 1) { + baseType = baseConstructorType; + } + else { + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } + if (baseType === unknownType) { + return; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + return; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + return; + } + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + function areAllOuterTypeParametersApplied(type) { + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } + function isValidBaseType(type) { + return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || + type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== unknownType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + } + } + else { + error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + } + } + } + } + } + } + function isIndependentInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230) { + if (declaration.flags & 64) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064, true); + if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 ? 1 : 2; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { + type.objectFlags |= 4; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + if (!pushTypeResolution(symbol, 2)) { + return unknownType; + } + var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 || d.kind === 231; }); + var type = getTypeFromTypeNode(declaration.kind === 283 ? declaration.typeExpression : declaration.type); + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + switch (expr.kind) { + case 9: + case 8: + return true; + case 192: + return expr.operator === 38 && + expr.operand.kind === 8; + case 71: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + default: + return false; + } + } + 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 (member.initializer && member.initializer.kind === 9) { + return links.enumKind = 1; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 : 1; + } + 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) { + 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); + } + } + } + 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; + } + } + 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)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(16384); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 | 64)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152) { + return getDeclaredTypeOfAlias(symbol); + } + return unknownType; + } + function isIndependentTypeReference(node) { + if (node.typeArguments) { + for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { + var typeNode = _a[_i]; + if (!isIndependentType(typeNode)) { + return false; + } + } + } + return true; + } + function isIndependentType(node) { + switch (node.kind) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 134: + case 105: + case 139: + case 95: + case 130: + case 173: + return true; + case 164: + return isIndependentType(node.elementType); + case 159: + return isIndependentTypeReference(node); + } + return false; + } + function isIndependentVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isIndependentType(typeNode) : !node.initializer; + } + function isIndependentFunctionLikeDeclaration(node) { + if (node.kind !== 152) { + var typeNode = ts.getEffectiveReturnTypeNode(node); + if (!typeNode || !isIndependentType(typeNode)) { + return false; + } + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (!isIndependentVariableLikeDeclaration(parameter)) { + return false; + } + } + return true; + } + function isIndependentMember(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 149: + case 148: + return isIndependentVariableLikeDeclaration(declaration); + case 151: + case 150: + case 152: + return isIndependentFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); + type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + } + return type; + } + function getTypeWithThisArgument(type, thisArgument) { + if (getObjectFlags(type) & 4) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + } + } + else if (type.flags & 131072) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + } + return type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === source.symbol.members) { + members = ts.createSymbolTable(source.declaredProperties); + } + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, false) : + getIndexInfoOfType(instantiatedBaseType, 0); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { + return undefined; + } + } + return [signature]; + } + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); + if (!match) { + return undefined; + } + if (!ts.contains(result, match)) { + (result || (result = [])).push(match); + } + } + return result; + } + function getUnionSignatures(types, kind) { + var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + if (!result || !findMatchingSignature(result, signature, false, true, true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + if (unionSignatures.length > 1) { + s = cloneSignature(signature); + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + s.resolvedReturnType = undefined; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + 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; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + var callSignatures = getUnionSignatures(type.types, 0); + var constructSignatures = getUnionSignatures(type.types, 1); + var stringIndexInfo = getUnionIndexInfo(type.types, 0); + var numberIndexInfo = getUnionIndexInfo(type.types, 1); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_4 = function (i) { + var t = type.types[i]; + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); + }; + for (var i = 0; i < types.length; i++) { + _loop_4(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048) { + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members.get("__call")); + var constructSignatures = getSignaturesOfSymbol(members.get("__new")); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + var members = emptySymbols; + var constructSignatures = ts.emptyArray; + var stringIndexInfo = undefined; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + if (symbol.flags & 32) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (32768 | 131072 | 540672)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, false); + } + } + var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + if (symbol.flags & (16 | 8192)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } + } + } + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 170) { + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var propertySymbol = _a[_i]; + addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); + } + if (getIndexInfoOfType(modifiersType, 0)) { + addMemberForKeyType(stringType); + } + } + else { + var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t, propertySymbol) { + var iterationMapper = createTypeMapper([typeParameter], [t]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + if (t.flags & 32) { + var propName = ts.escapeLeadingUnderscores(t.value); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216); + var prop = createSymbol(4 | (isOptional ? 16777216 : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; + prop.type = propType; + if (propertySymbol) { + prop.syntheticOrigin = propertySymbol; + prop.declarations = propertySymbol.declarations; + } + members.set(propName, prop); + } + else if (t.flags & 2) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 170) { + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function isPartialMappedType(type) { + return getObjectFlags(type) & 32 && !!type.declaration.questionToken; + } + function isGenericMappedType(type) { + return getObjectFlags(type) & 32 && + maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 | 262144); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 32768) { + if (type.objectFlags & 4) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 65536) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 131072) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + function getPropertiesOfObjectType(type) { + if (type.flags & 32768) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + function getPropertyOfObjectType(type, name) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + if (type.flags & 65536) { break; } } - detachedComments.push(comment); - lastComment = comment; - } - if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); - var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); - if (nodeLine >= lastCommentLine + 2) { - emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); - emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; - } + type.resolvedProperties = getNamedMembers(members); } + return type.resolvedProperties; } - return currentDetachedCommentInfo; - function isPinnedComment(comment) { - return text.charCodeAt(comment.pos + 1) === 42 && - text.charCodeAt(comment.pos + 2) === 33; + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 196608 ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); } - } - ts.emitDetachedComments = emitDetachedComments; - function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { - if (text.charCodeAt(commentPos + 1) === 42) { - var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); - var lineCount = lineMap.length; - var firstCommentLineIndent = void 0; - for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { - var nextLineStart = (currentLine + 1) === lineCount - ? text.length + 1 - : lineMap[currentLine + 1]; - if (pos !== commentPos) { - if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536) { + var props = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var memberType = _a[_i]; + if (memberType.flags & 8190) { + continue; } - var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); - if (spacesToEmit > 0) { - var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); - var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); - writer.rawWrite(indentSizeSpaceString); - while (numberOfSingleSpacesToEmit) { - writer.rawWrite(" "); - numberOfSingleSpacesToEmit--; + for (var _b = 0, _c = getPropertiesOfType(memberType); _b < _c.length; _b++) { + var escapedName = _c[_b].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); } } - else { - writer.rawWrite(""); + } + return ts.arrayFrom(props.values()); + } + else { + return getPropertiesOfType(type); + } + } + function getConstraintOfType(type) { + return type.flags & 16384 ? getConstraintOfTypeParameter(type) : + type.flags & 524288 ? getConstraintOfIndexedAccess(type) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var baseObjectType = getBaseConstraintOfType(type.objectType); + var baseIndexType = getBaseConstraintOfType(type.indexType); + return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (540672 | 196608)) { + var constraint = getResolvedBaseConstraint(type); + if (constraint !== noConstraintType && constraint !== circularConstraintType) { + return constraint; + } + } + else if (type.flags & 262144) { + return stringType; + } + return undefined; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + function getResolvedBaseConstraint(type) { + var typeStack; + var circular; + if (!type.resolvedBaseConstraint) { + typeStack = []; + var constraint = getBaseConstraint(type); + type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + } + return type.resolvedBaseConstraint; + function getBaseConstraint(t) { + if (ts.contains(typeStack, t)) { + circular = true; + return undefined; + } + typeStack.push(t); + var result = computeBaseConstraint(t); + typeStack.pop(); + return result; + } + function computeBaseConstraint(t) { + if (t.flags & 16384) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType ? constraint : + constraint ? getBaseConstraint(constraint) : undefined; + } + if (t.flags & 196608) { + var types = t.types; + var baseTypes = []; + 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); + } + } + return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 262144) { + return stringType; + } + if (t.flags & 524288) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + } + function getDefaultFromTypeParameter(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + } + } + return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + } + function getApparentType(type) { + var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : + t.flags & 262178 ? globalStringType : + t.flags & 84 ? globalNumberType : + t.flags & 136 ? globalBooleanType : + t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : + t.flags & 16777216 ? emptyObjectType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var types = containingType.types; + var isUnion = containingType.flags & 65536; + var excludeModifiers = isUnion ? 24 : 0; + var commonFlags = isUnion ? 0 : 16777216; + var syntheticFlag = 4; + var checkFlags = 0; + 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + if (!props) { + props = [prop]; + } + else if (!ts.contains(props, prop)) { + props.push(prop); + } + checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | + (!(modifiers & 24) ? 64 : 0) | + (modifiers & 16 ? 128 : 0) | + (modifiers & 8 ? 256 : 0) | + (modifiers & 32 ? 512 : 0); + if (!isMethodLike(prop)) { + syntheticFlag = 2; + } + } + else if (isUnion) { + checkFlags |= 16; } } - writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); - pos = nextLineStart; + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16)) { + return props[0]; + } + var propTypes = []; + var declarations = []; + var commonType = undefined; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; + if (prop.declarations) { + ts.addRange(declarations, prop.declarations); + } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + checkFlags |= 32; + } + propTypes.push(type); + } + var result = createSymbol(4 | commonFlags, name); + result.checkFlags = syntheticFlag | checkFlags; + result.containingType = containingType; + result.declarations = declarations; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; + } + function getPropertyOfType(type, name) { + type = getApparentType(type); + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 196608) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 229376) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 229376) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; } } - else { - writer.write(text.substring(commentPos, commentEnd)); + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; } - } - ts.writeCommentRange = writeCommentRange; - function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { - var end = Math.min(commentEnd, nextLineStart - 1); - var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); - if (currentLineText) { - writer.write(currentLineText); - if (end !== commentEnd) { - writer.writeLine(); + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, true); + } + } + return undefined; + } + function getTypeParametersFromDeclaration(declaration) { + var result; + ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + var tp = getDeclaredTypeOfTypeParameter(node.symbol); + if (!ts.contains(result, tp)) { + if (!result) { + result = []; + } + result.push(tp); + } + }); + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + if (ts.isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 272) { + return true; + } + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 272; + } + } + } } } - else { - writer.writeLiteral(newLine); - } - } - function calculateIndent(text, pos, end) { - var currentLineIndent = 0; - for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { - if (text.charCodeAt(pos) === 9) { - currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); - } - else { - currentLineIndent++; + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } - return currentLineIndent; - } - function hasModifiers(node) { - return getModifierFlags(node) !== 0; - } - ts.hasModifiers = hasModifiers; - function hasModifier(node, flags) { - return (getModifierFlags(node) & flags) !== 0; - } - ts.hasModifier = hasModifier; - function getModifierFlags(node) { - if (node.modifierFlagsCache & 536870912) { - return node.modifierFlagsCache & ~536870912; - } - var flags = 0; - if (node.modifiers) { - for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { - var modifier = _a[_i]; - flags |= modifierToFlag(modifier.kind); - } - } - if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) { - flags |= 1; - } - node.modifierFlagsCache = flags | 536870912; - return flags; - } - ts.getModifierFlags = getModifierFlags; - function modifierToFlag(token) { - switch (token) { - case 115: return 32; - case 114: return 4; - case 113: return 16; - case 112: return 8; - case 117: return 128; - case 84: return 1; - case 124: return 2; - case 76: return 2048; - case 79: return 512; - case 120: return 256; - case 131: return 64; - } - return 0; - } - ts.modifierToFlag = modifierToFlag; - function isLogicalOperator(token) { - return token === 54 - || token === 53 - || token === 51; - } - ts.isLogicalOperator = isLogicalOperator; - function isAssignmentOperator(token) { - return token >= 58 && token <= 70; - } - ts.isAssignmentOperator = isAssignmentOperator; - function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 201 && - node.parent.token === 85 && - isClassLike(node.parent.parent)) { - return node.parent.parent; - } - } - ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; - function isAssignmentExpression(node, excludeCompoundAssignment) { - return isBinaryExpression(node) - && (excludeCompoundAssignment - ? node.operatorToken.kind === 58 - : isAssignmentOperator(node.operatorToken.kind)) - && isLeftHandSideExpression(node.left); - } - ts.isAssignmentExpression = isAssignmentExpression; - function isDestructuringAssignment(node) { - if (isAssignmentExpression(node, true)) { - var kind = node.left.kind; - return kind === 178 - || kind === 177; - } - return false; - } - ts.isDestructuringAssignment = isDestructuringAssignment; - function isSupportedExpressionWithTypeArguments(node) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; - function isSupportedExpressionWithTypeArgumentsRest(node) { - if (node.kind === 71) { - return true; - } - else if (isPropertyAccessExpression(node)) { - return isSupportedExpressionWithTypeArgumentsRest(node.expression); - } - else { - return false; - } - } - function isExpressionWithTypeArgumentsInClassExtendsClause(node) { - return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; - } - ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; - function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 201 - && isEntityNameExpression(node.expression) - && node.parent - && node.parent.token === 108 - && node.parent.parent - && isClassLike(node.parent.parent); - } - ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; - function isEntityNameExpression(node) { - return node.kind === 71 || - node.kind === 179 && isEntityNameExpression(node.expression); - } - ts.isEntityNameExpression = isEntityNameExpression; - function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 143 && node.parent.right === node) || - (node.parent.kind === 179 && node.parent.name === node); - } - ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; - function isEmptyObjectLiteral(expression) { - return expression.kind === 178 && - expression.properties.length === 0; - } - ts.isEmptyObjectLiteral = isEmptyObjectLiteral; - function isEmptyArrayLiteral(expression) { - return expression.kind === 177 && - expression.elements.length === 0; - } - ts.isEmptyArrayLiteral = isEmptyArrayLiteral; - function getLocalSymbolForExportDefault(symbol) { - return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined; - } - ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function isExportDefaultSymbol(symbol) { - return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512); - } - function tryExtractTypeScriptExtension(fileName) { - return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; - function getExpandedCharCodes(input) { - var output = []; - var length = input.length; - for (var i = 0; i < length; i++) { - var charCode = input.charCodeAt(i); - if (charCode < 0x80) { - output.push(charCode); - } - else if (charCode < 0x800) { - output.push((charCode >> 6) | 192); - output.push((charCode & 63) | 128); - } - else if (charCode < 0x10000) { - output.push((charCode >> 12) | 224); - output.push(((charCode >> 6) & 63) | 128); - output.push((charCode & 63) | 128); - } - else if (charCode < 0x20000) { - output.push((charCode >> 18) | 240); - output.push(((charCode >> 12) & 63) | 128); - output.push(((charCode >> 6) & 63) | 128); - output.push((charCode & 63) | 128); - } - else { - ts.Debug.assert(false, "Unexpected code point"); - } - } - return output; - } - var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - function convertToBase64(input) { - var result = ""; - var charCodes = getExpandedCharCodes(input); - var i = 0; - var length = charCodes.length; - var byte1, byte2, byte3, byte4; - while (i < length) { - byte1 = charCodes[i] >> 2; - byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; - byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; - byte4 = charCodes[i + 2] & 63; - if (i + 1 >= length) { - byte3 = byte4 = 64; - } - else if (i + 2 >= length) { - byte4 = 64; - } - result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); - i += 3; - } - return result; - } - ts.convertToBase64 = convertToBase64; - var carriageReturnLineFeed = "\r\n"; - var lineFeed = "\n"; - function getNewLineCharacter(options) { - switch (options.newLine) { - case 0: - return carriageReturnLineFeed; - case 1: - return lineFeed; - } - if (ts.sys) { - return ts.sys.newLine; - } - return carriageReturnLineFeed; - } - ts.getNewLineCharacter = getNewLineCharacter; - function isSimpleExpression(node) { - return isSimpleExpressionWorker(node, 0); - } - ts.isSimpleExpression = isSimpleExpression; - function isSimpleExpressionWorker(node, depth) { - if (depth <= 5) { - var kind = node.kind; - if (kind === 9 - || kind === 8 - || kind === 12 - || kind === 13 - || kind === 71 - || kind === 99 - || kind === 97 - || kind === 101 - || kind === 86 - || kind === 95) { + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { return true; } - else if (kind === 179) { - return isSimpleExpressionWorker(node.expression, depth + 1); + if (node.initializer) { + var signatureDeclaration = node.parent; + var signature = getSignatureFromDeclaration(signatureDeclaration); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= signature.minArgumentCount; } - else if (kind === 180) { - return isSimpleExpressionWorker(node.expression, depth + 1) - && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; } - else if (kind === 192 - || kind === 193) { - return isSimpleExpressionWorker(node.operand, depth + 1); + return false; + } + function createTypePredicateFromTypePredicateNode(node) { + var parameterName = node.parameterName; + if (parameterName.kind === 71) { + return { + kind: 1, + parameterName: parameterName ? parameterName.escapedText : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; } - else if (kind === 194) { - return node.operatorToken.kind !== 40 - && isSimpleExpressionWorker(node.left, depth + 1) - && isSimpleExpressionWorker(node.right, depth + 1); + else { + return { + kind: 0, + type: getTypeFromTypeNode(node.type) + }; } - else if (kind === 195) { - return isSimpleExpressionWorker(node.condition, depth + 1) - && isSimpleExpressionWorker(node.whenTrue, depth + 1) - && isSimpleExpressionWorker(node.whenFalse, depth + 1); - } - else if (kind === 190 - || kind === 189 - || kind === 188) { - return isSimpleExpressionWorker(node.expression, depth + 1); - } - else if (kind === 177) { - return node.elements.length === 0; - } - else if (kind === 178) { - return node.properties.length === 0; - } - else if (kind === 181) { - if (!isSimpleExpressionWorker(node.expression, depth + 1)) { - return false; + } + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!getDefaultFromTypeParameter(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } } - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (!isSimpleExpressionWorker(argument, depth + 1)) { + } + return minTypeArgumentCount; + } + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + var numTypeParameters = ts.length(typeParameters); + if (numTypeParameters) { + var numTypeArguments = ts.length(typeArguments); + var isJavaScript = ts.isInJavaScriptFile(location); + if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (!typeArguments) { + typeArguments = []; + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, typeArguments); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + } + } + } + return typeArguments; + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = undefined; + var hasThisParameter = void 0; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455, undefined, undefined); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this") { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (param.type && param.type.kind === 173) { + hasLiteralTypes = true; + } + var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !param.type || + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + if ((declaration.kind === 153 || declaration.kind === 154) && + !ts.hasDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 153 ? 154 : 153; + var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 152 ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 158 ? + createTypePredicateFromTypePredicateNode(declaration.type) : + undefined; + var hasRestLikeParameter = ts.hasRestParameter(declaration); + if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { + hasRestLikeParameter = true; + var syntheticArgsSymbol = createSymbol(3, "args"); + syntheticArgsSymbol.type = anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + parameters.push(syntheticArgsSymbol); + } + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { + if (isJSConstructSignature) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { + return classType; + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 154); + return getAnnotatedAccessorType(setter); + } + if (ts.nodeIsMissing(declaration.body)) { + return anyType; + } + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 71: + return node.escapedText === "arguments" && ts.isPartOfExpression(node); + case 149: + case 151: + case 153: + case 154: + return node.name.kind === 144 + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var node = symbol.declarations[i]; + switch (node.kind) { + case 160: + case 161: + case 228: + case 151: + case 150: + case 152: + case 155: + case 156: + case 157: + case 153: + case 154: + case 186: + case 187: + case 273: + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + break; + } + } + result.push(getSignatureFromDeclaration(node)); + } + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3)) { + return unknownType; + } + var type = void 0; + if (signature.target) { + type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); + } + else if (signature.unionSignatures) { + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); + } + else { + type = getReturnTypeFromBody(signature.declaration); + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var declaration = signature.declaration; + 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); + } + } + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + if (getObjectFlags(type) & 4 && type.target === globalArrayType) { + return type.typeArguments[0]; + } + } + return anyType; + } + function getSignatureInstantiation(signature, typeArguments) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); + } + function getErasedSignature(signature) { + if (!signature.typeParameters) + return signature; + if (!signature.erasedSignatureCache) { + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); + } + return signature.erasedSignatureCache; + } + function getOrCreateTypeFromSignature(signature) { + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; + var type = createObjectType(16); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index"); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 ? 133 : 136; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = decl; + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 145).constraint; + } + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_5 = types.length; + var i = 0; + while (i < length_5) { + var startId = types[i].id; + var count = 1; + while (i + count < length_5 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + function getPropagatingFlagsOfTypes(types, excludeKinds) { + var result = 0; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 14680064; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : 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(typeArgs, typeParameters, minTypeArgumentCount, node)); + return createTypeReference(type, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + } + return instantiation; + } + function getTypeFromTypeAliasReference(node, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return unknownType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + function getTypeFromNonGenericTypeReference(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 159: + return node.typeName; + case 201: + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); + if (symbol === unknownSymbol) { + return unknownType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + if (symbol.flags & 107455 && isJSDocTypeReference(node)) { + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; + } + } + resolveTypeReferenceName(getTypeReferenceName(node), 793064); + return valueType; + } + return getTypeFromNonGenericTypeReference(node, symbol); + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 | 64)) { + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function isJSDocTypeReference(node) { + return node.flags & 1048576 && node.kind === 159; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + if (node.typeName.escapedText === "Object") { + if (node.typeArguments && node.typeArguments.length === 2) { + var indexed = getTypeFromTypeNode(node.typeArguments[0]); + var target = getTypeFromTypeNode(node.typeArguments[1]); + var index = createIndexInfo(target, false); + if (indexed === stringType || indexed === numberType) { + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + } + } + return anyType; + } + switch (node.typeName.escapedText) { + case "String": + return stringType; + case "Number": + return numberType; + case "Boolean": + return booleanType; + case "Void": + return voidType; + case "Undefined": + return undefinedType; + case "Null": + return nullType; + case "Function": + case "function": + return globalFunctionType; + case "Array": + case "array": + return !node.typeArguments || !node.typeArguments.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getUnionType([type, nullType]) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 793064; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 107455; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + 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) { + links.resolvedType = getWidenedType(checkExpression(node.exprName)); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + switch (declaration.kind) { + case 229: + case 230: + case 232: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 32768)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName(undefined, name, meaning, diagnostic, name); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 793064, undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + function getExportedTypeFromNamespace(namespace, name) { + var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); + return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); + } + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384); + typeParameters.push(typeParameter); + var property = createSymbol(4, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(8 | 4); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + return type; + } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + } + return links.resolvedType; + } + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 65536) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144) { + if (flags & 2048) + typeSet.containsUndefined = true; + if (flags & 4096) + typeSet.containsNull = true; + if (!(flags & 2097152)) + typeSet.containsNonWideningType = true; + } + else if (!(flags & 8192)) { + if (flags & 2) + typeSet.containsString = true; + if (flags & 4) + typeSet.containsNumber = true; + if (flags & 96) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } + } + } + function addTypesToUnion(typeSet, types) { + 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_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function isSubtypeOfAny(candidate, types) { + 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; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } return true; } + return false; } - return false; - } - var syntaxKindCache = []; - function formatSyntaxKind(kind) { - var syntaxKindEnum = ts.SyntaxKind; - if (syntaxKindEnum) { - var cached = syntaxKindCache[kind]; - if (cached !== undefined) { - return cached; + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; } - for (var name in syntaxKindEnum) { - if (syntaxKindEnum[name] === kind) { - var result = kind + " (" + name + ")"; - syntaxKindCache[kind] = result; + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 && types.containsString || + t.flags & 64 && types.containsNumber || + t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + addTypesToUnion(typeSet, types); + if (typeSet.containsAny) { + return anyType; + } + if (subtypeReduction) { + removeSubtypes(typeSet); + } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } + if (typeSet.length === 0) { + return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : + typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : + neverType; + } + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); + type = createType(65536 | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, type) { + if (type.flags & 131072) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1) { + typeSet.containsAny = true; + } + else if (type.flags & 8192) { + typeSet.containsNever = true; + } + else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { + typeSet.containsEmptyObject = true; + } + else if ((strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { + if (type.flags & 32768) { + typeSet.containsObjectType = true; + } + if (type.flags & 65536 && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } + if (!(type.flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } + } + } + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; + addTypeToIntersection(typeSet, type); + } + } + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return emptyObjectType; + } + var typeSet = []; + addTypesToIntersection(typeSet, types); + if (typeSet.containsNever) { + return neverType; + } + if (typeSet.containsAny) { + return anyType; + } + if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { + typeSet.push(emptyObjectType); + } + if (typeSet.length === 1) { + return typeSet[0]; + } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); + type = createType(131072 | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + neverType : + getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : + type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; + var propName = indexType.flags & 96 ? + ts.escapeLeadingUnderscores("" + indexType.value) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? + ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || + getIndexInfoOfType(objectType, 0) || + undefined; + if (indexInfo) { + if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + 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.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)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + return unknownType; + } + return anyType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + if (maybeTypeOfKind(indexType, 540672 | 262144) || + maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1) { + return objectType; + } + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 && !(indexType.flags & 8190)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (node.symbol.members.size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + function getSpreadType(left, right) { + if (left.flags & 1 || right.flags & 1) { + return anyType; + } + if (left.flags & 8192) { + return right; + } + if (right.flags & 8192) { + return left; + } + if (left.flags & 65536) { + return mapType(left, function (t) { return getSpreadType(t, right); }); + } + if (right.flags & 65536) { + return mapType(right, function (t) { return getSpreadType(left, t); }); + } + if (right.flags & 16777216) { + return emptyObjectType; + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + stringIndexInfo = getIndexInfoOfType(right, 0); + numberIndexInfo = getIndexInfoOfType(right, 1); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + var rightProp = _a[_i]; + var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); + if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 && !(leftProp.flags & 32768) + || skippedPrivateMembers.has(leftProp.escapedName) + || isClassMethod(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 | (leftProp.flags & 16777216); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + } + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getNonReadonlySymbol(prop) { + if (!isReadonlySymbol(prop)) { + return prop; + } + var flags = 4 | (prop.flags & 16777216); + var result = createSymbol(flags, prop.escapedName); + result.type = getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.syntheticOrigin = prop; + return result; + } + function isClassMethod(prop) { + return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + 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.value, type.symbol); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; + } + 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) { + var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { + if (!(ts.getModifierFlags(container) & 32) && + (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return unknownType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 119: + case 268: + case 269: + return anyType; + case 136: + return stringType; + case 133: + return numberType; + case 122: + return booleanType; + case 137: + return esSymbolType; + case 105: + return voidType; + case 139: + return undefinedType; + case 95: + return nullType; + case 130: + return neverType; + case 134: + return node.flags & 65536 ? anyType : nonPrimitiveType; + case 169: + case 99: + return getTypeFromThisTypeNode(node); + case 173: + return getTypeFromLiteralTypeNode(node); + case 159: + return getTypeFromTypeReference(node); + case 158: + return booleanType; + case 201: + return getTypeFromTypeReference(node); + case 162: + return getTypeFromTypeQueryNode(node); + case 164: + return getTypeFromArrayTypeNode(node); + case 165: + return getTypeFromTupleTypeNode(node); + case 166: + return getTypeFromUnionTypeNode(node); + case 167: + return getTypeFromIntersectionTypeNode(node); + case 270: + return getTypeFromJSDocNullableTypeNode(node); + case 168: + case 271: + case 272: + case 267: + return getTypeFromTypeNode(node.type); + case 160: + case 161: + case 163: + case 285: + case 273: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 170: + return getTypeFromTypeOperatorNode(node); + case 171: + return getTypeFromIndexedAccessTypeNode(node); + case 172: + return getTypeFromMappedTypeNode(node); + case 71: + case 143: + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + case 274: + return getTypeFromJSDocVariadicType(node); + default: + return unknownType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + var result = []; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; + result.push(instantiator(v, mapper)); + } + return result; + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + mapper.mappedTypes = sources; + return mapper; + } + function createTypeEraser(sources) { + return createTypeMapper(sources, undefined); + } + function createBackreferenceMapper(typeParameters, index) { + var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + mapper.mappedTypes = typeParameters; + return mapper; + } + function isInferenceContext(mapper) { + return !!mapper.signature; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.signature, mapper.flags | 2, mapper.inferences) : + mapper; + } + function identityMapper(type) { + return type; + } + function combineTypeMappers(mapper1, mapper2) { + var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; + mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); + return mapper; + } + function createReplacementMapper(source, target, baseMapper) { + var mapper = function (t) { return t === source ? target : baseMapper(t); }; + mapper.mappedTypes = baseMapper.mappedTypes; + return mapper; + } + function cloneTypeParameter(typeParameter) { + var result = createType(16384); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + var freshTypePredicate; + if (signature.typeParameters && !eraseTypeParameters) { + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + if (signature.typePredicate) { + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); + } + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + if (ts.getCheckFlags(symbol) & 1) { + var links = getSymbolLinks(symbol); + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + var result = createSymbol(symbol.flags, symbol.escapedName); + result.checkFlags = 1; + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + return result; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(16 | 64, type.symbol); + result.target = type.objectFlags & 64 ? type.target : type; + result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144) { + var typeVariable_1 = constraintType.type; + if (typeVariable_1.flags & 16384) { + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + } + return t; + }); + } + } + } + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 | 32768 | 131072 | 524288); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 | 64, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } + var mappedTypes = mapper.mappedTypes; + return !!ts.findAncestor(symbol.declarations[0], function (node) { + if (node.kind === 233 || node.kind === 265) { + return "quit"; + } + switch (node.kind) { + case 160: + case 161: + case 228: + case 151: + case 150: + case 152: + case 155: + case 156: + case 157: + case 153: + case 154: + case 186: + case 187: + case 229: + case 199: + case 230: + case 231: + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var d = typeParameters_1[_i]; + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { + return true; + } + } + } + if (ts.isClassLike(node) || node.kind === 230) { + var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + if (thisType && ts.contains(mappedTypes, thisType)) { + return true; + } + } + break; + case 172: + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { + return true; + } + break; + case 273: + var func = node; + for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { + var p = _b[_a]; + if (ts.contains(mappedTypes, getTypeOfNode(p))) { + return true; + } + } + break; + } + }); + } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 265 || parentKind === 234; + } + return false; + } + function instantiateType(type, mapper) { + if (type && mapper !== identityMapper) { + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; + } + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384) { + return mapper(type); + } + if (type.flags & 32768) { + if (type.objectFlags & 16) { + return type.symbol && + type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && + (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; + } + if (type.objectFlags & 32) { + return instantiateCached(type, mapper, instantiateMappedType); + } + if (type.objectFlags & 4) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + } + } + if (type.flags & 65536 && !(type.flags & 8190)) { + return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + return type; + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 186: + case 187: + return isContextSensitiveFunctionLikeDeclaration(node); + case 178: + return ts.forEach(node.properties, isContextSensitive); + case 177: + return ts.forEach(node.elements, isContextSensitive); + case 195: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 194: + return node.operatorToken.kind === 54 && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 261: + return isContextSensitive(node.initializer); + case 151: + case 150: + return isContextSensitiveFunctionLikeDeclaration(node); + case 185: + return isContextSensitive(node.expression); + case 254: + return ts.forEach(node.properties, isContextSensitive); + case 253: + return node.initializer && isContextSensitive(node.initializer); + case 256: + return node.expression && isContextSensitive(node.expression); + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + if (node.typeParameters) { + return false; + } + if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + if (node.kind === 187) { + return false; + } + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length) { + var result = createObjectType(16, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; return result; } } + else if (type.flags & 131072) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; } - else { - return kind.toString(); + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); } - } - ts.formatSyntaxKind = formatSyntaxKind; - function getRangePos(range) { - return range ? range.pos : -1; - } - ts.getRangePos = getRangePos; - function getRangeEnd(range) { - return range ? range.end : -1; - } - ts.getRangeEnd = getRangeEnd; - function movePos(pos, value) { - return ts.positionIsSynthesized(pos) ? -1 : pos + value; - } - ts.movePos = movePos; - function createRange(pos, end) { - return { pos: pos, end: end }; - } - ts.createRange = createRange; - function moveRangeEnd(range, end) { - return createRange(range.pos, end); - } - ts.moveRangeEnd = moveRangeEnd; - function moveRangePos(range, pos) { - return createRange(pos, range.end); - } - ts.moveRangePos = moveRangePos; - function moveRangePastDecorators(node) { - return node.decorators && node.decorators.length > 0 - ? moveRangePos(node, node.decorators.end) - : node; - } - ts.moveRangePastDecorators = moveRangePastDecorators; - function moveRangePastModifiers(node) { - return node.modifiers && node.modifiers.length > 0 - ? moveRangePos(node, node.modifiers.end) - : moveRangePastDecorators(node); - } - ts.moveRangePastModifiers = moveRangePastModifiers; - function isCollapsedRange(range) { - return range.pos === range.end; - } - ts.isCollapsedRange = isCollapsedRange; - function collapseRangeToStart(range) { - return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); - } - ts.collapseRangeToStart = collapseRangeToStart; - function collapseRangeToEnd(range) { - return isCollapsedRange(range) ? range : moveRangePos(range, range.end); - } - ts.collapseRangeToEnd = collapseRangeToEnd; - function createTokenRange(pos, token) { - return createRange(pos, pos + ts.tokenToString(token).length); - } - ts.createTokenRange = createTokenRange; - function rangeIsOnSingleLine(range, sourceFile) { - return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); - } - ts.rangeIsOnSingleLine = rangeIsOnSingleLine; - function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { - return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); - } - ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; - function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { - return positionsAreOnSameLine(range1.end, range2.end, sourceFile); - } - ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; - function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { - return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); - } - ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; - function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { - return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); - } - ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; - function positionsAreOnSameLine(pos1, pos2, sourceFile) { - return pos1 === pos2 || - getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); - } - ts.positionsAreOnSameLine = positionsAreOnSameLine; - function getStartPositionOfRange(range, sourceFile) { - return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); - } - ts.getStartPositionOfRange = getStartPositionOfRange; - function isDeclarationNameOfEnumOrNamespace(node) { - var parseNode = ts.getParseTreeNode(node); - if (parseNode) { - switch (parseNode.parent.kind) { - case 232: - case 233: - return parseNode === parseNode.parent.name; + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + function isTypeInstanceOf(source, target) { + return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + } + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; + } + function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + if (source === target) { + return -1; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0; + } + if (source.typeParameters) { + source = instantiateSignatureInContextOf(source, target); + } + var result = -1; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType, false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0; + } + result &= related; + } + } + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); + var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); + var related = callbacks ? + compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : + !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + } + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0; + } + } + else { + result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + if (source.kind === 1) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; } } - return false; - } - ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; - function getInitializedVariables(node) { - return ts.filter(node.declarations, isInitializedVariable); - } - ts.getInitializedVariables = getInitializedVariables; - function isInitializedVariable(node) { - return node.initializer !== undefined; - } - function isMergedWithClass(node) { - if (node.symbol) { - for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 229 && declaration !== node) { + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 16777216 ? true : + type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + false; + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined) { + return relation; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { + enumRelation.set(id, false); + return false; + } + 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.escapedName); + if (!targetProperty || !(targetProperty.flags & 8)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + } + enumRelation.set(id, false); + return false; + } + } + } + enumRelation.set(id, true); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 8192) + return false; + if (t & 1 || s & 8192) + return true; + if (s & 262178 && t & 2) + return true; + if (s & 32 && s & 256 && + t & 32 && !(t & 256) && + source.value === target.value) + return true; + if (s & 84 && t & 4) + return true; + if (s & 64 && s & 256 && + t & 64 && !(t & 256) && + source.value === target.value) + return true; + if (s & 136 && t & 8) + return true; + if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + 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 (s & 4096 && (!strictNullChecks || t & 4096)) + return true; + if (s & 32768 && t & 16777216) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (s & 1) + return true; + if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 && source.flags & 1048576) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 1048576) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 32768 && target.flags & 32768) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + return related === 1; + } + } + if (source.flags & 1032192 || target.flags & 1032192) { + return checkTypeRelatedTo(source, target, relation, undefined); + } + return false; + } + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + var errorInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0; + var overflow = false; + var isIntersectionConstituent = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return result !== 0; + function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, undefined, 256); + targetType = typeToString(target, undefined, 256); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608)) { + return false; + } + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + function isRelatedTo(source, target, reportErrors, headMessage) { + if (source.flags & 96 && source.flags & 1048576) { + source = source.regularType; + } + if (target.flags & 96 && target.flags & 1048576) { + target = target.regularType; + } + if (source === target) + return -1; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1; + if (getObjectFlags(source) & 128 && source.flags & 1048576) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0; + } + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && + !(source.flags & 196608) && + !(target.flags & 65536) && + !isIntersectionConstituent && + source !== globalObjectType && + getPropertiesOfType(source).length > 0 && + isWeakType(target) && + !hasCommonProperties(source, target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + return 0; + } + var result = 0; + var saveErrorInfo = errorInfo; + var saveIsIntersectionConstituent = isIntersectionConstituent; + isIntersectionConstituent = false; + if (source.flags & 65536) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); + } + else { + if (target.flags & 65536) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190)); + } + else if (target.flags & 131072) { + isIntersectionConstituent = true; + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 131072) { + result = someTypeRelatedToType(source, target, false); + } + if (!result && (source.flags & 1032192 || target.flags & 1032192)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + } + } + } + isIntersectionConstituent = saveIsIntersectionConstituent; + if (!result && reportErrors) { + if (source.flags & 32768 && target.flags & 8190) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 32768 && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + if (source.flags & 32768 && target.flags & 32768) { + return recursiveTypeRelatedTo(source, target, false); + } + if (source.flags & 65536 && target.flags & 65536 || + source.flags & 131072 && target.flags & 131072) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0; + } + function hasExcessProperties(source, target, reportErrors) { + if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { + var isComparingJsxAttributes = !!(source.flags & 33554432); + if ((relation === assignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + var _loop_5 = function (prop) { + if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + ts.Debug.assert(!!errorNode); + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + errorNode = prop.valueDeclaration; + } + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_5(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, false); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 65536 && containsType(targetTypes, source)) { + return -1; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, false); + if (related) { + return related; + } + } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); + } + return 0; + } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 65536 && containsType(sourceTypes, target)) { + return -1; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(source, target, reportErrors) { + var sources = source.typeArguments || ts.emptyArray; + var targets = target.typeArguments || ts.emptyArray; + if (sources.length !== targets.length && relation === identityRelation) { + return 0; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1; + for (var i = 0; i < length; i++) { + var related = isRelatedTo(sources[i], targets[i], reportErrors); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function recursiveTypeRelatedTo(source, target, reportErrors) { + if (overflow) { + return 0; + } + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2) { + relation.set(id, 3); + } + else { + return related === 1 ? -1 : 0; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + if (id === maybeKeys[i]) { + return 1; + } + } + if (depth === 100) { + overflow = true; + return 0; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2; + var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 || depth === 0) { + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1); + } + maybeCount = maybeStart; + } + } + else { + relation.set(id, reportErrors ? 3 : 2); + maybeCount = maybeStart; + } + return result; + } + function structuredTypeRelatedTo(source, target, reportErrors) { + var result; + var saveErrorInfo = errorInfo; + if (target.flags & 16384) { + if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144) { + if (source.flags & 262144) { + if (result = isRelatedTo(target.type, source.type, false)) { + return result; + } + } + var constraint = getConstraintOfType(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + else if (target.flags & 524288) { + var constraint = getConstraintOfType(target); + if (constraint) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + if (source.flags & 16384) { + if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + var constraint = getConstraintOfTypeParameter(source); + if (constraint || !(target.flags & 16777216)) { + if (!constraint || constraint.flags & 1) { + constraint = emptyObjectType; + } + constraint = getTypeWithThisArgument(constraint, source); + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else if (source.flags & 524288) { + var constraint = getConstraintOfType(source); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (target.flags & 524288 && source.indexType === target.indexType) { + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + } + else { + if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + return result; + } + } + var sourceIsPrimitive = !!(source.flags & 8190); + if (relation !== identityRelation) { + source = getApparentType(source); + } + if (source.flags & (32768 | 131072) && target.flags & 32768) { + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + result = -1; + } + else if (isGenericMappedType(target)) { + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0; + } + else { + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + return 0; + } + function mappedTypeRelatedTo(source, target, reportErrors) { + var sourceReadonly = !!source.declaration.readonlyToken; + var sourceOptional = !!source.declaration.questionToken; + var targetReadonly = !!target.declaration.readonlyToken; + var targetOptional = !!target.declaration.questionToken; + var modifiersRelated = relation === identityRelation ? + sourceReadonly === targetReadonly && sourceOptional === targetOptional : + relation === comparableRelation || !sourceOptional || targetOptional; + if (modifiersRelated) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var result = -1; + var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp !== targetProp) { + if (!sourceProp) { + if (!(targetProp.flags & 16777216) || requireOptionalProperties) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); + } + return 0; + } + } + else if (!(targetProp.flags & 4194304)) { + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 || targetPropFlags & 8) { + 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)); + } + return 0; + } + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (reportErrors) { + if (sourcePropFlags & 8 && targetPropFlags & 8) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); + } + } + return 0; + } + } + else if (targetPropFlags & 16) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0; + } + } + else if (sourcePropFlags & 16) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0; + } + result &= related; + if (relation !== comparableRelation && sourceProp.flags & 16777216 && !(targetProp.flags & 16777216)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0; + } + } + } + } + return result; + } + function isWeakType(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216); }); + } + if (type.flags & 131072) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(source.flags & 33554432); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 32768 && target.flags & 32768)) { + return 0; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0; + } + var result = -1; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1; + } + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0; + } + } + var result = -1; + var saveErrorInfo = errorInfo; + 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], true, reportErrors); + if (!related) { + return 0; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + 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, true, 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 result; + } + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, false, false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0; + } + var result = -1; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); + if (!related) { + return 0; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 1 && !sourceIsPrimitive) { + return -1; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 && getIndexInfoOfType(source, 0); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1; + if (kind === 0) { + var sourceNumberInfo = getIndexInfoOfType(source, 1); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; + if (targetAccessibility === 8) { + return true; + } + if (targetAccessibility === 16 && sourceAccessibility !== 8) { + return true; + } + if (targetAccessibility !== 16 && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + function forEachProperty(prop, callback) { + 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.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + 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 ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } + function isAbstractConstructorType(type) { + if (getObjectFlags(type) & 16) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && ts.getModifierFlags(declaration) & 128) { + return true; + } + } + } + return false; + } + function isDeeplyNestedType(type, stack, depth) { + if (depth >= 5 && type.flags & 32768) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 32768 && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + if (sourceProp === targetProp) { + return -1; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0; + } + } + else { + if ((sourceProp.flags & 16777216) !== (targetProp.flags & 16777216)) { + return 0; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + if (source === target) { + return -1; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0; + } + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0; + } + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0; + } + result &= related; + } + } + } + var targetLen = target.parameters.length; + for (var i = 0; i < targetLen; i++) { + var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); + var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var related = compareTypes(s, t); + if (!related) { + return 0; + } + result &= related; + } + if (!ignoreReturnTypes) { + result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function isRestParameterIndex(signature, parameterIndex) { + return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getUnionType(types, true); + } + function isArrayType(type) { + return getObjectFlags(type) & 4 && type.target === globalArrayType; + } + function isArrayLikeType(type) { + return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isTupleLikeType(type) { + return !!getPropertyOfType(type, "0"); + } + function isUnitType(type) { + return (type.flags & (224 | 2048 | 4096)) !== 0; + } + function isLiteralType(type) { + return type.flags & 8 ? true : + type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + 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 & 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) { + return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + result |= getFalsyFlags(t); + } + return result; + } + function getFalsyFlags(type) { + return type.flags & 65536 ? getFalsyFlagsOfTypes(type.types) : + 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 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; + } + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && + getSignaturesOfType(type, 0).length === 0 && + getSignaturesOfType(type, 1).length === 0; + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + function getRegularTypeOfObjectLiteral(type) { + if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576; + regularNew.objectFlags |= 128; + type.regularType = regularNew; + return regularNew; + } + function getWidenedProperty(prop) { + var original = getTypeOfSymbol(prop); + var widened = getWidenedType(original); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getWidenedTypeOfObjectLiteral(type) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + members.set(prop.escapedName, prop.flags & 4 ? getWidenedProperty(prop) : prop); + } + var stringIndexInfo = getIndexInfoOfType(type, 0); + var numberIndexInfo = getIndexInfoOfType(type, 1); + return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + } + function getWidenedConstituentType(type) { + return type.flags & 6144 ? type : getWidenedType(type); + } + function getWidenedType(type) { + if (type.flags & 6291456) { + if (type.flags & 6144) { + return anyType; + } + if (getObjectFlags(type) & 128) { + return getWidenedTypeOfObjectLiteral(type); + } + if (type.flags & 65536) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 65536) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (getObjectFlags(type) & 128) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 2097152) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + return errorReported; + } + function reportImplicitAnyError(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + var diagnostic; + switch (declaration.kind) { + case 149: + case 148: + diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + break; + case 146: + diagnostic = declaration.dotDotDotToken ? + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + break; + case 176: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 228: + case 151: + case 150: + case 153: + case 154: + case 186: + case 187: + if (!declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + break; + default: + diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + } + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { + if (!reportWideningErrorsInType(type)) { + reportImplicitAnyError(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var count; + if (source.hasRestParameter && target.hasRestParameter) { + count = Math.max(sourceMax, targetMax); + } + else if (source.hasRestParameter) { + count = targetMax; + } + else if (target.hasRestParameter) { + count = sourceMax; + } + else { + count = Math.min(sourceMax, targetMax); + } + for (var i = 0; i < count; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + } + function createInferenceContext(signature, flags, baseInferences) { + var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + var context = mapper; + context.mappedTypes = signature.typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 || + objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 && type.symbol && type.symbol.flags & (16 | 8192 | 2048 | 32) || + objectFlags & 32 || + type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var inference = createInferenceInfo(typeParameter); + var inferences = [inference]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 16777216; + var members = ts.createSymbolTable(); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + members.set(prop.escapedName, inferredProp); + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + inference.candidates = undefined; + inferTypes(inferences, sourceType, templateType); + return inference.candidates && getUnionType(inference.candidates, true); + } + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + 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++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (64 | 32)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 540672) { + if (source.flags & 8388608 || source === silentNeverType) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (!inference.candidates || priority < inference.priority) { + inference.candidates = [source]; + inference.priority = priority; + } + else if (priority === inference.priority) { + inference.candidates.push(source); + } + if (!(priority & 4) && target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + } + else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + for (var i = 0; i < count; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 196608) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 196608) { + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + source = getApparentType(source); + if (source.flags & 32768) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (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); + } + } + } + } + function getInferenceInfoForType(type) { + if (type.flags & 540672) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144) { + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + var savePriority = priority; + priority |= 2; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return; + } + if (constraintType.flags & 16384) { + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target); + } + function inferFromProperties(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + for (var i = 0; i < len; i++) { + inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + } + } + function inferFromSignature(source, target) { + forEachMatchingParameterType(source, target, inferFromTypes); + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 0); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1) || + getIndexTypeOfType(source, 0) || + getImplicitIndexTypeOfType(source, 1); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (isTypeIdenticalTo(t, type)) { return true; } } + return false; } - return false; - } - ts.isMergedWithClass = isMergedWithClass; - function isFirstDeclarationOfKind(node, kind) { - return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; - } - ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; - function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); - } - ts.isNodeArray = isNodeArray; - function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13; - } - ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; - function isLiteralKind(kind) { - return 8 <= kind && kind <= 13; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 || kind === 13; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isLiteralExpression(node) { - return isLiteralKind(node.kind); - } - ts.isLiteralExpression = isLiteralExpression; - function isTemplateLiteralKind(kind) { - return 13 <= kind && kind <= 16; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateHead(node) { - return node.kind === 14; - } - ts.isTemplateHead = isTemplateHead; - function isTemplateMiddleOrTemplateTail(node) { - var kind = node.kind; - return kind === 15 - || kind === 16; - } - ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; - function isIdentifier(node) { - return node.kind === 71; - } - ts.isIdentifier = isIdentifier; - function isGeneratedIdentifier(node) { - return isIdentifier(node) && node.autoGenerateKind > 0; - } - ts.isGeneratedIdentifier = isGeneratedIdentifier; - function isModifier(node) { - return isModifierKind(node.kind); - } - ts.isModifier = isModifier; - function isQualifiedName(node) { - return node.kind === 143; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 144; - } - ts.isComputedPropertyName = isComputedPropertyName; - function isEntityName(node) { - var kind = node.kind; - return kind === 143 - || kind === 71; - } - ts.isEntityName = isEntityName; - function isPropertyName(node) { - var kind = node.kind; - return kind === 71 - || kind === 9 - || kind === 8 - || kind === 144; - } - ts.isPropertyName = isPropertyName; - function isModuleName(node) { - var kind = node.kind; - return kind === 71 - || kind === 9; - } - ts.isModuleName = isModuleName; - function isBindingName(node) { - var kind = node.kind; - return kind === 71 - || kind === 174 - || kind === 175; - } - ts.isBindingName = isBindingName; - function isTypeParameter(node) { - return node.kind === 145; - } - ts.isTypeParameter = isTypeParameter; - function isParameter(node) { - return node.kind === 146; - } - ts.isParameter = isParameter; - function isDecorator(node) { - return node.kind === 147; - } - ts.isDecorator = isDecorator; - function isMethodDeclaration(node) { - return node.kind === 151; - } - ts.isMethodDeclaration = isMethodDeclaration; - function isClassElement(node) { - var kind = node.kind; - return kind === 152 - || kind === 149 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 157 - || 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 - || kind === 262 - || kind === 263 - || kind === 151 - || kind === 153 - || kind === 154 - || kind === 247; - } - ts.isObjectLiteralElementLike = isObjectLiteralElementLike; - function isTypeNodeKind(kind) { - return (kind >= 158 && kind <= 173) - || kind === 119 - || kind === 133 - || kind === 134 - || kind === 122 - || kind === 136 - || kind === 137 - || kind === 99 - || kind === 105 - || kind === 139 - || kind === 95 - || kind === 130 - || kind === 201; - } - function isTypeNode(node) { - return isTypeNodeKind(node.kind); - } - ts.isTypeNode = isTypeNode; - function isArrayBindingPattern(node) { - return node.kind === 175; - } - ts.isArrayBindingPattern = isArrayBindingPattern; - function isObjectBindingPattern(node) { - return node.kind === 174; - } - ts.isObjectBindingPattern = isObjectBindingPattern; - function isBindingPattern(node) { - if (node) { - var kind = node.kind; - return kind === 175 - || kind === 174; - } - return false; - } - ts.isBindingPattern = isBindingPattern; - function isAssignmentPattern(node) { - var kind = node.kind; - return kind === 177 - || kind === 178; - } - ts.isAssignmentPattern = isAssignmentPattern; - function isBindingElement(node) { - return node.kind === 176; - } - ts.isBindingElement = isBindingElement; - function isArrayBindingElement(node) { - var kind = node.kind; - return kind === 176 - || kind === 200; - } - ts.isArrayBindingElement = isArrayBindingElement; - function isDeclarationBindingElement(bindingElement) { - switch (bindingElement.kind) { - case 226: - case 146: - case 176: - return true; - } - return false; - } - ts.isDeclarationBindingElement = isDeclarationBindingElement; - function isBindingOrAssignmentPattern(node) { - return isObjectBindingOrAssignmentPattern(node) - || isArrayBindingOrAssignmentPattern(node); - } - ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; - function isObjectBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 174: - case 178: - return true; - } - return false; - } - ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; - function isArrayBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 175: - case 177: - return true; - } - return false; - } - ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; - function isArrayLiteralExpression(node) { - return node.kind === 177; - } - ts.isArrayLiteralExpression = isArrayLiteralExpression; - function isObjectLiteralExpression(node) { - return node.kind === 178; - } - ts.isObjectLiteralExpression = isObjectLiteralExpression; - function isPropertyAccessExpression(node) { - return node.kind === 179; - } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isPropertyAccessOrQualifiedName(node) { - var kind = node.kind; - return kind === 179 - || kind === 143; - } - ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; - function isElementAccessExpression(node) { - return node.kind === 180; - } - ts.isElementAccessExpression = isElementAccessExpression; - function isBinaryExpression(node) { - return node.kind === 194; - } - ts.isBinaryExpression = isBinaryExpression; - function isConditionalExpression(node) { - return node.kind === 195; - } - ts.isConditionalExpression = isConditionalExpression; - function isCallExpression(node) { - return node.kind === 181; - } - ts.isCallExpression = isCallExpression; - function isTemplateLiteral(node) { - var kind = node.kind; - return kind === 196 - || kind === 13; - } - ts.isTemplateLiteral = isTemplateLiteral; - function isSpreadExpression(node) { - return node.kind === 198; - } - ts.isSpreadExpression = isSpreadExpression; - function isExpressionWithTypeArguments(node) { - return node.kind === 201; - } - ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 - || kind === 180 - || kind === 182 - || kind === 181 - || kind === 249 - || kind === 250 - || kind === 183 - || kind === 177 - || kind === 185 - || kind === 178 - || kind === 199 - || kind === 186 - || kind === 71 - || kind === 12 - || kind === 8 - || kind === 9 - || kind === 13 - || kind === 196 - || kind === 86 - || kind === 95 - || kind === 99 - || kind === 101 - || kind === 97 - || kind === 203 - || kind === 204; - } - function isLeftHandSideExpression(node) { - return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 - || kind === 193 - || kind === 188 - || kind === 189 - || kind === 190 - || kind === 191 - || kind === 184 - || isLeftHandSideExpressionKind(kind); - } - function isUnaryExpression(node) { - return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isUnaryExpression = isUnaryExpression; - function isExpressionKind(kind) { - return kind === 195 - || kind === 197 - || kind === 187 - || kind === 194 - || kind === 198 - || kind === 202 - || kind === 200 - || kind === 297 - || isUnaryExpressionKind(kind); - } - function isExpression(node) { - return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isExpression = isExpression; - function isAssertionExpression(node) { - var kind = node.kind; - return kind === 184 - || kind === 202; - } - ts.isAssertionExpression = isAssertionExpression; - function isPartiallyEmittedExpression(node) { - return node.kind === 296; - } - ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; - function isNotEmittedStatement(node) { - return node.kind === 295; - } - ts.isNotEmittedStatement = isNotEmittedStatement; - function isNotEmittedOrPartiallyEmittedNode(node) { - return isNotEmittedStatement(node) - || isPartiallyEmittedExpression(node); - } - ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - function isOmittedExpression(node) { - return node.kind === 200; - } - ts.isOmittedExpression = isOmittedExpression; - function isTemplateSpan(node) { - return node.kind === 205; - } - ts.isTemplateSpan = isTemplateSpan; - function isBlock(node) { - return node.kind === 207; - } - ts.isBlock = isBlock; - function isConciseBody(node) { - return isBlock(node) - || isExpression(node); - } - ts.isConciseBody = isConciseBody; - function isFunctionBody(node) { - return isBlock(node); - } - ts.isFunctionBody = isFunctionBody; - function isForInitializer(node) { - return isVariableDeclarationList(node) - || isExpression(node); - } - ts.isForInitializer = isForInitializer; - function isVariableDeclaration(node) { - return node.kind === 226; - } - ts.isVariableDeclaration = isVariableDeclaration; - function isVariableDeclarationList(node) { - return node.kind === 227; - } - ts.isVariableDeclarationList = isVariableDeclarationList; - function isCaseBlock(node) { - return node.kind === 235; - } - ts.isCaseBlock = isCaseBlock; - function isModuleBody(node) { - var kind = node.kind; - return kind === 234 - || kind === 233 - || kind === 71; - } - ts.isModuleBody = isModuleBody; - function isNamespaceBody(node) { - var kind = node.kind; - return kind === 234 - || kind === 233; - } - ts.isNamespaceBody = isNamespaceBody; - function isJSDocNamespaceBody(node) { - var kind = node.kind; - return kind === 71 - || kind === 233; - } - ts.isJSDocNamespaceBody = isJSDocNamespaceBody; - function isImportEqualsDeclaration(node) { - return node.kind === 237; - } - ts.isImportEqualsDeclaration = isImportEqualsDeclaration; - function isImportDeclaration(node) { - return node.kind === 238; - } - ts.isImportDeclaration = isImportDeclaration; - function isImportClause(node) { - return node.kind === 239; - } - ts.isImportClause = isImportClause; - function isNamedImportBindings(node) { - var kind = node.kind; - return kind === 241 - || kind === 240; - } - ts.isNamedImportBindings = isNamedImportBindings; - function isImportSpecifier(node) { - return node.kind === 242; - } - ts.isImportSpecifier = isImportSpecifier; - function isNamedExports(node) { - return node.kind === 245; - } - ts.isNamedExports = isNamedExports; - function isExportSpecifier(node) { - 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; - } - ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; - function isDeclarationKind(kind) { - return kind === 187 - || kind === 176 - || kind === 229 - || kind === 199 - || kind === 152 - || kind === 232 - || kind === 264 - || kind === 246 - || kind === 228 - || kind === 186 - || kind === 153 - || kind === 239 - || kind === 237 - || kind === 242 - || kind === 230 - || kind === 253 - || kind === 151 - || kind === 150 - || kind === 233 - || kind === 236 - || kind === 240 - || kind === 146 - || kind === 261 - || kind === 149 - || kind === 148 - || kind === 154 - || kind === 262 - || kind === 231 - || kind === 145 - || kind === 226 - || kind === 290; - } - function isDeclarationStatementKind(kind) { - return kind === 228 - || kind === 247 - || kind === 229 - || kind === 230 - || kind === 231 - || kind === 232 - || kind === 233 - || kind === 238 - || kind === 237 - || kind === 244 - || kind === 243 - || kind === 236; - } - function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 - || kind === 217 - || kind === 225 - || kind === 212 - || kind === 210 - || kind === 209 - || kind === 215 - || kind === 216 - || kind === 214 - || kind === 211 - || kind === 222 - || kind === 219 - || kind === 221 - || kind === 223 - || kind === 224 - || kind === 208 - || kind === 213 - || kind === 220 - || kind === 295 - || kind === 299 - || kind === 298; - } - function isDeclaration(node) { - return isDeclarationKind(node.kind); - } - ts.isDeclaration = isDeclaration; - function isDeclarationStatement(node) { - return isDeclarationStatementKind(node.kind); - } - ts.isDeclarationStatement = isDeclarationStatement; - function isStatementButNotDeclaration(node) { - return isStatementKindButNotDeclarationKind(node.kind); - } - ts.isStatementButNotDeclaration = isStatementButNotDeclaration; - function isStatement(node) { - var kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) - || isDeclarationStatementKind(kind) - || kind === 207; - } - ts.isStatement = isStatement; - function isModuleReference(node) { - var kind = node.kind; - return kind === 248 - || kind === 143 - || kind === 71; - } - ts.isModuleReference = isModuleReference; - function isJsxOpeningElement(node) { - return node.kind === 251; - } - ts.isJsxOpeningElement = isJsxOpeningElement; - function isJsxClosingElement(node) { - return node.kind === 252; - } - ts.isJsxClosingElement = isJsxClosingElement; - function isJsxTagNameExpression(node) { - var kind = node.kind; - return kind === 99 - || kind === 71 - || kind === 179; - } - ts.isJsxTagNameExpression = isJsxTagNameExpression; - function isJsxChild(node) { - var kind = node.kind; - return kind === 249 - || kind === 256 - || kind === 250 - || kind === 10; - } - ts.isJsxChild = isJsxChild; - function isJsxAttributes(node) { - var kind = node.kind; - return kind === 254; - } - ts.isJsxAttributes = isJsxAttributes; - function isJsxAttributeLike(node) { - var kind = node.kind; - return kind === 253 - || kind === 255; - } - ts.isJsxAttributeLike = isJsxAttributeLike; - function isJsxSpreadAttribute(node) { - return node.kind === 255; - } - ts.isJsxSpreadAttribute = isJsxSpreadAttribute; - function isJsxAttribute(node) { - return node.kind === 253; - } - ts.isJsxAttribute = isJsxAttribute; - function isStringLiteralOrJsxExpression(node) { - var kind = node.kind; - return kind === 9 - || kind === 256; - } - ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; - function isJsxOpeningLikeElement(node) { - var kind = node.kind; - return kind === 251 - || kind === 250; - } - ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; - function isCaseOrDefaultClause(node) { - var kind = node.kind; - return kind === 257 - || kind === 258; - } - ts.isCaseOrDefaultClause = isCaseOrDefaultClause; - function isHeritageClause(node) { - return node.kind === 259; - } - ts.isHeritageClause = isHeritageClause; - function isCatchClause(node) { - return node.kind === 260; - } - ts.isCatchClause = isCatchClause; - function isPropertyAssignment(node) { - return node.kind === 261; - } - ts.isPropertyAssignment = isPropertyAssignment; - function isShorthandPropertyAssignment(node) { - return node.kind === 262; - } - ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; - function isEnumMember(node) { - return node.kind === 264; - } - ts.isEnumMember = isEnumMember; - function isSourceFile(node) { - return node.kind === 265; - } - ts.isSourceFile = isSourceFile; - function isWatchSet(options) { - 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)); + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } } - var tmp = previous; - previous = current; - current = tmp; + return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } - return previous[previous.length - 1]; - } - ts.levenshtein = levenshtein; -})(ts || (ts = {})); -(function (ts) { - function getDefaultLibFileName(options) { - switch (options.target) { - case 5: - return "lib.esnext.full.d.ts"; - case 4: - return "lib.es2017.full.d.ts"; - case 3: - return "lib.es2016.full.d.ts"; - case 2: - return "lib.es6.d.ts"; - default: - return "lib.d.ts"; + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190 | 262144); } - } - ts.getDefaultLibFileName = getDefaultLibFileName; - function textSpanEnd(span) { - return span.start + span.length; - } - ts.textSpanEnd = textSpanEnd; - function textSpanIsEmpty(span) { - return span.length === 0; - } - ts.textSpanIsEmpty = textSpanIsEmpty; - function textSpanContainsPosition(span, position) { - return position >= span.start && position < textSpanEnd(span); - } - ts.textSpanContainsPosition = textSpanContainsPosition; - function textSpanContainsTextSpan(span, other) { - return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); - } - ts.textSpanContainsTextSpan = textSpanContainsTextSpan; - function textSpanOverlapsWith(span, other) { - var overlapStart = Math.max(span.start, other.start); - var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); - return overlapStart < overlapEnd; - } - ts.textSpanOverlapsWith = textSpanOverlapsWith; - function textSpanOverlap(span1, span2) { - var overlapStart = Math.max(span1.start, span2.start); - var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (overlapStart < overlapEnd) { - return createTextSpanFromBounds(overlapStart, overlapEnd); + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + if (inference.candidates) { + var signature = context.signature; + var widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; + var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? + getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2) { + inferredType = silentNeverType; + } + else { + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4)); + } + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; } - return undefined; - } - ts.textSpanOverlap = textSpanOverlap; - function textSpanIntersectsWithTextSpan(span, other) { - return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; - } - ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; - function textSpanIntersectsWith(span, start, length) { - var end = start + length; - return start <= textSpanEnd(span) && end >= span.start; - } - ts.textSpanIntersectsWith = textSpanIntersectsWith; - function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { - var end1 = start1 + length1; - var end2 = start2 + length2; - return start2 <= end1 && end2 >= start1; - } - ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; - function textSpanIntersectsWithPosition(span, position) { - return position <= textSpanEnd(span) && position >= span.start; - } - ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; - function textSpanIntersection(span1, span2) { - var intersectStart = Math.max(span1.start, span2.start); - var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); - if (intersectStart <= intersectEnd) { - return createTextSpanFromBounds(intersectStart, intersectEnd); + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; } - return undefined; - } - ts.textSpanIntersection = textSpanIntersection; - function createTextSpan(start, length) { - if (start < 0) { - throw new Error("start < 0"); + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; } - if (length < 0) { - throw new Error("length < 0"); + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 107455 | 1048576, ts.Diagnostics.Cannot_find_name_0, node, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + } + return links.resolvedSymbol; } - return { start: start, length: length }; - } - ts.createTextSpan = createTextSpan; - function createTextSpanFromBounds(start, end) { - return createTextSpan(start, end - start); - } - ts.createTextSpanFromBounds = createTextSpanFromBounds; - function textChangeRangeNewSpan(range) { - return createTextSpan(range.span.start, range.newLength); - } - ts.textChangeRangeNewSpan = textChangeRangeNewSpan; - function textChangeRangeIsUnchanged(range) { - return textSpanIsEmpty(range.span) && range.newLength === 0; - } - ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; - function createTextChangeRange(span, newLength) { - if (newLength < 0) { - throw new Error("newLength < 0"); + function isInTypeQuery(node) { + return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); } - return { span: span, newLength: newLength }; - } - ts.createTextChangeRange = createTextChangeRange; - ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); - function collapseTextChangeRangesAcrossMultipleVersions(changes) { - if (changes.length === 0) { - return ts.unchangedTextChangeRange; + function getFlowCacheKey(node) { + if (node.kind === 71) { + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 99) { + return "0"; + } + if (node.kind === 179) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + } + if (node.kind === 176) { + var container = node.parent.parent; + var key = container.kind === 176 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; } - if (changes.length === 1) { - return changes[0]; + function getLeftmostIdentifierOrThis(node) { + switch (node.kind) { + case 71: + case 99: + return node; + case 179: + return getLeftmostIdentifierOrThis(node.expression); + } + return undefined; } - var change0 = changes[0]; - var oldStartN = change0.span.start; - var oldEndN = textSpanEnd(change0.span); - var newEndN = oldStartN + change0.newLength; - for (var i = 1; i < changes.length; i++) { - var nextChange = changes[i]; - var oldStart1 = oldStartN; - var oldEnd1 = oldEndN; - var newEnd1 = newEndN; - var oldStart2 = nextChange.span.start; - var oldEnd2 = textSpanEnd(nextChange.span); - var newEnd2 = oldStart2 + nextChange.newLength; - oldStartN = Math.min(oldStart1, oldStart2); - oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); - newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + function getBindingElementNameText(element) { + if (element.parent.kind === 174) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 71: + return ts.unescapeLeadingUnderscores(name.escapedText); + case 144: + return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + case 9: + case 8: + return name.text; + default: + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + element.parent.elements.indexOf(element); + } } - return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); - } - ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; - function getTypeParameterOwner(d) { - if (d && d.kind === 145) { - for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230) { - return current; + function isMatchingReference(source, target) { + switch (source.kind) { + case 71: + return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 226 || target.kind === 176) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 99: + return target.kind === 99; + case 97: + return target.kind === 97; + case 179: + return target.kind === 179 && + source.name.escapedText === target.name.escapedText && + isMatchingReference(source.expression, target.expression); + case 176: + if (target.kind !== 179) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 176 && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 226) { + var maybeId = source.parent.parent.initializer; + return maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function containsMatchingReference(source, target) { + while (source.kind === 179) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 179 && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 71) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 179) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 65536) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 179 && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 65536)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 8192) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 2) { + return strictNullChecks ? 4079361 : 4194049; + } + if (flags & 32) { + var isEmpty = type.value === ""; + return strictNullChecks ? + isEmpty ? 3030785 : 1982209 : + isEmpty ? 3145473 : 4194049; + } + if (flags & (4 | 16)) { + return strictNullChecks ? 4079234 : 4193922; + } + if (flags & 64) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 3030658 : 1982082 : + isZero ? 3145346 : 4193922; + } + if (flags & 8) { + return strictNullChecks ? 4078980 : 4193668; + } + if (flags & 136) { + return strictNullChecks ? + type === falseType ? 3030404 : 1981828 : + type === falseType ? 3145092 : 4193668; + } + if (flags & 32768) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 : 8376288 : + strictNullChecks ? 6166480 : 8378320; + } + if (flags & (1024 | 2048)) { + return 2457472; + } + if (flags & 4096) { + return 2340752; + } + if (flags & 512) { + return strictNullChecks ? 1981320 : 4193160; + } + if (flags & 16777216) { + return strictNullChecks ? 6166480 : 8378320; + } + if (flags & 540672) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 196608) { + return getTypeFactsOfTypes(type.types); + } + return 8388607; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 131072), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getTypeOfPropertyOfType(type, text) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || + getIndexTypeOfType(type, 0) || + unknownType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + checkIteratedTypeOrElementType(type, undefined, false, false) || + unknownType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 194 && parent.parent.left === parent || + parent.parent.kind === 216 && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 215: + return stringType; + case 216: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; + case 194: + return getAssignedTypeOfBinaryExpression(parent); + case 188: + return undefinedType; + case 177: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 198: + return getAssignedTypeOfSpreadExpression(parent); + case 261: + return getAssignedTypeOfPropertyAssignment(parent); + case 262: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return unknownType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 174 ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 215) { + return stringType; + } + if (node.parent.parent.kind === 216) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; + } + return unknownType; + } + function getInitialType(node) { + return node.kind === 226 ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node) { + return node.kind === 226 || node.kind === 176 ? + getInitialType(node) : + getAssignedType(node); + } + function isEmptyArrayAssignment(node) { + return node.kind === 226 && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 176 && node.parent.kind === 194 && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 185: + return getReferenceCandidate(node.expression); + case 194: + switch (node.operatorToken.kind) { + case 58: + return getReferenceCandidate(node.left); + case 26: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 185 || + parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || + parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 257) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + var type = getTypeOfSwitchClause(clause); + if (type === undefined) { + return links.switchTypes = ts.emptyArray; + } + links.switchTypes.push(type); + } + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 65536) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 65536) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; + } + function mapType(type, mapper) { + if (!(type.flags & 65536)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + function createEvolvingArrayType(elementType) { + var result = createObjectType(256); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 ? + autoArrayType : + createArrayType(elementType.flags & 65536 ? + getUnionType(elementType.types, true) : + elementType); + } + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; + if (!(t.flags & 8192)) { + if (!(getObjectFlags(t) & 256)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.escapedText === "length" || + parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 180 && + parent.expression === root && + parent.parent.kind === 194 && + parent.parent.operatorToken.kind === 58 && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 97) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { + return declaredType; + } + var visitedFlowStart = visitedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + visitedFlowCount = visitedFlowStart; + var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + while (true) { + if (flow.flags & 1024) { + for (var i = visitedFlowStart; i < visitedFlowCount; i++) { + if (visitedFlowNodes[i] === flow) { + return visitedFlowTypes[i]; + } + } + } + var type = void 0; + if (flow.flags & 4096) { + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048) { + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 96) { + type = getTypeAtFlowCondition(flow); + } + else if (flow.flags & 128) { + type = getTypeAtSwitchClause(flow); + } + else if (flow.flags & 12) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flow.flags & 4 ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flow.flags & 256) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 2) { + var container = flow.container; + if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { + flow = container.flowNode; + continue; + } + type = initialType; + } + else { + type = convertAutoToAny(declaredType); + } + if (flow.flags & 1024) { + visitedFlowNodes[visitedFlowCount] = flow; + visitedFlowTypes[visitedFlowCount] = type; + visitedFlowCount++; + } + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; + } + if (containsMatchingReference(reference, node)) { + return declaredType; + } + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 181 ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256) { + var evolvedType_1 = type; + if (node.kind === 181) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 8192) { + return flowType; + } + var assumeTrue = (flow.flags & 32) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 && antecedent.lock.locked) { + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + if (type === declaredType && declaredType === initialType) { + return type; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); + } + } + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (type === declaredType) { + break; + } + } + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + return expr.kind === 179 && + computedType.flags & 65536 && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(computedType, expr.name.escapedText); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.escapedText; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 58: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 32: + case 33: + case 34: + case 35: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 189 && right_1.kind === 9) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 189 && left_1.kind === 9) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 93: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 26: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1) { + return type; + } + if (operator === 33 || operator === 35) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 6144) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 32 || operator === 33; + var facts = doubleEquals ? + assumeTrue ? 65536 : 524288 : + value.kind === 95 ? + assumeTrue ? 32768 : 262144 : + assumeTrue ? 16384 : 131072; + return getTypeWithFacts(type, facts); + } + if (type.flags & 16810497) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + if (containsMatchingReference(reference, target)) { + return declaredType; + } + return type; + } + if (operator === 33 || operator === 35) { + assumeTrue = !assumeTrue; + } + if (assumeTrue && !(type.flags & 65536)) { + var targetType = typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 540672) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 : + typeofNEFacts.get(literal.text) || 8192; + return getTypeWithFacts(type, facts); + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + if (containsMatchingReference(reference, left)) { + return declaredType; + } + return type; + } + var rightType = getTypeOfExpression(expr.right); + if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + var constructSignatures = void 0; + if (getObjectFlags(rightType) & 2) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; + } + else if (getObjectFlags(rightType) & 16) { + constructSignatures = getSignaturesOfType(rightType, 1); + } + if (constructSignatures && constructSignatures.length) { + targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + } + } + if (targetType) { + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + } + return type; + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + if (type.flags & 65536) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 8192)) { + return assignableType; + } + } + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 71: + case 99: + case 97: + case 179: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 181: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 185: + return narrowType(type, expr.expression, assumeTrue); + case 194: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 192: + if (expr.operator === 51) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + if (location.kind === 71) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 234 || + node.kind === 265 || + node.kind === 149; + }); + } + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304)) { + links.flags |= 4194304; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); + } + function markParameterAssignments(node) { + if (node.kind === 71) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 146 && + declaration.initializer && + getFalsyFlags(declaredType) & 2048 && + !(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) { + return unknownType; + } + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2) { + if (container.kind === 187) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192; + return getTypeOfSymbol(symbol); + } + if (isNonLocalAlias(symbol, 107455) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32) { + if (declaration.kind === 229 + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 199) { + var container = ts.getThisContainer(node, false); + while (container !== undefined) { + if (container.parent === declaration) { + if (container.kind === 149 && ts.hasModifier(container, 32)) { + getNodeLinks(declaration).flags |= 8388608; + getNodeLinks(node).flags |= 16777216; + } + break; + } + container = ts.getThisContainer(container, false); + } + } + } + checkCollisionWithCapturedSuperVariable(node, node); + checkCollisionWithCapturedThisVariable(node, node); + checkCollisionWithCapturedNewTargetVariable(node, node); + checkNestedBlockScopedBinding(node, symbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152; + if (localOrExportSymbol.flags & 3) { + if (assignmentKind === 1) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + var isParameter = ts.getRootDeclaration(declaration).kind === 146; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || + flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + var assumeInitialized = isParameter || isAlias || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || + node.parent.kind === 203 || + ts.isInAmbientContext(declaration); + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : + type === autoType || type === autoArrayType ? undefinedType : + getNullableType(type, 2048); + var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + 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); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 || + (symbol.flags & (2 | 32)) === 0 || + symbol.valueDeclaration.parent.kind === 260) { + return; + } + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + getNodeLinks(current).flags |= 65536; + } + if (container.kind === 214 && + ts.getAncestor(symbol.valueDeclaration, 227).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152; + } + getNodeLinks(symbol.valueDeclaration).flags |= 262144; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072; + } + } + function isAssignedInBodyOfForStatement(node, container) { + var current = node; + while (current.parent.kind === 185) { + current = current.parent; + } + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 192 || current.parent.kind === 193)) { + var expr = current.parent; + isAssigned = expr.operator === 43 || expr.operator === 44; + } + if (!isAssigned) { + return false; + } + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2; + if (container.kind === 149 || container.kind === 152) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4; + } + else { + getNodeLinks(container).flags |= 4; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + if (!superCall || superCall.end > node.pos) { + error(node, diagnosticMessage); } } } - } - ts.getTypeParameterOwner = getTypeParameterOwner; - function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); - } - ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 176 || ts.isBindingPattern(node))) { - node = node.parent; - } - return node; - } - function getCombinedModifierFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = ts.getModifierFlags(node); - if (node.kind === 226) { - node = node.parent; - } - if (node && node.kind === 227) { - flags |= ts.getModifierFlags(node); - node = node.parent; - } - if (node && node.kind === 208) { - flags |= ts.getModifierFlags(node); - } - return flags; - } - ts.getCombinedModifierFlags = getCombinedModifierFlags; - function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 226) { - node = node.parent; - } - if (node && node.kind === 227) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 208) { - flags |= node.flags; - } - return flags; - } - ts.getCombinedNodeFlags = getCombinedNodeFlags; - function validateLocaleAndSetLanguage(locale, sys, errors) { - var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); - if (!matchResult) { - if (errors) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + function checkThisExpression(node) { + var container = ts.getThisContainer(node, true); + var needToCaptureLexicalThis = false; + if (container.kind === 152) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } - return; + if (container.kind === 187) { + container = ts.getThisContainer(container, false); + needToCaptureLexicalThis = (languageVersion < 2); + } + switch (container.kind) { + case 233: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + break; + case 232: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + break; + case 152: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + } + break; + case 149: + case 148: + if (ts.getModifierFlags(container) & 32) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + } + break; + case 144: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node, container); + } + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + if (container.kind === 186 && + container.parent.kind === 194 && + ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { + var className = container.parent + .left + .expression + .expression; + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { + return getInferredClassType(classSymbol); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return thisType; + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + } + if (noImplicitThis) { + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return anyType; } - var language = matchResult[1]; - var territory = matchResult[3]; - if (!trySetLanguageAndTerritory(language, territory, errors)) { - trySetLanguageAndTerritory(language, undefined, errors); + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 273) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this") { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } } - function trySetLanguageAndTerritory(language, territory, errors) { - var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); - var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); - var filePath = ts.combinePaths(containingDirectoryPath, language); - if (territory) { - filePath = filePath + "-" + territory; + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; + var container = ts.getSuperContainer(node, true); + var needToCaptureLexicalThis = false; + if (!isCallExpression) { + while (container && container.kind === 187) { + container = ts.getSuperContainer(container, true); + needToCaptureLexicalThis = languageVersion < 2; + } } - filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); - if (!sys.fileExists(filePath)) { - return false; + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); + if (current && current.kind === 144) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return unknownType; } - var fileContents = ""; - try { - fileContents = sys.readFile(filePath); + if (!isCallExpression && container.kind === 152) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); } - catch (e) { - if (errors) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + if ((ts.getModifierFlags(container) & 32) || isCallExpression) { + nodeCheckFlag = 512; + } + else { + nodeCheckFlag = 256; + } + getNodeLinks(node).flags |= nodeCheckFlag; + if (container.kind === 151 && ts.getModifierFlags(container) & 256) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096; + } + else { + getNodeLinks(container).flags |= 2048; + } + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 178) { + if (languageVersion < 2) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + return anyType; + } + } + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return unknownType; + } + return nodeCheckFlag === 512 + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + return container.kind === 152; + } + else { + if (ts.isClassLike(container.parent) || container.parent.kind === 178) { + if (ts.getModifierFlags(container) & 32) { + return container.kind === 151 || + container.kind === 150 || + container.kind === 153 || + container.kind === 154; + } + else { + return container.kind === 151 || + container.kind === 150 || + container.kind === 153 || + container.kind === 154 || + container.kind === 149 || + container.kind === 148 || + container.kind === 152; + } + } } return false; } - try { - ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + function getContainingObjectLiteral(func) { + return (func.kind === 151 || + func.kind === 153 || + func.kind === 154) && func.parent.kind === 178 ? func.parent : + func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 187) { + return undefined; } - catch (e) { - if (errors) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 261) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { + var target = func.parent.left; + if (target.kind === 179 || target.kind === 180) { + return checkExpressionCached(target.expression); + } + } + } + return undefined; + } + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); + } + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + } + } + } + return undefined; + } + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 146) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, true, false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 176) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + return functionFlags & 2 + ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) + : contextualReturnType; + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (node.parent.kind === 146 && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + if (functionDecl.kind === 152 || + ts.getEffectiveReturnTypeNode(functionDecl) || + isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + } + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); + if (argIndex >= 0) { + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + return getTypeAtPosition(signature, argIndex); + } + return undefined; + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 183) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var operator = binaryExpression.operatorToken.kind; + if (ts.isAssignmentOperator(operator)) { + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { + return undefined; + } + if (node === binaryExpression.right) { + return getTypeOfExpression(binaryExpression.left); + } + } + else if (operator === 54) { + var type = getContextualType(binaryExpression); + if (!type && node === binaryExpression.right) { + type = getTypeOfExpression(binaryExpression.left); + } + return type; + } + else if (operator === 53 || operator === 26) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } + return undefined; + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; + return prop ? getTypeOfSymbol(prop) : undefined; + }); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + } + function contextualTypeIsTupleLikeType(type) { + return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + } + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (isInsideWithStatementBody(node)) { + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!ts.hasDynamicName(element)) { + var symbolName = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || + getIndexTypeOfContextualType(type, 0); + } + return undefined; + } + function getContextualTypeForElementExpression(node) { + var arrayLiteral = node.parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + if (type) { + var index = ts.indexOf(arrayLiteral.elements, node); + return getTypeOfPropertyOfContextualType(type, "" + index) + || getIndexTypeOfContextualType(type, 1) + || getIteratedTypeOrElementType(type, undefined, false, false, false); + } + return undefined; + } + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForJsxExpression(node) { + var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? + node.parent.parent : + node.parent.openingElement.attributes; + var attributesType = getContextualType(jsxAttributes); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + if (ts.isJsxAttribute(node.parent)) { + return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + } + else if (node.parent.kind === 249) { + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + } + else { + return attributesType; + } + } + function getContextualTypeForJsxAttribute(attribute) { + var attributesType = getContextualType(attribute.parent); + if (ts.isJsxAttribute(attribute)) { + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + } + else { + return attributesType; + } + } + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); + return type && getApparentType(type); + } + function getContextualType(node) { + if (isInsideWithStatementBody(node)) { + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 176: + return getContextualTypeForInitializerExpression(node); + case 187: + case 219: + return getContextualTypeForReturnExpression(node); + case 197: + return getContextualTypeForYieldOperand(parent); + case 181: + case 182: + return getContextualTypeForArgument(parent, node); + case 184: + case 202: + return getTypeFromTypeNode(parent.type); + case 194: + return getContextualTypeForBinaryOperand(node); + case 261: + case 262: + return getContextualTypeForObjectLiteralElement(parent); + case 263: + return getApparentTypeOfContextualType(parent.parent); + case 177: + return getContextualTypeForElementExpression(node); + case 195: + return getContextualTypeForConditionalOperand(node); + case 205: + ts.Debug.assert(parent.parent.kind === 196); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 185: + return getContextualType(parent); + case 256: + return getContextualTypeForJsxExpression(parent); + case 253: + case 255: + return getContextualTypeForJsxAttribute(parent); + case 251: + case 250: + return getAttributesTypeFromJsxOpeningLikeElement(parent); + } + return undefined; + } + function getContextualMapper(node) { + node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return node ? node.contextualMapper : identityMapper; + } + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfStructuredType(type, 0); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 186 || node.kind === 187; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 65536)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { + return undefined; + } + else { + signatureList.push(signature); + } + } + } + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + result.resolvedReturnType = undefined; + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); + } + function hasDefaultValue(node) { + return (node.kind === 176 && !!node.initializer) || + (node.kind === 194 && node.operatorToken.kind === 58); + } + function checkArrayLiteral(node, checkMode) { + var elements = node.elements; + var hasSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; + if (inDestructuringPattern && e.kind === 198) { + var restArrayType = checkExpression(e.expression, checkMode); + var restElementType = getIndexTypeOfType(restArrayType, 1) || + getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var type = checkExpressionForMutableLocation(e, checkMode); + elementTypes.push(type); + } + hasSpreadElement = hasSpreadElement || e.kind === 198; + } + if (!hasSpreadElement) { + if (inDestructuringPattern && elementTypes.length) { + var type = cloneTypeReference(createTupleType(elementTypes)); + type.pattern = node; + return type; + } + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { + var patternElements = pattern.elements; + for (var i = elementTypes.length; i < patternElements.length; i++) { + var patternElement = patternElements[i]; + if (hasDefaultValue(patternElement)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else { + if (patternElement.kind !== 200) { + error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(unknownType); + } + } + } + if (elementTypes.length) { + return createTupleType(elementTypes); + } + } + } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, true) : + strictNullChecks ? neverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 144: + return isNumericComputedName(name); + case 71: + return isNumericLiteralName(name.escapedText); + case 8: + case 9: + return isNumericLiteralName(name.text); + default: + return false; + } + } + function isNumericComputedName(name) { + return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || isTypeOfKind(type, kind); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + 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 { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; + return createIndexInfo(unionType, false); + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable = ts.createSymbolTable(); + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); + var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + var isInJSFile = ts.isInJavaScriptFile(node); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 261 || + memberDecl.kind === 262 || + ts.isObjectLiteralMethod(memberDecl)) { + var jsdocType = void 0; + if (isInJSFile) { + jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); + } + var type = void 0; + if (memberDecl.kind === 261) { + type = checkPropertyAssignment(memberDecl, checkMode); + } + else if (memberDecl.kind === 151) { + type = checkObjectLiteralMethod(memberDecl, checkMode); + } + else { + ts.Debug.assert(memberDecl.kind === 262); + type = checkExpressionForMutableLocation(memberDecl.name, checkMode); + } + if (jsdocType) { + checkTypeAssignableTo(type, jsdocType, memberDecl); + type = jsdocType; + } + typeFlags |= type.flags; + var prop = createSymbol(4 | member.flags, member.escapedName); + if (inDestructuringPattern) { + var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216; + } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } + } + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 263) { + if (languageVersion < 2) { + checkExternalEmitHelpers(memberDecl, 2); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type); + offset = i + 1; + continue; + } + else { + ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); + checkNodeDeferred(memberDecl); + } + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName)) { + if (!(prop.flags & 16777216)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + } + if (spread.flags & 32768) { + spread.flags |= propagatedFlags; + spread.flags |= 1048576; + spread.objectFlags |= 128; + spread.symbol = node.symbol; + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; + var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; + result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); + result.objectFlags |= 128; + if (patternWithComputedProperties) { + result.objectFlags |= 512; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144)) { + propagatedFlags |= (result.flags & 14680064); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 | 4096 | 2048 | 16777216) || + type.flags & 32768 && !isGenericMappedType(type) || + type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + } + function checkJsxSelfClosingElement(node) { + checkJsxOpeningLikeElement(node); + return getJsxGlobalElementType() || anyType; + } + function checkJsxElement(node) { + checkJsxOpeningLikeElement(node.openingElement); + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + return getJsxGlobalElementType() || anyType; + } + function isUnhyphenatedJsxName(name) { + return name.indexOf("-") < 0; + } + function isJsxIntrinsicIdentifier(tagName) { + switch (tagName.kind) { + case 179: + case 99: + return false; + case 71: + return ts.isIntrinsicJsxName(tagName.escapedText); + default: + ts.Debug.fail(); + } + } + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + 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; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = attributeDecl.initializer ? + checkExpression(attributeDecl.initializer, checkMode) : + trueType; + var attributeSymbol = createSymbol(4 | 33554432 | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + attributesArray.push(attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 255); + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpression(attributeDecl.expression); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createSymbolTable(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; + if (!filter || filter(attr)) { + attributesTable.set(attr.escapedName, attr); + } + } + } + var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; + if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { + var childrenTypes = []; + 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); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { + error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName)); + } + var childrenPropSymbol = createSymbol(4 | 33554432, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + createArrayType(getUnionType(childrenTypes, false)); + attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + } + } + 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, ts.emptyArray, ts.emptyArray, undefined, undefined); + result.flags |= 33554432 | 4194304; + result.objectFlags |= 128; + return result; + } + } + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); + } + function getJsxType(name) { + var jsxType = jsxTypes.get(name); + if (jsxType === undefined) { + jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); + } + return jsxType; + } + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + if (!ts.isIdentifier(node.tagName)) + throw ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1; + return links.resolvedSymbol = intrinsicProp; + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + links.jsxFlags |= 2; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + function getJsxElementInstanceType(node, valueType) { + ts.Debug.assert(!(valueType.flags & 65536)); + if (isTypeAny(valueType)) { + return anyType; + } + var signatures = getSignaturesOfType(valueType, 1); + if (signatures.length === 0) { + signatures = getSignaturesOfType(valueType, 0); + if (signatures.length === 0) { + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return unknownType; + } + } + 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); + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + function getJsxElementPropertiesName() { + if (!_hasComputedJsxElementPropertiesName) { + _hasComputedJsxElementPropertiesName = true; + _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); + } + return _jsxElementPropertiesName; + } + function getJsxElementChildrenPropertyname() { + if (!_hasComputedJsxElementChildrenPropertyName) { + _hasComputedJsxElementChildrenPropertyName = true; + _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); + } + 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)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); + 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) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + } + } + } + return undefined; + } + function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { + ts.Debug.assert(!(elementType.flags & 65536)); + if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + var candidatesOutArray = []; + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + var result = void 0; + var allMatchingAttributesType = void 0; + for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { + 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++) { + var attribute = _b[_a]; + if (ts.isJsxAttribute(attribute) && + isUnhyphenatedJsxName(attribute.name.escapedText) && + !getPropertyOfType(paramType, attribute.name.escapedText)) { + shouldBeCandidate = false; + break; + } + } + if (shouldBeCandidate) { + result = intersectTypes(result, paramType); + } + allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); + } + } + if (!result) { + result = allMatchingAttributesType; + } + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + result = intersectTypes(intrinsicAttributes, result); + } + return result; + } + } + return undefined; + } + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { + if (!elementType) { + elementType = checkExpression(openingLikeElement.tagName); + } + if (elementType.flags & 65536) { + var types = elementType.types; + return getUnionType(types.map(function (type) { + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); + }), true); + } + if (elementType.flags & 2) { + return anyType; + } + else if (elementType.flags & 32) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); + if (indexSignatureType) { + return indexSignatureType; + } + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + } + return anyType; + } + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? + tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : + defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); + if (statelessAttributesType) { + return statelessAttributesType; + } + if (elementClassType) { + checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + if (isTypeAny(elemInstanceType)) { + return elemInstanceType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + return anyType; + } + else if (propsName === "") { + return elemInstanceType; + } + else { + var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + if (!attributesType) { + return emptyObjectType; + } + else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + return attributesType; + } + else { + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; + } + else { + return links.resolvedJsxElementAttributesType = unknownType; + } + } + return links.resolvedJsxElementAttributesType; + } + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var elemClassType = getJsxGlobalElementClassType(); + return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); + } + return links.resolvedJsxElementAttributesType; + } + function getAllAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, true); + } + } + function getAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, false); + } + } + function getJsxAttributePropertySymbol(attrib) { + var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); + var prop = getPropertyOfType(attributesType, attrib.name.escapedText); + return prop || unknownSymbol; + } + function getJsxGlobalElementClassType() { + if (!deferredJsxElementClassType) { + deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); + } + return deferredJsxElementClassType; + } + function getJsxGlobalElementType() { + if (!deferredJsxElementType) { + deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); + } + return deferredJsxElementType; + } + function getJsxGlobalStatelessElementType() { + if (!deferredJsxStatelessElementType) { + var jsxElementType = getJsxGlobalElementType(); + if (jsxElementType) { + deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); + } + } + return deferredJsxStatelessElementType; + } + function getJsxIntrinsicTagNames() { + var intrinsics = getJsxType(JsxNames.IntrinsicElements); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + if ((compilerOptions.jsx || 0) === 0) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxGlobalElementType() === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElement(node) { + checkGrammarJsxElement(node); + checkJsxPreconditions(node); + var reactRefErr = diagnostics && compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(); + var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); + if (reactSym) { + reactSym.isReferenced = true; + if (reactSym.flags & 2097152 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + checkJsxAttributesAssignableToTagNameAttributes(node); + } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || + resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfObjectType(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) : + getCustomJsxElementAttributesType(openingLikeElement, false); + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { + return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); + }); + if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + } + else { + 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.escapedText, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + break; + } + } + } + } + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + } + return type; + } + else { + return unknownType; + } + } + function getDeclarationKindFromSymbol(s) { + return s.valueDeclaration ? s.valueDeclaration.kind : 149; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + function isMethodLike(symbol) { + return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); + } + function checkPropertyAccessibility(node, left, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 179 || node.kind === 226 ? + node.name : + node.right; + 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; + } + if (left.kind === 97) { + if (languageVersion < 2) { + var hasNonMethodDeclaration = forEachProperty(prop, function (p) { + var propKind = getDeclarationKindFromSymbol(p); + return propKind !== 151 && propKind !== 150; + }); + if (hasNonMethodDeclaration) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128) { + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + if (!(flags & 24)) { + return true; + } + if (flags & 8) { + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + if (left.kind === 97) { + return true; + } + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + if (!enclosingClass) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + if (flags & 32) { + return true; + } + if (type.flags & 16384 && type.isThisType) { + type = getConstraintOfTypeParameter(type); + } + if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); + } + function checkNonNullType(type, errorNode) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; + if (kind) { + error(errorNode, kind & 2048 ? kind & 4096 ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + var t = getNonNullableType(type); + return t.flags & (6144 | 8192) ? unknownType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.escapedText); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0); + if (stringIndexType) { + return stringIndexType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + if (prop.valueDeclaration.kind === 229 && + node.parent && node.parent.kind !== 159 && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); + return unknownType; + } + } + if (node.kind !== 179 || assignmentKind === 1 || + !(prop.flags & (3 | 4 | 98304)) && + !(prop.flags & 8192 && propType.flags & 65536)) { + return propType; + } + 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.escapedText)) { + 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(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455); + return suggestion && suggestion.escapedName; + } + 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(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.escapedName; + } + } + 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; + var justCheckExactMatches = false; + 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]; + var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); + if (candidate.flags & meaning && + candidateName && + Math.abs(candidateName.length - name.length) < maximumLengthDifference) { + candidateName = candidateName.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + 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) { + justCheckExactMatches = true; + bestCandidate = 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 + : node.left; + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { + if (type !== unknownType && !isTypeAny(type)) { + var prop = getPropertyOfType(type, propertyName); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); + } + if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } } return false; } return true; } - } - ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; - function getOriginalNode(node, nodeTest) { - if (node) { - while (node.original !== undefined) { - node = node.original; + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 227) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 71) { + return getResolvedSymbol(initializer); + } + return undefined; + } + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); + } + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 71) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 215 && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 182 && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return unknownType; + } + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === unknownType) { + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + if ((expressionType.flags & 512) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); + if (!globalESSymbol) { + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + 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); + } + else if (node.kind !== 147) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + 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) { + if (lastParent && parent === lastParent) { + index++; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); } } - return !nodeTest || nodeTest(node) ? node : undefined; - } - ts.getOriginalNode = getOriginalNode; - function isParseTreeNode(node) { - return (node.flags & 8) === 0; - } - ts.isParseTreeNode = isParseTreeNode; - function getParseTreeNode(node, nodeTest) { - if (node === undefined || isParseTreeNode(node)) { - return node; + function getSpreadArgumentIndex(args) { + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (arg && arg.kind === 198) { + return i; + } + } + return -1; } - node = getOriginalNode(node); - if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { - return node; + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; + var typeArguments; + var callIsIncomplete; + var isDecorator; + var spreadArgIndex = -1; + if (ts.isJsxOpeningLikeElement(node)) { + return true; + } + if (node.kind === 183) { + var tagExpression = node; + argCount = args.length; + typeArguments = undefined; + if (tagExpression.template.kind === 196) { + var templateExpression = tagExpression.template; + var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); + ts.Debug.assert(lastSpan !== undefined); + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + var templateLiteral = tagExpression.template; + ts.Debug.assert(templateLiteral.kind === 13); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 147) { + isDecorator = true; + typeArguments = undefined; + argCount = getEffectiveArgumentCount(node, undefined, signature); + } + else { + var callExpression = node; + if (!callExpression.arguments) { + ts.Debug.assert(callExpression.kind === 182); + return signature.minArgumentCount === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + callIsIncomplete = callExpression.arguments.end === callExpression.end; + typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); + } + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + var hasRightNumberOfTypeArgs = !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + if (!hasRightNumberOfTypeArgs) { + return false; + } + if (spreadArgIndex >= 0) { + return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; + } + if (!signature.hasRestParameter && argCount > signature.parameters.length) { + return false; + } + var hasEnoughArguments = argCount >= signature.minArgumentCount; + return callIsIncomplete || hasEnoughArguments; + } + function getSingleCallSignature(type) { + if (type.flags & 32768) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { + var context = createInferenceContext(signature, 1); + forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); + } + return getSignatureInstantiation(signature, getInferredTypes(context)); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + if (ts.isExpression(node)) { + var contextualType = getContextualType(node); + if (contextualType) { + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 200) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i); + if (argType === undefined) { + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + argType = checkExpressionWithContextualType(arg, paramType, mapper); + } + inferTypes(context.inferences, argType, paramType); + } + } + if (excludeArgument) { + for (var i = 0; i < argCount; i++) { + if (excludeArgument[i] === false) { + var arg = args[i]; + var paramType = getTypeAtPosition(signature, i); + inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); + } + } + } + return getInferredTypes(context); + } + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + var typeParameters = signature.typeParameters; + var typeArgumentsAreAssignable = true; + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + if (typeArgumentsAreAssignable) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); + } + } + } + return typeArgumentsAreAssignable; + } + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { + var callIsIncomplete = node.attributes.end === node.end; + if (callIsIncomplete) { + return true; + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var paramType = getTypeAtPosition(signature, 0); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); + var argProperties = getPropertiesOfType(attributesType); + for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { + var arg = argProperties_1[_i]; + if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { + return false; + } + } + return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 182) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + if (arg === undefined || arg.kind !== 200) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } + } + } + return true; + } + function getThisArgumentOfCall(node) { + if (node.kind === 181) { + var callee = node.expression; + if (callee.kind === 179) { + return callee.expression; + } + else if (callee.kind === 180) { + return callee.expression; + } + } + } + function getEffectiveCallArguments(node) { + if (node.kind === 183) { + var template = node.template; + var args_4 = [undefined]; + if (template.kind === 196) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + else if (node.kind === 147) { + return undefined; + } + else if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + } + else { + return node.arguments || ts.emptyArray; + } + } + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 147) { + switch (node.parent.kind) { + case 229: + case 199: + return 1; + case 149: + return 2; + case 151: + case 153: + case 154: + if (languageVersion === 0) { + return 2; + } + return signature.parameters.length >= 3 ? 3 : 2; + case 146: + return 3; + } + } + else { + return args.length; + } + } + function getEffectiveDecoratorFirstArgumentType(node) { + if (node.kind === 229) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + if (node.kind === 146) { + node = node.parent; + if (node.kind === 152) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + } + if (node.kind === 149 || + node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + return getParentTypeOfClassElement(node); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorSecondArgumentType(node) { + if (node.kind === 229) { + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + } + if (node.kind === 146) { + node = node.parent; + if (node.kind === 152) { + return anyType; + } + } + if (node.kind === 149 || + node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + var element = node; + switch (element.name.kind) { + case 71: + return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + case 8: + case 9: + return getLiteralType(element.name.text); + case 144: + var nameType = checkComputedPropertyName(element.name); + if (isTypeOfKind(nameType, 512)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorThirdArgumentType(node) { + if (node.kind === 229) { + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 146) { + return numberType; + } + if (node.kind === 149) { + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 151 || + node.kind === 153 || + node.kind === 154) { + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + function getEffectiveArgumentType(node, argIndex) { + if (node.kind === 147) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 183) { + return getGlobalTemplateStringsArrayType(); + } + return undefined; + } + function getEffectiveArgument(node, args, argIndex) { + if (node.kind === 147 || + (argIndex === 0 && node.kind === 183)) { + return undefined; + } + return args[argIndex]; + } + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 147) { + return node.expression; + } + else if (argIndex === 0 && node.kind === 183) { + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + var isTaggedTemplate = node.kind === 183; + var isDecorator = node.kind === 147; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var typeArguments; + if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { + typeArguments = node.typeArguments; + if (node.expression.kind !== 97) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + reorderCandidates(signatures, candidates); + if (!candidates.length) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + var excludeArgument; + var excludeCount = 0; + if (!isDecorator) { + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + excludeCount++; + } + } + } + var candidateForArgumentError; + var candidateForTypeArgumentError; + var result; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + if (candidateForArgumentError) { + if (isJsxOpeningOrSelfClosingElement) { + return candidateForArgumentError; + } + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); + } + else if (candidateForTypeArgumentError) { + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); + } + 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) { + ts.Debug.assert(candidates.length > 0); + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { + var typeArguments_2 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_2.length > typeParameters.length) { + typeArguments_2.pop(); + } + while (typeArguments_2.length < typeParameters.length) { + typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + candidates[bestIndex] = instantiated; + return instantiated; + } + return candidate; + } + return resolveErrorCall(node); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var originalCandidate = candidates[candidateIndex]; + if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + continue; + } + var candidate = void 0; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + undefined; + while (true) { + candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } + } + else { + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; + break; + } + if (excludeCount === 0) { + candidates[candidateIndex] = candidate; + return candidate; + } + excludeCount--; + if (excludeCount > 0) { + excludeArgument[ts.indexOf(excludeArgument, true)] = false; + } + else { + excludeArgument = undefined; + } + } + } + return undefined; + } + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + return i; + } + if (candidate.parameters.length > maxParams) { + maxParams = candidate.parameters.length; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray) { + if (node.expression.kind === 97) { + var superType = checkSuperExpression(node.expression); + if (superType !== unknownType) { + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + if (funcType !== unknownType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + if (constructSignatures.length) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + } + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + if (funcType.flags & 65536) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } + function resolveNewExpression(node, candidatesOutArray) { + if (node.arguments && languageVersion < 1) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + return resolveErrorCall(node); + } + 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(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + var constructSignatures = getSignaturesOfType(expressionType, 1); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray); + } + var callSignatures = getSignaturesOfType(expressionType, 0); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray); + if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + return signature; + } + error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + return resolveErrorCall(node); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getModifierFlags(declaration); + if (!(modifiers & 24)) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + while (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 && + baseType.symbol === declaration.parent.symbol) { + return true; + } + baseTypes = getBaseTypes(baseType); + } + } + if (modifiers & 8) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function resolveTaggedTemplateExpression(node, candidatesOutArray) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 229: + case 199: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 146: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 149: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 151: + case 153: + case 154: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0); + var constructSignatures = getSignaturesOfType(apparentType, 1); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = void 0; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + ts.Debug.assert(!(elementType.flags & 65536)); + var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); + return callSignature; + } + function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { + if (elementType.flags & 65536) { + var types = elementType.types; + var result = void 0; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; + result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); + } + return result; + } + var callSignatures = elementType && getSignaturesOfType(elementType, 0); + if (callSignatures && callSignatures.length > 0) { + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + } + return undefined; + } + function resolveSignature(node, candidatesOutArray) { + switch (node.kind) { + case 181: + return resolveCallExpression(node, candidatesOutArray); + case 182: + return resolveNewExpression(node, candidatesOutArray); + case 183: + return resolveTaggedTemplateExpression(node, candidatesOutArray); + case 147: + return resolveDecorator(node, candidatesOutArray); + case 251: + case 250: + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + } + ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + } + function getResolvedSignature(node, candidatesOutArray) { + var links = getNodeLinks(node); + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray); + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + function isJavaScriptConstructor(node) { + if (ts.isInJavaScriptFile(node)) { + if (ts.getJSDocClassTag(node)) + return true; + var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : + ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + undefined; + return symbol && symbol.members !== undefined; + } + return false; + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && getObjectFlags(type) & 16 + && getSymbolLinks(type.symbol).inferredClassType === type; + } + function checkCallExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 97) { + return voidType; + } + if (node.kind === 182) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 152 && + declaration.kind !== 156 && + declaration.kind !== 161 && + !ts.isJSDocConstructSignature(declaration)) { + var funcSymbol = node.expression.kind === 71 ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { + funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); + } + if (funcSymbol && funcSymbol.flags & 16 && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { + return getInferredClassType(funcSymbol); + } + else if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + return getReturnTypeOfSignature(signature); + } + function checkImportCallExpression(node) { + checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 2048 || specifierType.flags & 4096 || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, true)) { + return false; + } + if (!ts.isIdentifier(node.expression)) + throw ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455, undefined, undefined); + if (!resolvedRequire) { + return true; + } + if (resolvedRequire.flags & 2097152) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 + ? 228 + : resolvedRequire.flags & 3 + ? 226 + : 0; + if (targetDeclarationKind !== 0) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + return ts.isInAmbientContext(decl); + } + return false; + } + function checkTaggedTemplateExpression(node) { + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== unknownType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return unknownType; + } + else if (container.kind === 152) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && declaration.initializer) { + return getNullableType(type, 2048); + } + } + return type; + } + function getTypeAtPosition(signature, pos) { + return signature.hasRestParameter ? + pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : + pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + } + function getTypeOfFirstParameterOfSignature(signature) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + var parameter = ts.lastOrUndefined(signature.parameters); + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + function assignBindingElementTypes(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + assignBindingElementTypes(element); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); + if (links.type === emptyObjectType && + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); + } + assignBindingElementTypes(parameter.valueDeclaration); + } + } + function createPromiseType(promisedType) { + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType) { + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return unknownType; + } + else if (!getGlobalPromiseConstructorSymbol(true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!func.body) { + return unknownType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 207) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = void 0; + if (functionFlags & 1) { + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 + ? createAsyncIterableIteratorType(anyType) + : createIterableIteratorType(anyType); + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (!types) { + return functionFlags & 2 + ? createPromiseReturnType(func, neverType) + : neverType; + } + if (types.length === 0) { + return functionFlags & 2 + ? createPromiseReturnType(func, voidType) + : voidType; + } + } + type = getUnionType(types, true); + if (functionFlags & 1) { + type = functionFlags & 2 + ? createAsyncIterableIteratorType(type) + : createIterableIteratorType(type); + } + } + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } + var widenedType = getWidenedType(type); + return (functionFlags & 3) === 2 + ? createPromiseReturnType(func, widenedType) + : widenedType; + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var functionFlags = ts.getFunctionFlags(func); + ts.forEachYieldExpression(func.body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (yieldExpression.asteriskToken) { + type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); + } + if (functionFlags & 2) { + type = checkAwaitedType(type, expr, yieldExpression.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2) { + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 8192) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 186 || func.kind === 187)) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (!ts.contains(aggregatedTypes, undefinedType)) { + aggregatedTypes.push(undefinedType); + } + } + return aggregatedTypes; + } + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { + return; + } + if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256; + if (returnType && returnType.flags & 8192) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186) { + checkGrammarForGenerator(node); + } + if (checkMode === 1 && isContextSensitive(node)) { + checkNodeDeferred(node); + return anyFunctionType; + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(node.symbol); + if (!(links.flags & 1024)) { + var contextualSignature = getContextualSignature(node); + if (!(links.flags & 1024)) { + links.flags |= 1024; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + checkNodeDeferred(node); + } + } + if (produceDiagnostics && node.kind !== 151) { + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + } + return type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnOrPromisedType = returnTypeNode && + ((functionFlags & 3) === 2 ? + checkAsyncFunctionReturnType(node) : + getTypeFromTypeNode(returnTypeNode)); + if ((functionFlags & 1) === 0) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!returnTypeNode) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 207) { + checkSourceElement(node.body); + } + else { + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + if ((functionFlags & 3) === 2) { + 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); + } + else { + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + } + } + } + registerForUnusedIdentifiersCheck(node); + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlySymbol(symbol) { + 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); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + if (symbol.flags & 4 && + (expr.kind === 179 || expr.kind === 180) && + expr.expression.kind === 99) { + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 152)) { + return true; + } + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 179 || expr.kind === 180) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 71) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 240; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + var node = ts.skipOuterExpressions(expr, 2 | 1); + if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 179 && expr.kind !== 180) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 16384)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 38 && node.operand.kind === 8) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + switch (node.operator) { + case 37: + case 38: + case 52: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 512)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + return numberType; + case 51: + var facts = getTypeFacts(operandType) & (1048576 | 2097152); + return facts === 1048576 ? falseType : + facts === 2097152 ? trueType : + booleanType; + case 43: + case 44: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + return unknownType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + function maybeTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 196608) { + var types = type.types; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 65536) { + var types = type.types; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; + if (!isTypeOfKind(t, kind)) { + return false; + } + } + return true; + } + if (type.flags & 131072) { + var types = type.types; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isConstEnumObjectType(type) { + return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (isTypeOfKind(leftType, 8190)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + if (!(isTypeAny(rightType) || + getSignaturesOfType(rightType, 0).length || + getSignaturesOfType(rightType, 1).length || + isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + 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)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType) { + var properties = node.properties; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + } + return sourceType; + } + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 261 || property.kind === 262) { + var name = property.name; + if (name.kind === 144) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var text = ts.getTextOfPropertyName(name); + var type = isTypeAny(objectLiteralType) + ? objectLiteralType + : getTypeOfPropertyOfType(objectLiteralType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || + getIndexTypeOfType(objectLiteralType, 0); + if (type) { + if (property.kind === 262) { + return checkDestructuringAssignment(property, type); + } + else { + return checkDestructuringAssignment(property.initializer, type); + } + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 263) { + if (languageVersion < 5) { + checkExternalEmitHelpers(property, 4); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + if (languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || unknownType; + var elements = node.elements; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 200) { + if (element.kind !== 198) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) + ? getTypeOfPropertyOfType(sourceType, propName) + : elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + else { + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + var target; + if (exprOrAssignment.kind === 262) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { + sourceType = getTypeWithFacts(sourceType, 131072); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 194 && target.operatorToken.kind === 58) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 178) { + return checkObjectLiteralAssignment(target, sourceType); + } + if (target.kind === 177) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 263 ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableTo(sourceType, targetType, target, undefined); + } + return sourceType; + } + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 71: + case 9: + case 12: + case 183: + case 196: + case 13: + case 8: + case 101: + case 86: + case 95: + case 139: + case 186: + case 199: + case 187: + case 177: + case 178: + case 189: + case 203: + case 250: + case 249: + return true; + case 195: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 194: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 192: + case 193: + switch (node.operator) { + case 51: + case 37: + case 38: + case 52: + return true; + } + return false; + case 190: + case 184: + case 202: + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], true); + } + function checkBinaryExpression(node, checkMode) { + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 58 && (left.kind === 178 || left.kind === 177)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + } + var leftType = checkExpression(left, checkMode); + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 39: + case 40: + case 61: + case 62: + case 41: + case 63: + case 42: + case 64: + case 38: + case 60: + case 45: + case 65: + case 46: + case 66: + case 47: + case 67: + case 49: + case 69: + case 50: + case 70: + case 48: + case 68: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + if ((leftType.flags & 136) && + (rightType.flags & 136) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + } + else { + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + if (leftOk && rightOk) { + checkAssignmentOperator(numberType); + } + } + return numberType; + case 37: + case 59: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { + resultType = numberType; + } + else { + if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 59) { + checkAssignmentOperator(resultType); + } + return resultType; + case 27: + case 29: + case 30: + case 31: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + reportOperatorError(); + } + } + return booleanType; + case 32: + case 33: + case 34: + case 35: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 93: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 92: + return checkInExpression(left, right, leftType, rightType); + case 53: + return getTypeFacts(leftType) & 1048576 ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 54: + return getTypeFacts(leftType) & 2097152 ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; + case 58: + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + case 26: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + } + function isEvalNode(node) { + return node.kind === 71 && node.escapedText === "eval"; + } + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : + maybeTypeOfKind(rightType, 512) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 49: + case 69: + return 54; + case 50: + case 70: + return 35; + case 48: + case 68: + return 53; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { + checkTypeAssignableTo(valueType, leftType, left, undefined); + } + } + } + function reportOperatorError() { + error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + if (produceDiagnostics) { + if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + if (node.expression) { + var func = ts.getContainingFunction(node); + var functionFlags = func && ts.getFunctionFlags(func); + if (node.asteriskToken) { + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); + } + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256); + } + } + if (functionFlags & 1) { + var expressionType = checkExpressionCached(node.expression); + var expressionElementType = void 0; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); + } + var returnType = ts.getEffectiveReturnTypeNode(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2) !== 0) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(functionFlags & 2 + ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionElementType, signatureElementType, node.expression, undefined); + } + else { + checkTypeAssignableTo(functionFlags & 2 + ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionType, signatureElementType, node.expression, undefined); + } + } + } + } + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getBestChoiceType(type1, type2); + } + function checkLiteralExpression(node) { + if (node.kind === 8) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8: + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 101: + return trueType; + case 86: + return falseType; + } + } + function checkTemplateExpression(node) { + ts.forEach(node.templateSpans, function (templateSpan) { + checkExpression(templateSpan.expression); + }); + return stringType; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var saveContextualType = node.contextualType; + var saveContextualMapper = node.contextualMapper; + node.contextualType = contextualType; + node.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 : + contextualMapper ? 2 : 0; + var result = checkExpression(node, checkMode); + node.contextualType = saveContextualType; + node.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 184 || node.kind === 202; + } + function checkDeclarationInitializer(declaration) { + var type = getTypeOfExpression(declaration.initializer, true); + return ts.getCombinedNodeFlags(declaration) & 2 || + ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 540672) { + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + if (constraint.flags & (2 | 4 | 8 | 16)) { + return true; + } + contextualType = constraint; + } + return maybeTypeOfKind(contextualType, (224 | 262144)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode) { + var type = checkExpression(node, checkMode); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } + function checkPropertyAssignment(node, checkMode) { + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + checkGrammarMethod(node); + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + function getTypeOfExpression(node, cache) { + if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + return cache ? checkExpressionCached(node) : checkExpression(node); + } + function getContextFreeTypeOfExpression(node) { + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = getTypeOfExpression(node); + node.contextualType = saveContextualType; + return type; + } + function checkExpression(node, checkMode) { + var type; + if (node.kind === 143) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + var ok = (node.parent.kind === 179 && node.parent.expression === node) || + (node.parent.kind === 180 && node.parent.expression === node) || + ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281; }); }); + if (typecasts && typecasts.length) { + var cast_1 = typecasts[0]; + return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); + } + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode) { + switch (node.kind) { + case 71: + return checkIdentifier(node); + case 99: + return checkThisExpression(node); + case 97: + return checkSuperExpression(node); + case 95: + return nullWideningType; + case 9: + case 8: + case 101: + case 86: + return checkLiteralExpression(node); + case 196: + return checkTemplateExpression(node); + case 13: + return stringType; + case 12: + return globalRegExpType; + case 177: + return checkArrayLiteral(node, checkMode); + case 178: + return checkObjectLiteral(node, checkMode); + case 179: + return checkPropertyAccessExpression(node); + case 180: + return checkIndexedAccess(node); + case 181: + if (node.expression.kind === 91) { + return checkImportCallExpression(node); + } + case 182: + return checkCallExpression(node); + case 183: + return checkTaggedTemplateExpression(node); + case 185: + return checkParenthesizedExpression(node, checkMode); + case 199: + return checkClassExpression(node); + case 186: + case 187: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 189: + return checkTypeOfExpression(node); + case 184: + case 202: + return checkAssertion(node); + case 203: + return checkNonNullAssertion(node); + case 204: + return checkMetaProperty(node); + case 188: + return checkDeleteExpression(node); + case 190: + return checkVoidExpression(node); + case 191: + return checkAwaitExpression(node); + case 192: + return checkPrefixUnaryExpression(node); + case 193: + return checkPostfixUnaryExpression(node); + case 194: + return checkBinaryExpression(node, checkMode); + case 195: + return checkConditionalExpression(node, checkMode); + case 198: + return checkSpreadExpression(node, checkMode); + case 200: + return undefinedWideningType; + case 197: + return checkYieldExpression(node); + case 256: + return checkJsxExpression(node, checkMode); + case 249: + return checkJsxElement(node); + case 250: + return checkJsxSelfClosingElement(node); + case 254: + return checkJsxAttributes(node, checkMode); + case 251: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return unknownType; + } + function checkTypeParameter(node) { + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.getModifierFlags(node) & 92) { + func = ts.getContainingFunction(node); + if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (ts.indexOf(func.parameters, node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 152 || func.kind === 156 || func.kind === 161) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + } + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 && param.name.escapedText === parameter.escapedText) { + return i; + } + } + } + return -1; + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 187: + case 155: + case 228: + case 186: + case 160: + case 151: + case 150: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 71 && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 175 || name.kind === 174) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + if (node.kind === 157) { + checkGrammarIndexSignature(node); + } + else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || + node.kind === 155 || node.kind === 152 || + node.kind === 156) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); + } + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); + } + if ((functionFlags & 3) !== 0 && languageVersion < 2) { + checkExternalEmitHelpers(node, 128); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 156: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 155: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 | 1)) === 1) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 + ? createAsyncIterableIteratorType(generatorElementType) + : createIterableIteratorType(generatorElementType); + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3) === 2) { + checkAsyncFunctionReturnType(node); + } + } + if (noUnusedIdentifiers && !node.body) { + checkUnusedTypeParameters(node); + } + } + } + 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.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 152) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3); + } + } + } + else { + var isStatic = ts.getModifierFlags(member) & 32; + var names = isStatic ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 153: + addName(names, member.name, memberName, 1); + break; + case 154: + addName(names, member.name, memberName, 2); + break; + case 149: + addName(names, member.name, memberName, 3); + break; + case 151: + addName(names, member.name, memberName, 4); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4) { + if (meaning !== 4) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.getModifierFlags(member) & 32; + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbol(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148) { + var memberName = void 0; + switch (member.name.kind) { + case 9: + case 8: + memberName = member.name.text; + break; + case 71: + memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 230) { + var nodeSymbol = getSymbolOfNode(node); + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 136: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 133: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + checkFunctionOrMethodDeclaration(node); + if (ts.getModifierFlags(node) & 128 && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + checkSignatureDeclaration(node); + checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function containsSuperCallAsComputedPropertyName(n) { + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); + } + function containsSuperCall(n) { + if (ts.isSuperCall(n)) { + return true; + } + else if (ts.isFunctionLike(n)) { + return false; + } + else if (ts.isClassLike(n)) { + return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); + } + return ts.forEachChild(n, containsSuperCall); + } + function markThisReferencesAsErrors(n) { + if (n.kind === 99) { + error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + } + else if (n.kind !== 186 && n.kind !== 228) { + ts.forEachChild(n, markThisReferencesAsErrors); + } + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 149 && + !(ts.getModifierFlags(n) & 32) && + !!n.initializer; + } + var containingClassDecl = node.parent; + if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 153) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { + if (!(node.flags & 256)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + var otherKind = node.kind === 153 ? 154 : 153; + var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (otherAccessor) { + if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 153) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + mapper = createTypeMapper(typeParameters, typeArguments); + } + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 159 && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== unknownType) { + if (node.typeArguments) { + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var symbol = getNodeLinks(node).resolvedSymbol; + var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); + } + } + 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)); + } + } + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { + grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + } + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 524288)) { + return type; + } + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + return type; + } + if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { + var constraint = getBaseConstraintOfType(objectType); + if (constraint && getIndexInfoOfType(constraint, 1)) { + return type; + } + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); + } + function isPrivateWithinAmbient(node) { + return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + if (n.parent.kind !== 230 && + n.parent.kind !== 229 && + n.parent.kind !== 199 && + ts.isInAmbientContext(n)) { + if (!(flags & 2)) { + flags |= 1; + } + flags |= 2; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 | 16)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 | 2 | 8 | 16 | 128; + var someNodeFlags = 0; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 151 || node.kind === 150) && + (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); + if (reportError) { + var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + if (ts.getModifierFlags(node) & 128) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var current = declarations_5[_i]; + var node = current; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; + if (inAmbientContextOrInterface) { + previousDeclaration = undefined; + } + if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + 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; + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + var symbol = node.localSymbol; + if (!symbol) { + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + return; + } + } + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0; + var nonExportedDeclarationSpaces = 0; + var defaultExportedDeclarationSpaces = 0; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); + if (effectiveDeclarationFlags & 1) { + if (effectiveDeclarationFlags & 512) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function getDeclarationSpaces(d) { + switch (d.kind) { + case 230: + case 231: + return 2; + case 233: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 + ? 4 | 1 + : 4; + case 229: + case 232: + return 2 | 1; + case 237: + var result_3 = 0; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 226: + case 176: + case 228: + case 242: + return 1; + default: + ts.Debug.fail(ts.SyntaxKind[d.kind]); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + function getPromisedTypeOfPromise(promise, errorNode) { + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); + } + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 65536) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { + if (errorNode) { + ts.Debug.assert(!!diagnosticMessage); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + function checkAsyncFunctionReturnType(node) { + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } + } + else { + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + if (promiseConstructorName.kind === 71 && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + } + return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 229: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 146: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 149: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 151: + case 153: + case 154: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + } + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 ? 793064 : 1920) | 2097152, undefined, undefined); + if (rootSymbol + && rootSymbol.flags & 2097152 + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + 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.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168: + return getEntityNameForDecoratorMetadata(node.type); + case 159: + return node.typeName; + } + } + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + function checkDecorators(node) { + if (!node.decorators) { + return; + } + if (!ts.nodeCanBeDecorated(node)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8); + if (node.kind === 146) { + checkExternalEmitHelpers(firstDecorator, 32); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16); + switch (node.kind) { + case 229: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 151: + case 153: + case 154: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 149: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 146: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDoc(node) { + if (!ts.isInJavaScriptFile(node)) { + return; + } + ts.forEach(node.jsDoc, checkSourceElement); + } + function checkJSDocComment(node) { + if (node.tags) { + for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + checkSourceElement(tag); + } + } + } + function checkFunctionOrMethodDeclaration(node) { + checkJSDoc(node); + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + if (node.name && node.name.kind === 144) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + var firstDeclaration = ts.find(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + checkFunctionOrConstructorSymbol(symbol); + } + } + } + checkSourceElement(node.body); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if ((functionFlags & 1) === 0) { + var returnOrPromisedType = returnTypeNode && (functionFlags & 2 + ? checkAsyncFunctionReturnType(node) + : getTypeFromTypeNode(returnTypeNode)); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !returnTypeNode) { + if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (functionFlags & 1 && ts.nodeIsPresent(node.body)) { + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + registerForUnusedIdentifiersCheck(node); + } + function registerForUnusedIdentifiersCheck(node) { + if (deferredUnusedIdentifierNodes) { + deferredUnusedIdentifierNodes.push(node); + } + } + function checkUnusedIdentifiers() { + if (deferredUnusedIdentifierNodes) { + for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { + var node = deferredUnusedIdentifierNodes_1[_i]; + switch (node.kind) { + case 265: + case 233: + checkUnusedModuleMembers(node); + break; + case 229: + case 199: + checkUnusedClassMembers(node); + checkUnusedTypeParameters(node); + break; + case 230: + checkUnusedTypeParameters(node); + break; + case 207: + case 235: + case 214: + case 215: + case 216: + checkUnusedLocalsAndParameters(node); + break; + case 152: + case 186: + case 228: + case 187: + case 151: + case 153: + case 154: + if (node.body) { + checkUnusedLocalsAndParameters(node); + } + checkUnusedTypeParameters(node); + break; + case 150: + case 155: + case 156: + case 157: + case 160: + case 161: + checkUnusedTypeParameters(node); + break; + case 231: + checkUnusedTypeParameters(node); + break; + } + } + } + } + function checkUnusedLocalsAndParameters(node) { + if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + 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(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + } + } + }); + } + } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 226 && ts.isForInOrOfStatement(declaration.parent.parent)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 71 && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95; + } + function checkUnusedClassMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.members) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 151 || member.kind === 149) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { + error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + } + } + else if (member.kind === 152) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + } + } + } + } + } + } + } + function checkUnusedTypeParameters(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.typeParameters) { + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var typeParameter = _a[_i]; + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + } + } + } + } + } + function checkUnusedModuleMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + } + }); + } + } + function checkBlock(node) { + if (node.kind === 207) { + checkGrammarStatementInAmbientContext(node); + } + ts.forEach(node.statements, checkSourceElement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 149 || + node.kind === 148 || + node.kind === 151 || + node.kind === 150 || + node.kind === 153 || + node.kind === 154) { + return false; + } + if (ts.isInAmbientContext(node)) { + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { + return false; + } + return true; + } + function checkCollisionWithCapturedThisVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_this")) { + potentialThisCollisions.push(node); + } + } + function checkCollisionWithCapturedNewTargetVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + potentialNewTargetCollisions.push(node); + } + } + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4) { + var isDeclaration_1 = node.kind !== 71; + if (isDeclaration_1) { + 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); + } + return true; + } + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8) { + var isDeclaration_2 = node.kind !== 71; + if (isDeclaration_2) { + 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); + } + return true; + } + }); + } + function checkCollisionWithCapturedSuperVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_super")) { + return; + } + var enclosingClass = ts.getContainingClass(node); + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + return; + } + if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { + var isDeclaration_3 = node.kind !== 71; + if (isDeclaration_3) { + error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); + } + } + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { + return; + } + var parent = getDeclarationContainer(node); + if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + if (node.kind === 226 && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1) { + if (!ts.isIdentifier(node.name)) + throw ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3, undefined, undefined); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); + var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + var namesShareScope = container && + (container.kind === 207 && ts.isFunctionLike(container.parent) || + container.kind === 234 || + container.kind === 233 || + container.kind === 265); + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 146) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + return; + } + if (n.kind === 179) { + return visit(n.expression); + } + else if (n.kind === 71) { + var symbol = resolveName(n, n.escapedText, 107455 | 2097152, undefined, undefined); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 146 || + symbol.valueDeclaration.kind === 176) { + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + (current.parent.kind === 149 && + !(ts.hasModifier(current.parent, 32)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + checkSourceElement(node.type); + if (!node.name) { + return; + } + if (node.name.kind === 144) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 176) { + if (node.parent.kind === 174 && languageVersion < 5) { + checkExternalEmitHelpers(node, 4); + } + if (node.propertyName && node.propertyName.kind === 144) { + checkComputedPropertyName(node.propertyName); + } + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + markPropertyAsReferenced(property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); + } + } + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512); + } + ts.forEach(node.name.elements, checkSourceElement); + } + if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + if (ts.isBindingPattern(node.name)) { + if (node.initializer && node.parent.parent.kind !== 215) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + if (node === symbol.valueDeclaration) { + if (node.initializer && node.parent.parent.kind !== 215) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); + checkParameterInitializer(node); + } + } + else { + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { + error(node.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(node.name), typeToString(type), typeToString(declarationType)); + } + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + 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)); + } + } + if (node.kind !== 149 && node.kind !== 148) { + checkExportsOnMergedDeclarations(node); + if (node.kind === 226 || node.kind === 176) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 146 && right.kind === 226) || + (left.kind === 226 && right.kind === 146)) { + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 | + 16 | + 256 | + 128 | + 64 | + 32; + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { + if (node.modifiers && node.parent.kind === 178) { + if (ts.getFunctionFlags(node) & 2) { + if (node.modifiers.length > 1) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function checkExpressionStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 209) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkExpression(node.expression); + } + function checkWhileStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.statement); + } + function checkForStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 227) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 227) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.kind === 216) { + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); + } + } + else if (compilerOptions.downlevelIteration && languageVersion < 2) { + checkExternalEmitHelpers(node, 256); + } + } + if (node.initializer.kind === 227) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + if (varExpr.kind === 177 || varExpr.kind === 178) { + checkDestructuringAssignment(varExpr, iteratedType || unknownType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + if (iteratedType) { + checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + checkGrammarForInOrForOfStatement(node); + var rightType = checkNonNullExpression(node.expression); + if (node.initializer.kind === 227) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 177 || varExpr.kind === 178) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, true) || anyType; + } + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + var uplevelIteration = languageVersion >= 2; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + if (allowStringInput) { + if (arrayType.flags & 65536) { + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, true); + } + } + else if (arrayType.flags & 262178) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + if (arrayType.flags & 8192) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1); + if (hasStringConstituent && arrayElementType) { + if (arrayElementType.flags & 262178) { + return stringType; + } + return getUnionType([arrayElementType, stringType], true); + } + return arrayElementType; + } + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return typeAsIterable.iteratedTypeOfIterable; + } + if (isReferenceToType(type, getGlobalIterableType(false)) || + isReferenceToType(type, getGlobalIterableIteratorType(false))) { + return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType && getSignaturesOfType(methodType, 0); + if (!ts.some(signatures)) { + if (errorNode) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + return asyncMethodType + ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); + if (isTypeAny(nextResult)) { + return undefined; + } + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, !isAsyncGenerator, false) + || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + } + function isGetAccessorWithAnnotatedSetAccessor(node) { + return node.kind === 153 + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154)) !== undefined; + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 + ? getPromisedTypeOfPromise(returnType) + : returnType; + return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); + } + function checkReturnStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + var functionBlock = ts.getContainingFunction(node); + if (!functionBlock) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + } + } + var func = ts.getContainingFunction(node); + if (func) { + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + if (strictNullChecks || node.expression || returnType.flags & 8192) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1) { + return; + } + if (func.kind === 154) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 152) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableTo(exprType, returnType, node); + } + } + } + else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + } + function checkWithStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + if (clause.kind === 258 && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 257) { + var caseClause = clause; + var caseType = checkExpression(caseClause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 222 && current.label.escapedText === node.label.escapedText) { + var sourceFile = ts.getSourceFileOfNode(node); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); + return true; + } + }); + } + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); + var stringIndexType = getIndexTypeOfType(type, 0); + var numberIndexType = getIndexTypeOfType(type, 1); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); + }); + if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { + var classDeclaration = type.symbol.valueDeclaration; + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + if (!errorNode && (getObjectFlags(type) & 2)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + var propDeclaration = prop.valueDeclaration; + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + return; + } + var errorNode; + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (getObjectFlags(containingType) & 2) { + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + switch (name.escapedText) { + case "any": + case "number": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, typeParameters) { + var maxTypeArgumentCount = ts.length(typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + var numTypeParameters = ts.length(declaration.typeParameters); + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = declaration.typeParameters[i]; + var target = typeParameters[i]; + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); + var targetConstraint = getConstraintFromTypeParameter(target); + if ((sourceConstraint || targetConstraint) && + (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { + return false; + } + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !(ts.getModifierFlags(node) & 512)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkTypeParameters(node.typeParameters); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + if (!ts.isInAmbientContext(node)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + if (languageVersion < 2) { + checkExternalEmitHelpers(baseTypeNode.parent, 1); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== unknownType) { + if (isValidBaseType(t)) { + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + } + else { + error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.getModifierFlags(declaration) & 8) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + function getTargetSymbol(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; }); + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 229 || d.kind === 230; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + 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) { + var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { + if (derivedClassDecl.kind === 199) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { + continue; + } + if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { + continue; + } + var errorMessage = void 0; + if (isMethodLike(base)) { + if (derived.flags & 98304) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 4) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkInterfaceDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384)) { + nodeLinks.flags |= 16384; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + 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); + } + } + 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; + } + } + 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; + case 47: return left >>> right; + case 45: return left << right; + case 50: return left ^ right; + case 39: return left * right; + case 41: return left / right; + case 37: return left + right; + case 38: return left - right; + case 42: return left % right; + } + } + 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.escapedText); + case 180: + case 179: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384) { + var name = void 0; + if (ex.kind === 179) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + 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; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isConst(node); + if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + if (declaration.kind !== 232) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 229 || + (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && + !ts.isInAmbientContext(declaration)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!inAmbientContext && node.name.kind === 9) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + if (symbol.flags & 512 + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + var mergedClass = ts.getDeclarationOfKind(symbol, 229); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + if (checkBody && node.body) { + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 208: + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 243: + case 244: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 237: + case 238: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 176: + case 226: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + case 229: + case 232: + case 228: + case 230: + case 233: + case 231: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + var reportError = !(symbol.flags & 33554432); + if (!reportError) { + reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 71: + return node; + case 143: + do { + node = node.left; + } while (node.kind !== 71); + return node; + case 179: + do { + node = node.expression; + } while (node.kind !== 71); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 265 && !inAmbientExternalModule) { + error(moduleName, node.kind === 244 ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + if (!isTopLevelInExternalModuleAugmentation(node)) { + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | + (symbol.flags & 793064 ? 793064 : 0) | + (symbol.flags & 1920 ? 1920 : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 246 ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; + error(node, message, symbolToString(symbol)); + } + if (compilerOptions.isolatedModules + && node.kind === 246 + && !(target.flags & 107455) + && !ts.isInAmbientContext(node)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 240) { + checkImportBinding(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + return; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.getModifierFlags(node) & 1) { + markExportAsReferenced(node); + } + if (ts.isInternalModuleImportEqualsDeclaration(node)) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 107455) { + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 793064) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + grammarErrorOnNode(node, ts.Diagnostics.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); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && + !node.moduleSpecifier && ts.isInAmbientContext(node); + if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + checkExternalEmitHelpers(node, 32768); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 | 793064 | 1920 | 2097152, undefined, undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + return; + } + var container = node.parent.kind === 265 ? node.parent : node.parent.parent; + if (container.kind === 233 && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 71) { + markExportAsReferenced(node); + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (modulekind === ts.ModuleKind.System) { + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + var exports = getExportsOfModule(moduleSymbol); + exports && exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + if (flags & (1920 | 64 | 384)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 && exportedDeclarationsCount <= 2) { + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + links.exportsChecked = true; + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 && declaration.kind !== 151) || + !!declaration.body; + } + } + function checkSourceElement(node) { + if (!node) { + return; + } + var kind = node.kind; + if (cancellationToken) { + switch (kind) { + case 233: + case 229: + case 230: + case 228: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 145: + return checkTypeParameter(node); + case 146: + return checkParameter(node); + case 149: + case 148: + return checkPropertyDeclaration(node); + case 160: + case 161: + case 155: + case 156: + return checkSignatureDeclaration(node); + case 157: + return checkSignatureDeclaration(node); + case 151: + case 150: + return checkMethodDeclaration(node); + case 152: + return checkConstructorDeclaration(node); + case 153: + case 154: + return checkAccessorDeclaration(node); + case 159: + return checkTypeReferenceNode(node); + case 158: + return checkTypePredicate(node); + case 162: + return checkTypeQuery(node); + case 163: + return checkTypeLiteral(node); + case 164: + return checkArrayType(node); + case 165: + return checkTupleType(node); + case 166: + case 167: + return checkUnionOrIntersectionType(node); + case 168: + case 170: + return checkSourceElement(node.type); + case 275: + return checkJSDocComment(node); + case 279: + return checkSourceElement(node.typeExpression); + case 273: + checkSignatureDeclaration(node); + case 274: + case 271: + case 270: + case 268: + case 269: + if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + return; + case 267: + return checkSourceElement(node.type); + case 171: + return checkIndexedAccessType(node); + case 172: + return checkMappedType(node); + case 228: + return checkFunctionDeclaration(node); + case 207: + case 234: + return checkBlock(node); + case 208: + return checkVariableStatement(node); + case 210: + return checkExpressionStatement(node); + case 211: + return checkIfStatement(node); + case 212: + return checkDoStatement(node); + case 213: + return checkWhileStatement(node); + case 214: + return checkForStatement(node); + case 215: + return checkForInStatement(node); + case 216: + return checkForOfStatement(node); + case 217: + case 218: + return checkBreakOrContinueStatement(node); + case 219: + return checkReturnStatement(node); + case 220: + return checkWithStatement(node); + case 221: + return checkSwitchStatement(node); + case 222: + return checkLabeledStatement(node); + case 223: + return checkThrowStatement(node); + case 224: + return checkTryStatement(node); + case 226: + return checkVariableDeclaration(node); + case 176: + return checkBindingElement(node); + case 229: + return checkClassDeclaration(node); + case 230: + return checkInterfaceDeclaration(node); + case 231: + return checkTypeAliasDeclaration(node); + case 232: + return checkEnumDeclaration(node); + case 233: + return checkModuleDeclaration(node); + case 238: + return checkImportDeclaration(node); + case 237: + return checkImportEqualsDeclaration(node); + case 244: + return checkExportDeclaration(node); + case 243: + return checkExportAssignment(node); + case 209: + checkGrammarStatementInAmbientContext(node); + return; + case 225: + checkGrammarStatementInAmbientContext(node); + return; + case 247: + return checkMissingDeclaration(node); + } + } + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 186: + case 187: + case 151: + case 150: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 153: + case 154: + checkAccessorDeclaration(node); + break; + case 199: + checkClassExpressionDeferred(node); + break; + } + } + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1)) { + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; + } + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + deferredNodes = []; + deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + ts.forEach(node.statements, checkSourceElement); + checkDeferredNodes(); + if (ts.isExternalModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile) { + checkUnusedIdentifiers(); + } + deferredNodes = undefined; + deferredUnusedIdentifierNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1; + } + } + function getDiagnostics(sourceFile, ct) { + try { + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + function isInsideWithStatementBody(node) { + if (node) { + while (node.parent) { + if (node.parent.kind === 220 && node.parent.statement === node) { + return true; + } + node = node.parent; + } + } + return false; + } + function getSymbolsInScope(location, meaning) { + if (isInsideWithStatementBody(location)) { + return []; + } + var symbols = ts.createSymbolTable(); + var memberFlags = 0; + populateSymbols(); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 233: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475); + break; + case 232: + copySymbols(getSymbolOfNode(location).exports, meaning & 8); + break; + case 199: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + case 229: + case 230: + if (!(memberFlags & 32)) { + copySymbols(getSymbolOfNode(location).members, meaning & 793064); + } + break; + case 186: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + memberFlags = ts.getModifierFlags(location); + location = location.parent; + } + copySymbols(globals, meaning); + } + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 71 && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 145: + case 229: + case 230: + case 231: + case 232: + return true; + } + } + function isTypeReferenceIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 143) { + node = node.parent; + } + return node.parent && node.parent.kind === 159; + } + function isHeritageClauseElementIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 179) { + node = node.parent; + } + return node.parent && node.parent.kind === 201; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 143) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 237) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 243) { + return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1: + case 3: + return getSymbolOfNode(entityName.parent); + case 4: + case 2: + case 5: + return getSymbolOfNode(entityName.parent.parent); + } + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJavaScriptFile(entityName) && + entityName.parent.kind === 179 && + entityName.parent === entityName.parent.parent.left) { + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, 107455 | 793064 | 1920 | 2097152); + } + if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { + var importEqualsDeclaration = ts.getAncestor(entityName, 237); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); + } + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0; + if (entityName.parent.kind === 201) { + meaning = 793064; + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 107455; + } + } + else { + meaning = 1920; + } + meaning |= 2097152; + var entityNameSymbol = resolveEntityName(entityName, meaning); + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 279) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 145 && entityName.parent.parent.kind === 282) { + ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isPartOfExpression(entityName)) { + if (ts.nodeIsMissing(entityName)) { + return undefined; + } + if (entityName.kind === 71) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + return getIntrinsicTagSymbol(entityName.parent); + } + return resolveEntityName(entityName, 107455, false, true); + } + else if (entityName.kind === 179 || entityName.kind === 143) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 179) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 159 ? 793064 : 1920; + return resolveEntityName(entityName, meaning, false, true); + } + else if (entityName.parent.kind === 253) { + return getJsxAttributePropertySymbol(entityName.parent); + } + if (entityName.parent.kind === 158) { + return resolveEntityName(entityName, 1); + } + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 265) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + if (isInsideWithStatementBody(node)) { + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + return getSymbolOfNode(node.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(node.parent.parent); + } + if (node.kind === 71) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (node.parent.kind === 176 && + node.parent.parent.kind === 174 && + node === node.parent.propertyName) { + var typeOfPattern = getTypeOfNode(node.parent.parent); + var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 71: + case 179: + case 143: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 99: + var container = ts.getThisContainer(node, false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + case 97: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); + return type.symbol; + case 169: + return getTypeFromTypeNode(node).symbol; + case 123: + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 152) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 9: + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { + return resolveExternalModuleName(node, node); + } + case 8: + if (node.parent.kind === 180 && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); + if (objectType === unknownType) + return undefined; + var apparentType = getApparentType(objectType); + if (apparentType === unknownType) + return undefined; + return getPropertyOfType(apparentType, node.text); + } + break; + } + return undefined; + } + function getShorthandAssignmentValueSymbol(location) { + if (location && location.kind === 262) { + return resolveEntityName(location.name, 107455 | 2097152); + } + return undefined; + } + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 2097152); + } + function getTypeOfNode(node) { + if (isInsideWithStatementBody(node)) { + return unknownType; + } + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + var containingClass = ts.getContainingClass(node); + var classType = getTypeOfNode(containingClass); + typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + } + return typeFromTypeNode; + } + if (ts.isPartOfExpression(node)) { + return getRegularTypeOfExpression(node); + } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + var classNode = ts.getContainingClass(node); + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var baseType = getBaseTypes(classType)[0]; + return baseType && getTypeWithThisArgument(baseType, classType.thisType); + } + if (isTypeDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + } + if (ts.isDeclaration(node)) { + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getTypeOfSymbol(symbol); + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, true); + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + } + return unknownType; + } + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 178 || expr.kind === 177); + if (expr.parent.kind === 216) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + if (expr.parent.kind === 194) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + if (expr.parent.kind === 261) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + } + ts.Debug.assert(expr.parent.kind === 177); + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + } + function getPropertySymbolOfDestructuringAssignment(location) { + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.getModifierFlags(node) & 32 + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function getRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6) { + var symbols_4 = []; + var name_2 = symbol.escapedName; + ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { + var symbol = getPropertyOfType(t, name_2); + if (symbol) { + symbols_4.push(symbol); + } + }); + return symbols_4; + } + else if (symbol.flags & 33554432) { + var transient = symbol; + if (transient.leftSpread) { + return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); + } + if (transient.syntheticOrigin) { + return getRootSymbols(transient.syntheticOrigin); + } + var target = void 0; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + if (target) { + return [target]; + } + } + return [symbol]; + } + function isArgumentsLocalBinding(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576) { + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + function getReferencedImportDeclaration(node) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (isNonLocalAlias(symbol, 107455)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.escapedName, 107455, undefined, undefined)) { + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072) { + var isDeclaredInLoop = nodeLinks_1.flags & 262144; + var inLoopInitializer = ts.isIterationStatement(container, false); + var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + function getReferencedDeclarationWithCollidingName(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + function isDeclarationWithCollidingName(node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 237: + case 239: + case 240: + case 242: + case 246: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 244: + var exportClause = node.exportClause; + return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + case 243: + return node.expression + && node.expression.kind === 71 + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(node) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + return target.flags & 107455 && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + } + if (checkChildren) { + return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + return signaturesOfSymbol.length > 1 || + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92); + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 264: + case 179: + case 180: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 264) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8)) { + if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { + return getEnumMemberValue(symbol.valueDeclaration); + } + } + return undefined; + } + function isFunctionType(type) { + return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; + } + function getTypeReferenceSerializationKind(typeName, location) { + var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); + var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === unknownType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 1) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeOfKind(type, 136)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeOfKind(type, 84)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeOfKind(type, 262178)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeOfKind(type, 512)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 | 131072)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : unknownType; + if (flags & 8192) { + type = getNullableType(type, 2048); + } + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + var signature = getSignatureFromDeclaration(signatureDeclaration); + getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + } + function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + var type = getWidenedType(getRegularTypeOfExpression(expr)); + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 107455 | 1048576 | 2097152, undefined, undefined); + } + function getReferencedValueDeclaration(reference) { + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 && type.flags & 1048576); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); + } + function createResolver() { + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : undefined; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + writeTypeOfDeclaration: writeTypeOfDeclaration, + writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, + writeTypeOfExpression: writeTypeOfExpression, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + }; + function getTypeReferenceDirectivesForEntityName(node) { + if (!fileToDirective) { + return undefined; + } + var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) + ? 107455 | 1048576 + : 793064 | 1920; + var symbol = resolveEntityName(node, meaning, true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + if (!symbol.declarations) { + return false; + } + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { + return false; + } + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 265); + } + function initializeTypeChecker() { + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + if (augmentations) { + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + mergeModuleAugmentation(augmentation); + } + } + } + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); + getSymbolLinks(unknownSymbol).type = unknownType; + globalArrayType = getGlobalType("Array", 1, true); + globalObjectType = getGlobalType("Object", 0, true); + globalFunctionType = getGlobalType("Function", 0, true); + globalStringType = getGlobalType("String", 0, true); + globalNumberType = getGlobalType("Number", 0, true); + globalBooleanType = getGlobalType("Boolean", 0, true); + globalRegExpType = getGlobalType("RegExp", 0, true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", 1); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1; helper <= 32768; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1: return "__extends"; + case 2: return "__assign"; + case 4: return "__rest"; + case 8: return "__decorate"; + case 16: return "__metadata"; + case 32: return "__param"; + case 64: return "__awaiter"; + case 128: return "__generator"; + case 256: return "__values"; + case 512: return "__read"; + case 1024: return "__spread"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; + case 32768: return "__exportStar"; + default: ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node)) { + if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 153 || node.kind === 154) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var flags = 0; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 131) { + if (node.kind === 148 || node.kind === 150) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 157) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 76: + if (node.kind !== 232 && node.parent.kind === 229) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); + } + break; + case 114: + case 113: + case 112: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 113) { + lastProtected = modifier; + } + else if (modifier.kind === 112) { + lastPrivate = modifier; + } + if (flags & 28) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 234 || node.parent.kind === 265) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128) { + if (modifier.kind === 112) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 115: + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 234 || node.parent.kind === 265) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32; + lastStatic = modifier; + break; + case 131: + if (flags & 64) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64; + lastReadonly = modifier; + break; + case 84: + if (flags & 1) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 229) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1; + break; + case 79: + var container = node.parent.kind === 265 ? node.parent : node.parent.parent; + if (container.kind === 233 && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512; + break; + case 124: + if (flags & 2) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 229) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2; + lastDeclare = modifier; + break; + case 117: + if (flags & 128) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 229) { + if (node.kind !== 151 && + node.kind !== 149 && + node.kind !== 153 && + node.kind !== 154) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128; + break; + case 120: + if (flags & 256) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 146) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256; + lastAsync = modifier; + break; + } + } + if (node.kind === 152) { + if (flags & 32) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + } + else if (flags & 256) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return; + } + else if ((node.kind === 238 || node.kind === 237) && flags & 2) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256) { + return checkGrammarAsyncModifier(node, lastAsync); + } + } + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 153: + case 154: + case 152: + case 149: + case 148: + case 151: + case 150: + case 157: + case 233: + case 238: + case 237: + case 244: + case 243: + case 186: + case 187: + case 146: + return false; + default: + if (node.parent.kind === 234 || node.parent.kind === 265) { + return false; + } + switch (node.kind) { + case 228: + return nodeHasAnyModifiersExcept(node, 120); + case 229: + return nodeHasAnyModifiersExcept(node, 117); + case 230: + case 208: + case 231: + return true; + case 232: + return nodeHasAnyModifiersExcept(node, 76); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 151: + case 228: + case 186: + case 187: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list) { + if (list && list.hasTrailingComma) { + var start = list.end - ",".length; + var end = list.end; + var sourceFile = ts.getSourceFileOfNode(list[0]); + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (checkGrammarForDisallowedTrailingComma(typeParameters)) { + return true; + } + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function checkGrammarFunctionLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (node.kind === 187) { + var arrowFunction = node; + var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + if (startLine !== endLine) { + return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + } + return false; + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.getModifierFlags(parameter) !== 0) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + } + function checkGrammarIndexSignature(node) { + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(node, args) { + if (args) { + var sourceFile = ts.getSourceFileOfNode(node); + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 200) { + return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + } + function checkGrammarArguments(node, args) { + return checkGrammarForOmittedArgument(node, args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + var sourceFile = ts.getSourceFileOfNode(node); + return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + if (node.kind !== 144) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 228 || + node.kind === 186 || + node.kind === 151); + if (ts.isInAmbientContext(node)) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + if (questionToken) { + return grammarErrorOnNode(questionToken, message); + } + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var seen = ts.createUnderscoreEscapedMap(); + var Property = 1; + var GetAccessor = 2; + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263) { + continue; + } + var name = prop.name; + if (name.kind === 144) { + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 120 || prop.kind !== 151) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + var currentKind = void 0; + if (prop.kind === 261 || prop.kind === 262) { + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8) { + checkGrammarNumericLiteral(name); + } + currentKind = Property; + } + else if (prop.kind === 151) { + currentKind = Property; + } + else if (prop.kind === 153) { + currentKind = GetAccessor; + } + else if (prop.kind === 154) { + currentKind = SetAccessor; + } + else { + ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === Property && existingKind === Property) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { + if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 255) { + continue; + } + var jsxAttr = attr; + var name = jsxAttr.name; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + var initializer = jsxAttr.initializer; + if (initializer && initializer.kind === 256 && !initializer.expression) { + return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384) === 0) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 227) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 215 + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (ts.isInAmbientContext(accessor)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { + return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.getModifierFlags(accessor) & 128) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 153 ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 154) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + } + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarForNonSymbolComputedProperty(node, message) { + if (ts.isDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || + checkGrammarFunctionLikeDeclaration(node) || + checkGrammarForGenerator(node)) { + return true; + } + if (node.parent.kind === 178) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (ts.isClassLike(node.parent)) { + if (ts.isInAmbientContext(node)) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + } + else if (!node.body) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + } + } + else if (node.parent.kind === 230) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + } + else if (node.parent.kind === 163) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 222: + if (node.label && current.label.escapedText === node.label.escapedText) { + var isMisplacedContinueLabel = node.kind === 217 + && !ts.isIterationStatement(current.statement, true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 221: + if (node.kind === 218 && !node.label) { + return false; + } + break; + default: + if (ts.isIterationStatement(current, false) && !node.label) { + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 218 + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 218 + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.lastOrUndefined(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + if (node.name.kind === 175 || node.name.kind === 174) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (node.initializer) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 || expr.kind === 8 || + expr.kind === 192 && expr.operator === 38 && + expr.operand.kind === 8; + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { + if (ts.isInAmbientContext(node)) { + if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 71) { + if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 71) { + if (name.originalKeywordKind === 110) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 211: + case 212: + case 213: + case 220: + case 214: + case 215: + case 216: + return false; + case 222: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + if (node.keywordToken === 94) { + if (node.name.escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + } + function checkGrammarConstructorTypeParameters(node) { + if (node.typeParameters) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + if (node.type) { + return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + else if (node.parent.kind === 230) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 163) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (ts.isInAmbientContext(node) && node.initializer) { + return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + if (node.kind === 230 || + node.kind === 231 || + node.kind === 238 || + node.kind === 237 || + node.kind === 244 || + node.kind === 243 || + node.kind === 236 || + ts.getModifierFlags(node) & (2 | 1 | 512)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 208) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + } + function checkGrammarSourceFile(node) { + return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (ts.isInAmbientContext(node)) { + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { + var links_1 = getNodeLinks(node.parent); + if (!links_1.hasReportedStatementInAmbientContext) { + return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + } + } + } + function checkGrammarNumericLiteral(node) { + if (node.numericLiteralFlags & 4) { + var diagnosticMessage = void 0; + if (languageVersion >= 1) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 173)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 264)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); + return true; + } + } + function getAmbientModules() { + var result = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { + result.push(global); + } + }); + return result; + } + function checkGrammarImportCallExpression(node) { + if (modulekind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } } - return undefined; } - ts.getParseTreeNode = getParseTreeNode; - function unescapeIdentifier(identifier) { - return identifier.length >= 3 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 && identifier.charCodeAt(2) === 95 ? identifier.substr(1) : identifier; + ts.createTypeChecker = createTypeChecker; + function isDeclarationNameOrImportPropertyName(name) { + switch (name.parent.kind) { + case 242: + case 246: + return true; + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 239: + case 237: + case 240: + case 242: + return true; + case 71: + return decl.parent.kind === 242; + default: + return false; + } } - ts.unescapeIdentifier = unescapeIdentifier; })(ts || (ts = {})); var ts; (function (ts) { @@ -12058,13 +40520,13 @@ var ts; return node; } function createLiteralFromNode(sourceNode) { - var node = createStringLiteral(sourceNode.text); + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; return node; } function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71); - node.text = ts.escapeIdentifier(text); + node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; node.autoGenerateKind = 0; node.autoGenerateId = 0; @@ -12076,7 +40538,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(node.text, typeArguments), node) + ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -12250,13 +40712,14 @@ var ts; return node; } ts.createProperty = createProperty; - function updateProperty(node, decorators, modifiers, name, type, initializer) { + function updateProperty(node, decorators, modifiers, name, questionToken, type, initializer) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name + || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer), node) + ? updateNode(createProperty(decorators, modifiers, name, questionToken, type, initializer), node) : node; } ts.updateProperty = updateProperty; @@ -12296,6 +40759,7 @@ var ts; || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name + || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type @@ -12491,7 +40955,7 @@ var ts; ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { var node = createSynthesizedNode(164); - node.elementType = ts.parenthesizeElementTypeMember(elementType); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } ts.createArrayTypeNode = createArrayTypeNode; @@ -12692,7 +41156,7 @@ var ts; function updatePropertyAccess(node, expression, name) { return node.expression !== expression || node.name !== name - ? updateNode(setEmitFlags(createPropertyAccess(expression, name), getEmitFlags(node)), node) + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) : node; } ts.updatePropertyAccess = updatePropertyAccess; @@ -13962,28 +42426,28 @@ var ts; } ts.getMutableClone = getMutableClone; function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295); + var node = createSynthesizedNode(287); node.original = original; setTextRange(node, original); return node; } ts.createNotEmittedStatement = createNotEmittedStatement; function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299); + var node = createSynthesizedNode(291); node.emitNode = {}; node.original = original; return node; } ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker; function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298); + var node = createSynthesizedNode(290); node.emitNode = {}; node.original = original; return node; } ts.createMergeDeclarationMarker = createMergeDeclarationMarker; function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296); + var node = createSynthesizedNode(288); node.expression = expression; node.original = original; setTextRange(node, original); @@ -13999,7 +42463,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297) { + if (node.kind === 289) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26) { @@ -14009,7 +42473,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297); + var node = createSynthesizedNode(289); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -14033,6 +42497,10 @@ var ts; return node; } ts.updateBundle = updateBundle; + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression(undefined, undefined, undefined, undefined, param ? [param] : [], undefined, createBlock(statements, true)), undefined, paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; function createComma(left, right) { return createBinary(left, 26, right); } @@ -14135,11 +42603,6 @@ var ts; return range; } ts.setTextRange = setTextRange; - function getEmitFlags(node) { - var emitNode = node.emitNode; - return emitNode && emitNode.flags; - } - ts.getEmitFlags = getEmitFlags; function setEmitFlags(node, emitFlags) { getOrCreateEmitNode(node).flags = emitFlags; return node; @@ -14155,6 +42618,11 @@ var ts; return node; } ts.setSourceMapRange = setSourceMapRange; + var SourceMapSource; + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; function getTokenSourceMapRange(node, token) { var emitNode = node.emitNode; var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; @@ -14406,12 +42874,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(jsxFactory.right.text); - right.text = jsxFactory.right.text; + var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(jsxFactory.text, parent); + return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -14634,27 +43102,27 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_1 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, undefined, undefined, undefined, getAccessor.parameters, undefined, getAccessor.body); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_1.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, undefined, undefined, undefined, setAccessor.parameters, undefined, setAccessor.body); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_1.push(setter); + properties_8.push(setter); } - properties_1.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_1.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_1, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), firstAccessor); return ts.aggregateTransformFlags(expression); } @@ -14736,8 +43204,20 @@ var ts; return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); } ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + ts.Debug.assert(!!node.body); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (node.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; } function addPrologue(target, source, ensureUseStrict, visitor) { var offset = addStandardPrologue(target, source, ensureUseStrict); @@ -14792,8 +43272,8 @@ var ts; ts.startsWithUseStrict = startsWithUseStrict; function ensureUseStrict(statements) { var foundUseStrict = false; - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; if (ts.isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { foundUseStrict = true; @@ -14813,7 +43293,7 @@ var ts; } ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var skipped = skipPartiallyEmittedExpressions(operand); + var skipped = ts.skipPartiallyEmittedExpressions(operand); if (skipped.kind === 185) { return operand; } @@ -14825,7 +43305,7 @@ var ts; function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var binaryOperatorPrecedence = ts.getOperatorPrecedence(194, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(194, binaryOperator); - var emittedOperand = skipPartiallyEmittedExpressions(operand); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1: @@ -14866,7 +43346,7 @@ var ts; || binaryOperator === 50; } function getLiteralKindOfBinaryPlusOperand(node) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } @@ -14886,7 +43366,7 @@ var ts; } function parenthesizeForConditionalHead(condition) { var conditionalPrecedence = ts.getOperatorPrecedence(195, 55); - var emittedCondition = skipPartiallyEmittedExpressions(condition); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { return ts.createParen(condition); @@ -14901,7 +43381,7 @@ var ts; } ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression; function parenthesizeForNew(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { case 181: return ts.createParen(expression); @@ -14914,7 +43394,7 @@ var ts; } ts.parenthesizeForNew = parenthesizeForNew; function parenthesizeForAccess(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 182 || emittedExpression.arguments)) { return expression; @@ -14952,7 +43432,7 @@ var ts; } ts.parenthesizeListElements = parenthesizeListElements; function parenthesizeExpressionForList(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); var commaPrecedence = ts.getOperatorPrecedence(194, 26); return expressionPrecedence > commaPrecedence @@ -14961,14 +43441,14 @@ var ts; } ts.parenthesizeExpressionForList = parenthesizeExpressionForList; function parenthesizeExpressionForExpressionStatement(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; - var kind = skipPartiallyEmittedExpressions(callee).kind; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; if (kind === 186 || kind === 187) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); - return recreatePartiallyEmittedExpressions(expression, mutableCall); + return recreateOuterExpressions(expression, mutableCall, 4); } } else { @@ -14991,31 +43471,32 @@ var ts; return member; } ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 162: + case 170: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; function parenthesizeElementTypeMembers(members) { return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); } ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; function parenthesizeTypeParameters(typeParameters) { if (ts.some(typeParameters)) { - var nodeArray = ts.createNodeArray(); + var params = []; for (var i = 0; i < typeParameters.length; ++i) { var entry = typeParameters[i]; - nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? ts.createParenthesizedType(entry) : entry); } - return nodeArray; + return ts.createNodeArray(params); } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { - if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { - var clone_1 = ts.getMutableClone(originalOuterExpression); - clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); - return clone_1; - } - return newInnerExpression; - } function getLeftmostExpression(node) { while (true) { switch (node.kind) { @@ -15033,7 +43514,7 @@ var ts; case 179: node = node.expression; continue; - case 296: + case 288: node = node.expression; continue; } @@ -15054,6 +43535,21 @@ var ts; OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7; } + switch (node.kind) { + case 185: + return (kinds & 1) !== 0; + case 184: + case 202: + case 203: + return (kinds & 2) !== 0; + case 288: + return (kinds & 4) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7; } var previousNode; @@ -15066,7 +43562,7 @@ var ts; node = skipAssertions(node); } if (kinds & 4) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); } } while (previousNode !== node); return node; @@ -15080,19 +43576,29 @@ var ts; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node)) { + while (ts.isAssertionExpression(node) || node.kind === 203) { node = node.expression; } return node; } ts.skipAssertions = skipAssertions; - function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296) { - node = node.expression; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 185: return ts.updateParen(outerExpression, expression); + case 184: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 202: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 203: return ts.updateNonNullExpression(outerExpression, expression); + case 288: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } - return node; } - ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7; } + if (outerExpression && isOuterExpression(outerExpression, kinds)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { node.startsOnNewLine = true; return node; @@ -15104,23 +43610,33 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { - if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } - var helpers = ts.getEmitHelpers(node); - if (helpers) { - for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { - var helper = helpers_2[_i]; - if (!helper.scoped) { - var parseNode = ts.getOriginalNode(node, ts.isSourceFile); - var emitNode = ts.getOrCreateEmitNode(parseNode); - return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = hasExportStarsToExportValues + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } } } } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } } } ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; @@ -15184,7 +43700,7 @@ var ts; if (ts.isAssignmentExpression(bindingElement, true)) { return bindingElement.right; } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); } } @@ -15207,7 +43723,7 @@ var ts; if (ts.isAssignmentExpression(bindingElement, true)) { return getTargetOfBindingOrAssignmentElement(bindingElement.left); } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } return bindingElement; @@ -15333,27237 +43849,6 @@ var ts; return node; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; - function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { - var externalImports = []; - var exportSpecifiers = ts.createMultiMap(); - var exportedBindings = []; - var uniqueExports = ts.createMap(); - var exportedNames; - var hasExportDefault = false; - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); - var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - if (externalHelpersImportDeclaration) { - externalImports.push(externalHelpersImportDeclaration); - } - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 238: - externalImports.push(node); - break; - case 237: - if (node.moduleReference.kind === 248) { - externalImports.push(node); - } - break; - case 244: - if (node.moduleSpecifier) { - if (!node.exportClause) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } - else { - externalImports.push(node); - } - } - else { - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - if (!uniqueExports.get(specifier.name.text)) { - var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(name.text, specifier); - var decl = resolver.getReferencedImportDeclaration(name) - || resolver.getReferencedValueDeclaration(name); - if (decl) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); - } - uniqueExports.set(specifier.name.text, true); - exportedNames = ts.append(exportedNames, specifier.name); - } - } - } - break; - case 243: - if (node.isExportEquals && !exportEquals) { - exportEquals = node; - } - break; - case 208: - if (ts.hasModifier(node, 1)) { - for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { - var decl = _e[_d]; - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); - } - } - break; - case 228: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - case 229: - if (ts.hasModifier(node, 1)) { - if (ts.hasModifier(node, 512)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - } - } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; - } - ts.collectExternalModuleInfo = collectExternalModuleInfo; - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { - if (ts.isBindingPattern(decl.name)) { - for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); - } - } - } - else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(decl.name.text)) { - uniqueExports.set(decl.name.text, true); - exportedNames = ts.append(exportedNames, decl.name); - } - } - return exportedNames; - } - function multiMapSparseArrayAdd(map, key, value) { - var values = map[key]; - if (values) { - values.push(value); - } - else { - map[key] = values = [value]; - } - return values; - } -})(ts || (ts = {})); -var ts; -(function (ts) { - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - function createNode(kind, pos, end) { - if (kind === 265) { - return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); - } - else if (kind === 71) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 143) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } - else { - return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); - } - } - ts.createNode = createNode; - function visitNode(cbNode, node) { - if (node) { - return cbNode(node); - } - } - function visitNodeArray(cbNodes, nodes) { - if (nodes) { - return cbNodes(nodes); - } - } - function visitEachNode(cbNode, nodes) { - if (nodes) { - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; - var result = cbNode(node); - if (result) { - return result; - } - } - } - } - function forEachChild(node, cbNode, cbNodeArray) { - if (!node) { - return; - } - var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; - var cbNodes = cbNodeArray || cbNode; - switch (node.kind) { - case 143: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); - case 145: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.constraint) || - visitNode(cbNode, node.default) || - visitNode(cbNode, node.expression); - case 262: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.equalsToken) || - visitNode(cbNode, node.objectAssignmentInitializer); - case 263: - return visitNode(cbNode, node.expression); - case 146: - case 149: - case 148: - case 261: - case 226: - case 176: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 160: - case 161: - case 155: - case 156: - case 157: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 151: - case 150: - case 152: - case 153: - case 154: - case 186: - case 228: - case 187: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.equalsGreaterThanToken) || - visitNode(cbNode, node.body); - case 159: - return visitNode(cbNode, node.typeName) || - visitNodes(cbNodes, node.typeArguments); - case 158: - return visitNode(cbNode, node.parameterName) || - visitNode(cbNode, node.type); - case 162: - return visitNode(cbNode, node.exprName); - case 163: - return visitNodes(cbNodes, node.members); - case 164: - return visitNode(cbNode, node.elementType); - case 165: - return visitNodes(cbNodes, node.elementTypes); - case 166: - case 167: - return visitNodes(cbNodes, node.types); - case 168: - case 170: - return visitNode(cbNode, node.type); - case 171: - return visitNode(cbNode, node.objectType) || - visitNode(cbNode, node.indexType); - case 172: - return visitNode(cbNode, node.readonlyToken) || - visitNode(cbNode, node.typeParameter) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); - case 173: - return visitNode(cbNode, node.literal); - case 174: - case 175: - return visitNodes(cbNodes, node.elements); - case 177: - return visitNodes(cbNodes, node.elements); - case 178: - return visitNodes(cbNodes, node.properties); - case 179: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.name); - case 180: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.argumentExpression); - case 181: - case 182: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments) || - visitNodes(cbNodes, node.arguments); - case 183: - return visitNode(cbNode, node.tag) || - visitNode(cbNode, node.template); - case 184: - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.expression); - case 185: - return visitNode(cbNode, node.expression); - case 188: - return visitNode(cbNode, node.expression); - case 189: - return visitNode(cbNode, node.expression); - case 190: - return visitNode(cbNode, node.expression); - case 192: - return visitNode(cbNode, node.operand); - case 197: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 191: - return visitNode(cbNode, node.expression); - case 193: - return visitNode(cbNode, node.operand); - case 194: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.operatorToken) || - visitNode(cbNode, node.right); - case 202: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.type); - case 203: - return visitNode(cbNode, node.expression); - case 204: - return visitNode(cbNode, node.name); - case 195: - return visitNode(cbNode, node.condition) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.whenTrue) || - visitNode(cbNode, node.colonToken) || - visitNode(cbNode, node.whenFalse); - case 198: - return visitNode(cbNode, node.expression); - case 207: - case 234: - return visitNodes(cbNodes, node.statements); - case 265: - return visitNodes(cbNodes, node.statements) || - visitNode(cbNode, node.endOfFileToken); - case 208: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.declarationList); - case 227: - return visitNodes(cbNodes, node.declarations); - case 210: - return visitNode(cbNode, node.expression); - case 211: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.thenStatement) || - visitNode(cbNode, node.elseStatement); - case 212: - return visitNode(cbNode, node.statement) || - visitNode(cbNode, node.expression); - case 213: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 214: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.condition) || - visitNode(cbNode, node.incrementor) || - visitNode(cbNode, node.statement); - case 215: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 216: - return visitNode(cbNode, node.awaitModifier) || - visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 217: - case 218: - return visitNode(cbNode, node.label); - case 219: - return visitNode(cbNode, node.expression); - case 220: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 221: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 235: - return visitNodes(cbNodes, node.clauses); - case 257: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 258: - return visitNodes(cbNodes, node.statements); - case 222: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); - case 223: - return visitNode(cbNode, node.expression); - case 224: - return visitNode(cbNode, node.tryBlock) || - visitNode(cbNode, node.catchClause) || - visitNode(cbNode, node.finallyBlock); - case 260: - return visitNode(cbNode, node.variableDeclaration) || - visitNode(cbNode, node.block); - case 147: - return visitNode(cbNode, node.expression); - case 229: - case 199: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 230: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 231: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); - case 232: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 264: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 233: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); - case 237: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); - case 238: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.importClause) || - visitNode(cbNode, node.moduleSpecifier); - case 239: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.namedBindings); - case 236: - return visitNode(cbNode, node.name); - case 240: - return visitNode(cbNode, node.name); - case 241: - case 245: - return visitNodes(cbNodes, node.elements); - case 244: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.exportClause) || - visitNode(cbNode, node.moduleSpecifier); - case 242: - case 246: - return visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name); - case 243: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.expression); - case 196: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 205: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144: - return visitNode(cbNode, node.expression); - case 259: - return visitNodes(cbNodes, node.types); - case 201: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments); - case 248: - 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) || - visitNode(cbNode, node.closingElement); - case 250: - case 251: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.attributes); - case 254: - return visitNodes(cbNodes, node.properties); - case 253: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 255: - return visitNode(cbNode, node.expression); - case 256: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.expression); - case 252: - return visitNode(cbNode, node.tagName); - case 267: - return visitNode(cbNode, node.type); - case 271: - return visitNodes(cbNodes, node.types); - case 272: - return visitNodes(cbNodes, node.types); - case 270: - return visitNode(cbNode, node.elementType); - case 274: - return visitNode(cbNode, node.type); - case 273: - return visitNode(cbNode, node.type); - case 275: - return visitNode(cbNode, node.literal); - case 277: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 278: - return visitNode(cbNode, node.type); - case 279: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 280: - return visitNode(cbNode, node.type); - case 281: - return visitNode(cbNode, node.type); - case 282: - return visitNode(cbNode, node.type); - case 276: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.type); - case 283: - return visitNodes(cbNodes, node.tags); - case 286: - return visitNode(cbNode, node.preParameterName) || - visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.postParameterName); - case 287: - return visitNode(cbNode, node.typeExpression); - case 288: - return visitNode(cbNode, node.typeExpression); - case 285: - return visitNode(cbNode, node.typeExpression); - case 289: - return visitNodes(cbNodes, node.typeParameters); - case 290: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.jsDocTypeLiteral); - case 292: - return visitNodes(cbNodes, node.jsDocPropertyTags); - case 291: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - case 296: - return visitNode(cbNode, node.expression); - case 293: - return visitNode(cbNode, node.literal); - } - } - ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { - if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); - return result; - } - ts.createSourceFile = createSourceFile; - function parseIsolatedEntityName(text, languageVersion) { - return Parser.parseIsolatedEntityName(text, languageVersion); - } - ts.parseIsolatedEntityName = parseIsolatedEntityName; - function isExternalModule(file) { - return file.externalModuleIndicator !== undefined; - } - ts.isExternalModule = isExternalModule; - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - } - ts.updateSourceFile = updateSourceFile; - function parseIsolatedJSDocComment(content, start, length) { - var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDoc) { - Parser.fixupParentReferences(result.jsDoc); - } - return result; - } - ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocTypeExpressionForTests(content, start, length) { - return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); - } - ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - var Parser; - (function (Parser) { - var scanner = ts.createScanner(5, true); - var disallowInAndDecoratorContext = 2048 | 8192; - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - var sourceFile; - var parseDiagnostics; - var syntaxCursor; - var currentToken; - var sourceText; - var nodeCount; - var identifiers; - var identifierCount; - var parsingContext; - var contextFlags; - var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { - scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); - clearState(); - return result; - } - Parser.parseSourceFile = parseSourceFile; - function parseIsolatedEntityName(content, languageVersion) { - initializeState(content, languageVersion, undefined, 1); - nextToken(); - var entityName = parseEntityName(true); - var isInvalid = token() === 1 && !parseDiagnostics.length; - clearState(); - return isInvalid ? entityName : undefined; - } - Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function getLanguageVariant(scriptKind) { - return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 ? 1 : 0; - } - function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { - NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); - SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); - sourceText = _sourceText; - syntaxCursor = _syntaxCursor; - parseDiagnostics = []; - parsingContext = 0; - identifiers = ts.createMap(); - identifierCount = 0; - nodeCount = 0; - contextFlags = scriptKind === 1 || scriptKind === 2 ? 65536 : 0; - parseErrorBeforeNextFinishedNode = false; - scanner.setText(sourceText); - scanner.setOnError(scanError); - scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(getLanguageVariant(scriptKind)); - } - function clearState() { - scanner.setText(""); - scanner.setOnError(undefined); - parseDiagnostics = undefined; - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); - sourceFile.flags = contextFlags; - nextToken(); - processReferenceComments(sourceFile); - sourceFile.statements = parseList(0, parseStatement); - ts.Debug.assert(token() === 1); - sourceFile.endOfFileToken = parseTokenNode(); - setExternalModuleIndicator(sourceFile); - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.identifiers = identifiers; - sourceFile.parseDiagnostics = parseDiagnostics; - if (setParentNodes) { - fixupParentReferences(sourceFile); - } - return sourceFile; - } - function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; - } - node.jsDoc.push(jsDoc); - } - } - return node; - } - function fixupParentReferences(rootNode) { - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDoc) { - for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - jsDoc.parent = n; - parent = jsDoc; - forEachChild(jsDoc, visitNode); - } - } - parent = saveParent; - } - } - } - Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); - nodeCount++; - sourceFile.text = sourceText; - sourceFile.bindDiagnostics = []; - sourceFile.languageVersion = languageVersion; - sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); - sourceFile.scriptKind = scriptKind; - return sourceFile; - } - function setContextFlag(val, flag) { - if (val) { - contextFlags |= flag; - } - else { - contextFlags &= ~flag; - } - } - function setDisallowInContext(val) { - setContextFlag(val, 2048); - } - function setYieldContext(val) { - setContextFlag(val, 4096); - } - function setDecoratorContext(val) { - setContextFlag(val, 8192); - } - function setAwaitContext(val) { - setContextFlag(val, 16384); - } - function doOutsideOfContext(context, func) { - var contextFlagsToClear = context & contextFlags; - if (contextFlagsToClear) { - setContextFlag(false, contextFlagsToClear); - var result = func(); - setContextFlag(true, contextFlagsToClear); - return result; - } - return func(); - } - function doInsideOfContext(context, func) { - var contextFlagsToSet = context & ~contextFlags; - if (contextFlagsToSet) { - setContextFlag(true, contextFlagsToSet); - var result = func(); - setContextFlag(false, contextFlagsToSet); - return result; - } - return func(); - } - function allowInAnd(func) { - return doOutsideOfContext(2048, func); - } - function disallowInAnd(func) { - return doInsideOfContext(2048, func); - } - function doInYieldContext(func) { - return doInsideOfContext(4096, func); - } - function doInDecoratorContext(func) { - return doInsideOfContext(8192, func); - } - function doInAwaitContext(func) { - return doInsideOfContext(16384, func); - } - function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(16384, func); - } - function doInYieldAndAwaitContext(func) { - return doInsideOfContext(4096 | 16384, func); - } - function inContext(flags) { - return (contextFlags & flags) !== 0; - } - function inYieldContext() { - return inContext(4096); - } - function inDisallowInContext() { - return inContext(2048); - } - function inDecoratorContext() { - return inContext(8192); - } - function inAwaitContext() { - return inContext(16384); - } - function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); - } - function parseErrorAtPosition(start, length, message, arg0) { - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (!lastError || start !== lastError.start) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); - } - parseErrorBeforeNextFinishedNode = true; - } - function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); - } - function getNodePos() { - return scanner.getStartPos(); - } - function getNodeEnd() { - return scanner.getStartPos(); - } - function token() { - return currentToken; - } - function nextToken() { - return currentToken = scanner.scan(); - } - function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); - } - function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); - } - function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); - } - function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); - } - function scanJsxText() { - return currentToken = scanner.scanJsxToken(); - } - function scanJsxAttributeValue() { - return currentToken = scanner.scanJsxAttributeValue(); - } - function speculationHelper(callback, isLookAhead) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var saveContextFlags = contextFlags; - var result = isLookAhead - ? scanner.lookAhead(callback) - : scanner.tryScan(callback); - ts.Debug.assert(saveContextFlags === contextFlags); - if (!result || isLookAhead) { - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - } - return result; - } - function lookAhead(callback) { - return speculationHelper(callback, true); - } - function tryParse(callback) { - return speculationHelper(callback, false); - } - function isIdentifier() { - if (token() === 71) { - return true; - } - if (token() === 116 && inYieldContext()) { - return false; - } - if (token() === 121 && inAwaitContext()) { - return false; - } - return token() > 107; - } - function parseExpected(kind, diagnosticMessage, shouldAdvance) { - if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { - if (shouldAdvance) { - nextToken(); - } - return true; - } - if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage); - } - else { - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); - } - return false; - } - function parseOptional(t) { - if (token() === t) { - nextToken(); - return true; - } - return false; - } - function parseOptionalToken(t) { - if (token() === t) { - return parseTokenNode(); - } - return undefined; - } - function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { - return parseOptionalToken(t) || - createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); - } - function parseTokenNode() { - var node = createNode(token()); - nextToken(); - return finishNode(node); - } - function canParseSemicolon() { - if (token() === 25) { - return true; - } - return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); - } - function parseSemicolon() { - if (canParseSemicolon()) { - if (token() === 25) { - nextToken(); - } - return true; - } - else { - return parseExpected(25); - } - } - function createNode(kind, pos) { - nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); - } - return kind >= 143 ? new NodeConstructor(kind, pos, pos) : - kind === 71 ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); - } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } - array.pos = pos; - array.end = pos; - return array; - } - function finishNode(node, end) { - node.end = end === undefined ? scanner.getStartPos() : end; - if (contextFlags) { - node.flags |= contextFlags; - } - if (parseErrorBeforeNextFinishedNode) { - parseErrorBeforeNextFinishedNode = false; - node.flags |= 32768; - } - return node; - } - function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { - if (reportAtCurrentPosition) { - parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); - } - else { - parseErrorAtCurrentToken(diagnosticMessage, arg0); - } - var result = createNode(kind, scanner.getStartPos()); - result.text = ""; - return finishNode(result); - } - function internIdentifier(text) { - text = ts.escapeIdentifier(text); - var identifier = identifiers.get(text); - if (identifier === undefined) { - identifiers.set(text, identifier = text); - } - return identifier; - } - function createIdentifier(isIdentifier, diagnosticMessage) { - identifierCount++; - if (isIdentifier) { - var node = createNode(71); - if (token() !== 71) { - node.originalKeywordKind = token(); - } - node.text = internIdentifier(scanner.getTokenValue()); - nextToken(); - return finishNode(node); - } - return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); - } - function parseIdentifier(diagnosticMessage) { - return createIdentifier(isIdentifier(), diagnosticMessage); - } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8; - } - function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 || token() === 8) { - return parseLiteralNode(true); - } - if (allowComputedPropertyNames && token() === 21) { - return parseComputedPropertyName(); - } - return parseIdentifierName(); - } - function parsePropertyName() { - return parsePropertyNameWorker(true); - } - function parseSimplePropertyName() { - return parsePropertyNameWorker(false); - } - function isSimplePropertyName() { - return token() === 9 || token() === 8 || ts.tokenIsIdentifierOrKeyword(token()); - } - function parseComputedPropertyName() { - var node = createNode(144); - parseExpected(21); - node.expression = allowInAnd(parseExpression); - parseExpected(22); - return finishNode(node); - } - function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); - } - function nextTokenIsOnSameLineAndCanFollowModifier() { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); - } - function nextTokenCanFollowModifier() { - if (token() === 76) { - return nextToken() === 83; - } - if (token() === 84) { - nextToken(); - if (token() === 79) { - return lookAhead(nextTokenIsClassOrFunctionOrAsync); - } - return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); - } - if (token() === 79) { - return nextTokenIsClassOrFunctionOrAsync(); - } - if (token() === 115) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); - } - function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); - } - function canFollowModifier() { - return token() === 21 - || token() === 17 - || token() === 39 - || token() === 24 - || isLiteralPropertyName(); - } - function nextTokenIsClassOrFunctionOrAsync() { - nextToken(); - return token() === 75 || token() === 89 || - (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); - } - function isListElement(parsingContext, inErrorRecovery) { - var node = currentNode(parsingContext); - if (node) { - return true; - } - switch (parsingContext) { - case 0: - case 1: - case 3: - return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); - case 2: - return token() === 73 || token() === 79; - case 4: - return lookAhead(isTypeMemberStart); - case 5: - return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); - case 6: - return token() === 21 || isLiteralPropertyName(); - case 12: - return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); - case 17: - return isLiteralPropertyName(); - case 9: - return token() === 21 || token() === 24 || isLiteralPropertyName(); - case 7: - if (token() === 17) { - return lookAhead(isValidHeritageClauseObjectLiteral); - } - if (!inErrorRecovery) { - return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - else { - return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - case 8: - return isIdentifierOrPattern(); - case 10: - return token() === 26 || token() === 24 || isIdentifierOrPattern(); - case 18: - return isIdentifier(); - case 11: - case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); - case 16: - return isStartOfParameter(); - case 19: - case 20: - return token() === 26 || isStartOfType(); - case 21: - return isHeritageClause(); - case 22: - return ts.tokenIsIdentifierOrKeyword(token()); - case 13: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; - case 14: - return true; - case 23: - case 24: - case 26: - return JSDocParser.isJSDocType(); - case 25: - return isSimplePropertyName(); - } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); - } - function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17); - if (nextToken() === 18) { - var next = nextToken(); - return next === 26 || next === 17 || next === 85 || next === 108; - } - return true; - } - function nextTokenIsIdentifier() { - nextToken(); - return isIdentifier(); - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); - } - function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 || - token() === 85) { - return lookAhead(nextTokenIsStartOfExpression); - } - return false; - } - function nextTokenIsStartOfExpression() { - nextToken(); - return isStartOfExpression(); - } - function isListTerminator(kind) { - if (token() === 1) { - return true; - } - switch (kind) { - case 1: - case 2: - case 4: - case 5: - case 6: - case 12: - case 9: - case 22: - return token() === 18; - case 3: - return token() === 18 || token() === 73 || token() === 79; - case 7: - return token() === 17 || token() === 85 || token() === 108; - case 8: - return isVariableDeclaratorListTerminator(); - case 18: - return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; - case 11: - return token() === 20 || token() === 25; - case 15: - case 20: - case 10: - return token() === 22; - case 16: - case 17: - return token() === 20 || token() === 22; - case 19: - return token() !== 26; - case 21: - return token() === 17 || token() === 18; - case 13: - return token() === 29 || token() === 41; - case 14: - return token() === 27 && lookAhead(nextTokenIsSlash); - case 23: - return token() === 20 || token() === 56 || token() === 18; - case 24: - return token() === 29 || token() === 18; - case 26: - return token() === 22 || token() === 18; - case 25: - return token() === 18; - } - } - function isVariableDeclaratorListTerminator() { - if (canParseSemicolon()) { - return true; - } - if (isInOrOfKeyword(token())) { - return true; - } - if (token() === 36) { - return true; - } - return false; - } - function isInSomeParsingContext() { - for (var kind = 0; kind < 27; kind++) { - if (parsingContext & (1 << kind)) { - if (isListElement(kind, true) || isListTerminator(kind)) { - return true; - } - } - } - return false; - } - function parseList(kind, parseElement) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - while (!isListTerminator(kind)) { - if (isListElement(kind, false)) { - var element = parseListElement(kind, parseElement); - result.push(element); - continue; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function parseListElement(parsingContext, parseElement) { - var node = currentNode(parsingContext); - if (node) { - return consumeNode(node); - } - return parseElement(); - } - function currentNode(parsingContext) { - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - return undefined; - } - var node = syntaxCursor.currentNode(scanner.getStartPos()); - if (ts.nodeIsMissing(node)) { - return undefined; - } - if (node.intersectsChange) { - return undefined; - } - if (ts.containsParseError(node)) { - return undefined; - } - var nodeContextFlags = node.flags & 96256; - if (nodeContextFlags !== contextFlags) { - return undefined; - } - if (!canReuseNode(node, parsingContext)) { - return undefined; - } - return node; - } - function consumeNode(node) { - scanner.setTextPos(node.end); - nextToken(); - return node; - } - function canReuseNode(node, parsingContext) { - switch (parsingContext) { - case 5: - return isReusableClassMember(node); - case 2: - return isReusableSwitchClause(node); - case 0: - case 1: - case 3: - return isReusableStatement(node); - case 6: - return isReusableEnumMember(node); - case 4: - return isReusableTypeMember(node); - case 8: - return isReusableVariableDeclaration(node); - case 16: - return isReusableParameter(node); - case 17: - return false; - case 21: - case 18: - case 20: - case 19: - case 11: - case 12: - case 7: - case 13: - case 14: - } - return false; - } - function isReusableClassMember(node) { - if (node) { - switch (node.kind) { - case 152: - case 157: - case 153: - case 154: - case 149: - case 206: - return true; - case 151: - var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 && - methodDeclaration.name.originalKeywordKind === 123; - return !nameIsConstructor; - } - } - return false; - } - function isReusableSwitchClause(node) { - if (node) { - switch (node.kind) { - case 257: - case 258: - return true; - } - } - return false; - } - function isReusableStatement(node) { - if (node) { - switch (node.kind) { - case 228: - case 208: - case 207: - case 211: - case 210: - case 223: - case 219: - case 221: - case 218: - case 217: - case 215: - case 216: - case 214: - case 213: - case 220: - case 209: - case 224: - case 222: - case 212: - case 225: - case 238: - case 237: - case 244: - case 243: - case 233: - case 229: - case 230: - case 232: - case 231: - return true; - } - } - return false; - } - function isReusableEnumMember(node) { - return node.kind === 264; - } - function isReusableTypeMember(node) { - if (node) { - switch (node.kind) { - case 156: - case 150: - case 157: - case 148: - case 155: - return true; - } - } - return false; - } - function isReusableVariableDeclaration(node) { - if (node.kind !== 226) { - return false; - } - var variableDeclarator = node; - return variableDeclarator.initializer === undefined; - } - function isReusableParameter(node) { - if (node.kind !== 146) { - return false; - } - var parameter = node; - return parameter.initializer === undefined; - } - function abortParsingListOrMoveToNextToken(kind) { - parseErrorAtCurrentToken(parsingContextErrors(kind)); - if (isInSomeParsingContext()) { - return true; - } - nextToken(); - return false; - } - function parsingContextErrors(context) { - switch (context) { - case 0: return ts.Diagnostics.Declaration_or_statement_expected; - case 1: return ts.Diagnostics.Declaration_or_statement_expected; - case 2: return ts.Diagnostics.case_or_default_expected; - case 3: return ts.Diagnostics.Statement_expected; - case 17: - case 4: return ts.Diagnostics.Property_or_signature_expected; - case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; - case 6: return ts.Diagnostics.Enum_member_expected; - case 7: return ts.Diagnostics.Expression_expected; - case 8: return ts.Diagnostics.Variable_declaration_expected; - case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; - case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; - case 11: return ts.Diagnostics.Argument_expression_expected; - case 12: return ts.Diagnostics.Property_assignment_expected; - case 15: return ts.Diagnostics.Expression_or_comma_expected; - case 16: return ts.Diagnostics.Parameter_declaration_expected; - case 18: return ts.Diagnostics.Type_parameter_declaration_expected; - case 19: return ts.Diagnostics.Type_argument_expected; - case 20: return ts.Diagnostics.Type_expected; - case 21: return ts.Diagnostics.Unexpected_token_expected; - case 22: return ts.Diagnostics.Identifier_expected; - case 13: return ts.Diagnostics.Identifier_expected; - case 14: return ts.Diagnostics.Identifier_expected; - case 23: return ts.Diagnostics.Parameter_declaration_expected; - case 24: return ts.Diagnostics.Type_argument_expected; - case 26: return ts.Diagnostics.Type_expected; - case 25: return ts.Diagnostics.Property_assignment_expected; - } - } - function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - var commaStart = -1; - while (true) { - if (isListElement(kind, false)) { - result.push(parseListElement(kind, parseElement)); - commaStart = scanner.getTokenPos(); - if (parseOptional(26)) { - continue; - } - commaStart = -1; - if (isListTerminator(kind)) { - break; - } - parseExpected(26); - if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - } - continue; - } - if (isListTerminator(kind)) { - break; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - if (commaStart >= 0) { - result.hasTrailingComma = true; - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function createMissingList() { - return createNodeArray(); - } - function parseBracketedList(kind, parseElement, open, close) { - if (parseExpected(open)) { - var result = parseDelimitedList(kind, parseElement); - parseExpected(close); - return result; - } - return createMissingList(); - } - function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(23)) { - var node = createNode(143, entity.pos); - node.left = entity; - node.right = parseRightSideOfDot(allowReservedWords); - entity = finishNode(node); - } - return entity; - } - function parseRightSideOfDot(allowIdentifierNames) { - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { - var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - if (matchesPattern) { - return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); - } - } - return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); - } - function parseTemplateExpression() { - var template = createNode(196); - template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); - do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; - return finishNode(template); - } - function parseTemplateSpan() { - var span = createNode(205); - span.expression = allowInAnd(parseExpression); - var literal; - if (token() === 18) { - reScanTemplateToken(); - literal = parseTemplateMiddleOrTemplateTail(); - } - else { - literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); - } - span.literal = literal; - return finishNode(span); - } - function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); - } - function parseTemplateHead() { - var fragment = parseLiteralLikeNode(token(), false); - ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); - return fragment; - } - function parseTemplateMiddleOrTemplateTail() { - var fragment = parseLiteralLikeNode(token(), false); - ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); - return fragment; - } - function parseLiteralLikeNode(kind, internName) { - var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = internName ? internIdentifier(text) : text; - if (scanner.hasExtendedUnicodeEscape()) { - node.hasExtendedUnicodeEscape = true; - } - if (scanner.isUnterminated()) { - node.isUnterminated = true; - } - if (node.kind === 8) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); - } - nextToken(); - finishNode(node); - return node; - } - function parseTypeReference() { - var node = createNode(159); - node.typeName = parseEntityName(false, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } - return finishNode(node); - } - function parseThisTypePredicate(lhs) { - nextToken(); - var node = createNode(158, lhs.pos); - node.parameterName = lhs; - node.type = parseType(); - return finishNode(node); - } - function parseThisTypeNode() { - var node = createNode(169); - nextToken(); - return finishNode(node); - } - function parseTypeQuery() { - var node = createNode(162); - parseExpected(103); - node.exprName = parseEntityName(true); - return finishNode(node); - } - function parseTypeParameter() { - var node = createNode(145); - node.name = parseIdentifier(); - if (parseOptional(85)) { - if (isStartOfType() || !isStartOfExpression()) { - node.constraint = parseType(); - } - else { - node.expression = parseUnaryExpressionOrHigher(); - } - } - if (parseOptional(58)) { - node.default = parseType(); - } - return finishNode(node); - } - function parseTypeParameters() { - if (token() === 27) { - return parseBracketedList(18, parseTypeParameter, 27, 29); - } - } - function parseParameterType() { - if (parseOptional(56)) { - return parseType(); - } - return undefined; - } - function isStartOfParameter() { - return token() === 24 || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 || token() === 99; - } - function parseParameter() { - var node = createNode(146); - if (token() === 99) { - node.name = createIdentifier(true); - node.type = parseParameterType(); - return finishNode(node); - } - node.decorators = parseDecorators(); - node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24); - node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { - nextToken(); - } - node.questionToken = parseOptionalToken(55); - node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(true); - return addJSDocComment(finishNode(node)); - } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(true); - } - function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 36; - signature.typeParameters = parseTypeParameters(); - signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); - if (returnTokenRequired) { - parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); - } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); - } - } - function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - if (parseExpected(19)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(yieldContext); - setAwaitContext(awaitContext); - var result = parseDelimitedList(16, parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20) && requireCompleteParameterList) { - return undefined; - } - return result; - } - return requireCompleteParameterList ? undefined : createMissingList(); - } - function parseTypeMemberSemicolon() { - if (parseOptional(26)) { - return; - } - parseSemicolon(); - } - function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156) { - parseExpected(94); - } - fillSignature(56, false, false, false, node); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); - } - function isIndexSignature() { - if (token() !== 21) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); - } - function isUnambiguouslyIndexSignature() { - nextToken(); - if (token() === 24 || token() === 22) { - return true; - } - if (ts.isModifierKind(token())) { - nextToken(); - if (isIdentifier()) { - return true; - } - } - else if (!isIdentifier()) { - return false; - } - else { - nextToken(); - } - if (token() === 56 || token() === 26) { - return true; - } - if (token() !== 55) { - return false; - } - nextToken(); - return token() === 56 || token() === 26 || token() === 22; - } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.parameters = parseBracketedList(16, parseParameter, 21, 22); - node.type = parseTypeAnnotation(); - parseTypeMemberSemicolon(); - return finishNode(node); - } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (token() === 19 || token() === 27) { - var method = createNode(150, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - fillSignature(56, false, false, false, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); - } - else { - var property = createNode(148, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - if (token() === 58) { - property.initializer = parseNonParameterInitializer(); - } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); - } - } - function isTypeMemberStart() { - if (token() === 19 || token() === 27) { - return true; - } - var idToken; - while (ts.isModifierKind(token())) { - idToken = true; - nextToken(); - } - if (token() === 21) { - return true; - } - if (isLiteralPropertyName()) { - idToken = true; - nextToken(); - } - if (idToken) { - return token() === 19 || - token() === 27 || - token() === 55 || - token() === 56 || - token() === 26 || - canParseSemicolon(); - } - return false; - } - function parseTypeMember() { - if (token() === 19 || token() === 27) { - return parseSignatureMember(155); - } - if (token() === 94 && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(156); - } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); - } - return parsePropertyOrMethodSignature(fullStart, modifiers); - } - function isStartOfConstructSignature() { - nextToken(); - return token() === 19 || token() === 27; - } - function parseTypeLiteral() { - var node = createNode(163); - node.members = parseObjectTypeMembers(); - return finishNode(node); - } - function parseObjectTypeMembers() { - var members; - if (parseExpected(17)) { - members = parseList(4, parseTypeMember); - parseExpected(18); - } - else { - members = createMissingList(); - } - return members; - } - function isStartOfMappedType() { - nextToken(); - if (token() === 131) { - nextToken(); - } - return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; - } - function parseMappedTypeParameter() { - var node = createNode(145); - node.name = parseIdentifier(); - parseExpected(92); - node.constraint = parseType(); - return finishNode(node); - } - function parseMappedType() { - var node = createNode(172); - parseExpected(17); - node.readonlyToken = parseOptionalToken(131); - parseExpected(21); - node.typeParameter = parseMappedTypeParameter(); - parseExpected(22); - node.questionToken = parseOptionalToken(55); - node.type = parseTypeAnnotation(); - parseSemicolon(); - parseExpected(18); - return finishNode(node); - } - function parseTupleType() { - var node = createNode(165); - node.elementTypes = parseBracketedList(20, parseType, 21, 22); - return finishNode(node); - } - function parseParenthesizedType() { - var node = createNode(168); - parseExpected(19); - node.type = parseType(); - parseExpected(20); - return finishNode(node); - } - function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161) { - parseExpected(94); - } - fillSignature(36, false, false, false, node); - return finishNode(node); - } - function parseKeywordAndNoDot() { - var node = parseTokenNode(); - return token() === 23 ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(173); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8; - } - function parseNonArrayType() { - switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 139: - case 130: - case 134: - var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); - case 9: - case 8: - case 101: - case 86: - return parseLiteralTypeNode(); - case 38: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 105: - case 95: - return parseTokenNode(); - case 99: { - var thisKeyword = parseThisTypeNode(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { - return parseThisTypePredicate(thisKeyword); - } - else { - return thisKeyword; - } - } - case 103: - return parseTypeQuery(); - case 17: - return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21: - return parseTupleType(); - case 19: - return parseParenthesizedType(); - default: - return parseTypeReference(); - } - } - function isStartOfType() { - switch (token()) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 105: - case 139: - case 95: - case 99: - case 103: - case 130: - case 17: - case 21: - case 27: - case 49: - case 48: - case 94: - case 9: - case 8: - case 101: - case 86: - case 134: - return true; - case 38: - return lookAhead(nextTokenIsNumericLiteral); - case 19: - return lookAhead(isStartOfParenthesizedOrFunctionType); - default: - return isIdentifier(); - } - } - function isStartOfParenthesizedOrFunctionType() { - nextToken(); - return token() === 20 || isStartOfParameter() || isStartOfType(); - } - function parseArrayTypeOrHigher() { - var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { - if (isStartOfType()) { - var node = createNode(171, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22); - type = finishNode(node); - } - else { - var node = createNode(164, type.pos); - node.elementType = type; - parseExpected(22); - type = finishNode(node); - } - } - return type; - } - function parseTypeOperator(operator) { - var node = createNode(170); - parseExpected(operator); - node.operator = operator; - node.type = parseTypeOperatorOrHigher(); - return finishNode(node); - } - function parseTypeOperatorOrHigher() { - switch (token()) { - case 127: - return parseTypeOperator(127); - } - return parseArrayTypeOrHigher(); - } - function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { - parseOptional(operator); - var type = parseConstituentType(); - if (token() === operator) { - var types = createNodeArray([type], type.pos); - while (parseOptional(operator)) { - types.push(parseConstituentType()); - } - types.end = getNodeEnd(); - var node = createNode(kind, type.pos); - node.types = types; - type = finishNode(node); - } - return type; - } - function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); - } - function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); - } - function isStartOfFunctionType() { - if (token() === 27) { - return true; - } - return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); - } - function skipParameterStart() { - if (ts.isModifierKind(token())) { - parseModifiers(); - } - if (isIdentifier() || token() === 99) { - nextToken(); - return true; - } - if (token() === 21 || token() === 17) { - var previousErrorCount = parseDiagnostics.length; - parseIdentifierOrPattern(); - return previousErrorCount === parseDiagnostics.length; - } - return false; - } - function isUnambiguouslyStartOfFunctionType() { - nextToken(); - if (token() === 20 || token() === 24) { - return true; - } - if (skipParameterStart()) { - if (token() === 56 || token() === 26 || - token() === 55 || token() === 58) { - return true; - } - if (token() === 20) { - nextToken(); - if (token() === 36) { - return true; - } - } - } - return false; - } - function parseTypeOrTypePredicate() { - var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); - var type = parseType(); - if (typePredicateVariable) { - var node = createNode(158, typePredicateVariable.pos); - node.parameterName = typePredicateVariable; - node.type = type; - return finishNode(node); - } - else { - return type; - } - } - function parseTypePredicatePrefix() { - var id = parseIdentifier(); - if (token() === 126 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - return id; - } - } - function parseType() { - return doOutsideOfContext(20480, parseTypeWorker); - } - function parseTypeWorker() { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160); - } - if (token() === 94) { - return parseFunctionOrConstructorType(161); - } - return parseUnionTypeOrHigher(); - } - function parseTypeAnnotation() { - return parseOptional(56) ? parseType() : undefined; - } - function isStartOfLeftHandSideExpression() { - switch (token()) { - case 99: - case 97: - case 95: - case 101: - case 86: - case 8: - case 9: - case 13: - case 14: - case 19: - case 21: - case 17: - case 89: - case 75: - case 94: - case 41: - case 63: - case 71: - return true; - default: - return isIdentifier(); - } - } - function isStartOfExpression() { - if (isStartOfLeftHandSideExpression()) { - return true; - } - switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 43: - case 44: - case 27: - case 121: - case 116: - return true; - default: - if (isBinaryOperator()) { - return true; - } - return isIdentifier(); - } - } - function isStartOfExpressionStatement() { - return token() !== 17 && - token() !== 89 && - token() !== 75 && - token() !== 57 && - isStartOfExpression(); - } - function parseExpression() { - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var expr = parseAssignmentExpressionOrHigher(); - var operatorToken; - while ((operatorToken = parseOptionalToken(26))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); - } - if (saveDecoratorContext) { - setDecoratorContext(true); - } - return expr; - } - function parseInitializer(inParameter) { - if (token() !== 58) { - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { - return undefined; - } - } - parseExpected(58); - return parseAssignmentExpressionOrHigher(); - } - function parseAssignmentExpressionOrHigher() { - if (isYieldExpression()) { - return parseYieldExpression(); - } - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); - if (arrowExpression) { - return arrowExpression; - } - var expr = parseBinaryExpressionOrHigher(0); - if (expr.kind === 71 && token() === 36) { - return parseSimpleArrowFunctionExpression(expr); - } - if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); - } - return parseConditionalExpressionRest(expr); - } - function isYieldExpression() { - if (token() === 116) { - if (inYieldContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); - } - return false; - } - function nextTokenIsIdentifierOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && isIdentifier(); - } - function parseYieldExpression() { - var node = createNode(197); - nextToken(); - if (!scanner.hasPrecedingLineBreak() && - (token() === 39 || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - else { - return finishNode(node); - } - } - function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node; - if (asyncModifier) { - node = createNode(187, asyncModifier.pos); - node.modifiers = asyncModifier; - } - else { - node = createNode(187, identifier.pos); - } - var parameter = createNode(146, identifier.pos); - parameter.name = identifier; - finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - node.body = parseArrowFunctionExpressionBody(!!asyncModifier); - return addJSDocComment(finishNode(node)); - } - function tryParseParenthesizedArrowFunctionExpression() { - var triState = isParenthesizedArrowFunctionExpression(); - if (triState === 0) { - return undefined; - } - var arrowFunction = triState === 1 - ? parseParenthesizedArrowFunctionExpressionHead(true) - : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); - if (!arrowFunction) { - return undefined; - } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); - var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 36 || lastToken === 17) - ? parseArrowFunctionExpressionBody(isAsync) - : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); - } - function isParenthesizedArrowFunctionExpression() { - if (token() === 19 || token() === 27 || token() === 120) { - return lookAhead(isParenthesizedArrowFunctionExpressionWorker); - } - if (token() === 36) { - return 1; - } - return 0; - } - function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120) { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return 0; - } - if (token() !== 19 && token() !== 27) { - return 0; - } - } - var first = token(); - var second = nextToken(); - if (first === 19) { - if (second === 20) { - var third = nextToken(); - switch (third) { - case 36: - case 56: - case 17: - return 1; - default: - return 0; - } - } - if (second === 21 || second === 17) { - return 2; - } - if (second === 24) { - return 1; - } - if (!isIdentifier()) { - return 0; - } - if (nextToken() === 56) { - return 1; - } - return 2; - } - else { - ts.Debug.assert(first === 27); - if (!isIdentifier()) { - return 0; - } - if (sourceFile.languageVariant === 1) { - var isArrowFunctionInJsx = lookAhead(function () { - var third = nextToken(); - if (third === 85) { - var fourth = nextToken(); - switch (fourth) { - case 58: - case 29: - return false; - default: - return true; - } - } - else if (third === 26) { - return true; - } - return false; - }); - if (isArrowFunctionInJsx) { - return 1; - } - return 0; - } - return 2; - } - } - function parsePossibleParenthesizedArrowFunctionExpressionHead() { - return parseParenthesizedArrowFunctionExpressionHead(false); - } - function tryParseAsyncSimpleArrowFunctionExpression() { - if (token() === 120) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1) { - var asyncModifier = parseModifiersForArrowFunction(); - var expr = parseBinaryExpressionOrHigher(0); - return parseSimpleArrowFunctionExpression(expr, asyncModifier); - } - } - return undefined; - } - function isUnParenthesizedAsyncArrowFunctionWorker() { - if (token() === 120) { - nextToken(); - if (scanner.hasPrecedingLineBreak() || token() === 36) { - return 0; - } - var expr = parseBinaryExpressionOrHigher(0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { - return 1; - } - } - return 0; - } - function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187); - node.modifiers = parseModifiersForArrowFunction(); - var isAsync = !!(ts.getModifierFlags(node) & 256); - fillSignature(56, false, isAsync, !allowAmbiguity, node); - if (!node.parameters) { - return undefined; - } - if (!allowAmbiguity && token() !== 36 && token() !== 17) { - return undefined; - } - return node; - } - function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17) { - return parseFunctionBlock(false, isAsync, false); - } - if (token() !== 25 && - token() !== 89 && - token() !== 75 && - isStartOfStatement() && - !isStartOfExpressionStatement()) { - return parseFunctionBlock(false, isAsync, true); - } - return isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); - } - function parseConditionalExpressionRest(leftOperand) { - var questionToken = parseOptionalToken(55); - if (!questionToken) { - return leftOperand; - } - var node = createNode(195, leftOperand.pos); - node.condition = leftOperand; - node.questionToken = questionToken; - node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseBinaryExpressionOrHigher(precedence) { - var leftOperand = parseUnaryExpressionOrHigher(); - return parseBinaryExpressionRest(precedence, leftOperand); - } - function isInOrOfKeyword(t) { - return t === 92 || t === 142; - } - function parseBinaryExpressionRest(precedence, leftOperand) { - while (true) { - reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); - var consumeCurrentOperator = token() === 40 ? - newPrecedence >= precedence : - newPrecedence > precedence; - if (!consumeCurrentOperator) { - break; - } - if (token() === 92 && inDisallowInContext()) { - break; - } - if (token() === 118) { - if (scanner.hasPrecedingLineBreak()) { - break; - } - else { - nextToken(); - leftOperand = makeAsExpression(leftOperand, parseType()); - } - } - else { - leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); - } - } - return leftOperand; - } - function isBinaryOperator() { - if (inDisallowInContext() && token() === 92) { - return false; - } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54: - return 1; - case 53: - return 2; - case 49: - return 3; - case 50: - return 4; - case 48: - return 5; - case 32: - case 33: - case 34: - case 35: - return 6; - case 27: - case 29: - case 30: - case 31: - case 93: - case 92: - case 118: - return 7; - case 45: - case 46: - case 47: - return 8; - case 37: - case 38: - return 9; - case 39: - case 41: - case 42: - return 10; - case 40: - return 11; - } - return -1; - } - function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194, left.pos); - node.left = left; - node.operatorToken = operatorToken; - node.right = right; - return finishNode(node); - } - function makeAsExpression(left, right) { - var node = createNode(202, left.pos); - node.expression = left; - node.type = right; - return finishNode(node); - } - function parsePrefixUnaryExpression() { - var node = createNode(192); - node.operator = token(); - nextToken(); - node.operand = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseDeleteExpression() { - var node = createNode(188); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseTypeOfExpression() { - var node = createNode(189); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseVoidExpression() { - var node = createNode(190); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function isAwaitExpression() { - if (token() === 121) { - if (inAwaitContext()) { - return true; - } - return lookAhead(nextTokenIsIdentifierOnSameLine); - } - return false; - } - function parseAwaitExpression() { - var node = createNode(191); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseUnaryExpressionOrHigher() { - if (isUpdateExpression()) { - var incrementExpression = parseIncrementExpression(); - return token() === 40 ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : - incrementExpression; - } - var unaryOperator = token(); - var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184) { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); - } - else { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); - } - } - return simpleUnaryExpression; - } - function parseSimpleUnaryExpression() { - switch (token()) { - case 37: - case 38: - case 52: - case 51: - return parsePrefixUnaryExpression(); - case 80: - return parseDeleteExpression(); - case 103: - return parseTypeOfExpression(); - case 105: - return parseVoidExpression(); - case 27: - return parseTypeAssertion(); - case 121: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - default: - return parseIncrementExpression(); - } - } - function isUpdateExpression() { - switch (token()) { - case 37: - case 38: - case 52: - case 51: - case 80: - case 103: - case 105: - case 121: - return false; - case 27: - if (sourceFile.languageVariant !== 1) { - return false; - } - default: - return true; - } - } - function parseIncrementExpression() { - if (token() === 43 || token() === 44) { - var node = createNode(192); - node.operator = token(); - nextToken(); - node.operand = parseLeftHandSideExpressionOrHigher(); - return finishNode(node); - } - else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { - return parseJsxElementOrSelfClosingElement(true); - } - var expression = parseLeftHandSideExpressionOrHigher(); - ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193, expression.pos); - node.operand = expression; - node.operator = token(); - nextToken(); - return finishNode(node); - } - return expression; - } - function parseLeftHandSideExpressionOrHigher() { - var expression = token() === 97 - ? parseSuperExpression() - : parseMemberExpressionOrHigher(); - return parseCallExpressionRest(expression); - } - function parseMemberExpressionOrHigher() { - var expression = parsePrimaryExpression(); - return parseMemberExpressionRest(expression); - } - function parseSuperExpression() { - var expression = parseTokenNode(); - if (token() === 19 || token() === 23 || token() === 21) { - return expression; - } - var node = createNode(179, expression.pos); - node.expression = expression; - parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - node.name = parseRightSideOfDot(true); - return finishNode(node); - } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 71) { - return lhs.text === rhs.text; - } - if (lhs.kind === 99) { - return true; - } - return lhs.name.text === rhs.name.text && - tagNamesAreEquivalent(lhs.expression, rhs.expression); - } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); - var result; - if (opening.kind === 251) { - var node = createNode(249, opening.pos); - node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); - node.closingElement = parseJsxClosingElement(inExpressionContext); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); - } - result = finishNode(node); - } - else { - ts.Debug.assert(opening.kind === 250); - result = opening; - } - if (inExpressionContext && token() === 27) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); - if (invalidElement) { - parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194, result.pos); - badNode.end = invalidElement.end; - badNode.left = result; - badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26, false, undefined); - badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; - return badNode; - } - } - return result; - } - function parseJsxText() { - var node = createNode(10, scanner.getStartPos()); - node.containsOnlyWhiteSpaces = currentToken === 11; - currentToken = scanner.scanJsxToken(); - return finishNode(node); - } - function parseJsxChild() { - switch (token()) { - case 10: - case 11: - return parseJsxText(); - case 17: - return parseJsxExpression(false); - case 27: - return parseJsxElementOrSelfClosingElement(false); - } - ts.Debug.fail("Unknown JSX child kind " + token()); - } - function parseJsxChildren(openingTagName) { - var result = createNodeArray(); - var saveParsingContext = parsingContext; - parsingContext |= 1 << 14; - while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28) { - break; - } - else if (token() === 1) { - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); - break; - } - else if (token() === 7) { - break; - } - var child = parseJsxChild(); - if (child) { - result.push(child); - } - } - result.end = scanner.getTokenPos(); - parsingContext = saveParsingContext; - return result; - } - function parseJsxAttributes() { - var jsxAttributes = createNode(254); - jsxAttributes.properties = parseList(13, parseJsxAttribute); - return finishNode(jsxAttributes); - } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { - var fullStart = scanner.getStartPos(); - parseExpected(27); - var tagName = parseJsxElementName(); - var attributes = parseJsxAttributes(); - var node; - if (token() === 29) { - node = createNode(251, fullStart); - scanJsxText(); - } - else { - parseExpected(41); - if (inExpressionContext) { - parseExpected(29); - } - else { - parseExpected(29, undefined, false); - scanJsxText(); - } - node = createNode(250, fullStart); - } - node.tagName = tagName; - node.attributes = attributes; - return finishNode(node); - } - function parseJsxElementName() { - scanJsxIdentifier(); - var expression = token() === 99 ? - parseTokenNode() : parseIdentifierName(); - while (parseOptional(23)) { - var propertyAccess = createNode(179, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); - expression = finishNode(propertyAccess); - } - return expression; - } - function parseJsxExpression(inExpressionContext) { - var node = createNode(256); - parseExpected(17); - if (token() !== 18) { - node.dotDotDotToken = parseOptionalToken(24); - node.expression = parseAssignmentExpressionOrHigher(); - } - if (inExpressionContext) { - parseExpected(18); - } - else { - parseExpected(18, undefined, false); - scanJsxText(); - } - return finishNode(node); - } - function parseJsxAttribute() { - if (token() === 17) { - return parseJsxSpreadAttribute(); - } - scanJsxIdentifier(); - var node = createNode(253); - node.name = parseIdentifierName(); - if (token() === 58) { - switch (scanJsxAttributeValue()) { - case 9: - node.initializer = parseLiteralNode(); - break; - default: - node.initializer = parseJsxExpression(true); - break; - } - } - return finishNode(node); - } - function parseJsxSpreadAttribute() { - var node = createNode(255); - parseExpected(17); - parseExpected(24); - node.expression = parseExpression(); - parseExpected(18); - return finishNode(node); - } - function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252); - parseExpected(28); - node.tagName = parseJsxElementName(); - if (inExpressionContext) { - parseExpected(29); - } - else { - parseExpected(29, undefined, false); - scanJsxText(); - } - return finishNode(node); - } - function parseTypeAssertion() { - var node = createNode(184); - parseExpected(27); - node.type = parseType(); - parseExpected(29); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseMemberExpressionRest(expression) { - while (true) { - var dotToken = parseOptionalToken(23); - if (dotToken) { - var propertyAccess = createNode(179, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(true); - expression = finishNode(propertyAccess); - continue; - } - if (token() === 51 && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var nonNullExpression = createNode(203, expression.pos); - nonNullExpression.expression = expression; - expression = finishNode(nonNullExpression); - continue; - } - if (!inDecoratorContext() && parseOptional(21)) { - var indexedAccess = createNode(180, expression.pos); - indexedAccess.expression = expression; - if (token() !== 22) { - indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { - var literal = indexedAccess.argumentExpression; - literal.text = internIdentifier(literal.text); - } - } - parseExpected(22); - expression = finishNode(indexedAccess); - continue; - } - if (token() === 13 || token() === 14) { - var tagExpression = createNode(183, expression.pos); - tagExpression.tag = expression; - tagExpression.template = token() === 13 - ? parseLiteralNode() - : parseTemplateExpression(); - expression = finishNode(tagExpression); - continue; - } - return expression; - } - } - function parseCallExpressionRest(expression) { - while (true) { - expression = parseMemberExpressionRest(expression); - if (token() === 27) { - var typeArguments = tryParse(parseTypeArgumentsInExpression); - if (!typeArguments) { - return expression; - } - var callExpr = createNode(181, expression.pos); - callExpr.expression = expression; - callExpr.typeArguments = typeArguments; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - else if (token() === 19) { - var callExpr = createNode(181, expression.pos); - callExpr.expression = expression; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - return expression; - } - } - function parseArgumentList() { - parseExpected(19); - var result = parseDelimitedList(11, parseArgumentExpression); - parseExpected(20); - return result; - } - function parseTypeArgumentsInExpression() { - if (!parseOptional(27)) { - return undefined; - } - var typeArguments = parseDelimitedList(19, parseType); - if (!parseExpected(29)) { - return undefined; - } - return typeArguments && canFollowTypeArgumentsInExpression() - ? typeArguments - : undefined; - } - function canFollowTypeArgumentsInExpression() { - switch (token()) { - case 19: - case 23: - case 20: - case 22: - case 56: - case 25: - case 55: - case 32: - case 34: - case 33: - case 35: - case 53: - case 54: - case 50: - case 48: - case 49: - case 18: - case 1: - return true; - case 26: - case 17: - default: - return false; - } - } - function parsePrimaryExpression() { - switch (token()) { - case 8: - case 9: - case 13: - return parseLiteralNode(); - case 99: - case 97: - case 95: - case 101: - case 86: - return parseTokenNode(); - case 19: - return parseParenthesizedExpression(); - case 21: - return parseArrayLiteralExpression(); - case 17: - return parseObjectLiteralExpression(); - case 120: - if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { - break; - } - return parseFunctionExpression(); - case 75: - return parseClassExpression(); - case 89: - return parseFunctionExpression(); - case 94: - return parseNewExpression(); - case 41: - case 63: - if (reScanSlashToken() === 12) { - return parseLiteralNode(); - } - break; - case 14: - return parseTemplateExpression(); - } - return parseIdentifier(ts.Diagnostics.Expression_expected); - } - function parseParenthesizedExpression() { - var node = createNode(185); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - return finishNode(node); - } - function parseSpreadElement() { - var node = createNode(198); - parseExpected(24); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseArgumentOrArrayLiteralElement() { - return token() === 24 ? parseSpreadElement() : - token() === 26 ? createNode(200) : - parseAssignmentExpressionOrHigher(); - } - function parseArgumentExpression() { - return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); - } - function parseArrayLiteralExpression() { - var node = createNode(177); - parseExpected(21); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); - parseExpected(22); - return finishNode(node); - } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125)) { - return parseAccessorDeclaration(153, fullStart, decorators, modifiers); - } - else if (parseContextualModifier(135)) { - return parseAccessorDeclaration(154, fullStart, decorators, modifiers); - } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24); - if (dotDotDotToken) { - var spreadElement = createNode(263, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - var asteriskToken = parseOptionalToken(39); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); - } - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); - if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(58); - if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); - } - return addJSDocComment(finishNode(shorthandDeclaration)); - } - else { - var propertyAssignment = createNode(261, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; - parseExpected(56); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); - } - } - function parseObjectLiteralExpression() { - var node = createNode(178); - parseExpected(17); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); - parseExpected(18); - return finishNode(node); - } - function parseFunctionExpression() { - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var node = createNode(186); - node.modifiers = parseModifiers(); - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - var isGenerator = !!node.asteriskToken; - var isAsync = !!(ts.getModifierFlags(node) & 256); - node.name = - isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : - isGenerator ? doInYieldContext(parseOptionalIdentifier) : - isAsync ? doInAwaitContext(parseOptionalIdentifier) : - parseOptionalIdentifier(); - fillSignature(56, isGenerator, isAsync, false, node); - node.body = parseFunctionBlock(isGenerator, isAsync, false); - if (saveDecoratorContext) { - setDecoratorContext(true); - } - return addJSDocComment(finishNode(node)); - } - function parseOptionalIdentifier() { - return isIdentifier() ? parseIdentifier() : undefined; - } - function parseNewExpression() { - var fullStart = scanner.getStartPos(); - parseExpected(94); - if (parseOptional(23)) { - var node_1 = createNode(204, fullStart); - node_1.keywordToken = 94; - node_1.name = parseIdentifierName(); - return finishNode(node_1); - } - var node = createNode(182, fullStart); - node.expression = parseMemberExpressionOrHigher(); - node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 19) { - node.arguments = parseArgumentList(); - } - return finishNode(node); - } - function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207); - if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.statements = parseList(1, parseStatement); - parseExpected(18); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseFunctionBlock(allowYield, allowAwait, ignoreMissingOpenBrace, diagnosticMessage) { - var savedYieldContext = inYieldContext(); - setYieldContext(allowYield); - var savedAwaitContext = inAwaitContext(); - setAwaitContext(allowAwait); - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(false); - } - var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); - if (saveDecoratorContext) { - setDecoratorContext(true); - } - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - return block; - } - function parseEmptyStatement() { - var node = createNode(209); - parseExpected(25); - return finishNode(node); - } - function parseIfStatement() { - var node = createNode(211); - parseExpected(90); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82) ? parseStatement() : undefined; - return finishNode(node); - } - function parseDoStatement() { - var node = createNode(212); - parseExpected(81); - node.statement = parseStatement(); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - parseOptional(25); - return finishNode(node); - } - function parseWhileStatement() { - var node = createNode(213); - parseExpected(106); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.statement = parseStatement(); - return finishNode(node); - } - function parseForOrForInOrForOfStatement() { - var pos = getNodePos(); - parseExpected(88); - var awaitToken = parseOptionalToken(121); - parseExpected(19); - var initializer = undefined; - if (token() !== 25) { - if (token() === 104 || token() === 110 || token() === 76) { - initializer = parseVariableDeclarationList(true); - } - else { - initializer = disallowInAnd(parseExpression); - } - } - var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142) : parseOptional(142)) { - var forOfStatement = createNode(216, pos); - forOfStatement.awaitModifier = awaitToken; - forOfStatement.initializer = initializer; - forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20); - forOrForInOrForOfStatement = forOfStatement; - } - else if (parseOptional(92)) { - var forInStatement = createNode(215, pos); - forInStatement.initializer = initializer; - forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20); - forOrForInOrForOfStatement = forInStatement; - } - else { - var forStatement = createNode(214, pos); - forStatement.initializer = initializer; - parseExpected(25); - if (token() !== 25 && token() !== 20) { - forStatement.condition = allowInAnd(parseExpression); - } - parseExpected(25); - if (token() !== 20) { - forStatement.incrementor = allowInAnd(parseExpression); - } - parseExpected(20); - forOrForInOrForOfStatement = forStatement; - } - forOrForInOrForOfStatement.statement = parseStatement(); - return finishNode(forOrForInOrForOfStatement); - } - function parseBreakOrContinueStatement(kind) { - var node = createNode(kind); - parseExpected(kind === 218 ? 72 : 77); - if (!canParseSemicolon()) { - node.label = parseIdentifier(); - } - parseSemicolon(); - return finishNode(node); - } - function parseReturnStatement() { - var node = createNode(219); - parseExpected(96); - if (!canParseSemicolon()) { - node.expression = allowInAnd(parseExpression); - } - parseSemicolon(); - return finishNode(node); - } - function parseWithStatement() { - var node = createNode(220); - parseExpected(107); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - node.statement = parseStatement(); - return finishNode(node); - } - function parseCaseClause() { - var node = createNode(257); - parseExpected(73); - node.expression = allowInAnd(parseExpression); - parseExpected(56); - node.statements = parseList(3, parseStatement); - return finishNode(node); - } - function parseDefaultClause() { - var node = createNode(258); - parseExpected(79); - parseExpected(56); - node.statements = parseList(3, parseStatement); - return finishNode(node); - } - function parseCaseOrDefaultClause() { - return token() === 73 ? parseCaseClause() : parseDefaultClause(); - } - function parseSwitchStatement() { - var node = createNode(221); - parseExpected(98); - parseExpected(19); - node.expression = allowInAnd(parseExpression); - parseExpected(20); - var caseBlock = createNode(235, scanner.getStartPos()); - parseExpected(17); - caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); - parseExpected(18); - node.caseBlock = finishNode(caseBlock); - return finishNode(node); - } - function parseThrowStatement() { - var node = createNode(223); - parseExpected(100); - node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); - parseSemicolon(); - return finishNode(node); - } - function parseTryStatement() { - var node = createNode(224); - parseExpected(102); - node.tryBlock = parseBlock(false); - node.catchClause = token() === 74 ? parseCatchClause() : undefined; - if (!node.catchClause || token() === 87) { - parseExpected(87); - node.finallyBlock = parseBlock(false); - } - return finishNode(node); - } - function parseCatchClause() { - var result = createNode(260); - parseExpected(74); - if (parseExpected(19)) { - result.variableDeclaration = parseVariableDeclaration(); - } - parseExpected(20); - result.block = parseBlock(false); - return finishNode(result); - } - function parseDebuggerStatement() { - var node = createNode(225); - parseExpected(78); - parseSemicolon(); - return finishNode(node); - } - function parseExpressionOrLabeledStatement() { - var fullStart = scanner.getStartPos(); - var expression = allowInAnd(parseExpression); - if (expression.kind === 71 && parseOptional(56)) { - var labeledStatement = createNode(222, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); - } - else { - var expressionStatement = createNode(210, fullStart); - expressionStatement.expression = expression; - parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); - } - } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsClassKeywordOnSameLine() { - nextToken(); - return token() === 75 && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsFunctionKeywordOnSameLine() { - nextToken(); - return token() === 89 && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { - nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8) && !scanner.hasPrecedingLineBreak(); - } - function isDeclaration() { - while (true) { - switch (token()) { - case 104: - case 110: - case 76: - case 89: - case 75: - case 83: - return true; - case 109: - case 138: - return nextTokenIsIdentifierOnSameLine(); - case 128: - case 129: - return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117: - case 120: - case 124: - case 112: - case 113: - case 114: - case 131: - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - continue; - case 141: - nextToken(); - return token() === 17 || token() === 71 || token() === 84; - case 91: - nextToken(); - return token() === 9 || token() === 39 || - token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); - case 84: - nextToken(); - if (token() === 58 || token() === 39 || - token() === 17 || token() === 79 || - token() === 118) { - return true; - } - continue; - case 115: - nextToken(); - continue; - default: - return false; - } - } - } - function isStartOfDeclaration() { - return lookAhead(isDeclaration); - } - function isStartOfStatement() { - switch (token()) { - case 57: - case 25: - case 17: - case 104: - case 110: - case 89: - case 75: - case 83: - case 90: - case 81: - case 106: - case 88: - case 77: - case 72: - case 96: - case 107: - case 98: - case 100: - case 102: - case 78: - case 74: - case 87: - return true; - case 76: - case 84: - case 91: - return isStartOfDeclaration(); - case 120: - case 124: - case 109: - case 128: - case 129: - case 138: - case 141: - return true; - case 114: - case 112: - case 113: - case 115: - case 131: - return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - default: - return isStartOfExpression(); - } - } - function nextTokenIsIdentifierOrStartOfDestructuring() { - nextToken(); - return isIdentifier() || token() === 17 || token() === 21; - } - function isLetDeclaration() { - return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); - } - function parseStatement() { - switch (token()) { - case 25: - return parseEmptyStatement(); - case 17: - return parseBlock(false); - case 104: - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - case 110: - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), undefined, undefined); - } - break; - case 89: - return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); - case 75: - return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); - case 90: - return parseIfStatement(); - case 81: - return parseDoStatement(); - case 106: - return parseWhileStatement(); - case 88: - return parseForOrForInOrForOfStatement(); - case 77: - return parseBreakOrContinueStatement(217); - case 72: - return parseBreakOrContinueStatement(218); - case 96: - return parseReturnStatement(); - case 107: - return parseWithStatement(); - case 98: - return parseSwitchStatement(); - case 100: - return parseThrowStatement(); - case 102: - case 74: - case 87: - return parseTryStatement(); - case 78: - return parseDebuggerStatement(); - case 57: - return parseDeclaration(); - case 120: - case 109: - case 138: - case 128: - case 129: - case 124: - case 76: - case 83: - case 84: - case 91: - case 112: - case 113: - case 114: - case 117: - case 115: - case 131: - case 141: - if (isStartOfDeclaration()) { - return parseDeclaration(); - } - break; - } - return parseExpressionOrLabeledStatement(); - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - switch (token()) { - case 104: - case 110: - case 76: - return parseVariableStatement(fullStart, decorators, modifiers); - case 89: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 75: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 109: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 138: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 83: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141: - case 128: - case 129: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 91: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 84: - nextToken(); - switch (token()) { - case 79: - case 58: - return parseExportAssignment(fullStart, decorators, modifiers); - case 118: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); - default: - return parseExportDeclaration(fullStart, decorators, modifiers); - } - default: - if (decorators || modifiers) { - var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); - } - } - } - function nextTokenIsIdentifierOrStringLiteralOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); - } - function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 17 && canParseSemicolon()) { - parseSemicolon(); - return; - } - return parseFunctionBlock(isGenerator, isAsync, false, diagnosticMessage); - } - function parseArrayBindingElement() { - if (token() === 26) { - return createNode(200); - } - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); - node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(false); - return finishNode(node); - } - function parseObjectBindingElement() { - var node = createNode(176); - node.dotDotDotToken = parseOptionalToken(24); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56) { - node.name = propertyName; - } - else { - parseExpected(56); - node.propertyName = propertyName; - node.name = parseIdentifierOrPattern(); - } - node.initializer = parseBindingElementInitializer(false); - return finishNode(node); - } - function parseObjectBindingPattern() { - var node = createNode(174); - parseExpected(17); - node.elements = parseDelimitedList(9, parseObjectBindingElement); - parseExpected(18); - return finishNode(node); - } - function parseArrayBindingPattern() { - var node = createNode(175); - parseExpected(21); - node.elements = parseDelimitedList(10, parseArrayBindingElement); - parseExpected(22); - return finishNode(node); - } - function isIdentifierOrPattern() { - return token() === 17 || token() === 21 || isIdentifier(); - } - function parseIdentifierOrPattern() { - if (token() === 21) { - return parseArrayBindingPattern(); - } - if (token() === 17) { - return parseObjectBindingPattern(); - } - return parseIdentifier(); - } - function parseVariableDeclaration() { - var node = createNode(226); - node.name = parseIdentifierOrPattern(); - node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(false); - } - return finishNode(node); - } - function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227); - switch (token()) { - case 104: - break; - case 110: - node.flags |= 1; - break; - case 76: - node.flags |= 2; - break; - default: - ts.Debug.fail(); - } - nextToken(); - if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { - node.declarations = createMissingList(); - } - else { - var savedDisallowIn = inDisallowInContext(); - setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8, parseVariableDeclaration); - setDisallowInContext(savedDisallowIn); - } - return finishNode(node); - } - function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20; - } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.declarationList = parseVariableDeclarationList(false); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(89); - node.asteriskToken = parseOptionalToken(39); - node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); - var isGenerator = !!node.asteriskToken; - var isAsync = ts.hasModifier(node, 256); - fillSignature(56, isGenerator, isAsync, false, node); - node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152, pos); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(123); - fillSignature(56, false, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false, false, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; - var isGenerator = !!asteriskToken; - var isAsync = ts.hasModifier(method, 256); - fillSignature(56, isGenerator, isAsync, false, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - property.initializer = ts.hasModifier(property, 32) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); - parseSemicolon(); - return addJSDocComment(finishNode(property)); - } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(39); - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55); - if (asteriskToken || token() === 19 || token() === 27) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); - } - } - function parseNonParameterInitializer() { - return parseInitializer(false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.name = parsePropertyName(); - fillSignature(56, false, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false, false); - return addJSDocComment(finishNode(node)); - } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114: - case 112: - case 113: - case 115: - case 131: - return true; - default: - return false; - } - } - function isClassMemberStart() { - var idToken; - if (token() === 57) { - return true; - } - while (ts.isModifierKind(token())) { - idToken = token(); - if (isClassMemberModifier(idToken)) { - return true; - } - nextToken(); - } - if (token() === 39) { - return true; - } - if (isLiteralPropertyName()) { - idToken = token(); - nextToken(); - } - if (token() === 21) { - return true; - } - if (idToken !== undefined) { - if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { - return true; - } - switch (token()) { - case 19: - case 27: - case 56: - case 58: - case 55: - return true; - default: - return canParseSemicolon(); - } - } - return false; - } - function parseDecorators() { - var decorators; - while (true) { - var decoratorStart = getNodePos(); - if (!parseOptional(57)) { - break; - } - var decorator = createNode(147, decoratorStart); - decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); - } - return decorators; - } - function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; - while (true) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 76 && permitInvalidConstAsModifier) { - if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { - break; - } - } - else { - if (!parseAnyContextualModifier()) { - break; - } - } - var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseModifiersForArrowFunction() { - var modifiers; - if (token() === 120) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - nextToken(); - var modifier = finishNode(createNode(modifierKind, modifierStart)); - modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseClassElement() { - if (token() === 25) { - var result = createNode(206); - nextToken(); - return finishNode(result); - } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - if (token() === 123) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); - } - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); - } - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 || - token() === 8 || - token() === 39 || - token() === 21) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); - } - if (decorators || modifiers) { - var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); - } - ts.Debug.fail("Should not have attempted to parse class member declaration."); - } - function parseClassExpression() { - return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); - } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); - } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(75); - node.name = parseNameOfClassDeclarationOrExpression(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17)) { - node.members = parseClassMembers(); - parseExpected(18); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseNameOfClassDeclarationOrExpression() { - return isIdentifier() && !isImplementsClause() - ? parseIdentifier() - : undefined; - } - function isImplementsClause() { - return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); - } - function parseHeritageClauses() { - if (isHeritageClause()) { - return parseList(21, parseHeritageClause); - } - return undefined; - } - function parseHeritageClause() { - var tok = token(); - if (tok === 85 || tok === 108) { - var node = createNode(259); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; - } - function parseExpressionWithTypeArguments() { - var node = createNode(201); - node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27) { - node.typeArguments = parseBracketedList(19, parseType, 27, 29); - } - return finishNode(node); - } - function isHeritageClause() { - return token() === 85 || token() === 108; - } - function parseClassMembers() { - return parseList(5, parseClassElement); - } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(109); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); - } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(138); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - parseExpected(58); - node.type = parseType(); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseEnumMember() { - var node = createNode(264, scanner.getStartPos()); - node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); - } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(83); - node.name = parseIdentifier(); - if (parseExpected(17)) { - node.members = parseDelimitedList(6, parseEnumMember); - parseExpected(18); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseModuleBlock() { - var node = createNode(234, scanner.getStartPos()); - if (parseExpected(17)) { - node.statements = parseList(1, parseStatement); - parseExpected(18); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233, fullStart); - var namespaceFlag = flags & 16; - node.decorators = decorators; - node.modifiers = modifiers; - node.flags |= flags; - node.name = parseIdentifier(); - node.body = parseOptional(23) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) - : parseModuleBlock(); - return addJSDocComment(finishNode(node)); - } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141) { - node.name = parseIdentifier(); - node.flags |= 512; - } - else { - node.name = parseLiteralNode(true); - } - if (token() === 17) { - node.body = parseModuleBlock(); - } - else { - parseSemicolon(); - } - return finishNode(node); - } - function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = 0; - if (token() === 141) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - else if (parseOptional(129)) { - flags |= 16; - } - else { - parseExpected(128); - if (token() === 9) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); - } - function isExternalModuleReference() { - return token() === 132 && - lookAhead(nextTokenIsOpenParen); - } - function nextTokenIsOpenParen() { - return nextToken() === 19; - } - function nextTokenIsSlash() { - return nextToken() === 41; - } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; - parseExpected(118); - parseExpected(129); - exportDeclaration.name = parseIdentifier(); - parseSemicolon(); - return finishNode(exportDeclaration); - } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(91); - var afterImportPos = scanner.getStartPos(); - var identifier; - if (isIdentifier()) { - identifier = parseIdentifier(); - if (token() !== 26 && token() !== 140) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); - } - } - var importDeclaration = createNode(238, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; - if (identifier || - token() === 39 || - token() === 17) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140); - } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); - parseSemicolon(); - return finishNode(importDeclaration); - } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; - parseExpected(58); - importEqualsDeclaration.moduleReference = parseModuleReference(); - parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); - } - function parseImportClause(identifier, fullStart) { - var importClause = createNode(239, fullStart); - if (identifier) { - importClause.name = identifier; - } - if (!importClause.name || - parseOptional(26)) { - importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); - } - return finishNode(importClause); - } - function parseModuleReference() { - return isExternalModuleReference() - ? parseExternalModuleReference() - : parseEntityName(false); - } - function parseExternalModuleReference() { - var node = createNode(248); - parseExpected(132); - parseExpected(19); - node.expression = parseModuleSpecifier(); - parseExpected(20); - return finishNode(node); - } - function parseModuleSpecifier() { - if (token() === 9) { - var result = parseLiteralNode(); - internIdentifier(result.text); - return result; - } - else { - return parseExpression(); - } - } - function parseNamespaceImport() { - var namespaceImport = createNode(240); - parseExpected(39); - parseExpected(118); - namespaceImport.name = parseIdentifier(); - return finishNode(namespaceImport); - } - function parseNamedImportsOrExports(kind) { - var node = createNode(kind); - node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); - return finishNode(node); - } - function parseExportSpecifier() { - return parseImportOrExportSpecifier(246); - } - function parseImportSpecifier() { - return parseImportOrExportSpecifier(242); - } - function parseImportOrExportSpecifier(kind) { - var node = createNode(kind); - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - var checkIdentifierStart = scanner.getTokenPos(); - var checkIdentifierEnd = scanner.getTextPos(); - var identifierName = parseIdentifierName(); - if (token() === 118) { - node.propertyName = identifierName; - parseExpected(118); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - checkIdentifierStart = scanner.getTokenPos(); - checkIdentifierEnd = scanner.getTextPos(); - node.name = parseIdentifierName(); - } - else { - node.name = identifierName; - } - if (kind === 242 && checkIdentifierIsKeyword) { - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); - } - return finishNode(node); - } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(39)) { - parseExpected(140); - node.moduleSpecifier = parseModuleSpecifier(); - } - else { - node.exportClause = parseNamedImportsOrExports(245); - if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { - parseExpected(140); - node.moduleSpecifier = parseModuleSpecifier(); - } - } - parseSemicolon(); - return finishNode(node); - } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(58)) { - node.isExportEquals = true; - } - else { - parseExpected(79); - } - node.expression = parseAssignmentExpressionOrHigher(); - parseSemicolon(); - return finishNode(node); - } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*".length; - return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function parseQualifiedName(left) { - var result = createNode(143, left.pos); - result.left = left; - result.right = parseIdentifierName(); - return finishNode(result); - } - function parseJSDocRecordType() { - var result = createNode(275); - result.literal = parseTypeLiteral(); - return finishNode(result); - } - function parseJSDocNonNullableType() { - var result = createNode(274); - nextToken(); - result.type = parseJSDocType(); - return finishNode(result); - } - function parseJSDocTupleType() { - var result = createNode(272); - nextToken(); - result.types = parseDelimitedList(26, parseJSDocType); - checkForTrailingComma(result.types); - parseExpected(22); - return finishNode(result); - } - function checkForTrailingComma(list) { - if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - var start = list.end - ",".length; - parseErrorAtPosition(start, ",".length, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function parseJSDocUnionType() { - var result = createNode(271); - nextToken(); - result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(20); - return finishNode(result); - } - function parseJSDocTypeList(firstType) { - ts.Debug.assert(!!firstType); - var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(49)) { - types.push(parseJSDocType()); - } - types.end = scanner.getStartPos(); - return types; - } - function parseJSDocAllType() { - var result = createNode(268); - nextToken(); - return finishNode(result); - } - function parseJSDocLiteralType() { - var result = createNode(293); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } - function parseJSDocUnknownOrNullableType() { - var pos = scanner.getStartPos(); - nextToken(); - if (token() === 26 || - token() === 18 || - token() === 20 || - token() === 29 || - token() === 58 || - token() === 49) { - var result = createNode(269, pos); - return finishNode(result); - } - else { - var result = createNode(273, pos); - result.type = parseJSDocType(); - return finishNode(result); - } - } - function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5, undefined, 1); - sourceFile = { languageVariant: 0, text: content }; - var jsDoc = parseJSDocCommentWorker(start, length); - var diagnostics = parseDiagnostics; - clearState(); - return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; - } - JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var comment = parseJSDocCommentWorker(start, length); - if (comment) { - comment.parent = parent; - } - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - 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; - var end = length === undefined ? content.length : start + length; - length = end - start; - ts.Debug.assert(start >= 0); - ts.Debug.assert(start <= end); - ts.Debug.assert(end <= content.length); - var tags; - var comments = []; - var result; - if (!isJsDocStart(content, start)) { - return result; - } - scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; - var state = 1; - var margin = undefined; - var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); - } - if (token() === 4) { - state = 0; - indent = 0; - nextJSDocToken(); - } - while (token() !== 1) { - switch (token()) { - case 57: - if (state === 0 || state === 1) { - removeTrailingNewlines(comments); - parseTag(indent); - state = 0; - advanceToken = false; - margin = undefined; - indent++; - } - else { - pushComment(scanner.getTokenText()); - } - break; - case 4: - comments.push(scanner.getTokenText()); - state = 0; - indent = 0; - break; - case 39: - var asterisk = scanner.getTokenText(); - if (state === 1 || state === 2) { - state = 2; - pushComment(asterisk); - } - else { - state = 1; - indent += asterisk.length; - } - break; - case 71: - pushComment(scanner.getTokenText()); - state = 2; - break; - case 5: - var whitespace = scanner.getTokenText(); - if (state === 2) { - comments.push(whitespace); - } - else if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - break; - case 1: - break; - default: - state = 2; - pushComment(scanner.getTokenText()); - break; - } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - result = createJSDocComment(); - }); - return result; - function removeLeadingNewlines(comments) { - while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { - comments.shift(); - } - } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { - comments.pop(); - } - } - function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 && - content.charCodeAt(start + 1) === 42 && - content.charCodeAt(start + 2) === 42 && - content.charCodeAt(start + 3) !== 42; - } - function createJSDocComment() { - var result = createNode(283, start); - result.tags = tags; - result.comment = comments.length ? comments.join("") : undefined; - return finishNode(result, end); - } - function skipWhitespace() { - while (token() === 5 || token() === 4) { - nextJSDocToken(); - } - } - function parseTag(indent) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return; - } - var tag; - if (tagName) { - switch (tagName.text) { - case "augments": - tag = parseAugmentsTag(atToken, tagName); - break; - case "arg": - case "argument": - case "param": - tag = parseParamTag(atToken, tagName); - break; - case "return": - case "returns": - tag = parseReturnTag(atToken, tagName); - break; - case "template": - tag = parseTemplateTag(atToken, tagName); - break; - case "type": - tag = parseTypeTag(atToken, tagName); - break; - case "typedef": - tag = parseTypedefTag(atToken, tagName); - break; - default: - tag = parseUnknownTag(atToken, tagName); - break; - } - } - else { - tag = parseUnknownTag(atToken, tagName); - } - if (!tag) { - return; - } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); - } - function parseTagComments(indent) { - var comments = []; - var state = 0; - var margin; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - while (token() !== 57 && token() !== 1) { - switch (token()) { - case 4: - if (state >= 1) { - state = 0; - comments.push(scanner.getTokenText()); - } - indent = 0; - break; - case 57: - break; - case 5: - if (state === 2) { - pushComment(scanner.getTokenText()); - } - else { - var whitespace = scanner.getTokenText(); - if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - } - break; - case 39: - if (state === 0) { - state = 1; - indent += scanner.getTokenText().length; - break; - } - default: - state = 2; - pushComment(scanner.getTokenText()); - break; - } - if (token() === 57) { - break; - } - nextJSDocToken(); - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - return comments; - } - function parseUnknownTag(atToken, tagName) { - var result = createNode(284, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - return finishNode(result); - } - function addTag(tag, comments) { - tag.comment = comments.join(""); - if (!tags) { - tags = createNodeArray([tag], tag.pos); - } - else { - tags.push(tag); - } - tags.end = tag.end; - } - function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17) { - return undefined; - } - return parseJSDocTypeExpression(); - }); - } - function parseParamTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name; - var isBracketed; - if (parseOptionalToken(21)) { - name = parseJSDocIdentifierName(); - skipWhitespace(); - isBracketed = true; - if (parseOptionalToken(58)) { - parseExpression(); - } - parseExpected(22); - } - else if (ts.tokenIsIdentifierOrKeyword(token())) { - name = parseJSDocIdentifierName(); - } - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var preName, postName; - if (typeExpression) { - postName = name; - } - else { - preName = name; - } - if (!typeExpression) { - typeExpression = tryParseTypeExpression(); - } - var result = createNode(286, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.preParameterName = preName; - result.typeExpression = typeExpression; - result.postParameterName = postName; - result.parameterName = postName || preName; - result.isBracketed = isBracketed; - return finishNode(result); - } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(287, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 288; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(288, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parsePropertyTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var result = createNode(291, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.name = name; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - var result = createNode(285, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseTypedefTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(290, atToken.pos); - typedefTag.atToken = atToken; - typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 || !rightNode.body) { - typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } - typedefTag.typeExpression = typeExpression; - skipWhitespace(); - if (typeExpression) { - if (typeExpression.type.kind === 277) { - var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 71) { - var name = jsDocTypeReference.name; - if (name.text === "Object") { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - } - } - if (!typedefTag.jsDocTypeLiteral) { - typedefTag.jsDocTypeLiteral = typeExpression.type; - } - } - else { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - return finishNode(typedefTag); - function scanChildTags() { - var jsDocTypeLiteral = createNode(292, scanner.getStartPos()); - var resumePos = scanner.getStartPos(); - var canParseTag = true; - var seenAsterisk = false; - var parentTagTerminated = false; - while (token() !== 1 && !parentTagTerminated) { - nextJSDocToken(); - switch (token()) { - case 57: - if (canParseTag) { - parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } - } - seenAsterisk = false; - break; - case 4: - resumePos = scanner.getStartPos() - 1; - canParseTag = true; - seenAsterisk = false; - break; - case 39: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 71: - canParseTag = false; - break; - case 1: - break; - } - } - scanner.setTextPos(resumePos); - return finishNode(jsDocTypeLiteral); - } - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23)) { - var jsDocNamespaceNode = createNode(233, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); - return jsDocNamespaceNode; - } - if (typeNameOrNamespaceName && flags & 4) { - typeNameOrNamespaceName.isInJSDocNamespace = true; - } - return typeNameOrNamespaceName; - } - } - function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 57); - var atToken = createNode(57, scanner.getStartPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return false; - } - switch (tagName.text) { - case "type": - if (parentTag.jsDocTypeTag) { - return false; - } - parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); - return true; - case "prop": - case "property": - var propertyTag = parsePropertyTag(atToken, tagName); - if (propertyTag) { - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } - parentTag.jsDocPropertyTags.push(propertyTag); - return true; - } - return false; - } - return false; - } - function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var typeParameters = createNodeArray(); - while (true) { - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var typeParameter = createNode(145, name.pos); - typeParameter.name = name; - finishNode(typeParameter); - typeParameters.push(typeParameter); - if (token() === 26) { - nextJSDocToken(); - skipWhitespace(); - } - else { - break; - } - } - var result = createNode(289, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeParameters = typeParameters; - finishNode(result); - typeParameters.end = result.end; - return result; - } - function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); - } - function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function createJSDocIdentifier(isIdentifier) { - if (!isIdentifier) { - parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - return undefined; - } - var pos = scanner.getTokenPos(); - var end = scanner.getTextPos(); - var result = createNode(71, pos); - result.text = content.substring(pos, end); - finishNode(result, end); - nextJSDocToken(); - return result; - } - } - JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; - })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); - })(Parser || (Parser = {})); - var IncrementalParser; - (function (IncrementalParser) { - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); - checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); - if (ts.textChangeRangeIsUnchanged(textChangeRange)) { - return sourceFile; - } - if (sourceFile.statements.length === 0) { - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); - } - var incrementalSourceFile = sourceFile; - ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); - incrementalSourceFile.hasBeenIncrementallyParsed = true; - var oldText = sourceFile.text; - var syntaxCursor = createSyntaxCursor(sourceFile); - var changeRange = extendToAffectedRange(sourceFile, textChangeRange); - checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); - ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); - ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); - ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); - var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; - updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); - return result; - } - IncrementalParser.updateSourceFile = updateSourceFile; - function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { - if (isArray) { - visitArray(element); - } - else { - visitNode(element); - } - return; - function visitNode(node) { - var text = ""; - if (aggressiveChecks && shouldCheckNode(node)) { - text = oldText.substring(node.pos, node.end); - } - if (node._children) { - node._children = undefined; - } - node.pos += delta; - node.end += delta; - if (aggressiveChecks && shouldCheckNode(node)) { - ts.Debug.assert(text === newText.substring(node.pos, node.end)); - } - forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - forEachChild(jsDocComment, visitNode, visitArray); - } - } - checkNodePositions(node, aggressiveChecks); - } - function visitArray(array) { - array._children = undefined; - array.pos += delta; - array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; - visitNode(node); - } - } - } - function shouldCheckNode(node) { - switch (node.kind) { - case 9: - case 8: - case 71: - return true; - } - return false; - } - function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { - ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); - ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); - ts.Debug.assert(element.pos <= element.end); - element.pos = Math.min(element.pos, changeRangeNewEnd); - if (element.end >= changeRangeOldEnd) { - element.end += delta; - } - else { - element.end = Math.min(element.end, changeRangeNewEnd); - } - ts.Debug.assert(element.pos <= element.end); - if (element.parent) { - ts.Debug.assert(element.pos >= element.parent.pos); - ts.Debug.assert(element.end <= element.parent.end); - } - } - function checkNodePositions(node, aggressiveChecks) { - if (aggressiveChecks) { - var pos_2 = node.pos; - forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; - }); - ts.Debug.assert(pos_2 <= node.end); - } - } - function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { - visitNode(sourceFile); - return; - function visitNode(child) { - ts.Debug.assert(child.pos <= child.end); - if (child.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); - return; - } - var fullEnd = child.end; - if (fullEnd >= changeStart) { - child.intersectsChange = true; - child._children = undefined; - adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - forEachChild(child, visitNode, visitArray); - checkNodePositions(child, aggressiveChecks); - return; - } - ts.Debug.assert(fullEnd < changeStart); - } - function visitArray(array) { - ts.Debug.assert(array.pos <= array.end); - if (array.pos > changeRangeOldEnd) { - moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); - return; - } - var fullEnd = array.end; - if (fullEnd >= changeStart) { - array.intersectsChange = true; - array._children = undefined; - adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; - visitNode(node); - } - return; - } - ts.Debug.assert(fullEnd < changeStart); - } - } - function extendToAffectedRange(sourceFile, changeRange) { - var maxLookahead = 1; - var start = changeRange.span.start; - for (var i = 0; start > 0 && i <= maxLookahead; i++) { - var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); - ts.Debug.assert(nearestNode.pos <= start); - var position = nearestNode.pos; - start = Math.max(0, position - 1); - } - var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); - var finalLength = changeRange.newLength + (changeRange.span.start - start); - return ts.createTextChangeRange(finalSpan, finalLength); - } - function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { - var bestResult = sourceFile; - var lastNodeEntirelyBeforePosition; - forEachChild(sourceFile, visit); - if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); - if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { - bestResult = lastChildOfLastEntireNodeBeforePosition; - } - } - return bestResult; - function getLastChild(node) { - while (true) { - var lastChild = getLastChildWorker(node); - if (lastChild) { - node = lastChild; - } - else { - return node; - } - } - } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } - function visit(child) { - if (ts.nodeIsMissing(child)) { - return; - } - if (child.pos <= position) { - if (child.pos >= bestResult.pos) { - bestResult = child; - } - if (position < child.end) { - forEachChild(child, visit); - return true; - } - else { - ts.Debug.assert(child.end <= position); - lastNodeEntirelyBeforePosition = child; - } - } - else { - ts.Debug.assert(child.pos > position); - return true; - } - } - } - function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { - var oldText = sourceFile.text; - if (textChangeRange) { - ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); - if (aggressiveChecks || ts.Debug.shouldAssert(3)) { - var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - var newTextPrefix = newText.substr(0, textChangeRange.span.start); - ts.Debug.assert(oldTextPrefix === newTextPrefix); - var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); - var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); - ts.Debug.assert(oldTextSuffix === newTextSuffix); - } - } - } - function createSyntaxCursor(sourceFile) { - var currentArray = sourceFile.statements; - var currentArrayIndex = 0; - ts.Debug.assert(currentArrayIndex < currentArray.length); - var current = currentArray[currentArrayIndex]; - var lastQueriedPosition = -1; - return { - currentNode: function (position) { - if (position !== lastQueriedPosition) { - if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { - currentArrayIndex++; - current = currentArray[currentArrayIndex]; - } - if (!current || current.pos !== position) { - findHighestListElementThatStartsAtPosition(position); - } - } - lastQueriedPosition = position; - ts.Debug.assert(!current || current.pos === position); - return current; - } - }; - function findHighestListElementThatStartsAtPosition(position) { - currentArray = undefined; - currentArrayIndex = -1; - current = undefined; - forEachChild(sourceFile, visitNode, visitArray); - return; - function visitNode(node) { - if (position >= node.pos && position < node.end) { - forEachChild(node, visitNode, visitArray); - return true; - } - return false; - } - function visitArray(array) { - if (position >= array.pos && position < array.end) { - for (var i = 0; i < array.length; i++) { - var child = array[i]; - if (child) { - if (child.pos === position) { - currentArray = array; - currentArrayIndex = i; - current = child; - return true; - } - else { - if (child.pos < position && position < child.end) { - forEachChild(child, visitNode, visitArray); - return true; - } - } - } - } - } - return false; - } - } - } - 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; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2; - } - else if ((node.kind === 238 || node.kind === 237) && !(ts.hasModifier(node, 1))) { - return 0; - } - else if (node.kind === 234) { - var state_1 = 0; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0: - return false; - case 2: - state_1 = 2; - return false; - case 1: - state_1 = 1; - return true; - } - }); - return state_1; - } - else if (node.kind === 233) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1; - } - else if (node.kind === 71 && node.isInJSDocNamespace) { - return 0; - } - else { - return 1; - } - } - 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"); - binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var languageVersion; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - var currentFlow; - var currentBreakTarget; - var currentContinueTarget; - var currentReturnTarget; - var currentTrueTarget; - var currentFalseTarget; - var preSwitchCaseFlow; - var activeLabels; - var hasExplicitReturn; - var emitFlags; - var inStrictMode; - var symbolCount = 0; - var Symbol; - var classifiableNames; - var unreachableFlow = { flags: 1 }; - var reportedUnreachableFlow = { flags: 1 }; - var subtreeTransformFlags = 0; - var skipTransformFlagAggregation; - function bindSourceFile(f, opts) { - file = f; - options = opts; - languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = ts.createMap(); - symbolCount = 0; - skipTransformFlagAggregation = file.isDeclarationFile; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = 0; - subtreeTransformFlags = 0; - } - return bindSourceFile; - function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 && !symbol.exports) { - symbol.exports = ts.createMap(); - } - if (symbolFlags & 6240 && !symbol.members) { - symbol.members = ts.createMap(); - } - if (symbolFlags & 107455) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233)) { - symbol.valueDeclaration = node; - } - } - } - function getDeclarationName(node) { - var name = ts.getNameOfDeclaration(node); - if (name) { - if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; - } - 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 name.text; - } - switch (node.kind) { - case 152: - return "__constructor"; - case 160: - case 155: - return "__call"; - case 161: - case 156: - return "__new"; - case 157: - return "__index"; - case 244: - return "__export"; - case 243: - return node.isExportEquals ? "export=" : "default"; - case 194: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2: - return "export="; - case 1: - case 4: - case 5: - return node.left.name.text; - case 3: - return node.left.expression.name.text; - } - ts.Debug.fail("Unknown binary declaration kind"); - break; - case 228: - case 229: - return ts.hasModifier(node, 512) ? "default" : undefined; - case 279: - return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 146: - ts.Debug.assert(node.parent.kind === 279); - var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); - return "arg" + index; - case 290: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71) { - nameFromParentNode = nameIdentifier.text; - } - } - } - return nameFromParentNode; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512); - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name === undefined) { - symbol = createSymbol(0, "__missing"); - } - else { - symbol = symbolTable.get(name); - if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0, name)); - } - if (name && (includes & 788448)) { - classifiableNames.set(name, name); - } - if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - symbolTable.set(name, symbol = createSymbol(0, name)); - } - else { - if (node.name) { - node.name.parent = node; - } - var message_1 = symbol.flags & 2 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - if (symbol.declarations && symbol.declarations.length) { - if (isDefaultExport) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 243 && !node.isExportEquals))) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0, name); - } - } - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1; - if (symbolFlags & 8388608) { - if (node.kind === 246 || (node.kind === 237 && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - else { - var isJSDocTypedefInJSDocNamespace = node.kind === 290 && - node.name && - node.name.kind === 71 && - node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | - (symbolFlags & 793064 ? 2097152 : 0) | - (symbolFlags & 1920 ? 4194304 : 0); - var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - } - function bindContainer(node, containerFlags) { - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - if (containerFlags & 1) { - container = blockScopeContainer = node; - if (containerFlags & 32) { - container.locals = ts.createMap(); - } - addToContainerChain(container); - } - else if (containerFlags & 2) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & 4) { - var saveCurrentFlow = currentFlow; - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - var saveReturnTarget = currentReturnTarget; - var saveActiveLabels = activeLabels; - var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !!ts.getImmediatelyInvokedFunctionExpression(node); - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { - currentFlow = { flags: 2 }; - if (containerFlags & (16 | 128)) { - currentFlow.container = node; - } - currentReturnTarget = undefined; - } - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - node.flags &= ~1408; - if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { - node.flags |= 128; - if (hasExplicitReturn) - node.flags |= 256; - } - if (node.kind === 265) { - node.flags |= emitFlags; - } - if (isIIFE) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - } - else { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & 64) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 : node.flags & ~64; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - function bindChildren(node) { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & 536870912) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - function bindEach(nodes) { - if (nodes === undefined) { - return; - } - if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var nodeArrayFlags = 0; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; - bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912; - } - nodes.transformFlags = nodeArrayFlags | 536870912; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - } - function bindEachChild(node) { - ts.forEachChild(node, bind, bindEach); - } - function bindChildrenWorker(node) { - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } - if (checkUnreachable(node)) { - bindEachChild(node); - return; - } - switch (node.kind) { - case 213: - bindWhileStatement(node); - break; - case 212: - bindDoStatement(node); - break; - case 214: - bindForStatement(node); - break; - case 215: - case 216: - bindForInOrForOfStatement(node); - break; - case 211: - bindIfStatement(node); - break; - case 219: - case 223: - bindReturnOrThrow(node); - break; - case 218: - case 217: - bindBreakOrContinueStatement(node); - break; - case 224: - bindTryStatement(node); - break; - case 221: - bindSwitchStatement(node); - break; - case 235: - bindCaseBlock(node); - break; - case 257: - bindCaseClause(node); - break; - case 222: - bindLabeledStatement(node); - break; - case 192: - bindPrefixUnaryExpressionFlow(node); - break; - case 193: - bindPostfixUnaryExpressionFlow(node); - break; - case 194: - bindBinaryExpressionFlow(node); - break; - case 188: - bindDeleteExpressionFlow(node); - break; - case 195: - bindConditionalExpressionFlow(node); - break; - case 226: - bindVariableDeclarationFlow(node); - break; - case 181: - bindCallExpressionFlow(node); - break; - case 283: - bindJSDocComment(node); - break; - case 290: - bindJSDocTypedefTag(node); - break; - default: - bindEachChild(node); - break; - } - } - function isNarrowingExpression(expr) { - switch (expr.kind) { - case 71: - case 99: - case 179: - return isNarrowableReference(expr); - case 181: - return hasNarrowableArgument(expr); - case 185: - return isNarrowingExpression(expr.expression); - case 194: - return isNarrowingBinaryExpression(expr); - case 192: - return expr.operator === 51 && isNarrowingExpression(expr.operand); - } - return false; - } - function isNarrowableReference(expr) { - return expr.kind === 71 || - expr.kind === 99 || - expr.kind === 97 || - expr.kind === 179 && isNarrowableReference(expr.expression); - } - function hasNarrowableArgument(expr) { - if (expr.arguments) { - for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === 179 && - isNarrowableReference(expr.expression.expression)) { - return true; - } - return false; - } - function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; - } - function isNarrowingBinaryExpression(expr) { - switch (expr.operatorToken.kind) { - case 58: - return isNarrowableReference(expr.left); - case 32: - case 33: - case 34: - case 35: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93: - return isNarrowableOperand(expr.left); - case 26: - return isNarrowingExpression(expr.right); - } - return false; - } - function isNarrowableOperand(expr) { - switch (expr.kind) { - case 185: - return isNarrowableOperand(expr.expression); - case 194: - switch (expr.operatorToken.kind) { - case 58: - return isNarrowableOperand(expr.left); - case 26: - return isNarrowableOperand(expr.right); - } - } - return isNarrowableReference(expr); - } - function createBranchLabel() { - return { - flags: 4, - antecedents: undefined - }; - } - function createLoopLabel() { - return { - flags: 8, - antecedents: undefined - }; - } - function setFlowNodeReferenced(flow) { - flow.flags |= flow.flags & 512 ? 1024 : 512; - } - function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1) && !ts.contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1) { - return antecedent; - } - if (!expression) { - return flags & 32 ? antecedent : unreachableFlow; - } - if (expression.kind === 101 && flags & 64 || - expression.kind === 86 && flags & 32) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; - } - function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: 128, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; - } - function createFlowAssignment(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 16, - antecedent: antecedent, - node: node - }; - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 256, - antecedent: antecedent, - node: node - }; - } - function finishFlowLabel(flow) { - var antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - function isStatementCondition(node) { - var parent = node.parent; - switch (parent.kind) { - case 211: - case 213: - case 212: - return parent.expression === node; - case 214: - case 195: - return parent.condition === node; - } - return false; - } - function isLogicalExpression(node) { - while (true) { - if (node.kind === 185) { - node = node.expression; - } - else if (node.kind === 192 && node.operator === 51) { - node = node.operand; - } - else { - return node.kind === 194 && (node.operatorToken.kind === 53 || - node.operatorToken.kind === 54); - } - } - } - function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 || - node.parent.kind === 192 && - node.parent.operator === 51) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - function bindCondition(node, trueTarget, falseTarget) { - var saveTrueTarget = currentTrueTarget; - var saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64, currentFlow, node)); - } - } - function bindIterativeStatement(node, breakTarget, continueTarget) { - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - function bindWhileStatement(node) { - var preWhileLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - function bindDoStatement(node) { - var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 - ? ts.lastOrUndefined(activeLabels) - : undefined; - var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); - var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - function bindForStatement(node) { - var preLoopLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindForInOrForOfStatement(node) { - var preLoopLabel = createLoopLabel(); - var postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - if (node.kind === 216) { - bind(node.awaitModifier); - } - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== 227) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindIfStatement(node) { - var thenLabel = createBranchLabel(); - var elseLabel = createBranchLabel(); - var postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - function bindReturnOrThrow(node) { - bind(node.expression); - if (node.kind === 219) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - function findActiveLabel(name) { - if (activeLabels) { - for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { - var label = activeLabels_1[_i]; - if (label.name === name) { - return label; - } - } - } - return undefined; - } - function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - function bindBreakOrContinueStatement(node) { - bind(node.label); - if (node.label) { - var activeLabel = findActiveLabel(node.label.text); - if (activeLabel) { - activeLabel.referenced = true; - bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; - } - if (node.finallyBlock) { - var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); - bind(node.finallyBlock); - if (!(currentFlow.flags & 1)) { - if ((flowAfterTry.flags & 1) && (flowAfterCatch.flags & 1)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } - } - if (!(currentFlow.flags & 1)) { - var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; - } - } - else { - currentFlow = finishFlowLabel(preFinallyLabel); - } - } - function bindSwitchStatement(node) { - var postSwitchLabel = createBranchLabel(); - bind(node.expression); - var saveBreakTarget = currentBreakTarget; - var savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258; }); - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - function bindCaseBlock(node) { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var clauses = node.clauses; - var fallthroughFlow = unreachableFlow; - for (var i = 0; i < clauses.length; i++) { - var clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - var clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - clauses.transformFlags = subtreeTransformFlags | 536870912; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - function bindCaseClause(node) { - var saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - bindEach(node.statements); - } - function pushActiveLabel(name, breakTarget, continueTarget) { - var activeLabel = { - name: name, - breakTarget: breakTarget, - continueTarget: continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - function popActiveLabel() { - activeLabels.pop(); - } - function bindLabeledStatement(node) { - var preStatementLabel = createLoopLabel(); - var postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - var activeLabel = pushActiveLabel(node.label.text, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); - } - if (!node.statement || node.statement.kind !== 212) { - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - } - function bindDestructuringTargetFlow(node) { - if (node.kind === 194 && node.operatorToken.kind === 58) { - bindAssignmentTargetFlow(node.left); - } - else { - bindAssignmentTargetFlow(node); - } - } - function bindAssignmentTargetFlow(node) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === 177) { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var e = _a[_i]; - if (e.kind === 198) { - bindAssignmentTargetFlow(e.expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === 178) { - for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { - var p = _c[_b]; - if (p.kind === 261) { - bindDestructuringTargetFlow(p.initializer); - } - else if (p.kind === 262) { - bindAssignmentTargetFlow(p.name); - } - else if (p.kind === 263) { - bindAssignmentTargetFlow(p.expression); - } - } - } - } - function bindLogicalExpression(node, trueTarget, falseTarget) { - var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51) { - var saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - bindEachChild(node); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { - bindAssignmentTargetFlow(node.operand); - } - } - } - function bindPostfixUnaryExpressionFlow(node) { - bindEachChild(node); - if (node.operator === 43 || node.operator === 44) { - bindAssignmentTargetFlow(node.operand); - } - } - function bindBinaryExpressionFlow(node) { - var operator = node.operatorToken.kind; - if (operator === 53 || operator === 54) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - bindEachChild(node); - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 58 && node.left.kind === 180) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - function bindDeleteExpressionFlow(node) { - bindEachChild(node); - if (node.expression.kind === 179) { - bindAssignmentTargetFlow(node.expression); - } - } - function bindConditionalExpressionFlow(node) { - var trueLabel = createBranchLabel(); - var falseLabel = createBranchLabel(); - var postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.questionToken); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.colonToken); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - function bindInitializedVariableFlow(node) { - var name = !ts.isOmittedExpression(node) ? node.name : undefined; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var child = _a[_i]; - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - function bindVariableDeclarationFlow(node) { - bindEachChild(node); - if (node.initializer || node.parent.parent.kind === 215 || node.parent.parent.kind === 216) { - bindInitializedVariableFlow(node); - } - } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 290) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - if (node.fullName && n === node.name && node.fullName.kind !== 71) { - return; - } - bind(n); - }); - } - function bindCallExpressionFlow(node) { - var expr = node.expression; - while (expr.kind === 185) { - expr = expr.expression; - } - if (expr.kind === 186 || expr.kind === 187) { - bindEach(node.typeArguments); - bindEach(node.arguments); - bind(node.expression); - } - else { - bindEachChild(node); - } - if (node.expression.kind === 179) { - var propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 199: - case 229: - case 232: - case 178: - case 163: - case 292: - case 275: - case 254: - return 1; - case 230: - return 1 | 64; - case 279: - case 233: - case 231: - case 172: - return 1 | 32; - case 265: - return 1 | 4 | 32; - case 151: - if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 | 4 | 32 | 8 | 128; - } - case 152: - case 228: - case 150: - case 153: - case 154: - case 155: - case 156: - case 157: - case 160: - case 161: - return 1 | 4 | 32 | 8; - case 186: - case 187: - return 1 | 4 | 32 | 8 | 16; - case 234: - return 4; - case 149: - return node.initializer ? 4 : 0; - case 260: - case 214: - case 215: - case 216: - case 235: - return 2; - case 207: - return ts.isFunctionLike(node.parent) ? 0 : 2; - } - return 0; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { - switch (container.kind) { - case 233: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199: - case 229: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 232: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163: - case 178: - case 230: - case 275: - case 292: - case 254: - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160: - case 161: - case 155: - case 156: - case 157: - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 186: - case 187: - case 279: - case 231: - case 172: - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 265 ? node : node.body; - if (body && (body.kind === 265 || body.kind === 234)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 244 || stat.kind === 243) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 32; - } - else { - node.flags &= ~32; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1)) { - errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (ts.isExternalModuleAugmentation(node)) { - declareModuleSymbol(node); - } - else { - var pattern = void 0; - if (node.name.kind === 9) { - var text = node.name.text; - if (ts.hasZeroOrOneAsteriskCharacter(text)) { - pattern = ts.tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - var symbol = declareSymbolAndAddToSymbolTable(node, 512, 106639); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } - } - } - else { - var state = declareModuleSymbol(node); - if (state !== 0) { - if (node.symbol.flags & (16 | 32 | 256)) { - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2; - if (node.symbol.constEnumOnlyModule === undefined) { - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function declareModuleSymbol(node) { - var state = getModuleInstanceState(node); - var instantiated = state !== 0; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 : 1024, instantiated ? 106639 : 0); - return state; - } - function bindFunctionOrConstructorType(node) { - var symbol = createSymbol(131072, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072); - var typeLiteralSymbol = createSymbol(2048, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048); - typeLiteralSymbol.members = ts.createMap(); - 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++) { - var prop = _a[_i]; - if (prop.kind === 263 || prop.name.kind !== 71) { - continue; - } - var identifier = prop.name; - var currentKind = prop.kind === 261 || prop.kind === 262 || prop.kind === 151 - ? 1 - : 2; - var existingKind = seen.get(identifier.text); - if (!existingKind) { - seen.set(identifier.text, currentKind); - continue; - } - if (currentKind === 1 && existingKind === 1) { - var span_1 = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - return bindAnonymousDeclaration(node, 4096, "__object"); - } - function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096, "__jsxAttributes"); - } - function bindJsxAttribute(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 233: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 265: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 107455); - } - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 108 && - node.originalKeywordKind <= 116 && - !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - if (inStrictMode && node.expression.kind === 71) { - var span_2 = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 71 && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71) { - var identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); - } - } - } - function getStrictModeEvalOrArgumentsMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - } - function getStrictModeBlockScopeFunctionDeclarationMessage(node) { - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2) { - if (blockScopeContainer.kind !== 265 && - blockScopeContainer.kind !== 233 && - !ts.isFunctionLike(blockScopeContainer)) { - var errorSpan = ts.getErrorSpanForNode(file, node); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - function checkStrictModePostfixUnaryExpression(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - function checkStrictModePrefixUnaryExpression(node) { - if (inStrictMode) { - if (node.operator === 43 || node.operator === 44) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var saveInStrictMode = inStrictMode; - if (ts.isInJavaScriptFile(node)) { - bindJSDocTypedefTagIfAny(node); - } - bindWorker(node); - if (node.kind > 142) { - var saveParent = parent; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags === 0) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; - } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 290) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; - } - } - } - } - function updateStrictModeStatementList(statements) { - if (!inStrictMode) { - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - case 71: - if (node.isInJSDocNamespace) { - var parentNode = node.parent; - while (parentNode && parentNode.kind !== 290) { - parentNode = parentNode.parent; - } - bindBlockScopedDeclaration(parentNode, 524288, 793064); - break; - } - case 99: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case 179: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - break; - case 194: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case 1: - bindExportsPropertyAssignment(node); - break; - case 2: - bindModuleExportsAssignment(node); - break; - case 3: - bindPrototypePropertyAssignment(node); - break; - case 4: - bindThisPropertyAssignment(node); - break; - case 5: - bindStaticPropertyAssignment(node); - break; - case 0: - break; - default: - ts.Debug.fail("Unknown special property assignment kind"); - } - return checkStrictModeBinaryExpression(node); - case 260: - return checkStrictModeCatchClause(node); - case 188: - return checkStrictModeDeleteExpression(node); - case 8: - return checkStrictModeNumericLiteral(node); - case 193: - return checkStrictModePostfixUnaryExpression(node); - case 192: - return checkStrictModePrefixUnaryExpression(node); - case 220: - return checkStrictModeWithStatement(node); - case 169: - seenThisKeyword = true; - return; - case 158: - return checkTypePredicate(node); - case 145: - return declareSymbolAndAddToSymbolTable(node, 262144, 530920); - case 146: - return bindParameter(node); - case 226: - case 176: - return bindVariableDeclarationOrBindingElement(node); - case 149: - case 148: - case 276: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); - case 291: - return bindJSDocProperty(node); - case 261: - case 262: - return bindPropertyOrMethodOrAccessor(node, 4, 0); - case 264: - return bindPropertyOrMethodOrAccessor(node, 8, 900095); - case 263: - case 255: - var root = container; - var hasRest = false; - while (root.parent) { - if (root.kind === 178 && - root.parent.kind === 194 && - root.parent.operatorToken.kind === 58 && - root.parent.left === root) { - hasRest = true; - break; - } - root = root.parent; - } - return; - case 155: - case 156: - case 157: - return declareSymbolAndAddToSymbolTable(node, 131072, 0); - case 151: - case 150: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 67108864 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); - case 228: - return bindFunctionDeclaration(node); - case 152: - return declareSymbolAndAddToSymbolTable(node, 16384, 0); - case 153: - return bindPropertyOrMethodOrAccessor(node, 32768, 41919); - case 154: - return bindPropertyOrMethodOrAccessor(node, 65536, 74687); - case 160: - case 161: - case 279: - return bindFunctionOrConstructorType(node); - case 163: - case 172: - case 292: - case 275: - return bindAnonymousDeclaration(node, 2048, "__type"); - case 178: - return bindObjectLiteralExpression(node); - case 186: - case 187: - return bindFunctionExpression(node); - case 181: - if (ts.isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - case 199: - case 229: - inStrictMode = true; - return bindClassLikeDeclaration(node); - case 230: - return bindBlockScopedDeclaration(node, 64, 792968); - case 290: - if (!node.fullName || node.fullName.kind === 71) { - return bindBlockScopedDeclaration(node, 524288, 793064); - } - break; - case 231: - return bindBlockScopedDeclaration(node, 524288, 793064); - case 232: - return bindEnumDeclaration(node); - case 233: - return bindModuleDeclaration(node); - case 254: - return bindJsxAttributes(node); - case 253: - return bindJsxAttribute(node, 4, 0); - case 237: - case 240: - case 242: - case 246: - return declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - case 236: - return bindNamespaceExportDeclaration(node); - case 239: - return bindImportClause(node); - case 244: - return bindExportDeclaration(node); - case 243: - return bindExportAssignment(node); - case 265: - updateStrictModeStatementList(node.statements); - return bindSourceFileIfExternalModule(); - case 207: - if (!ts.isFunctionLike(node.parent)) { - return; - } - case 234: - return updateStrictModeStatementList(node.statements); - } - } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 169) { - seenThisKeyword = true; - } - bind(type); - } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } - function bindExportAssignment(node) { - if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 8388608, getDeclarationName(node)); - } - else { - var flags = node.kind === 243 && ts.exportAssignmentIsAlias(node) - ? 8388608 - : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); - } - } - function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); - } - if (node.parent.kind !== 265) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608, 8388608); - } - function bindExportDeclaration(node) { - if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 33554432, getDeclarationName(node)); - } - else if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 33554432, 0); - } - } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 8388608, 8388608); - } - } - function setCommonJsModuleIndicator(node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } - } - } - function bindExportsPropertyAssignment(node) { - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 | 7340032, 0); - } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (node.kind === 71) { - var symbol = lookupSymbolForName(node.text); - if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === 226) { - var declaration = symbol.valueDeclaration; - if (declaration.initializer) { - return isExportsOrModuleExportsOrAliasOrAssignemnt(declaration.initializer); - } - } - } - return false; - } - function isExportsOrModuleExportsOrAliasOrAssignemnt(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, true) && (isExportsOrModuleExportsOrAliasOrAssignemnt(node.left) || isExportsOrModuleExportsOrAliasOrAssignemnt(node.right))); - } - function bindModuleExportsAssignment(node) { - var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { - setCommonJsModuleIndicator(node); - return; - } - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 | 7340032 | 512, 0); - } - function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, false); - switch (container.kind) { - case 228: - case 186: - container.symbol.members = container.symbol.members || ts.createMap(); - declareSymbol(container.symbol.members, container.symbol, node, 4, 0 & ~4); - break; - case 152: - case 149: - case 151: - case 153: - case 154: - var containingClass = container.parent; - var symbol = declareSymbol(ts.hasModifier(container, 32) ? containingClass.symbol.exports : containingClass.symbol.members, containingClass.symbol, node, 4, 0); - if (symbol) { - symbol.isReplaceableByMethod = true; - } - break; - } - } - function bindPrototypePropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var classPrototype = leftSideOfAssignment.expression; - var constructorFunction = classPrototype.expression; - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.text, leftSideOfAssignment, true); - } - function bindStaticPropertyAssignment(node) { - var leftSideOfAssignment = node.left; - var target = leftSideOfAssignment.expression; - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.text, leftSideOfAssignment, false); - } - } - function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; - } - if (!targetSymbol || !(targetSymbol.flags & (16 | 32))) { - return; - } - var symbolTable = isPrototypeProperty ? - (targetSymbol.members || (targetSymbol.members = ts.createMap())) : - (targetSymbol.exports || (targetSymbol.exports = ts.createMap())); - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4, 0); - } - function bindCallExpression(node) { - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, false)) { - setCommonJsModuleIndicator(node); - } - } - function bindClassLikeDeclaration(node) { - if (node.kind === 229) { - bindBlockScopedDeclaration(node, 32, 899519); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32, bindingName); - if (node.name) { - classifiableNames.set(node.name.text, node.name.text); - } - } - var symbol = node.symbol; - var prototypeSymbol = createSymbol(4 | 16777216, "prototype"); - var symbolExport = symbol.exports.get(prototypeSymbol.name); - if (symbolExport) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports.set(prototypeSymbol.name, prototypeSymbol); - prototypeSymbol.parent = symbol; - } - function bindEnumDeclaration(node) { - return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128, 899967) - : bindBlockScopedDeclaration(node, 256, 899327); - } - function bindVariableDeclarationOrBindingElement(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (!ts.isBindingPattern(node.name)) { - if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - declareSymbolAndAddToSymbolTable(node, 1, 107455); - } - else { - declareSymbolAndAddToSymbolTable(node, 1, 107454); - } - } - } - function bindParameter(node) { - if (inStrictMode && !ts.isInAmbientContext(node)) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, getDestructuringParameterName(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1, 107455); - } - if (ts.isParameterPropertyDeclaration(node)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 67108864 : 0), 0); - } - } - function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16, 106927); - } - else { - declareSymbolAndAddToSymbolTable(node, 16, 106927); - } - } - function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16, bindingName); - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024; - } - } - if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4, 0); - } - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); - } - function checkUnreachable(node) { - if (!(currentFlow.flags & 1)) { - return false; - } - if (currentFlow === unreachableFlow) { - var reportError = (ts.isStatementButNotDeclaration(node) && node.kind !== 209) || - node.kind === 229 || - (node.kind === 233 && shouldReportErrorOnModuleDeclaration(node)) || - (node.kind === 232 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentFlow = reportedUnreachableFlow; - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 || - ts.getCombinedNodeFlags(node.declarationList) & 3 || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - } - return true; - } - } - function computeTransformFlagsForNode(node, subtreeFlags) { - var kind = node.kind; - switch (kind) { - case 181: - return computeCallExpression(node, subtreeFlags); - case 182: - return computeNewExpression(node, subtreeFlags); - case 233: - return computeModuleDeclaration(node, subtreeFlags); - case 185: - return computeParenthesizedExpression(node, subtreeFlags); - case 194: - return computeBinaryExpression(node, subtreeFlags); - case 210: - return computeExpressionStatement(node, subtreeFlags); - case 146: - return computeParameter(node, subtreeFlags); - case 187: - return computeArrowFunction(node, subtreeFlags); - case 186: - return computeFunctionExpression(node, subtreeFlags); - case 228: - return computeFunctionDeclaration(node, subtreeFlags); - case 226: - return computeVariableDeclaration(node, subtreeFlags); - case 227: - return computeVariableDeclarationList(node, subtreeFlags); - case 208: - return computeVariableStatement(node, subtreeFlags); - case 222: - return computeLabeledStatement(node, subtreeFlags); - case 229: - return computeClassDeclaration(node, subtreeFlags); - case 199: - return computeClassExpression(node, subtreeFlags); - case 259: - return computeHeritageClause(node, subtreeFlags); - case 260: - return computeCatchClause(node, subtreeFlags); - case 201: - return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152: - return computeConstructor(node, subtreeFlags); - case 149: - return computePropertyDeclaration(node, subtreeFlags); - case 151: - return computeMethod(node, subtreeFlags); - case 153: - case 154: - return computeAccessor(node, subtreeFlags); - case 237: - return computeImportEquals(node, subtreeFlags); - case 179: - return computePropertyAccess(node, subtreeFlags); - default: - return computeOther(node, kind, subtreeFlags); - } - } - ts.computeTransformFlagsForNode = computeTransformFlagsForNode; - function computeCallExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (node.typeArguments) { - transformFlags |= 3; - } - if (subtreeFlags & 524288 - || isSuperOrSuperProperty(expression, expressionKind)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97: - return true; - case 179: - case 180: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97; - } - return false; - } - function computeNewExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= 3; - } - if (subtreeFlags & 524288) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function computeBinaryExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var operatorTokenKind = node.operatorToken.kind; - var leftKind = node.left.kind; - if (operatorTokenKind === 58 && leftKind === 178) { - transformFlags |= 8 | 192 | 3072; - } - else if (operatorTokenKind === 58 && leftKind === 177) { - transformFlags |= 192 | 3072; - } - else if (operatorTokenKind === 40 - || operatorTokenKind === 62) { - transformFlags |= 32; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeParameter(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var name = node.name; - var initializer = node.initializer; - var dotDotDotToken = node.dotDotDotToken; - if (node.questionToken - || node.type - || subtreeFlags & 4096 - || ts.isThisIdentifier(name)) { - transformFlags |= 3; - } - if (modifierFlags & 92) { - transformFlags |= 3 | 262144; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 8388608 || initializer || dotDotDotToken) { - transformFlags |= 192 | 131072; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeParenthesizedExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; - if (expressionKind === 202 - || expressionKind === 184) { - transformFlags |= 3; - } - if (expressionTransformFlags & 1024) { - transformFlags |= 1024; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeClassDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 274432) - || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; - } - function computeClassExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 274432 - || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; - } - function computeHeritageClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - switch (node.token) { - case 85: - transformFlags |= 192; - break; - case 108: - transformFlags |= 3; - break; - default: - ts.Debug.fail("Unexpected token for heritage clause"); - break; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeCatchClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; - } - function computeExpressionWithTypeArguments(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (node.typeArguments) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeConstructor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computeMethod(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (node.decorators - || ts.hasModifier(node, 2270) - || node.typeParameters - || node.type - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computeAccessor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.decorators - || ts.hasModifier(node, 2270) - || node.type - || !node.body) { - transformFlags |= 3; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; - } - function computePropertyDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags | 3; - if (node.initializer) { - transformFlags |= 8192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeFunctionDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body || (modifierFlags & 2)) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags | 33554432; - if (modifierFlags & 2270 - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (modifierFlags & 256) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 163840) { - transformFlags |= 192; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; - } - function computeFunctionExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (ts.hasModifier(node, 2270) - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 8 : 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 163840) { - transformFlags |= 192; - } - if (node.asteriskToken) { - transformFlags |= 768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; - } - function computeArrowFunction(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (ts.hasModifier(node, 2270) - || node.typeParameters - || node.type) { - transformFlags |= 3; - } - if (ts.hasModifier(node, 256)) { - transformFlags |= 16; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (subtreeFlags & 16384) { - transformFlags |= 32768; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; - } - function computePropertyAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeVariableDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags; - transformFlags |= 192 | 8388608; - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - if (node.type) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeVariableStatement(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var declarationListTransformFlags = node.declarationList.transformFlags; - if (modifierFlags & 2) { - transformFlags = 3; - } - else { - transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608) { - transformFlags |= 192; - } - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeLabeledStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (subtreeFlags & 4194304 - && ts.isIterationStatement(node, true)) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeImportEquals(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeExpressionStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 1024) { - transformFlags |= 192; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; - } - function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3; - var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2) === 0) { - transformFlags |= subtreeFlags; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; - } - function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432; - if (subtreeFlags & 8388608) { - transformFlags |= 192; - } - if (node.flags & 3) { - transformFlags |= 192 | 4194304; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; - } - function computeOther(node, kind, subtreeFlags) { - var transformFlags = subtreeFlags; - var excludeFlags = 536872257; - switch (kind) { - case 120: - case 191: - transformFlags |= 8 | 16; - break; - case 114: - case 112: - case 113: - case 117: - case 124: - case 76: - case 232: - case 264: - case 184: - case 202: - case 203: - case 131: - transformFlags |= 3; - break; - case 249: - case 250: - case 251: - case 10: - case 252: - case 253: - case 254: - case 255: - case 256: - transformFlags |= 4; - break; - case 13: - case 14: - case 15: - case 16: - case 196: - case 183: - case 262: - case 115: - case 204: - transformFlags |= 192; - break; - case 9: - if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192; - } - break; - case 8: - if (node.numericLiteralFlags & 48) { - transformFlags |= 192; - } - break; - case 216: - if (node.awaitModifier) { - transformFlags |= 8; - } - transformFlags |= 192; - break; - case 197: - transformFlags |= 8 | 192 | 16777216; - break; - case 119: - case 133: - case 130: - case 134: - case 136: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 158: - case 159: - case 160: - case 161: - case 162: - case 163: - case 164: - case 165: - case 166: - case 167: - case 168: - case 230: - case 231: - case 169: - case 170: - case 171: - case 172: - case 173: - transformFlags = 3; - excludeFlags = -3; - break; - case 144: - transformFlags |= 2097152; - if (subtreeFlags & 16384) { - transformFlags |= 65536; - } - break; - case 198: - transformFlags |= 192 | 524288; - break; - case 263: - transformFlags |= 8 | 1048576; - break; - case 97: - transformFlags |= 192; - break; - case 99: - transformFlags |= 16384; - break; - case 174: - transformFlags |= 192 | 8388608; - if (subtreeFlags & 524288) { - transformFlags |= 8 | 1048576; - } - excludeFlags = 537396545; - break; - case 175: - transformFlags |= 192 | 8388608; - excludeFlags = 537396545; - break; - case 176: - transformFlags |= 192; - if (node.dotDotDotToken) { - transformFlags |= 524288; - } - break; - case 147: - transformFlags |= 3 | 4096; - break; - case 178: - excludeFlags = 540087617; - if (subtreeFlags & 2097152) { - transformFlags |= 192; - } - if (subtreeFlags & 65536) { - transformFlags |= 16384; - } - if (subtreeFlags & 1048576) { - transformFlags |= 8; - } - break; - case 177: - case 182: - excludeFlags = 537396545; - if (subtreeFlags & 524288) { - transformFlags |= 192; - } - break; - case 212: - case 213: - case 214: - case 215: - if (subtreeFlags & 4194304) { - transformFlags |= 192; - } - break; - case 265: - if (subtreeFlags & 32768) { - transformFlags |= 192; - } - break; - case 219: - case 217: - case 218: - transformFlags |= 33554432; - break; - } - node.transformFlags = transformFlags | 536870912; - return transformFlags & ~excludeFlags; - } - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 && kind <= 173) { - return -3; - } - switch (kind) { - case 181: - case 182: - case 177: - return 537396545; - case 233: - return 574674241; - case 146: - return 536872257; - case 187: - return 601249089; - case 186: - case 228: - return 601281857; - case 227: - return 546309441; - case 229: - case 199: - return 539358529; - case 152: - return 601015617; - case 151: - case 153: - case 154: - return 601015617; - case 119: - case 133: - case 130: - case 136: - case 134: - case 122: - case 137: - case 105: - case 145: - case 148: - case 150: - case 155: - case 156: - case 157: - case 230: - case 231: - return -3; - case 178: - return 540087617; - case 260: - return 537920833; - case 174: - case 175: - return 537396545; - default: - return 536872257; - } - } - ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; -})(ts || (ts = {})); -var ts; -(function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; - var nextSymbolId = 1; - var nextNodeId = 1; - var nextMergeId = 1; - var nextFlowId = 1; - function getNodeId(node) { - if (!node.id) { - node.id = nextNodeId; - nextNodeId++; - } - return node.id; - } - ts.getNodeId = getNodeId; - function getSymbolId(symbol) { - if (!symbol.id) { - symbol.id = nextSymbolId; - nextSymbolId++; - } - return symbol.id; - } - ts.getSymbolId = getSymbolId; - function createTypeChecker(host, produceDiagnostics) { - var cancellationToken; - var requestedExternalEmitHelpers; - var externalHelpersModule; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var Type = ts.objectAllocator.getTypeConstructor(); - var Signature = ts.objectAllocator.getSignatureConstructor(); - var typeCount = 0; - var symbolCount = 0; - var enumCount = 0; - var symbolInstantiationDepth = 0; - var emptyArray = []; - var emptySymbols = ts.createMap(); - var compilerOptions = host.getCompilerOptions(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); - var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; - var emitResolver = createResolver(); - var nodeBuilder = createNodeBuilder(); - var undefinedSymbol = createSymbol(4, "undefined"); - undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4, "arguments"); - var checker = { - getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCount: function () { return typeCount; }, - isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, - isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, - isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, - getMergedSymbol: getMergedSymbol, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeOfSymbolAtLocation: function (symbol, location) { - location = ts.getParseTreeNode(location); - return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; - }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); - return getSymbolsOfParameterPropertyDeclaration(parameter, parameterName); - }, - getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, - getPropertiesOfType: getPropertiesOfType, - getPropertyOfType: getPropertyOfType, - getIndexInfoOfType: getIndexInfoOfType, - getSignaturesOfType: getSignaturesOfType, - getIndexTypeOfType: getIndexTypeOfType, - getBaseTypes: getBaseTypes, - getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, - getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); - return node ? getTypeFromTypeNode(node) : unknownType; - }, - getParameterType: getTypeAtPosition, - getReturnTypeOfSignature: getReturnTypeOfSignature, - getNonNullableType: getNonNullableType, - typeToTypeNode: nodeBuilder.typeToTypeNode, - indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, - signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, - getSymbolsInScope: function (location, meaning) { - location = ts.getParseTreeNode(location); - return location ? getSymbolsInScope(location, meaning) : []; - }, - getSymbolAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getSymbolAtLocation(node) : undefined; - }, - getShorthandAssignmentValueSymbol: function (node) { - node = ts.getParseTreeNode(node); - return node ? getShorthandAssignmentValueSymbol(node) : undefined; - }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); - return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; - }, - getTypeAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getTypeOfNode(node) : unknownType; - }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); - return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; - }, - signatureToString: function (signature, enclosingDeclaration, flags, kind) { - return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); - }, - typeToString: function (type, enclosingDeclaration, flags) { - return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); - }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); - }, - getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, - getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); - return node ? getContextualType(node) : undefined; - }, - getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); - return node ? getResolvedSignature(node, candidatesOutArray) : undefined; - }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, propertyName) : false; - }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); - return declaration ? getSignatureFromDeclaration(declaration) : undefined; - }, - isImplementationOfOverload: function (node) { - node = ts.getParseTreeNode(node, ts.isFunctionLike); - return node ? isImplementationOfOverload(node) : undefined; - }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - links.immediateTarget = getTargetOfAliasDeclaration(node, true); - } - return links.immediateTarget; - }, - getAliasedSymbol: resolveAlias, - getEmitResolver: getEmitResolver, - getExportsOfModule: getExportsOfModuleAsArray, - getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); - return node ? isOptionalParameter(node) : false; - }, - tryGetMemberInModuleExports: tryGetMemberInModuleExports, - tryFindAmbientModuleWithoutAugmentations: function (moduleName) { - return tryFindAmbientModule(moduleName, false); - }, - getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, - getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, - getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, - getBaseConstraintOfType: getBaseConstraintOfType, - }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var literalTypes = ts.createMap(); - var indexedAccessTypes = ts.createMap(); - var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4, "unknown"); - var resolvingSymbol = createSymbol(0, "__resolving__"); - var anyType = createIntrinsicType(1, "any"); - var autoType = createIntrinsicType(1, "any"); - var unknownType = createIntrinsicType(1, "unknown"); - var undefinedType = createIntrinsicType(2048, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 2097152, "undefined"); - var nullType = createIntrinsicType(4096, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 | 2097152, "null"); - var stringType = createIntrinsicType(2, "string"); - var numberType = createIntrinsicType(4, "number"); - var trueType = createIntrinsicType(128, "true"); - var falseType = createIntrinsicType(128, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512, "symbol"); - var voidType = createIntrinsicType(1024, "void"); - var neverType = createIntrinsicType(8192, "never"); - var silentNeverType = createIntrinsicType(8192, "never"); - var nonPrimitiveType = createIntrinsicType(16777216, "object"); - var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); - emptyTypeLiteralSymbol.members = ts.createMap(); - var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); - var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - anyFunctionType.flags |= 8388608; - var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, undefined, 0, false, false); - var enumNumberIndexInfo = createIndexInfo(stringType, true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, false); - var globals = ts.createMap(); - var patternAmbientModules; - var globalObjectType; - var globalFunctionType; - var globalArrayType; - var globalReadonlyArrayType; - var globalStringType; - var globalNumberType; - var globalBooleanType; - var globalRegExpType; - var globalThisType; - var anyArrayType; - var autoArrayType; - var anyReadonlyArrayType; - var deferredGlobalESSymbolConstructorSymbol; - var deferredGlobalESSymbolType; - var deferredGlobalTypedPropertyDescriptorType; - var deferredGlobalPromiseType; - var deferredGlobalPromiseConstructorSymbol; - var deferredGlobalPromiseConstructorLikeType; - var deferredGlobalIterableType; - var deferredGlobalIteratorType; - var deferredGlobalIterableIteratorType; - var deferredGlobalAsyncIterableType; - var deferredGlobalAsyncIteratorType; - var deferredGlobalAsyncIterableIteratorType; - var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; - var deferredNodes; - var deferredUnusedIdentifierNodes; - var flowLoopStart = 0; - var flowLoopCount = 0; - var visitedFlowCount = 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 = []; - var flowLoopCaches = []; - var flowLoopNodes = []; - var flowLoopKeys = []; - var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; - var potentialThisCollisions = []; - 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, - "boolean": 4, - "symbol": 8, - "undefined": 16384, - "object": 16, - "function": 32 - }); - var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128, - "number": 256, - "boolean": 512, - "symbol": 1024, - "undefined": 131072, - "object": 2048, - "function": 4096 - }); - var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType - }); - var typeofType = createTypeofType(); - var _jsxNamespace; - var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - var jsxTypes = ts.createMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - 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(); - return checker; - function getJsxNamespace() { - if (!_jsxNamespace) { - _jsxNamespace = "React"; - if (compilerOptions.jsxFactory) { - _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); - if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; - } - } - else if (compilerOptions.reactNamespace) { - _jsxNamespace = compilerOptions.reactNamespace; - } - } - return _jsxNamespace; - } - function getEmitResolver(sourceFile, cancellationToken) { - getDiagnostics(sourceFile, cancellationToken); - return emitResolver; - } - function error(location, message, arg0, arg1, arg2) { - var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); - diagnostics.add(diagnostic); - } - function createSymbol(flags, name) { - symbolCount++; - var symbol = (new Symbol(flags | 134217728, name)); - symbol.checkFlags = 0; - return symbol; - } - function isTransientSymbol(symbol) { - return (symbol.flags & 134217728) !== 0; - } - function getExcludedSymbolFlags(flags) { - var result = 0; - if (flags & 2) - result |= 107455; - if (flags & 1) - result |= 107454; - if (flags & 4) - result |= 0; - if (flags & 8) - result |= 900095; - if (flags & 16) - result |= 106927; - if (flags & 32) - result |= 899519; - if (flags & 64) - result |= 792968; - if (flags & 256) - result |= 899327; - if (flags & 128) - result |= 899967; - if (flags & 512) - result |= 106639; - if (flags & 8192) - result |= 99263; - if (flags & 32768) - result |= 41919; - if (flags & 65536) - result |= 74687; - if (flags & 262144) - result |= 530920; - if (flags & 524288) - result |= 793064; - if (flags & 8388608) - result |= 8388608; - return result; - } - function recordMergedSymbol(target, source) { - if (!source.mergeId) { - source.mergeId = nextMergeId; - nextMergeId++; - } - mergedSymbols[source.mergeId] = target; - } - function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags, symbol.name); - result.declarations = symbol.declarations.slice(0); - result.parent = symbol.parent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = ts.cloneMap(symbol.members); - if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); - recordMergedSymbol(result, symbol); - return result; - } - function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { - if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { - target.constEnumOnlyModule = false; - } - target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 && source.valueDeclaration.kind !== 233))) { - target.valueDeclaration = source.valueDeclaration; - } - ts.addRange(target.declarations, source.declarations); - if (source.members) { - if (!target.members) - target.members = ts.createMap(); - mergeSymbolTable(target.members, source.members); - } - if (source.exports) { - if (!target.exports) - target.exports = ts.createMap(); - mergeSymbolTable(target.exports, source.exports); - } - recordMergedSymbol(target, source); - } - else if (target.flags & 1024) { - 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - } - } - function mergeSymbolTable(target, source) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - } - else { - if (!(targetSymbol.flags & 134217728)) { - targetSymbol = cloneSymbol(targetSymbol); - target.set(id, targetSymbol); - } - mergeSymbol(targetSymbol, sourceSymbol); - } - }); - } - function mergeModuleAugmentation(moduleName) { - var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { - ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); - return; - } - if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports); - } - else { - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) - ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found - : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, true); - if (!mainModule) { - return; - } - mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920) { - mainModule = mainModule.flags & 134217728 ? mainModule : cloneSymbol(mainModule); - mergeSymbol(mainModule, moduleAugmentation.symbol); - } - else { - error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); - } - } - } - function addToSymbolTable(target, source, message) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (targetSymbol) { - ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(id, message)); - } - else { - target.set(id, sourceSymbol); - } - }); - function addDeclarationDiagnostic(id, message) { - return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; - } - } - function getSymbolLinks(symbol) { - if (symbol.flags & 134217728) - return symbol; - var id = getSymbolId(symbol); - return symbolLinks[id] || (symbolLinks[id] = {}); - } - function getNodeLinks(node) { - var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); - } - function getObjectFlags(type) { - return type.flags & 32768 ? type.objectFlags : 0; - } - function isGlobalSourceFile(node) { - return node.kind === 265 && !ts.isExternalOrCommonJsModule(node); - } - function getSymbol(symbols, name, meaning) { - if (meaning) { - var symbol = symbols.get(name); - if (symbol) { - ts.Debug.assert((ts.getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608) { - var target = resolveAlias(symbol); - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } - } - } - } - function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { - var constructorDeclaration = parameter.parent; - var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455); - if (parameterSymbol && propertySymbol) { - return [parameterSymbol, propertySymbol]; - } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); - } - function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { - var declarationFile = ts.getSourceFileOfNode(declaration); - var useFile = ts.getSourceFileOfNode(usage); - if (declarationFile !== useFile) { - if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out) || - ts.isInAmbientContext(declaration)) { - return true; - } - if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - return true; - } - var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); - } - if (declaration.pos <= usage.pos) { - if (declaration.kind === 176) { - var errorBindingElement = ts.getAncestor(usage, 176); - if (errorBindingElement) { - return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || - declaration.pos < errorBindingElement.pos; - } - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226), usage); - } - else if (declaration.kind === 226) { - return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); - } - return true; - } - if (usage.parent.kind === 246) { - return true; - } - var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); - function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); - switch (declaration.parent.parent.kind) { - case 208: - case 214: - case 216: - if (isSameScopeDescendentOf(usage, declaration, container)) { - return true; - } - break; - } - switch (declaration.parent.parent.kind) { - case 215: - case 216: - if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { - return true; - } - } - return false; - } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { - return !!ts.findAncestor(usage, function (current) { - if (current === container) { - return "quit"; - } - if (ts.isFunctionLike(current)) { - return true; - } - var initializerOfProperty = current.parent && - current.parent.kind === 149 && - current.parent.initializer === current; - if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32) { - if (declaration.kind === 151) { - return true; - } - } - else { - var isDeclarationInstanceProperty = declaration.kind === 149 && !(ts.getModifierFlags(declaration) & 32); - if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { - return true; - } - } - } - }); - } - } - 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; - var errorLocation = location; - var grandparent; - var isInExternalModule = false; - loop: while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - 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) { - useResult = result.flags & 262144 - ? lastLocation === location.type || - lastLocation.kind === 146 || - lastLocation.kind === 145 - : false; - } - if (meaning & 107455 && result.flags & 1) { - useResult = - lastLocation.kind === 146 || - (lastLocation === location.type && - result.valueDeclaration.kind === 146); - } - } - if (useResult) { - break loop; - } - else { - result = undefined; - } - } - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) - break; - isInExternalModule = true; - case 233: - var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 || ts.isAmbientModule(location)) { - if (result = moduleExports.get("default")) { - var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { - break loop; - } - result = undefined; - } - var moduleExport = moduleExports.get(name); - if (moduleExport && - moduleExport.flags === 8388608 && - ts.getDeclarationOfKind(moduleExport, 246)) { - break; - } - } - if (result = lookup(moduleExports, name, meaning & 8914931)) { - break loop; - } - break; - case 232: - if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8)) { - break loop; - } - break; - case 149: - case 148: - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32)) { - var ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455)) { - propertyWithInvalidInitializer = location; - } - } - } - break; - case 229: - case 199: - case 230: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064)) { - if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { - result = undefined; - break; - } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32) { - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); - return undefined; - } - break loop; - } - if (location.kind === 199 && meaning & 32) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; - case 144: - grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 230) { - 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; - } - } - break; - case 151: - case 150: - case 152: - case 153: - case 154: - case 228: - case 187: - if (meaning & 3 && name === "arguments") { - result = argumentsSymbol; - break loop; - } - break; - case 186: - if (meaning & 3 && name === "arguments") { - result = argumentsSymbol; - break loop; - } - if (meaning & 16) { - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; - } - } - break; - case 147: - if (location.parent && location.parent.kind === 146) { - location = location.parent; - } - if (location.parent && ts.isClassElement(location.parent)) { - location = location.parent; - } - break; - } - lastLocation = location; - location = location.parent; - } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { - result.isReferenced = true; - } - if (!result) { - result = lookup(globals, name, meaning); - } - if (!result) { - if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation) && - !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && - !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - 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; - } - if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer) { - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return undefined; - } - if (meaning & 2 || - ((meaning & 32 || meaning & 384) && (meaning & 107455) === 107455)) { - var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); - if (exportOrLocalSymbol.flags & 2 || exportOrLocalSymbol.flags & 32 || exportOrLocalSymbol.flags & 384) { - checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); - } - } - if (result && isInExternalModule && (meaning & 107455) === 107455) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); - } - } - } - return result; - } - function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 145 && decl.parent === container) { - return true; - } - } - return false; - } - function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 71 && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { - return false; - } - var container = ts.getThisContainer(errorLocation, true); - var location = container; - while (location) { - if (ts.isClassLike(location.parent)) { - var classSymbol = getSymbolOfNode(location.parent); - if (!classSymbol) { - break; - } - var constructorType = getTypeOfSymbol(classSymbol); - if (getPropertyOfType(constructorType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); - return true; - } - if (location === container && !(ts.getModifierFlags(location) & 32)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; - if (getPropertyOfType(instanceType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return true; - } - } - } - location = location.parent; - } - return false; - } - function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64, true)); - if (isError) { - error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - } - return isError; - } - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 71: - case 179: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } - } - function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 & ~107455, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); - return true; - } - } - return false; - } - 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); - return true; - } - } - return false; - } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (107455 & ~1024 & ~793064)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~107455, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, name); - return true; - } - } - else if (meaning & (793064 & ~1024 & ~107455)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 & ~793064, undefined, undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, name); - return true; - } - } - return false; - } - function checkResolvedBlockScopedVariable(result, errorLocation) { - ts.Debug.assert(!!(result.flags & 2 || result.flags & 32 || result.flags & 384)); - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232) ? d : undefined; }); - 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(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 256) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - } - } - function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); - } - function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237) { - return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); - } - } - function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); - } - function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248) { - return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); - } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); - } - function getTargetOfImportClause(node, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); - if (moduleSymbol) { - var exportDefaultSymbol = void 0; - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - exportDefaultSymbol = moduleSymbol; - } - else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); - } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { - return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - return exportDefaultSymbol; - } - } - function getTargetOfNamespaceImport(node, dontResolveAlias) { - var moduleSpecifier = node.parent.parent.moduleSpecifier; - return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); - } - function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 | 1920)) { - return valueSymbol; - } - var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); - result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); - result.parent = valueSymbol.parent || typeSymbol.parent; - if (valueSymbol.valueDeclaration) - result.valueDeclaration = valueSymbol.valueDeclaration; - if (typeSymbol.members) - result.members = typeSymbol.members; - if (valueSymbol.exports) - result.exports = valueSymbol.exports; - return result; - } - function getExportOfModule(symbol, name, dontResolveAlias) { - if (symbol.flags & 1536) { - return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); - } - } - function getPropertyOfVariable(symbol, name) { - if (symbol.flags & 3) { - var typeAnnotation = symbol.valueDeclaration.type; - if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); - } - } - } - function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); - if (targetSymbol) { - var name = specifier.propertyName || specifier.name; - if (name.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return moduleSymbol; - } - var symbolFromVariable = void 0; - if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text); - } - else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); - } - symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name.text, dontResolveAlias); - if (!symbolFromModule && allowSyntheticDefaultImports && name.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - var symbol = symbolFromModule && symbolFromVariable ? - combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : - symbolFromModule || symbolFromVariable; - if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); - } - return symbol; - } - } - } - function getTargetOfImportSpecifier(node, dontResolveAlias) { - return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); - } - function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { - return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); - } - function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : - resolveEntityName(node.propertyName || node.name, meaning, false, dontResolveAlias); - } - function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 107455 | 793064 | 1920, false, dontResolveAlias); - } - function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { - switch (node.kind) { - case 237: - return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239: - return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240: - return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242: - return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246: - return getTargetOfExportSpecifier(node, 107455 | 793064 | 1920, dontRecursivelyResolve); - case 243: - return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236: - return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - } - } - function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && symbol && symbol.flags & 8388608 && !(symbol.flags & (107455 | 793064 | 1920)); - return shouldResolve ? resolveAlias(symbol) : symbol; - } - function resolveAlias(symbol) { - ts.Debug.assert((symbol.flags & 8388608) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.target) { - links.target = resolvingSymbol; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - var target = getTargetOfAliasDeclaration(node); - if (links.target === resolvingSymbol) { - links.target = target || unknownSymbol; - } - else { - error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); - } - } - else if (links.target === resolvingSymbol) { - links.target = unknownSymbol; - } - return links.target; - } - function markExportAsReferenced(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target) { - var markAlias = target === unknownSymbol || - ((target.flags & 107455) && !isConstEnumOrConstEnumOnlyModule(target)); - if (markAlias) { - markAliasSymbolAsReferenced(symbol); - } - } - } - function markAliasSymbolAsReferenced(symbol) { - var links = getSymbolLinks(symbol); - if (!links.referenced) { - links.referenced = true; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - if (node.kind === 243) { - checkExpressionCached(node.expression); - } - else if (node.kind === 246) { - checkExpressionCached(node.propertyName || node.name); - } - else if (ts.isInternalModuleImportEqualsDeclaration(node)) { - checkExpressionCached(node.moduleReference); - } - } - } - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - if (entityName.kind === 71 && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (entityName.kind === 71 || entityName.parent.kind === 143) { - return resolveEntityName(entityName, 1920, false, dontResolveAlias); - } - else { - ts.Debug.assert(entityName.parent.kind === 237); - return resolveEntityName(entityName, 107455 | 793064 | 1920, false, dontResolveAlias); - } - } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); - } - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { - if (ts.nodeIsMissing(name)) { - return undefined; - } - var symbol; - if (name.kind === 71) { - var message = meaning === 1920 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); - if (!symbol) { - return undefined; - } - } - else if (name.kind === 143 || name.kind === 179) { - var left = void 0; - if (name.kind === 143) { - left = name.left; - } - else if (name.kind === 179 && - (name.expression.kind === 185 || ts.isEntityNameExpression(name.expression))) { - left = name.expression; - } - else { - return undefined; - } - var right = name.kind === 143 ? name.right : name.name; - var namespace = resolveEntityName(left, 1920, ignoreErrors, false, location); - if (!namespace || ts.nodeIsMissing(right)) { - return undefined; - } - else if (namespace === unknownSymbol) { - return namespace; - } - symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); - if (!symbol) { - if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); - } - return undefined; - } - } - else if (name.kind === 185) { - return ts.isEntityNameExpression(name.expression) ? - resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : - undefined; - } - else { - ts.Debug.fail("Unknown entity name kind."); - } - 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) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); - } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - if (moduleReferenceExpression.kind !== 9 && moduleReferenceExpression.kind !== 13) { - return; - } - var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); - } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - var moduleName = ts.escapeIdentifier(moduleReference); - 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; - } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); - var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); - if (sourceFile) { - if (sourceFile.symbol) { - return getMergedSymbol(sourceFile.symbol); - } - if (moduleNotFoundError) { - error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - } - return undefined; - } - if (patternAmbientModules) { - var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleName); - if (pattern) { - return getMergedSymbol(pattern.symbol); - } - } - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { - if (isForAugmentation) { - var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); - } - else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return undefined; - } - if (moduleNotFoundError) { - if (resolutionDiagnostic) { - error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); - } - else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(errorNode, moduleNotFoundError, moduleName); - } - } - } - return undefined; - } - function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; - } - function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { - 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)); - } - return symbol; - } - function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; - } - function getExportsOfModuleAsArray(moduleSymbol) { - return symbolsToArray(getExportsOfModule(moduleSymbol)); - } - function getExportsAndPropertiesOfModule(moduleSymbol) { - var exports = getExportsOfModuleAsArray(moduleSymbol); - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); - } - return exports; - } - function tryGetMemberInModuleExports(memberName, moduleSymbol) { - var symbolTable = getExportsOfModule(moduleSymbol); - if (symbolTable) { - return symbolTable.get(memberName); - } - } - function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; - } - function getExportsOfModule(moduleSymbol) { - var links = getSymbolLinks(moduleSymbol); - return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); - } - function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { - if (id === "default") - return; - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - if (lookupTable && exportNode) { - lookupTable.set(id, { - specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) - }); - } - } - else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { - var collisionTracker = lookupTable.get(id); - if (!collisionTracker.exportsWithDuplicate) { - collisionTracker.exportsWithDuplicate = [exportNode]; - } - else { - collisionTracker.exportsWithDuplicate.push(exportNode); - } - } - }); - } - function getExportsForModule(moduleSymbol) { - var visitedSymbols = []; - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - return visit(moduleSymbol) || moduleSymbol.exports; - function visit(symbol) { - if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { - return; - } - visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); - var exportStars = symbol.exports.get("__export"); - if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable_1 = ts.createMap(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); - } - lookupTable_1.forEach(function (_a, id) { - var exportsWithDuplicate = _a.exportsWithDuplicate; - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { - return; - } - for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { - var node = exportsWithDuplicate_1[_i]; - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, id)); - } - }); - extendExportSymbols(symbols, nestedSymbols); - } - return symbols; - } - } - function getMergedSymbol(symbol) { - var merged; - return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; - } - function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); - } - function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); - } - function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; - } - function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 || symbol.flags & 8388608 && resolveAlias(symbol).flags & 107455); - } - function findConstructorDeclaration(node) { - var members = node.members; - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var member = members_1[_i]; - if (member.kind === 152 && ts.nodeIsPresent(member.body)) { - return member; - } - } - } - function createType(flags) { - var result = new Type(checker, flags); - typeCount++; - result.id = typeCount; - return result; - } - function createIntrinsicType(kind, intrinsicName) { - var type = createType(kind); - type.intrinsicName = intrinsicName; - return type; - } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8; - type.intrinsicName = "boolean"; - return type; - } - function createObjectType(objectFlags, symbol) { - var type = createType(32768); - type.objectFlags = objectFlags; - type.symbol = symbol; - return type; - } - function createTypeofType() { - return getUnionType(ts.convertToArray(typeofEQFacts.keys(), getLiteralType)); - } - function isReservedMemberName(name) { - return name.charCodeAt(0) === 95 && - name.charCodeAt(1) === 95 && - name.charCodeAt(2) !== 95 && - name.charCodeAt(2) !== 64; - } - function getNamedMembers(members) { - var result; - members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } - } - }); - return result || emptyArray; - } - function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; - return type; - } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setStructuredTypeMembers(createObjectType(16, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function forEachSymbolTableInScope(enclosingDeclaration, callback) { - var result; - for (var location = enclosingDeclaration; location; location = location.parent) { - if (location.locals && !isGlobalSourceFile(location)) { - if (result = callback(location.locals)) { - return result; - } - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - case 233: - if (result = callback(getSymbolOfNode(location).exports)) { - return result; - } - break; - } - } - return callback(globals); - } - function getQualifiedLeftMeaning(rightMeaning) { - return rightMeaning === 107455 ? 107455 : 1920; - } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); - } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { - return undefined; - } - visitedSymbolTables.push(symbols); - var result = trySymbolTable(symbols); - visitedSymbolTables.pop(); - return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } - } - function trySymbolTable(symbols) { - if (isAccessible(symbols.get(symbol.name))) { - return [symbol]; - } - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) { - if (!useOnlyExternalAliasing || - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } - } - }); - } - } - if (symbol) { - if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - } - } - } - function needsQualification(symbol, enclosingDeclaration, meaning) { - var qualify = false; - forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - var symbolFromSymbolTable = symbolTable.get(symbol.name); - if (!symbolFromSymbolTable) { - return false; - } - if (symbolFromSymbolTable === symbol) { - return true; - } - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { - qualify = true; - return true; - } - return false; - }); - return qualify; - } - function isPropertyOrMethodDeclarationSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - switch (declaration.kind) { - case 149: - case 151: - case 153: - case 154: - continue; - default: - return false; - } - } - return true; - } - return false; - } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920) : undefined, - }; - } - return hasAccessibleDeclarations; - } - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); - } - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); - if (symbolExternalModule) { - var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); - if (symbolExternalModule !== enclosingExternalModule) { - return { - accessibility: 2, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) - }; - } - } - return { - accessibility: 1, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - }; - } - return { accessibility: 0 }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } - } - function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 && ts.isExternalOrCommonJsModule(declaration)); - } - function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { - var aliasesToMakeVisible; - if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { - return undefined; - } - return { accessibility: 0, aliasesToMakeVisible: aliasesToMakeVisible }; - function getIsDeclarationVisible(declaration) { - if (!isDeclarationVisible(declaration)) { - var anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1) && - isDeclarationVisible(anyImportSyntax.parent)) { - if (shouldComputeAliasToMakeVisible) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } - } - return true; - } - return false; - } - return true; - } - } - function isEntityNameVisible(entityName, enclosingDeclaration) { - var meaning; - if (entityName.parent.kind === 162 || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning = 107455 | 1048576; - } - else if (entityName.kind === 143 || entityName.kind === 179 || - entityName.parent.kind === 237) { - meaning = 1920; - } - else { - meaning = 793064; - } - var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol, true)) || { - accessibility: 1, - errorSymbolName: ts.getTextOfNode(firstIdentifier), - errorNode: firstIdentifier - }; - } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function typeToString(type, enclosingDeclaration, flags) { - 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) { - 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() { - return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - 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) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - } - }; - function createNodeBuilderContext(enclosingDeclaration, flags) { - return { - enclosingDeclaration: enclosingDeclaration, - flags: flags, - encounteredError: false, - symbolStack: undefined - }; - } - function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; - if (!type) { - context.encounteredError = true; - return undefined; - } - if (type.flags & 1) { - return ts.createKeywordTypeNode(119); - } - if (type.flags & 2) { - return ts.createKeywordTypeNode(136); - } - if (type.flags & 4) { - return ts.createKeywordTypeNode(133); - } - if (type.flags & 8) { - return ts.createKeywordTypeNode(122); - } - 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.setEmitFlags(ts.createLiteral(type.value), 16777216)); - } - if (type.flags & (64)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.value))); - } - if (type.flags & 128) { - return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); - } - if (type.flags & 1024) { - return ts.createKeywordTypeNode(105); - } - if (type.flags & 2048) { - return ts.createKeywordTypeNode(139); - } - if (type.flags & 4096) { - return ts.createKeywordTypeNode(95); - } - if (type.flags & 8192) { - return ts.createKeywordTypeNode(130); - } - if (type.flags & 512) { - return ts.createKeywordTypeNode(137); - } - if (type.flags & 16777216) { - return ts.createKeywordTypeNode(134); - } - if (type.flags & 16384 && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { - context.encounteredError = true; - } - } - return ts.createThis(); - } - var objectFlags = getObjectFlags(type); - if (objectFlags & 4) { - ts.Debug.assert(!!(type.flags & 32768)); - return typeReferenceToTypeNode(type); - } - if (type.flags & 16384 || objectFlags & 3) { - var name = symbolToName(type.symbol, context, 793064, false); - return ts.createTypeReferenceNode(name, undefined); - } - 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); - } - 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)) { - context.encounteredError = true; - } - return undefined; - } - } - 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, context); - return ts.createTypeOperatorNode(indexTypeNode); - } - if (type.flags & 524288) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); - var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); - return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); - } - ts.Debug.fail("Should be unreachable."); - function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768)); - var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; - var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - 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; - if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 | 512) || - shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 107455); - } - else if (ts.contains(context.symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - var entityName = symbolToName(typeAlias, context, 793064, false); - return ts.createTypeReferenceNode(entityName, undefined); - } - else { - return ts.createKeywordTypeNode(119); - } - } - else { - if (!context.symbolStack) { - context.symbolStack = []; - } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; - } - } - else { - return createTypeNodeFromObjectType(type); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); - } - } - } - function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - return createMappedTypeNodeFromType(type); - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.setEmitFlags(ts.createTypeLiteralNode(undefined), 1); - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160, context); - return signatureNode; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161, context); - return signatureNode; - } - } - var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; - var members = createTypeNodesFromResolvedType(resolved); - context.flags = savedFlags; - var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); - } - 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) { - 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - return ts.createTupleTypeNode(tupleConstituentNodes); - } - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { - context.encounteredError = true; - } - return undefined; - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - var qualifiedName = void 0; - if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - 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 { - qualifiedName = ts.createQualifiedName(namePart, undefined); - } - } - } - } - var entityName = undefined; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } - 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, context)); - } - for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156, context)); - } - if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0, context)); - } - if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1, context)); - } - var properties = resolvedType.properties; - if (!properties) { - return typeElements; - } - for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { - var propertySymbol = properties_2[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); - 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, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - typeElements.push(methodDeclaration); - } - } - else { - 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 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 ? 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.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, context); - } - 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, context) { - var name = symbolToName(type.symbol, context, 793064, true); - var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); - var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); - } - 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); - 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, context, meaning, expectsIdentifier) { - var chain; - var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { - chain = getSymbolChain(symbol, meaning, true); - ts.Debug.assert(chain && chain.length > 0); - } - else { - chain = [symbol]; - } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(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 typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - 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) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); - var parentSymbol; - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); - } - } - } - if (accessibleSymbolChain) { - return accessibleSymbolChain; - } - if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - return [symbol]; - } - } - } - 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; - } - } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144)) { - if (t.flags & (128 | 256)) { - 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); - } - } - if (flags & 4096) - result.push(nullType); - if (flags & 2048) - result.push(undefinedType); - return result || types; - } - function visibilityToString(flags) { - if (flags === 8) { - return "private"; - } - if (flags === 16) { - return "protected"; - } - return "public"; - } - function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168; }); - if (node.kind === 231) { - return getSymbolOfNode(node); - } - } - return undefined; - } - function isTopLevelInExternalModuleAugmentation(node) { - return node && node.parent && - node.parent.kind === 234 && - ts.isExternalModuleAugmentation(node.parent.parent); - } - function literalTypeToString(type) { - return type.flags & 32 ? "\"" + ts.escapeString(type.value) + "\"" : "" + type.value; - } - function getNameOfSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { - return ts.declarationNameToString(name); - } - if (declaration.parent && declaration.parent.kind === 226) { - return ts.declarationNameToString(declaration.parent.name); - } - switch (declaration.kind) { - case 199: - return "(Anonymous class)"; - case 186: - case 187: - return "(Anonymous function)"; - } - } - return symbol.name; - } - function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); - } - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - writePunctuation(writer, 21); - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 23); - writer.writeSymbol(symbolName, symbol); - } - } - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 128 & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & 16; - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~512; - if (type.flags & 16793231) { - writer.writeKeyword(!(globalFlags & 16) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 16384 && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (getObjectFlags(type) & 4) { - writeTypeReference(type, nextFlags); - } - 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 & (272 | 16384)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 512) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 196608) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (getObjectFlags(type) & (16 | 32)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 96) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 262144) { - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 64); - } - else if (type.flags & 524288) { - writeType(type.objectType, 64); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 17); - writeSpace(writer); - writePunctuation(writer, 24); - writeSpace(writer); - writePunctuation(writer, 18); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 ? 0 : 64); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); - } - if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 256); - pos++; - while (pos < end) { - writePunctuation(writer, 26); - writeSpace(writer); - writeType(typeArguments[pos], 0); - pos++; - } - writePunctuation(writer, 29); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 64); - writePunctuation(writer, 21); - writePunctuation(writer, 22); - } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23); - } - } - } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 64) { - writePunctuation(writer, 19); - } - if (type.flags & 65536) { - writeTypeList(formatUnionTypes(type.types), 49); - } - else { - writeTypeList(type.types, 48); - } - if (flags & 64) { - writePunctuation(writer, 20); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); - } - else if (ts.contains(symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); - } - else { - writeKeyword(writer, 119); - } - } - else { - if (!symbolStack) { - symbolStack = []; - } - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - else { - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 || declaration.parent.kind === 234; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 2) || - (ts.contains(symbolStack, symbol)); - } - } - } - function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 103); - writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); - writeSpace(writer); - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 67108864) { - writePunctuation(writer, 55); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 64) { - return true; - } - else if (flags & 256) { - var typeParameters = callSignature.target && (flags & 32) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (type.objectFlags & 32) { - if (getConstraintTypeFromMappedType(type).flags & (16384 | 262144)) { - writeMappedType(type); - return; - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 64) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 94); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8, undefined, symbolStack); - if (flags & 64) { - writePunctuation(writer, 20); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56); - writeSpace(writer); - writeType(t, 0); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); - if (type.declaration.questionToken) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 174) { - writePunctuation(writer, 17); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); - } - else if (bindingPattern.kind === 175) { - writePunctuation(writer, 21); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); - } - writePunctuation(writer, 22); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 176); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 256; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - flags = 0; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99); - } - writeSpace(writer); - writeKeyword(writer, 126); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 2048 && isTypeAny(returnType)) { - return; - } - if (flags & 8) { - writeSpace(writer); - writePunctuation(writer, 36); - } - else { - writePunctuation(writer, 56); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); - writeSpace(writer); - } - if (signature.target && (flags & 32)) { - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); - writeSpace(writer); - switch (kind) { - case 1: - writeKeyword(writer, 133); - break; - case 0: - writeKeyword(writer, 136); - break; - } - writePunctuation(writer, 22); - writePunctuation(writer, 56); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } - function isDeclarationVisible(node) { - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } - return false; - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 176: - return isDeclarationVisible(node.parent.parent); - case 226: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - return false; - } - case 233: - case 229: - case 230: - case 231: - case 228: - case 232: - case 237: - if (ts.isExternalModuleAugmentation(node)) { - return true; - } - var parent = getDeclarationContainer(node); - if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 237 && parent.kind !== 265 && ts.isInAmbientContext(parent))) { - return isGlobalSourceFile(parent); - } - return isDeclarationVisible(parent); - case 149: - case 148: - case 153: - case 154: - case 151: - case 150: - if (ts.getModifierFlags(node) & (8 | 16)) { - return false; - } - case 152: - case 156: - case 155: - case 157: - case 146: - case 234: - case 160: - case 161: - case 163: - case 159: - case 164: - case 165: - case 166: - case 167: - case 168: - return isDeclarationVisible(node.parent); - case 239: - case 240: - case 242: - return false; - case 145: - case 265: - case 236: - return true; - case 243: - return false; - default: - return false; - } - } - } - function collectLinkedAliases(node) { - var exportSymbol; - if (node.parent && node.parent.kind === 243) { - exportSymbol = resolveName(node.parent, node.text, 107455 | 793064 | 1920 | 8388608, ts.Diagnostics.Cannot_find_name_0, node); - } - else if (node.parent.kind === 246) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 | 793064 | 1920 | 8388608); - } - var result = []; - if (exportSymbol) { - buildVisibleNodeList(exportSymbol.declarations); - } - return result; - function buildVisibleNodeList(declarations) { - ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; - var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } - if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { - var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 | 793064 | 1920, undefined, undefined); - if (importSymbol) { - buildVisibleNodeList(importSymbol.declarations); - } - } - }); - } - } - function pushTypeResolution(target, propertyName) { - var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); - if (resolutionCycleStartIndex >= 0) { - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { - resolutionResults[i] = false; - } - return false; - } - resolutionTargets.push(target); - resolutionResults.push(true); - resolutionPropertyNames.push(propertyName); - return true; - } - function findResolutionCycleStartIndex(target, propertyName) { - for (var i = resolutionTargets.length - 1; i >= 0; i--) { - if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { - return -1; - } - if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { - return i; - } - } - return -1; - } - function hasType(target, propertyName) { - if (propertyName === 0) { - return getSymbolLinks(target).type; - } - if (propertyName === 2) { - return getSymbolLinks(target).declaredType; - } - if (propertyName === 1) { - return target.resolvedBaseConstructorType; - } - if (propertyName === 3) { - return target.resolvedReturnType; - } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); - } - function popTypeResolution() { - resolutionTargets.pop(); - resolutionPropertyNames.pop(); - return resolutionResults.pop(); - } - function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { - switch (node.kind) { - case 226: - case 227: - case 242: - case 241: - case 240: - case 239: - return false; - default: - return true; - } - }); - return node && node.parent; - } - function getTypeOfPrototypeProperty(prototype) { - var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); - return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; - } - function getTypeOfPropertyOfType(type, name) { - var prop = getPropertyOfType(type, name); - return prop ? getTypeOfSymbol(prop) : undefined; - } - function isTypeAny(type) { - return type && (type.flags & 1) !== 0; - } - function getTypeForBindingElementParent(node) { - var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, false); - } - function isComputedNonLiteralName(name) { - return name.kind === 144 && !ts.isStringOrNumericLiteral(name.expression); - } - function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144); }); - if (source.flags & 8192) { - return emptyObjectType; - } - if (source.flags & 65536) { - return mapType(source, function (t) { return getRestType(t, properties, symbol); }); - } - var members = ts.createMap(); - var names = ts.createMap(); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var name = properties_3[_i]; - names.set(ts.getTextOfPropertyName(name), true); - } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - var inNamesToRemove = names.has(prop.name); - 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); - } - } - var stringIndexInfo = getIndexInfoOfType(source, 0); - var numberIndexInfo = getIndexInfoOfType(source, 1); - return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getTypeForBindingElement(declaration) { - var pattern = declaration.parent; - var parentType = getTypeForBindingElementParent(pattern.parent); - if (parentType === unknownType) { - return unknownType; - } - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } - return parentType; - } - var type; - if (pattern.kind === 174) { - if (declaration.dotDotDotToken) { - if (!isValidSpreadType(parentType)) { - error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); - return unknownType; - } - var literalMembers = []; - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!element.dotDotDotToken) { - literalMembers.push(element.propertyName || element.name); - } - } - type = getRestType(parentType, literalMembers, declaration.symbol); - } - else { - var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - return anyType; - } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - var text = ts.getTextOfPropertyName(name); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || - getIndexTypeOfType(parentType, 0); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return unknownType; - } - } - } - else { - var elementType = checkIteratedTypeOrElementType(parentType, pattern, false, false); - if (declaration.dotDotDotToken) { - type = createArrayType(elementType); - } - else { - var propName = "" + ts.indexOf(pattern.elements, declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); - } - return unknownType; - } - } - } - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048)) { - type = getTypeWithFacts(type, 131072); - } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], true) : - type; - } - function getTypeForDeclarationFromJSDocComment(declaration) { - var jsdocType = ts.getJSDocType(declaration); - if (jsdocType) { - return getTypeFromTypeNode(jsdocType); - } - return undefined; - } - function isNullOrUndefined(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 95 || expr.kind === 71 && getResolvedSymbol(expr) === undefinedSymbol; - } - function isEmptyArrayLiteral(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 177 && expr.elements.length === 0; - } - function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048) : type; - } - function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 65536) { - var type = getTypeForDeclarationFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - if (declaration.parent.parent.kind === 215) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 | 262144) ? indexType : stringType; - } - if (declaration.parent.parent.kind === 216) { - var forOfStatement = declaration.parent.parent; - return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; - } - if (ts.isBindingPattern(declaration.parent)) { - return getTypeForBindingElement(declaration); - } - if (declaration.type) { - var declaredType = getTypeFromTypeNode(declaration.type); - return addOptionality(declaredType, declaration.questionToken && includeOptionality); - } - if ((noImplicitAny || declaration.flags & 65536) && - declaration.kind === 226 && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1) && !ts.isInAmbientContext(declaration)) { - if (!(ts.getCombinedNodeFlags(declaration) & 2) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { - return autoType; - } - if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { - return autoArrayType; - } - } - if (declaration.kind === 146) { - var func = declaration.parent; - if (func.kind === 154 && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153); - if (getter) { - var getterSignature = getSignatureFromDeclaration(getter); - var thisParameter = getAccessorThisParameter(func); - if (thisParameter && declaration === thisParameter) { - ts.Debug.assert(!thisParameter.type); - return getTypeOfSymbol(getterSignature.thisParameter); - } - return getReturnTypeOfSignature(getterSignature); - } - } - var type = void 0; - if (declaration.symbol.name === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } - if (type) { - return addOptionality(type, declaration.questionToken && includeOptionality); - } - } - if (declaration.initializer) { - var type = checkDeclarationInitializer(declaration); - return addOptionality(type, declaration.questionToken && includeOptionality); - } - if (ts.isJsxAttribute(declaration)) { - return trueType; - } - if (declaration.kind === 262) { - return checkIdentifier(declaration.name); - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, false, true); - } - return undefined; - } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { - 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 : - declaration.kind === 179 ? ts.getAncestor(declaration, 194) : - undefined; - if (!expression) { - return unknownType; - } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99) { - if (ts.getThisContainer(expression, false).kind === 152) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - 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)); - } - } - else if (!jsDocType) { - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); - } - } - var type = jsDocType || getUnionType(types, true); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); - } - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { - if (element.initializer) { - return checkDeclarationInitializer(element); - } - if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); - } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); - } - return anyType; - } - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); - var stringIndexInfo; - var hasComputedProperties = false; - ts.forEach(pattern.elements, function (e) { - var name = e.propertyName || e.name; - if (isComputedNonLiteralName(name)) { - hasComputedProperties = true; - return; - } - if (e.dotDotDotToken) { - stringIndexInfo = createIndexInfo(anyType, false); - return; - } - var text = ts.getTextOfPropertyName(name); - var flags = 4 | (e.initializer ? 67108864 : 0); - var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); - symbol.bindingElement = e; - members.set(symbol.name, symbol); - }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); - if (includePatternInType) { - result.pattern = pattern; - } - if (hasComputedProperties) { - result.objectFlags |= 512; - } - return result; - } - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { - var elements = pattern.elements; - var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 ? createIterableType(anyType) : anyArrayType; - } - var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); - if (includePatternInType) { - result = cloneTypeReference(result); - result.pattern = pattern; - } - return result; - } - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); - } - function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, true); - if (type) { - if (reportErrors) { - reportErrorsFromWidening(declaration, type); - } - if (declaration.kind === 261) { - return type; - } - return getWidenedType(type); - } - type = declaration.dotDotDotToken ? anyArrayType : anyType; - if (reportErrors && noImplicitAny) { - if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); - } - } - return type; - } - function declarationBelongsToPrivateAmbientMember(declaration) { - var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 ? root.parent : root; - return isPrivateWithinAmbient(memberDeclaration); - } - function getTypeOfVariableOrParameterOrProperty(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 16777216) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - if (declaration.kind === 243) { - return links.type = checkExpression(declaration.expression); - } - if (declaration.flags & 65536 && declaration.kind === 291 && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - var type = void 0; - if (declaration.kind === 194 || - declaration.kind === 179 && declaration.parent.kind === 194) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; - } - function getAnnotatedAccessorType(accessor) { - if (accessor) { - if (accessor.kind === 153) { - return accessor.type && getTypeFromTypeNode(accessor.type); - } - else { - var setterTypeAnnotation = ts.getSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); - } - } - return undefined; - } - function getAnnotatedAccessorThisParameter(accessor) { - var parameter = getAccessorThisParameter(accessor); - return parameter && parameter.symbol; - } - function getThisTypeOfDeclaration(declaration) { - return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); - } - function getTypeOfAccessors(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153); - var setter = ts.getDeclarationOfKind(symbol, 154); - if (getter && getter.flags & 65536) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - var type = void 0; - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; - } - else { - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; - } - else { - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - type = anyType; - } - } - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153); - error(getter_1, 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, symbolToString(symbol)); - } - } - links.type = type; - } - return links.type; - } - function getBaseTypeVariableOfClass(symbol) { - var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 ? baseConstructorType : undefined; - } - function getTypeOfFuncClassEnumModule(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 1536 && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else { - var type = createObjectType(16, symbol); - if (symbol.flags & 32) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; - } - else { - links.type = strictNullChecks && symbol.flags & 67108864 ? getNullableType(type, 2048) : type; - } - } - } - return links.type; - } - function getTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; - } - function getTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var targetSymbol = resolveAlias(symbol); - links.type = targetSymbol.flags & 107455 - ? getTypeOfSymbol(targetSymbol) - : unknownType; - } - return links.type; - } - function getTypeOfInstantiatedSymbol(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = unknownType; - } - else { - if (!pushTypeResolution(symbol, 0)) { - return unknownType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - } - return links.type; - } - function reportCircularityError(symbol) { - if (symbol.valueDeclaration.type) { - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - return unknownType; - } - if (noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - return anyType; - } - function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 1) { - return getTypeOfInstantiatedSymbol(symbol); - } - if (symbol.flags & (3 | 4)) { - return getTypeOfVariableOrParameterOrProperty(symbol); - } - if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { - return getTypeOfFuncClassEnumModule(symbol); - } - if (symbol.flags & 8) { - return getTypeOfEnumMember(symbol); - } - if (symbol.flags & 98304) { - return getTypeOfAccessors(symbol); - } - if (symbol.flags & 8388608) { - return getTypeOfAlias(symbol); - } - return unknownType; - } - function isReferenceToType(type, target) { - return type !== undefined - && target !== undefined - && (getObjectFlags(type) & 4) !== 0 - && type.target === target; - } - function getTargetType(type) { - return getObjectFlags(type) & 4 ? type.target : type; - } - function hasBaseType(type, checkBase) { - return check(type); - function check(type) { - if (getObjectFlags(type) & (3 | 4)) { - var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); - } - else if (type.flags & 131072) { - return ts.forEach(type.types, check); - } - } - } - function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } - } - return typeParameters; - } - function appendOuterTypeParameters(typeParameters, node) { - while (true) { - node = node.parent; - if (!node) { - return typeParameters; - } - if (node.kind === 229 || node.kind === 199 || - node.kind === 228 || node.kind === 186 || - node.kind === 151 || node.kind === 187) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } - } - } - } - function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230); - return appendOuterTypeParameters(undefined, declaration); - } - function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { - var result; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - if (node.kind === 230 || node.kind === 229 || - node.kind === 199 || node.kind === 231) { - var declaration = node; - if (declaration.typeParameters) { - result = appendTypeParameters(result, declaration.typeParameters); - } - } - } - return result; - } - function getTypeParametersOfClassOrInterface(symbol) { - return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); - } - function isMixinConstructorType(type) { - var signatures = getSignaturesOfType(type, 1); - if (signatures.length === 1) { - var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; - } - return false; - } - function isConstructorType(type) { - if (isValidBaseType(type) && getSignaturesOfType(type, 1).length > 0) { - return true; - } - if (type.flags & 540672) { - var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); - } - return false; - } - function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); - } - function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); - } - function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; - } - function getBaseConstructorTypeOfClass(type) { - if (!type.resolvedBaseConstructorType) { - var baseTypeNode = getBaseTypeNodeOfClass(type); - if (!baseTypeNode) { - return type.resolvedBaseConstructorType = undefinedType; - } - if (!pushTypeResolution(type, 1)) { - return unknownType; - } - var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 | 131072)) { - resolveStructuredTypeMembers(baseConstructorType); - } - if (!popTypeResolution()) { - error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = unknownType; - } - if (!(baseConstructorType.flags & 1) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); - return type.resolvedBaseConstructorType = unknownType; - } - type.resolvedBaseConstructorType = baseConstructorType; - } - return type.resolvedBaseConstructorType; - } - function getBaseTypes(type) { - if (!type.resolvedBaseTypes) { - if (type.objectFlags & 8) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 | 64)) { - if (type.symbol.flags & 32) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64) { - resolveBaseTypesOfInterface(type); - } - } - else { - ts.Debug.fail("type must be class or interface"); - } - } - return type.resolvedBaseTypes; - } - function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 | 131072 | 1))) { - 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, typeArgs); - } - else if (baseConstructorType.flags & 1) { - baseType = baseConstructorType; - } - else { - var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); - if (!constructors.length) { - error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; - } - baseType = getReturnTypeOfSignature(constructors[0]); - } - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } - if (baseType === unknownType) { - return; - } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; - } - if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - return; - } - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - function areAllOuterTypeParametersApplied(type) { - var outerTypeParameters = type.outerTypeParameters; - if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; - var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; - } - return true; - } - function isValidBaseType(type) { - return type.flags & (32768 | 16777216 | 1) && !isGenericMappedType(type) || - type.flags & 131072 && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); - } - function resolveBaseTypesOfInterface(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230 && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); - } - } - else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); - } - } - } - } - } - } - function isIndependentInterface(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230) { - if (declaration.flags & 64) { - return false; - } - var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); - if (baseTypeNodes) { - for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { - var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064, true); - if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { - return false; - } - } - } - } - } - } - return true; - } - function getDeclaredTypeOfClassOrInterface(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var kind = symbol.flags & 32 ? 1 : 2; - var type = links.declaredType = createObjectType(kind, symbol); - var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); - var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (outerTypeParameters || localTypeParameters || kind === 1 || !isIndependentInterface(symbol)) { - type.objectFlags |= 4; - type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); - type.outerTypeParameters = outerTypeParameters; - type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384); - type.thisType.isThisType = true; - type.thisType.symbol = symbol; - type.thisType.constraint = type; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - if (!pushTypeResolution(symbol, 2)) { - return unknownType; - } - var declaration = ts.getDeclarationOfKind(symbol, 290); - var type = void 0; - if (declaration) { - if (declaration.jsDocTypeLiteral) { - type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); - } - else { - type = getTypeFromTypeNode(declaration.typeExpression.type); - } - } - else { - declaration = ts.getDeclarationOfKind(symbol, 231); - type = getTypeFromTypeNode(declaration.type); - } - if (popTypeResolution()) { - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (typeParameters) { - links.typeParameters = typeParameters; - links.instantiations = ts.createMap(); - links.instantiations.set(getTypeListId(typeParameters), type); - } - } - else { - type = unknownType; - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); - } - links.declaredType = type; - } - return links.declaredType; - } - function isLiteralEnumMember(member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && - expr.operand.kind === 8 || - expr.kind === 71 && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); - } - 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 (member.initializer && member.initializer.kind === 9) { - return links.enumKind = 1; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; - } - } - } - } - return links.enumKind = hasNonLiteralMember ? 0 : 1; - } - 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) { - 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); - } - } - } - 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; - } - } - 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)); - if (!links.declaredType) { - links.declaredType = enumType; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeParameter(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(16384); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; - } - function getDeclaredTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; - } - function getDeclaredTypeOfSymbol(symbol) { - if (symbol.flags & (32 | 64)) { - return getDeclaredTypeOfClassOrInterface(symbol); - } - if (symbol.flags & 524288) { - return getDeclaredTypeOfTypeAlias(symbol); - } - if (symbol.flags & 262144) { - return getDeclaredTypeOfTypeParameter(symbol); - } - if (symbol.flags & 384) { - return getDeclaredTypeOfEnum(symbol); - } - if (symbol.flags & 8) { - return getDeclaredTypeOfEnumMember(symbol); - } - if (symbol.flags & 8388608) { - return getDeclaredTypeOfAlias(symbol); - } - return unknownType; - } - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; - } - function isIndependentType(node) { - switch (node.kind) { - case 119: - case 136: - case 133: - case 122: - case 137: - case 134: - case 105: - case 139: - case 95: - case 130: - case 173: - return true; - case 164: - return isIndependentType(node.elementType); - case 159: - return isIndependentTypeReference(node); - } - return false; - } - function isIndependentVariableLikeDeclaration(node) { - return node.type && isIndependentType(node.type) || !node.type && !node.initializer; - } - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152 && (!node.type || !isIndependentType(node.type))) { - return false; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; - } - function isIndependentMember(symbol) { - if (symbol.declarations && symbol.declarations.length === 1) { - var declaration = symbol.declarations[0]; - if (declaration) { - switch (declaration.kind) { - case 149: - case 148: - return isIndependentVariableLikeDeclaration(declaration); - case 151: - case 150: - case 152: - return isIndependentFunctionLikeDeclaration(declaration); - } - } - } - return false; - } - function createSymbolTable(symbols) { - var result = ts.createMap(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - result.set(symbol.name, symbol); - } - return result; - } - function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; - result.set(symbol.name, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); - } - return result; - } - function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { - var s = baseSymbols_1[_i]; - if (!symbols.has(s.name)) { - symbols.set(s.name, s); - } - } - } - function resolveDeclaredMembers(type) { - if (!type.declaredProperties) { - var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); - type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - } - return type; - } - function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4) { - var target = type.target; - var typeArguments = type.typeArguments; - if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); - } - } - else if (type.flags & 131072) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); - } - return type; - } - function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { - mapper = createTypeMapper(typeParameters, typeArguments); - members = createInstantiatedSymbolTable(source.declaredProperties, mapper, typeParameters.length === 1); - callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); - constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); - stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); - numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); - } - var baseTypes = getBaseTypes(source); - if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { - members = createSymbolTable(source.declaredProperties); - } - var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { - var baseType = baseTypes_1[_i]; - var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; - addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); - constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1)); - if (!stringIndexInfo) { - stringIndexInfo = instantiatedBaseType === anyType ? - createIndexInfo(anyType, false) : - getIndexInfoOfType(instantiatedBaseType, 0); - } - numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1); - } - } - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveClassOrInterfaceMembers(type) { - resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); - } - function resolveTypeReferenceMembers(type) { - var source = resolveDeclaredMembers(type.target); - var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); - var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? - type.typeArguments : ts.concatenate(type.typeArguments, [type]); - resolveObjectTypeMembers(type, source, typeParameters, typeArguments); - } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); - sig.declaration = declaration; - sig.typeParameters = typeParameters; - sig.parameters = parameters; - sig.thisParameter = thisParameter; - sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; - sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; - return sig; - } - function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); - } - function getDefaultConstructSignatures(classType) { - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - var baseSignatures = getSignaturesOfType(baseConstructorType, 1); - if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, undefined, 0, false, false)]; - } - var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); - var typeArgCount = ts.length(typeArguments); - var result = []; - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var baseSig = baseSignatures_1[_i]; - var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); - var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); - sig.typeParameters = classType.localTypeParameters; - sig.resolvedReturnType = classType; - result.push(sig); - } - } - return result; - } - function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { - for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { - var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { - return s; - } - } - } - function findMatchingSignatures(signatureLists, signature, listIndex) { - if (signature.typeParameters) { - if (listIndex > 0) { - return undefined; - } - for (var i = 1; i < signatureLists.length; i++) { - if (!findMatchingSignature(signatureLists[i], signature, false, false, false)) { - return undefined; - } - } - return [signature]; - } - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, true, true, true); - if (!match) { - return undefined; - } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } - } - return result; - } - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { - var signature = _a[_i]; - if (!result || !findMatchingSignature(result, signature, false, true, true)) { - var unionSignatures = findMatchingSignatures(signatureLists, signature, i); - if (unionSignatures) { - var s = signature; - if (unionSignatures.length > 1) { - s = cloneSignature(signature); - if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); - } - s.resolvedReturnType = undefined; - s.unionSignatures = unionSignatures; - } - (result || (result = [])).push(s); - } - } - } - } - return result || emptyArray; - } - function getUnionIndexInfo(types, kind) { - var indexTypes = []; - var isAnyReadonly = false; - 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; - } - indexTypes.push(indexInfo.type); - isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; - } - return createIndexInfo(getUnionType(indexTypes, true), isAnyReadonly); - } - function resolveUnionTypeMembers(type) { - var callSignatures = getUnionSignatures(type.types, 0); - var constructSignatures = getUnionSignatures(type.types, 1); - var stringIndexInfo = getUnionIndexInfo(type.types, 0); - var numberIndexInfo = getUnionIndexInfo(type.types, 1); - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function intersectTypes(type1, type2) { - return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); - } - function intersectIndexInfos(info1, info2) { - return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); - } - function unionSpreadIndexInfos(info1, info2) { - return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); - } - function includeMixinType(type, types, index) { - var mixedTypes = []; - for (var i = 0; i < types.length; i++) { - if (i === index) { - mixedTypes.push(type); - } - else if (isMixinConstructorType(types[i])) { - mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1)[0])); - } - } - return getIntersectionType(mixedTypes); - } - function resolveIntersectionTypeMembers(type) { - var callSignatures = emptyArray; - var constructSignatures = emptyArray; - var stringIndexInfo; - var numberIndexInfo; - var types = type.types; - var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_3 = function (i) { - var t = type.types[i]; - if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { - var signatures = getSignaturesOfType(t, 1); - if (signatures.length && mixinCount > 0) { - signatures = ts.map(signatures, function (s) { - var clone = cloneSignature(s); - clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); - return clone; - }); - } - constructSignatures = ts.concatenate(constructSignatures, signatures); - } - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0)); - stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0)); - numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); - }; - for (var i = 0; i < types.length; i++) { - _loop_3(i); - } - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveAnonymousTypeMembers(type) { - var symbol = type.symbol; - if (type.target) { - var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, false); - var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0), type.mapper); - var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1), type.mapper); - var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0), type.mapper); - var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1), type.mapper); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else if (symbol.flags & 2048) { - var members = symbol.members; - var callSignatures = getSignaturesOfSymbol(members.get("__call")); - var constructSignatures = getSignaturesOfSymbol(members.get("__new")); - var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0); - var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else { - var members = emptySymbols; - var constructSignatures = emptyArray; - var stringIndexInfo = undefined; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - } - if (symbol.flags & 32) { - var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 | 131072 | 540672)) { - members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); - } - else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, false); - } - } - var numberIndexInfo = symbol.flags & 384 ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); - if (symbol.flags & (16 | 8192)) { - type.callSignatures = getSignaturesOfSymbol(symbol); - } - } - } - function resolveMappedTypeMembers(type) { - var members = ts.createMap(); - var stringIndexInfo; - setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var typeParameter = getTypeParameterFromMappedType(type); - var constraintType = getConstraintTypeFromMappedType(type); - var templateType = getTemplateTypeFromMappedType(type); - var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); - var templateReadonly = !!type.declaration.readonlyToken; - var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170) { - for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { - var propertySymbol = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); - } - if (getIndexInfoOfType(modifiersType, 0)) { - addMemberForKeyType(stringType); - } - } - else { - var keyType = constraintType.flags & 540672 ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 ? getIndexType(getApparentType(keyType.type)) : keyType; - forEachType(iterationType, addMemberForKeyType); - } - setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { - var iterationMapper = createTypeMapper([typeParameter], [t]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; - var propType = instantiateType(templateType, templateMapper); - if (t.flags & 32) { - var propName = t.value; - var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); - var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 : 0; - prop.type = propType; - if (propertySymbol) { - prop.syntheticOrigin = propertySymbol; - } - members.set(propName, prop); - } - else if (t.flags & 2) { - stringIndexInfo = createIndexInfo(propType, templateReadonly); - } - } - } - function getTypeParameterFromMappedType(type) { - return type.typeParameter || - (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); - } - function getConstraintTypeFromMappedType(type) { - return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); - } - function getTemplateTypeFromMappedType(type) { - return type.templateType || - (type.templateType = type.declaration.type ? - instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : - unknownType); - } - function getModifiersTypeFromMappedType(type) { - if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170) { - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); - } - else { - var declaredType = getTypeFromMappedTypeNode(type.declaration); - var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; - } - } - return type.modifiersType; - } - function isGenericMappedType(type) { - if (getObjectFlags(type) & 32) { - var constraintType = getConstraintTypeFromMappedType(type); - return maybeTypeOfKind(constraintType, 540672 | 262144); - } - return false; - } - function resolveStructuredTypeMembers(type) { - if (!type.members) { - if (type.flags & 32768) { - if (type.objectFlags & 4) { - resolveTypeReferenceMembers(type); - } - else if (type.objectFlags & 3) { - resolveClassOrInterfaceMembers(type); - } - else if (type.objectFlags & 16) { - resolveAnonymousTypeMembers(type); - } - else if (type.objectFlags & 32) { - resolveMappedTypeMembers(type); - } - } - else if (type.flags & 65536) { - resolveUnionTypeMembers(type); - } - else if (type.flags & 131072) { - resolveIntersectionTypeMembers(type); - } - } - return type; - } - function getPropertiesOfObjectType(type) { - if (type.flags & 32768) { - return resolveStructuredTypeMembers(type).properties; - } - return emptyArray; - } - function getPropertyOfObjectType(type, name) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - } - } - function getPropertiesOfUnionOrIntersectionType(type) { - if (!type.resolvedProperties) { - var members = ts.createMap(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var current = _a[_i]; - for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { - var prop = _c[_b]; - if (!members.has(prop.name)) { - var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.name); - if (combinedProp) { - members.set(prop.name, combinedProp); - } - } - } - if (type.flags & 65536) { - break; - } - } - type.resolvedProperties = getNamedMembers(members); - } - return type.resolvedProperties; - } - function getPropertiesOfType(type) { - type = getApparentType(type); - return type.flags & 196608 ? - 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) : - getBaseConstraintOfType(type); - } - function getConstraintOfTypeParameter(typeParameter) { - return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; - } - function getConstraintOfIndexedAccess(type) { - var baseObjectType = getBaseConstraintOfType(type.objectType); - var baseIndexType = getBaseConstraintOfType(type.indexType); - return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; - } - function getBaseConstraintOfType(type) { - if (type.flags & (540672 | 196608)) { - var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } - } - else if (type.flags & 262144) { - return stringType; - } - return undefined; - } - function hasNonCircularBaseConstraint(type) { - return getResolvedBaseConstraint(type) !== circularConstraintType; - } - function getResolvedBaseConstraint(type) { - var typeStack; - var circular; - if (!type.resolvedBaseConstraint) { - typeStack = []; - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); - } - return type.resolvedBaseConstraint; - function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { - circular = true; - return undefined; - } - typeStack.push(t); - var result = computeBaseConstraint(t); - typeStack.pop(); - return result; - } - function computeBaseConstraint(t) { - if (t.flags & 16384) { - var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; - } - if (t.flags & 196608) { - var types = t.types; - var baseTypes = []; - 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); - } - } - return t.flags & 65536 && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 && baseTypes.length ? getIntersectionType(baseTypes) : - undefined; - } - if (t.flags & 262144) { - return stringType; - } - if (t.flags & 524288) { - var baseObjectType = getBaseConstraint(t.objectType); - var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; - return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; - } - return t; - } - } - function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); - } - function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameter(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; - } - function getApparentType(type) { - var t = type.flags & 540672 ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 ? globalStringType : - t.flags & 84 ? globalNumberType : - t.flags & 136 ? globalBooleanType : - t.flags & 512 ? getGlobalESSymbolType(languageVersion >= 2) : - t.flags & 16777216 ? emptyObjectType : - t; - } - function createUnionOrIntersectionProperty(containingType, name) { - var props; - var types = containingType.types; - var isUnion = containingType.flags & 65536; - var excludeModifiers = isUnion ? 24 : 0; - var commonFlags = isUnion ? 0 : 67108864; - var syntheticFlag = 4; - var checkFlags = 0; - 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { - commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } - checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | - (!(modifiers & 24) ? 64 : 0) | - (modifiers & 16 ? 128 : 0) | - (modifiers & 8 ? 256 : 0) | - (modifiers & 32 ? 512 : 0); - if (!isMethodLike(prop)) { - syntheticFlag = 2; - } - } - else if (isUnion) { - checkFlags |= 16; - } - } - } - if (!props) { - return undefined; - } - if (props.length === 1 && !(checkFlags & 16)) { - return props[0]; - } - var propTypes = []; - var declarations = []; - var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; - if (prop.declarations) { - ts.addRange(declarations, prop.declarations); - } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - checkFlags |= 32; - } - propTypes.push(type); - } - var result = createSymbol(4 | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; - result.containingType = containingType; - result.declarations = declarations; - result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); - return result; - } - function getUnionOrIntersectionProperty(type, name) { - var properties = type.propertyCache || (type.propertyCache = ts.createMap()); - var property = properties.get(name); - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties.set(name, property); - } - } - return property; - } - function getPropertyOfUnionOrIntersectionType(type, name) { - var property = getUnionOrIntersectionProperty(type, name); - return property && !(ts.getCheckFlags(property) & 16) ? property : undefined; - } - function getPropertyOfType(type, name) { - type = getApparentType(type); - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; - } - } - return getPropertyOfObjectType(globalObjectType, name); - } - if (type.flags & 196608) { - return getPropertyOfUnionOrIntersectionType(type, name); - } - return undefined; - } - function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.callSignatures : resolved.constructSignatures; - } - return emptyArray; - } - function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); - } - function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 ? resolved.stringIndexInfo : resolved.numberIndexInfo; - } - } - function getIndexTypeOfStructuredType(type, kind) { - var info = getIndexInfoOfStructuredType(type, kind); - return info && info.type; - } - function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); - } - function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); - } - function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { - var propTypes = []; - for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.name)) { - propTypes.push(getTypeOfSymbol(prop)); - } - } - if (propTypes.length) { - return getUnionType(propTypes, true); - } - } - return undefined; - } - function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 65536) { - var templateTag = ts.getJSDocTemplateTag(declaration); - if (templateTag) { - return getTypeParametersFromDeclaration(templateTag.typeParameters); - } - } - return undefined; - } - function getTypeParametersFromDeclaration(typeParameterDeclarations) { - var result = []; - ts.forEach(typeParameterDeclarations, function (node) { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - result.push(tp); - } - }); - return result; - } - function symbolsToArray(symbols) { - var result = []; - symbols.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - result.push(symbol); - } - }); - return result; - } - function isJSDocOptionalParameter(node) { - if (node.flags & 65536) { - if (node.type && node.type.kind === 278) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 278; - } - } - } - } - } - function tryFindAmbientModule(moduleName, withAugmentations) { - if (ts.isExternalModuleNameRelative(moduleName)) { - return undefined; - } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512); - return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; - } - function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { - return true; - } - if (node.initializer) { - var signatureDeclaration = node.parent; - var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); - ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; - } - var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); - if (iife) { - return !node.type && - !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; - } - return false; - } - function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 71) { - var parameterName = node.parameterName; - return { - kind: 1, - parameterName: parameterName ? parameterName.text : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; - } - else { - return { - kind: 0, - type: getTypeFromTypeNode(node.type) - }; - } - } - function getMinTypeArgumentCount(typeParameters) { - var minTypeArgumentCount = 0; - if (typeParameters) { - for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { - minTypeArgumentCount = i + 1; - } - } - } - return minTypeArgumentCount; - } - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { - var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { - if (!typeArguments) { - typeArguments = []; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = isJavaScript ? anyType : emptyObjectType; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : isJavaScript ? anyType : emptyObjectType; - } - } - } - return typeArguments; - } - function getSignatureFromDeclaration(declaration) { - var links = getNodeLinks(declaration); - if (!links.resolvedSignature) { - var parameters = []; - var hasLiteralTypes = false; - var minArgumentCount = 0; - var thisParameter = undefined; - var hasThisParameter = void 0; - var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); - var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); - for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { - var param = declaration.parameters[i]; - var paramSymbol = param.symbol; - if (paramSymbol && !!(paramSymbol.flags & 4) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.name, 107455, undefined, undefined); - paramSymbol = resolvedSymbol; - } - if (i === 0 && paramSymbol.name === "this") { - hasThisParameter = true; - thisParameter = param.symbol; - } - else { - parameters.push(paramSymbol); - } - if (param.type && param.type.kind === 173) { - hasLiteralTypes = true; - } - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; - if (!isOptionalParameter_1) { - minArgumentCount = parameters.length; - } - } - if ((declaration.kind === 153 || declaration.kind === 154) && - !ts.hasDynamicName(declaration) && - (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 ? 154 : 153; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); - if (other) { - thisParameter = getAnnotatedAccessorThisParameter(other); - } - } - var classType = declaration.kind === 152 ? - getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) - : undefined; - var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : - getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); - } - return links.resolvedSignature; - } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); - } - else if (classType) { - return classType; - } - else if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.flags & 65536) { - var type = getReturnTypeFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - if (declaration.kind === 153 && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } - } - function containsArgumentsReference(declaration) { - var links = getNodeLinks(declaration); - if (links.containsArgumentsReference === undefined) { - if (links.flags & 8192) { - links.containsArgumentsReference = true; - } - else { - links.containsArgumentsReference = traverse(declaration.body); - } - } - return links.containsArgumentsReference; - function traverse(node) { - if (!node) - return false; - switch (node.kind) { - case 71: - return node.text === "arguments" && ts.isPartOfExpression(node); - case 149: - case 151: - case 153: - case 154: - return node.name.kind === 144 - && traverse(node.name); - default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); - } - } - } - function getSignaturesOfSymbol(symbol) { - if (!symbol) - return emptyArray; - var result = []; - for (var i = 0; i < symbol.declarations.length; i++) { - var node = symbol.declarations[i]; - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 279: - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); - } - } - return result; - } - function resolveExternalModuleTypeByLiteral(name) { - var moduleSym = resolveExternalModuleName(name, name); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - return getTypeOfSymbol(resolvedModuleSymbol); - } - } - return anyType; - } - function getThisTypeOfSignature(signature) { - if (signature.thisParameter) { - return getTypeOfSymbol(signature.thisParameter); - } - } - function getReturnTypeOfSignature(signature) { - if (!signature.resolvedReturnType) { - if (!pushTypeResolution(signature, 3)) { - return unknownType; - } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), true); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - 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); - } - } - } - signature.resolvedReturnType = type; - } - return signature.resolvedReturnType; - } - function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; - } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); - var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); - var id = getTypeListId(typeArguments); - var instantiation = instantiations.get(id); - if (!instantiation) { - instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); - } - return instantiation; - } - function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), true); - } - function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), true); - } - return signature.erasedSignatureCache; - } - function getOrCreateTypeFromSignature(signature) { - if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 || signature.declaration.kind === 156; - var type = createObjectType(16); - type.members = emptySymbols; - type.properties = emptyArray; - type.callSignatures = !isConstructor ? [signature] : emptyArray; - type.constructSignatures = isConstructor ? [signature] : emptyArray; - signature.isolatedSignatureType = type; - } - return signature.isolatedSignatureType; - } - function getIndexSymbol(symbol) { - return symbol.members.get("__index"); - } - function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 ? 133 : 136; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var node = decl; - if (node.parameters.length === 1) { - var parameter = node.parameters[0]; - if (parameter && parameter.type && parameter.type.kind === syntaxKind) { - return node; - } - } - } - } - return undefined; - } - function createIndexInfo(type, isReadonly, declaration) { - return { type: type, isReadonly: isReadonly, declaration: declaration }; - } - function getIndexInfoOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64) !== 0, declaration); - } - return undefined; - } - function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145).constraint; - } - function getConstraintFromTypeParameter(typeParameter) { - if (!typeParameter.constraint) { - if (typeParameter.target) { - var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); - typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; - } - else { - var constraintDeclaration = getConstraintDeclaration(typeParameter); - typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; - } - } - return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; - } - function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145).parent); - } - function getTypeListId(types) { - var result = ""; - if (types) { - var length_4 = types.length; - var i = 0; - while (i < length_4) { - var startId = types[i].id; - var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; - } - } - return result; - } - function getPropagatingFlagsOfTypes(types, excludeKinds) { - var result = 0; - for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; - if (!(type.flags & excludeKinds)) { - result |= type.flags; - } - } - return result & 14680064; - } - function createTypeReference(target, typeArguments) { - var id = getTypeListId(typeArguments); - var type = target.instantiations.get(id); - if (!type) { - type = createObjectType(4, target.symbol); - target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, 0) : 0; - type.target = target; - type.typeArguments = typeArguments; - } - return type; - } - function cloneTypeReference(source) { - var type = createType(source.flags); - type.symbol = source.symbol; - type.objectFlags = source.objectFlags; - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return ts.length(type.target.typeParameters); - } - function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { - var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); - var typeParameters = type.localTypeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : 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(typeArgs, typeParameters, minTypeArgumentCount, node)); - return createTypeReference(type, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - return unknownType; - } - return type; - } - function getTypeAliasInstantiation(symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var links = getSymbolLinks(symbol); - var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); - var instantiation = links.instantiations.get(id); - if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); - } - return instantiation; - } - function getTypeFromTypeAliasReference(node, symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeParameters = getSymbolLinks(symbol).typeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); - return unknownType; - } - return getTypeAliasInstantiation(symbol, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return type; - } - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } - function getTypeReferenceName(node) { - switch (node.kind) { - case 159: - return node.typeName; - case 277: - return node.name; - case 201: - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; - } - } - return undefined; - } - function resolveTypeReferenceName(typeReferenceName) { - if (!typeReferenceName) { - return unknownSymbol; - } - 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, typeArguments); - } - if (symbol.flags & 524288) { - return getTypeFromTypeAliasReference(node, symbol, typeArguments); - } - if (symbol.flags & 107455 && node.kind === 277) { - return getTypeOfSymbol(symbol); - } - return getTypeFromNonGenericTypeReference(node, symbol); - } - function getPrimitiveTypeFromJSDocTypeReference(node) { - if (ts.isIdentifier(node.name)) { - switch (node.name.text) { - case "String": - return stringType; - case "Number": - return numberType; - case "Boolean": - return booleanType; - case "Void": - return voidType; - case "Undefined": - return undefinedType; - case "Null": - return nullType; - case "Object": - return anyType; - case "Function": - return anyFunctionType; - case "Array": - case "array": - return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined; - case "Promise": - case "promise": - return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; - } - } - } - function getTypeFromJSDocNullableTypeNode(node) { - var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; - } - function getTypeFromTypeReference(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var symbol = void 0; - var type = void 0; - if (node.kind === 277) { - type = getPrimitiveTypeFromJSDocTypeReference(node); - if (!type) { - var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(typeReferenceName); - type = getTypeReferenceType(node, symbol); - } - } - else { - var typeNameOrExpression = node.kind === 159 - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064) || unknownSymbol; - 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) { - links.resolvedType = getWidenedType(checkExpression(node.exprName)); - } - return links.resolvedType; - } - function getTypeOfGlobalSymbol(symbol, arity) { - function getTypeDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; - switch (declaration.kind) { - case 229: - case 230: - case 232: - return declaration; - } - } - } - if (!symbol) { - return arity ? emptyGenericType : emptyObjectType; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return arity ? emptyGenericType : emptyObjectType; - } - if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return arity ? emptyGenericType : emptyObjectType; - } - return type; - } - function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); - } - function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); - } - function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); - } - function getGlobalType(name, arity, reportErrors) { - var symbol = getGlobalTypeSymbol(name, reportErrors); - return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; - } - function getGlobalTypedPropertyDescriptorType() { - return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", 1, true)) || emptyGenericType; - } - function getGlobalTemplateStringsArrayType() { - return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", 0, true)) || emptyObjectType; - } - function getGlobalESSymbolConstructorSymbol(reportErrors) { - return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); - } - function getGlobalESSymbolType(reportErrors) { - return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", 0, reportErrors)) || emptyObjectType; - } - function getGlobalPromiseType(reportErrors) { - return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", 1, reportErrors)) || emptyGenericType; - } - function getGlobalPromiseConstructorSymbol(reportErrors) { - return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); - } - function getGlobalPromiseConstructorLikeType(reportErrors) { - return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", 0, reportErrors)) || emptyObjectType; - } - function getGlobalAsyncIterableType(reportErrors) { - return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIteratorType(reportErrors) { - return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIterableIteratorType(reportErrors) { - return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableType(reportErrors) { - return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIteratorType(reportErrors) { - return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableIteratorType(reportErrors) { - return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", 1, reportErrors)) || emptyGenericType; - } - function getGlobalTypeOrUndefined(name, arity) { - if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064, undefined); - return symbol && getTypeOfGlobalSymbol(symbol, arity); - } - function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920, undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064); - return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); - } - function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { - return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; - } - function createTypedPropertyDescriptorType(propertyType) { - return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); - } - function createAsyncIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(true), [iteratedType]); - } - function createAsyncIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(true), [iteratedType]); - } - function createIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableType(true), [iteratedType]); - } - function createIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(true), [iteratedType]); - } - function createArrayType(elementType) { - return createTypeFromGenericGlobalType(globalArrayType, [elementType]); - } - function getTypeFromArrayTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); - } - return links.resolvedType; - } - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384); - typeParameters.push(typeParameter); - var property = createSymbol(4, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(8 | 4); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384); - type.thisType.isThisType = true; - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); - } - function getTypeFromTupleTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); - } - return links.resolvedType; - } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - var flags = type.flags; - if (flags & 65536) { - addTypesToUnion(typeSet, type.types); - } - else if (flags & 1) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && flags & 6144) { - if (flags & 2048) - typeSet.containsUndefined = true; - if (flags & 4096) - typeSet.containsNull = true; - if (!(flags & 2097152)) - typeSet.containsNonWideningType = true; - } - else if (!(flags & 8192)) { - if (flags & 2) - typeSet.containsString = true; - if (flags & 4) - typeSet.containsNumber = true; - if (flags & 96) - typeSet.containsStringOrNumberLiteral = true; - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } - } - } - function addTypesToUnion(typeSet, types) { - 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_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function isSubtypeOfAny(candidate, types) { - 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; - } - } - return false; - } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 256) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types) { - if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { - return; - } - var i = types.length; - while (i > 0) { - i--; - if (isSubtypeOfAny(types[i], types)) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function removeRedundantLiteralTypes(types) { - var i = types.length; - while (i > 0) { - i--; - var t = types[i]; - var remove = t.flags & 32 && types.containsString || - t.flags & 64 && types.containsNumber || - t.flags & 96 && t.flags & 1048576 && containsType(types, t.regularType); - if (remove) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var typeSet = []; - addTypesToUnion(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsStringOrNumberLiteral) { - removeRedundantLiteralTypes(typeSet); - } - if (typeSet.length === 0) { - return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : - typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); - var type = unionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, 6144); - type = createType(65536 | propagatedFlags); - unionTypes.set(id, type); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromUnionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1) { - typeSet.containsAny = true; - } - else if (getObjectFlags(type) & 16 && isEmptyObjectType(type)) { - typeSet.containsEmptyObject = true; - } - else if (!(type.flags & 8192) && (strictNullChecks || !(type.flags & 6144)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768) { - typeSet.containsObjectType = true; - } - if (type.flags & 65536 && typeSet.unionIndex === undefined) { - typeSet.unionIndex = typeSet.length; - } - if (!(type.flags & 32768 && type.objectFlags & 16 && - type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { - typeSet.push(type); - } - } - } - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - addTypeToIntersection(typeSet, type); - } - } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } - var typeSet = []; - addTypesToIntersection(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { - typeSet.push(emptyObjectType); - } - if (typeSet.length === 1) { - return typeSet[0]; - } - var unionIndex = typeSet.unionIndex; - if (unionIndex !== undefined) { - var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), false, aliasSymbol, aliasTypeArguments); - } - var id = getTypeListId(typeSet); - var type = intersectionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, 6144); - type = createType(131072 | propagatedFlags); - intersectionTypes.set(id, type); - type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromIntersectionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function getIndexTypeForGenericType(type) { - if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144); - type.resolvedIndexType.type = type; - } - return type.resolvedIndexType; - } - function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.name, "__@") ? - neverType : - getLiteralType(ts.unescapeIdentifier(prop.name)); - } - function getLiteralTypeFromPropertyNames(type) { - return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); - } - function getIndexType(type) { - return maybeTypeOfKind(type, 540672) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 ? getConstraintTypeFromMappedType(type) : - type.flags & 1 || getIndexInfoOfType(type, 0) ? stringType : - getLiteralTypeFromPropertyNames(type); - } - function getIndexTypeOrString(type) { - var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; - } - function getTypeFromTypeOperatorNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); - } - return links.resolvedType; - } - function createIndexedAccessType(objectType, indexType) { - var type = createType(524288); - type.objectType = objectType; - type.indexType = indexType; - return type; - } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - var propName = indexType.flags & 96 ? - "" + indexType.value : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? - ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : - undefined; - if (propName !== undefined) { - var prop = getPropertyOfType(objectType, propName); - if (prop) { - if (accessExpression) { - if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return unknownType; - } - if (cacheSymbol) { - getNodeLinks(accessNode).resolvedSymbol = prop; - } - } - return getTypeOfSymbol(prop); - } - } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 | 84 | 512)) { - if (isTypeAny(objectType)) { - return anyType; - } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84) && getIndexInfoOfType(objectType, 1) || - getIndexInfoOfType(objectType, 0) || - undefined; - if (indexInfo) { - if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; - } - return indexInfo.type; - } - if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1)) { - error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); - } - } - return anyType; - } - } - 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.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)); - } - else { - error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); - } - return unknownType; - } - return anyType; - } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } - function getIndexedAccessType(objectType, indexType, accessNode) { - if (maybeTypeOfKind(indexType, 540672 | 262144) || - maybeTypeOfKind(objectType, 540672) && !(accessNode && accessNode.kind === 180) || - isGenericMappedType(objectType)) { - if (objectType.flags & 1) { - return objectType; - } - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - var id = objectType.id + "," + indexType.id; - var type = indexedAccessTypes.get(id); - if (!type) { - indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); - } - return type; - } - var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 && !(indexType.flags & 8190)) { - var propTypes = []; - for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { - var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, false); - if (propType === unknownType) { - return unknownType; - } - propTypes.push(propType); - } - return getUnionType(propTypes); - } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, true); - } - function getTypeFromIndexedAccessTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); - } - return links.resolvedType; - } - function getTypeFromMappedTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = createObjectType(32, node.symbol); - type.declaration = node; - type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - getConstraintTypeFromMappedType(type); - } - return links.resolvedType; - } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { - links.resolvedType = emptyTypeLiteralType; - } - else { - var type = createObjectType(16, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - } - } - return links.resolvedType; - } - function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 ? getSymbolOfNode(node.parent) : undefined; - } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); - return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; - } - function getSpreadType(left, right) { - if (left.flags & 1 || right.flags & 1) { - return anyType; - } - left = filterType(left, function (t) { return !(t.flags & 6144); }); - if (left.flags & 8192) { - return right; - } - right = filterType(right, function (t) { return !(t.flags & 6144); }); - if (right.flags & 8192) { - return left; - } - if (left.flags & 65536) { - return mapType(left, function (t) { return getSpreadType(t, right); }); - } - if (right.flags & 65536) { - return mapType(right, function (t) { return getSpreadType(left, t); }); - } - if (right.flags & 16777216) { - return emptyObjectType; - } - var members = ts.createMap(); - var skippedPrivateMembers = ts.createMap(); - var stringIndexInfo; - var numberIndexInfo; - if (left === emptyObjectType) { - stringIndexInfo = getIndexInfoOfType(right, 0); - numberIndexInfo = getIndexInfoOfType(right, 1); - } - else { - stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0), getIndexInfoOfType(right, 0)); - numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1), getIndexInfoOfType(right, 1)); - } - for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { - var rightProp = _a[_i]; - var isSetterWithoutGetter = rightProp.flags & 65536 && !(rightProp.flags & 32768); - if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 | 16)) { - skippedPrivateMembers.set(rightProp.name, true); - } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { - members.set(rightProp.name, getNonReadonlySymbol(rightProp)); - } - } - for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { - var leftProp = _c[_b]; - if (leftProp.flags & 65536 && !(leftProp.flags & 32768) - || skippedPrivateMembers.has(leftProp.name) - || isClassMethod(leftProp)) { - continue; - } - if (members.has(leftProp.name)) { - var rightProp = members.get(leftProp.name); - var rightType = getTypeOfSymbol(rightProp); - 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), rightType]); - result.leftSpread = leftProp; - result.rightSpread = rightProp; - result.declarations = declarations; - members.set(leftProp.name, result); - } - } - else { - members.set(leftProp.name, getNonReadonlySymbol(leftProp)); - } - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { - return prop; - } - var flags = 4 | (prop.flags & 67108864); - var result = createSymbol(flags, prop.name); - result.type = getTypeOfSymbol(prop); - result.declarations = prop.declarations; - result.syntheticOrigin = prop; - return result; - } - function isClassMethod(prop) { - return prop.flags & 8192 && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } - function createLiteralType(flags, value, symbol) { - var type = createType(flags); - 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.value, type.symbol); - freshType.regularType = type; - type.freshType = freshType; - } - return type.freshType; - } - return type; - } - function getRegularTypeOfLiteralType(type) { - return type.flags & 96 && type.flags & 1048576 ? type.regularType : type; - } - 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) { - var flags = (typeof value === "number" ? 64 : 32) | (enumId ? 256 : 0); - literalTypes.set(key, type = createLiteralType(flags, value, symbol)); - } - return type; - } - function getTypeFromLiteralTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); - } - return links.resolvedType; - } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; - } - return links.resolvedType; - } - function getTypeFromJSDocTupleType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); - links.resolvedType = createTupleType(types); - } - return links.resolvedType; - } - function getThisType(node) { - var container = ts.getThisContainer(node, false); - var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230)) { - if (!(ts.getModifierFlags(container) & 32) && - (container.kind !== 152 || ts.isNodeDescendantOf(node, container.body))) { - return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; - } - } - error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); - return unknownType; - } - function getTypeFromThisTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getThisType(node); - } - return links.resolvedType; - } - function getTypeFromTypeNode(node) { - switch (node.kind) { - case 119: - case 268: - case 269: - return anyType; - case 136: - return stringType; - case 133: - return numberType; - case 122: - return booleanType; - case 137: - return esSymbolType; - case 105: - return voidType; - case 139: - return undefinedType; - case 95: - return nullType; - case 130: - return neverType; - case 134: - return nonPrimitiveType; - case 169: - case 99: - return getTypeFromThisTypeNode(node); - case 173: - return getTypeFromLiteralTypeNode(node); - case 293: - return getTypeFromLiteralTypeNode(node.literal); - case 159: - case 277: - return getTypeFromTypeReference(node); - case 158: - return booleanType; - case 201: - return getTypeFromTypeReference(node); - case 162: - return getTypeFromTypeQueryNode(node); - case 164: - case 270: - return getTypeFromArrayTypeNode(node); - case 165: - return getTypeFromTupleTypeNode(node); - case 166: - case 271: - return getTypeFromUnionTypeNode(node); - case 167: - return getTypeFromIntersectionTypeNode(node); - case 273: - return getTypeFromJSDocNullableTypeNode(node); - case 168: - case 274: - case 281: - case 282: - case 278: - return getTypeFromTypeNode(node.type); - case 275: - return getTypeFromTypeNode(node.literal); - case 160: - case 161: - case 163: - case 292: - case 279: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170: - return getTypeFromTypeOperatorNode(node); - case 171: - return getTypeFromIndexedAccessTypeNode(node); - case 172: - return getTypeFromMappedTypeNode(node); - case 71: - case 143: - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - case 272: - return getTypeFromJSDocTupleType(node); - case 280: - return getTypeFromJSDocVariadicType(node); - default: - return unknownType; - } - } - function instantiateList(items, mapper, instantiator) { - if (items && items.length) { - var result = []; - for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { - var v = items_1[_i]; - result.push(instantiator(v, mapper)); - } - return result; - } - return items; - } - function instantiateTypes(types, mapper) { - return instantiateList(types, mapper, instantiateType); - } - function instantiateSignatures(signatures, mapper) { - return instantiateList(signatures, mapper, instantiateSignature); - } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } - function makeUnaryTypeMapper(source, target) { - return function (t) { return t === source ? target : t; }; - } - function makeBinaryTypeMapper(source1, target1, source2, target2) { - return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; - } - function makeArrayTypeMapper(sources, targets) { - return function (t) { - for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) { - return targets ? targets[i] : anyType; - } - } - return t; - }; - } - function createTypeMapper(sources, targets) { - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : - sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : - makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; - } - function createTypeEraser(sources) { - return createTypeMapper(sources, undefined); - } - function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; - } - function getInferenceMapper(context) { - if (!context.mapper) { - var mapper = function (t) { - var typeParameters = context.signature.typeParameters; - for (var i = 0; i < typeParameters.length; i++) { - if (t === typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); - } - } - return t; - }; - mapper.mappedTypes = context.signature.typeParameters; - mapper.context = context; - context.mapper = mapper; - } - return context.mapper; - } - function identityMapper(type) { - return type; - } - function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; - } - function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; - } - function cloneTypeParameter(typeParameter) { - var result = createType(16384); - result.symbol = typeParameter.symbol; - result.target = typeParameter; - return result; - } - function cloneTypePredicate(predicate, mapper) { - if (ts.isIdentifierTypePredicate(predicate)) { - return { - kind: 1, - parameterName: predicate.parameterName, - parameterIndex: predicate.parameterIndex, - type: instantiateType(predicate.type, mapper) - }; - } - else { - return { - kind: 0, - type: instantiateType(predicate.type, mapper) - }; - } - } - function instantiateSignature(signature, mapper, eraseTypeParameters) { - var freshTypeParameters; - var freshTypePredicate; - if (signature.typeParameters && !eraseTypeParameters) { - freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); - mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); - for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { - var tp = freshTypeParameters_1[_i]; - tp.mapper = mapper; - } - } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); - result.target = signature; - result.mapper = mapper; - return result; - } - function instantiateSymbol(symbol, mapper) { - if (ts.getCheckFlags(symbol) & 1) { - var links = getSymbolLinks(symbol); - symbol = links.target; - mapper = combineTypeMappers(links.mapper, mapper); - } - var result = createSymbol(symbol.flags, symbol.name); - result.checkFlags = 1; - result.declarations = symbol.declarations; - result.parent = symbol.parent; - result.target = symbol; - result.mapper = mapper; - if (symbol.valueDeclaration) { - result.valueDeclaration = symbol.valueDeclaration; - } - return result; - } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 | 64, type.symbol); - result.target = type.objectFlags & 64 ? type.target : type; - result.mapper = type.objectFlags & 64 ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function instantiateMappedType(type, mapper) { - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); - } - return t; - }); - } - } - } - return instantiateMappedObjectType(type, mapper); - } - function isMappableType(type) { - return type.flags & (16384 | 32768 | 131072 | 524288); - } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 | 64, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 || node.kind === 265) { - return "quit"; - } - switch (node.kind) { - case 160: - case 161: - case 228: - case 151: - case 150: - case 152: - case 155: - case 156: - case 157: - case 153: - case 154: - case 186: - case 187: - case 229: - case 199: - case 230: - case 231: - var declaration = node; - if (declaration.typeParameters) { - for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { - var d = _a[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 279: - var func = node; - for (var _b = 0, _c = func.parameters; _b < _c.length; _b++) { - var p = _c[_b]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 || parentKind === 234; - } - return false; - } - function instantiateType(type, mapper) { - if (type && mapper !== identityMapper) { - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - return type; - } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384) { - return mapper(type); - } - if (type.flags & 32768) { - if (type.objectFlags & 16) { - return type.symbol && - type.symbol.flags & (16 | 8192 | 32 | 2048 | 4096) && - (type.objectFlags & 64 || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; - } - if (type.objectFlags & 32) { - return instantiateCached(type, mapper, instantiateMappedType); - } - if (type.objectFlags & 4) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); - } - } - if (type.flags & 65536 && !(type.flags & 8190)) { - return getUnionType(instantiateTypes(type.types, mapper), false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - return type; - } - function instantiateIndexInfo(info, mapper) { - return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); - } - function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - switch (node.kind) { - case 186: - case 187: - return isContextSensitiveFunctionLikeDeclaration(node); - case 178: - return ts.forEach(node.properties, isContextSensitive); - case 177: - return ts.forEach(node.elements, isContextSensitive); - case 195: - return isContextSensitive(node.whenTrue) || - isContextSensitive(node.whenFalse); - case 194: - return node.operatorToken.kind === 54 && - (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261: - return isContextSensitive(node.initializer); - case 151: - case 150: - return isContextSensitiveFunctionLikeDeclaration(node); - case 185: - return isContextSensitive(node.expression); - case 254: - return ts.forEach(node.properties, isContextSensitive); - case 253: - return node.initializer && isContextSensitive(node.initializer); - case 256: - return node.expression && isContextSensitive(node.expression); - } - return false; - } - function isContextSensitiveFunctionLikeDeclaration(node) { - if (node.typeParameters) { - return false; - } - if (ts.forEach(node.parameters, function (p) { return !p.type; })) { - return true; - } - if (node.kind === 187) { - return false; - } - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); - } - function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); - } - function getTypeWithoutSignatures(type) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { - var result = createObjectType(16, type.symbol); - result.members = resolved.members; - result.properties = resolved.properties; - result.callSignatures = emptyArray; - result.constructSignatures = emptyArray; - return result; - } - } - else if (type.flags & 131072) { - return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); - } - return type; - } - function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); - } - function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 : 0; - } - function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 : 0; - } - function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); - } - function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); - } - function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); - } - function areTypesComparable(type1, type2) { - return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); - } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); - } - function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, false, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; - } - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { - if (source === target) { - return -1; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType && sourceThisType !== voidType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType, false) - || compareTypes(targetThisType, sourceThisType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); - } - return 0; - } - result &= related; - } - } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144) === (getFalsyFlags(targetType) & 6144); - var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, true, false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, false) || compareTypes(targetType, sourceType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); - } - return 0; - } - result &= related; - } - if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) { - return result; - } - var sourceReturnType = getReturnTypeOfSignature(source); - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); - } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0; - } - } - else { - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, false) || - compareTypes(sourceReturnType, targetReturnType, reportErrors); - } - } - return result; - } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { - if (source.kind !== target.kind) { - if (reportErrors) { - errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0; - } - if (source.kind === 1) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0; - } - } - var related = compareTypes(source.type, target.type, reportErrors); - if (related === 0 && reportErrors) { - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return related; - } - function isImplementationCompatibleWithOverload(implementation, overload) { - var erasedSource = getErasedSignature(implementation); - var erasedTarget = getErasedSignature(overload); - var sourceReturnType = getReturnTypeOfSignature(erasedSource); - var targetReturnType = getReturnTypeOfSignature(erasedTarget); - if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - return isSignatureAssignableTo(erasedSource, erasedTarget, true); - } - return false; - } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } - function isEmptyResolvedType(t) { - return t.properties.length === 0 && - t.callSignatures.length === 0 && - t.constructSignatures.length === 0 && - !t.stringIndexInfo && - !t.numberIndexInfo; - } - function isEmptyObjectType(type) { - return type.flags & 32768 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 65536 ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : - false; - } - function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { - if (sourceSymbol === targetSymbol) { - return true; - } - var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); - var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; - } - if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256) || !(targetSymbol.flags & 256)) { - enumRelation.set(id, false); - return false; - } - 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(getDeclaredTypeOfSymbol(targetSymbol), undefined, 128)); - } - enumRelation.set(id, false); - return false; - } - } - } - enumRelation.set(id, true); - return true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - var s = source.flags; - var t = target.flags; - if (t & 8192) - return false; - if (t & 1 || s & 8192) - return true; - if (s & 262178 && t & 2) - return true; - if (s & 32 && s & 256 && - t & 32 && !(t & 256) && - source.value === target.value) - return true; - if (s & 84 && t & 4) - return true; - if (s & 64 && s & 256 && - t & 64 && !(t & 256) && - source.value === target.value) - return true; - if (s & 136 && t & 8) - return true; - if (s & 16 && t & 16 && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; - 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 (s & 4096 && (!strictNullChecks || t & 4096)) - return true; - if (s & 32768 && t & 16777216) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1) - return true; - if (s & (4 | 64) && !(s & 256) && (t & 16 || t & 64 && t & 256)) - return true; - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 && source.flags & 1048576) { - source = source.regularType; - } - if (target.flags & 96 && target.flags & 1048576) { - target = target.regularType; - } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 32768 && target.flags & 32768) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - return related === 1; - } - } - if (source.flags & 1032192 || target.flags & 1032192) { - return checkTypeRelatedTo(source, target, relation, undefined); - } - return false; - } - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { - var errorInfo; - var sourceStack; - var targetStack; - var maybeStack; - var expandingFlags; - var depth = 0; - var overflow = false; - ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, !!errorNode, headMessage); - if (overflow) { - error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); - } - else if (errorInfo) { - if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return result !== 0; - function reportError(message, arg0, arg1, arg2) { - ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - } - function reportRelationError(message, source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 128); - targetType = typeToString(target, undefined, 128); - } - if (!message) { - if (relation === comparableRelation) { - message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; - } - else if (sourceType === targetType) { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; - } - else { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; - } - } - reportError(message, sourceType, targetType); - } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType(false) === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } - function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608)) { - return false; - } - var seenNonNullable = false; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 6144) { - continue; - } - if (seenNonNullable) { - return true; - } - seenNonNullable = true; - } - return false; - } - function isRelatedTo(source, target, reportErrors, headMessage) { - var result; - if (source.flags & 96 && source.flags & 1048576) { - source = source.regularType; - } - if (target.flags & 96 && target.flags & 1048576) { - target = target.regularType; - } - if (source === target) - return -1; - if (relation === identityRelation) { - return isIdenticalTo(source, target); - } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1; - if (getObjectFlags(source) & 128 && source.flags & 1048576) { - if (hasExcessProperties(source, target, reportErrors)) { - if (reportErrors) { - reportRelationError(headMessage, source, target); - } - return 0; - } - if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { - source = getRegularTypeOfObjectLiteral(source); - } - } - var saveErrorInfo = errorInfo; - if (source.flags & 65536) { - if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); - } - else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190)); - } - if (result) { - return result; - } - } - else { - if (target.flags & 65536) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190) && !(target.flags & 8190))) { - return result; - } - } - else if (target.flags & 131072) { - if (result = typeRelatedToEachType(source, target, reportErrors)) { - return result; - } - } - else if (source.flags & 131072) { - if (result = someTypeRelatedToType(source, target, false)) { - return result; - } - } - if (source.flags & 1032192 || target.flags & 1032192) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (reportErrors) { - if (source.flags & 32768 && target.flags & 8190) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 32768 && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - reportRelationError(headMessage, source, target); - } - return 0; - } - function isIdenticalTo(source, target) { - var result; - if (source.flags & 32768 && target.flags & 32768) { - return recursiveTypeRelatedTo(source, target, false); - } - if (source.flags & 65536 && target.flags & 65536 || - source.flags & 131072 && target.flags & 131072) { - if (result = eachTypeRelatedToSomeType(source, target)) { - if (result &= eachTypeRelatedToSomeType(target, source)) { - return result; - } - } - } - return 0; - } - function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { - var isComparingJsxAttributes = !!(source.flags & 33554432); - if ((relation === assignableRelation || relation === comparableRelation) && - (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { - return false; - } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { - if (reportErrors) { - ts.Debug.assert(!!errorNode); - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); - } - else { - errorNode = prop.valueDeclaration; - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); - } - } - return true; - } - } - } - return false; - } - function eachTypeRelatedToSomeType(source, target) { - var result = -1; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { - var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, false); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function typeRelatedToSomeType(source, target, reportErrors) { - var targetTypes = target.types; - if (target.flags & 65536 && containsType(targetTypes, source)) { - return -1; - } - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var type = targetTypes_1[_i]; - var related = isRelatedTo(source, type, false); - if (related) { - return related; - } - } - if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); - } - return 0; - } - function findMatchingDiscriminantType(source, target) { - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.name)) { - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); - if (targetType && isRelatedTo(sourceType, targetType)) { - return type; - } - } - } - } - } - } - function typeRelatedToEachType(source, target, reportErrors) { - var result = -1; - var targetTypes = target.types; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function someTypeRelatedToType(source, target, reportErrors) { - var sourceTypes = source.types; - if (source.flags & 65536 && containsType(sourceTypes, target)) { - return -1; - } - var len = sourceTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); - if (related) { - return related; - } - } - return 0; - } - function eachTypeRelatedToType(source, target, reportErrors) { - var result = -1; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; - var related = isRelatedTo(sourceType, target, reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function typeArgumentsRelatedTo(source, target, reportErrors) { - var sources = source.typeArguments || emptyArray; - var targets = target.typeArguments || emptyArray; - if (sources.length !== targets.length && relation === identityRelation) { - return 0; - } - var length = sources.length <= targets.length ? sources.length : targets.length; - var result = -1; - for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function recursiveTypeRelatedTo(source, target, reportErrors) { - if (overflow) { - return 0; - } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - if (reportErrors && related === 2) { - relation.set(id, 3); - } - else { - return related === 1 ? -1 : 0; - } - } - if (depth > 0) { - for (var i = 0; i < depth; i++) { - if (maybeStack[i].get(id)) { - return 1; - } - } - if (depth === 100) { - overflow = true; - return 0; - } - } - else { - sourceStack = []; - targetStack = []; - maybeStack = []; - expandingFlags = 0; - } - sourceStack[depth] = source; - targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); - maybeStack[depth].set(id, 1); - depth++; - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1; - expandingFlags = saveExpandingFlags; - depth--; - if (result) { - var maybeCache = maybeStack[depth]; - var destinationCache = (result === -1 || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyEntries(maybeCache, destinationCache); - } - else { - relation.set(id, reportErrors ? 3 : 2); - } - return result; - } - function structuredTypeRelatedTo(source, target, reportErrors) { - var result; - var saveErrorInfo = errorInfo; - if (target.flags & 16384) { - if (getObjectFlags(source) & 32 && getConstraintTypeFromMappedType(source) === getIndexType(target)) { - if (!source.declaration.questionToken) { - var templateType = getTemplateTypeFromMappedType(source); - var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); - if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { - return result; - } - } - } - } - else if (target.flags & 262144) { - if (source.flags & 262144) { - if (result = isRelatedTo(target.type, source.type, false)) { - return result; - } - } - var constraint = getConstraintOfType(target.type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { - return result; - } - } - } - else if (target.flags & 524288) { - var constraint = getConstraintOfType(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (source.flags & 16384) { - if (getObjectFlags(target) & 32 && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else { - var constraint = getConstraintOfTypeParameter(source); - if (constraint || !(target.flags & 16777216)) { - if (!constraint || constraint.flags & 1) { - constraint = emptyObjectType; - } - constraint = getTypeWithThisArgument(constraint, source); - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - } - else if (source.flags & 524288) { - var constraint = getConstraintOfType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else if (target.flags & 524288 && source.indexType === target.indexType) { - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - return result; - } - } - } - else { - if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { - return result; - } - } - var sourceIsPrimitive = !!(source.flags & 8190); - if (relation !== identityRelation) { - source = getApparentType(source); - } - if (source.flags & (32768 | 131072) && target.flags & 32768) { - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isGenericMappedType(source) || isGenericMappedType(target)) { - result = mappedTypeRelatedTo(source, target, reportStructuralErrors); - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 0, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 1, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 0, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1, sourceIsPrimitive, reportStructuralErrors); - } - } - } - } - } - if (result) { - errorInfo = saveErrorInfo; - return result; - } - } - } - return 0; - } - function mappedTypeRelatedTo(source, target, reportErrors) { - if (isGenericMappedType(target)) { - if (isGenericMappedType(source)) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; - if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); - } - } - } - else if (target.declaration.questionToken && isEmptyObjectType(source)) { - return -1; - } - } - else if (relation !== identityRelation) { - var resolved = resolveStructuredTypeMembers(target); - if (isEmptyResolvedType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & 1) { - return -1; - } - } - return 0; - } - function propertiesRelatedTo(source, target, reportErrors) { - if (relation === identityRelation) { - return propertiesIdenticalTo(source, target); - } - var result = -1; - var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128); - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var targetProp = properties_4[_i]; - var sourceProp = getPropertyOfType(source, targetProp.name); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 67108864) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0; - } - } - else if (!(targetProp.flags & 16777216)) { - var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); - if (sourcePropFlags & 8 || targetPropFlags & 8) { - 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)); - } - return 0; - } - if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { - if (reportErrors) { - if (sourcePropFlags & 8 && targetPropFlags & 8) { - reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); - } - else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 ? source : target), typeToString(sourcePropFlags & 8 ? target : source)); - } - } - return 0; - } - } - else if (targetPropFlags & 16) { - if (!isValidOverrideOf(sourceProp, targetProp)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); - } - return 0; - } - } - else if (sourcePropFlags & 16) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0; - } - var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); - } - return 0; - } - result &= related; - if (relation !== comparableRelation && sourceProp.flags & 67108864 && !(targetProp.flags & 67108864)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0; - } - } - } - } - return result; - } - function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 && target.flags & 32768)) { - return 0; - } - var sourceProperties = getPropertiesOfObjectType(source); - var targetProperties = getPropertiesOfObjectType(target); - if (sourceProperties.length !== targetProperties.length) { - return 0; - } - var result = -1; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; - var targetProp = getPropertyOfObjectType(target, sourceProp.name); - if (!targetProp) { - return 0; - } - var related = compareProperties(sourceProp, targetProp, isRelatedTo); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function signaturesRelatedTo(source, target, kind, reportErrors) { - if (relation === identityRelation) { - return signaturesIdenticalTo(source, target, kind); - } - if (target === anyFunctionType || source === anyFunctionType) { - return -1; - } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (kind === 1 && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0; - } - if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { - return 0; - } - } - var result = -1; - var saveErrorInfo = errorInfo; - 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; - } - result &= related; - } - } - 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 result; - } - function signatureRelatedTo(source, target, reportErrors) { - return compareSignaturesRelated(source, target, false, false, reportErrors, reportError, isRelatedTo); - } - function signaturesIdenticalTo(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (sourceSignatures.length !== targetSignatures.length) { - return 0; - } - var result = -1; - for (var i = 0; i < sourceSignatures.length; i++) { - var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], false, false, false, isRelatedTo); - if (!related) { - return 0; - } - result &= related; - } - return result; - } - function eachPropertyRelatedTo(source, target, kind, reportErrors) { - var result = -1; - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 || isNumericLiteralName(prop.name)) { - var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); - } - return 0; - } - result &= related; - } - } - return result; - } - function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { - var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); - if (!related && reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return related; - } - function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(source, target, kind); - } - var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 && !sourceIsPrimitive) { - return -1; - } - var sourceInfo = getIndexInfoOfType(source, kind) || - kind === 1 && getIndexInfoOfType(source, 0); - if (sourceInfo) { - return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); - } - if (isObjectLiteralType(source)) { - var related = -1; - if (kind === 0) { - var sourceNumberInfo = getIndexInfoOfType(source, 1); - if (sourceNumberInfo) { - related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); - } - } - if (related) { - related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); - } - return related; - } - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0; - } - function indexTypesIdenticalTo(source, target, indexKind) { - var targetInfo = getIndexInfoOfType(target, indexKind); - var sourceInfo = getIndexInfoOfType(source, indexKind); - if (!sourceInfo && !targetInfo) { - return -1; - } - if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { - return isRelatedTo(sourceInfo.type, targetInfo.type); - } - return 0; - } - function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { - if (!sourceSignature.declaration || !targetSignature.declaration) { - return true; - } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24; - if (targetAccessibility === 8) { - return true; - } - if (targetAccessibility === 16 && sourceAccessibility !== 8) { - return true; - } - if (targetAccessibility !== 16 && !sourceAccessibility) { - return true; - } - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); - } - return false; - } - } - function forEachProperty(prop, callback) { - 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); - var result = p && forEachProperty(p, callback); - if (result) { - return result; - } - } - return undefined; - } - return callback(prop); - } - function getDeclaringClass(prop) { - return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; - } - function isPropertyInClassDerivedFrom(prop, baseClass) { - return forEachProperty(prop, function (sp) { - var sourceClass = getDeclaringClass(sp); - return sourceClass ? hasBaseType(sourceClass, baseClass) : false; - }); - } - function isValidOverrideOf(sourceProp, targetProp) { - 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 ts.getDeclarationModifierFlagsFromSymbol(p) & 16 ? - !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; - } - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128) { - return true; - } - } - } - return false; - } - function isDeeplyNestedType(type, stack, depth) { - if (depth >= 5 && type.flags & 32768) { - var symbol = type.symbol; - if (symbol) { - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 32768 && t.symbol === symbol) { - count++; - if (count >= 5) - return true; - } - } - } - } - return false; - } - function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0; - } - function compareProperties(sourceProp, targetProp, compareTypes) { - if (sourceProp === targetProp) { - return -1; - } - var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24; - var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24; - if (sourcePropAccessibility !== targetPropAccessibility) { - return 0; - } - if (sourcePropAccessibility) { - if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { - return 0; - } - } - else { - if ((sourceProp.flags & 67108864) !== (targetProp.flags & 67108864)) { - return 0; - } - } - if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { - return 0; - } - return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - function isMatchingSignature(source, target, partialMatch) { - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { - return true; - } - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { - return true; - } - return false; - } - function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { - if (source === target) { - return -1; - } - if (!(isMatchingSignature(source, target, partialMatch))) { - return 0; - } - if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { - return 0; - } - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1; - if (!ignoreThisTypes) { - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType); - if (!related) { - return 0; - } - result &= related; - } - } - } - var targetLen = target.parameters.length; - for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); - var related = compareTypes(s, t); - if (!related) { - return 0; - } - result &= related; - } - if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - return result; - } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } - function isSupertypeOfEach(candidate, types) { - 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; - } - return true; - } - function literalTypesWithSameBaseType(types) { - var commonBaseType; - 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; - } - if (baseType === t || baseType !== commonBaseType) { - return false; - } - } - return true; - } - function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); - } - function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); - } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); - if (!primaryTypes.length) { - return getUnionType(types, true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - if (bestSupertypeScore === types.length - 1) { - break; - } - } - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); - } - function isArrayType(type) { - return getObjectFlags(type) & 4 && type.target === globalArrayType; - } - function isArrayLikeType(type) { - return getObjectFlags(type) & 4 && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144) && isTypeAssignableTo(type, anyReadonlyArrayType); - } - function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); - } - function isUnitType(type) { - return (type.flags & (224 | 2048 | 4096)) !== 0; - } - function isLiteralType(type) { - return type.flags & 8 ? true : - type.flags & 65536 ? type.flags & 256 ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfLiteralType(type) { - 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 & 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) { - return !!(getObjectFlags(type) & 4 && type.target.objectFlags & 8); - } - function getFalsyFlagsOfTypes(types) { - var result = 0; - 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.value === "" ? 32 : 0 : - type.flags & 64 ? type.value === 0 ? 64 : 0 : - type.flags & 128 ? type === falseType ? 128 : 0 : - type.flags & 7406; - } - 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; - } - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 | 2048)) !== 0 && - getSignaturesOfType(type, 0).length === 0 && - getSignaturesOfType(type, 1).length === 0; - } - function createSymbolWithType(source, type) { - var symbol = createSymbol(source.flags, source.name); - symbol.declarations = source.declarations; - symbol.parent = source.parent; - symbol.type = type; - symbol.target = source; - if (source.valueDeclaration) { - symbol.valueDeclaration = source.valueDeclaration; - } - return symbol; - } - function transformTypeOfMembers(type, f) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var property = _a[_i]; - var original = getTypeOfSymbol(property); - var updated = f(original); - members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); - } - return members; - } - function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 && type.flags & 1048576)) { - return type; - } - var regularType = type.regularType; - if (regularType) { - return regularType; - } - var resolved = type; - var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); - var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576; - regularNew.objectFlags |= 128; - type.regularType = regularNew; - return regularNew; - } - function getWidenedProperty(prop) { - var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); - return widened === original ? prop : createSymbolWithType(prop, widened); - } - function getWidenedTypeOfObjectLiteral(type) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - members.set(prop.name, prop.flags & 4 ? getWidenedProperty(prop) : prop); - } - var stringIndexInfo = getIndexInfoOfType(type, 0); - var numberIndexInfo = getIndexInfoOfType(type, 1); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - } - function getWidenedConstituentType(type) { - return type.flags & 6144 ? type : getWidenedType(type); - } - function getWidenedType(type) { - if (type.flags & 6291456) { - if (type.flags & 6144) { - return anyType; - } - if (getObjectFlags(type) & 128) { - return getWidenedTypeOfObjectLiteral(type); - } - if (type.flags & 65536) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); - } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); - } - } - return type; - } - function reportWideningErrorsInType(type) { - var errorReported = false; - if (type.flags & 65536) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (getObjectFlags(type) & 128) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); - } - errorReported = true; - } - } - } - return errorReported; - } - function reportImplicitAnyError(declaration, type) { - var typeAsString = typeToString(getWidenedType(type)); - var diagnostic; - switch (declaration.kind) { - case 149: - case 148: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; - break; - case 146: - diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; - break; - case 176: - diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; - break; - case 228: - case 151: - case 150: - case 153: - case 154: - case 186: - case 187: - if (!declaration.name) { - error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); - return; - } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; - break; - default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; - } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); - } - function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { - if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); - } - } - } - function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { - callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); - } - } - function createInferenceContext(signature, inferUnionTypes, useAnyForNoInferences) { - var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); - return { - signature: signature, - inferUnionTypes: inferUnionTypes, - inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length), - useAnyForNoInferences: useAnyForNoInferences - }; - } - function createTypeInferencesObject() { - return { - primary: undefined, - secondary: undefined, - topLevel: true, - isFixed: false, - }; - } - function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 || - objectFlags & 4 && ts.forEach(type.typeArguments, couldContainTypeVariables) || - objectFlags & 16 && type.symbol && type.symbol.flags & (8192 | 2048 | 32) || - objectFlags & 32 || - type.flags & 196608 && couldUnionOrIntersectionContainTypeVariables(type)); - } - function couldUnionOrIntersectionContainTypeVariables(type) { - if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); - } - return type.couldContainTypeVariables; - } - function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); - } - function inferTypeForHomomorphicMappedType(source, target) { - var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0); - if (properties.length === 0 && !indexInfo) { - return undefined; - } - var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var typeVariableArray = [typeVariable]; - var typeInferences = createTypeInferencesObject(); - var typeInferencesArray = [typeInferences]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 67108864; - 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)); - if (!inferredPropType) { - return undefined; - } - var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.name); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 : 0; - inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; - members.set(prop.name, inferredProp); - } - if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - typeInferences.primary = undefined; - typeInferences.secondary = undefined; - inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); - var inferences = typeInferences.primary || typeInferences.secondary; - return inferences && getUnionType(inferences, true); - } - } - function inferTypesWithContext(context, originalSource, originalTarget) { - inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); - } - function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var symbolStack; - var visited; - var inferiority = 0; - inferFromTypes(originalSource, originalTarget); - function inferFromTypes(source, target) { - if (!couldContainTypeVariables(target)) { - return; - } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - var sourceTypes = source.aliasTypeArguments; - var targetTypes = target.aliasTypeArguments; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - return; - } - 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++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } - var matchingTypes = void 0; - for (var _b = 0, _c = source.types; _b < _c.length; _b++) { - var t = _c[_b]; - if (typeIdenticalToSomeType(t, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t); - inferFromTypes(t, t); - } - else if (t.flags & (64 | 32)) { - var b = getBaseTypeOfLiteralType(t); - if (typeIdenticalToSomeType(b, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t, b); - } - } - } - if (matchingTypes) { - source = removeTypesFromUnionOrIntersection(source, matchingTypes); - target = removeTypesFromUnionOrIntersection(target, matchingTypes); - } - } - if (target.flags & 540672) { - if (source.flags & 8388608) { - return; - } - for (var i = 0; i < typeVariables.length; i++) { - if (target === typeVariables[i]) { - var inferences = typeInferences[i]; - if (!inferences.isFixed) { - var candidates = inferiority ? - inferences.secondary || (inferences.secondary = []) : - inferences.primary || (inferences.primary = []); - if (!ts.contains(candidates, source)) { - candidates.push(source); - } - if (target.flags & 16384 && !isTypeParameterAtTopLevel(originalTarget, target)) { - inferences.topLevel = false; - } - } - return; - } - } - } - else if (getObjectFlags(source) & 4 && getObjectFlags(target) & 4 && source.target === target.target) { - var sourceTypes = source.typeArguments || emptyArray; - var targetTypes = target.typeArguments || emptyArray; - var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; - for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 196608) { - var targetTypes = target.types; - var typeVariableCount = 0; - var typeVariable = void 0; - for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { - var t = targetTypes_3[_d]; - if (t.flags & 540672 && ts.contains(typeVariables, t)) { - typeVariable = t; - typeVariableCount++; - } - else { - inferFromTypes(source, t); - } - } - if (typeVariableCount === 1) { - inferiority++; - inferFromTypes(source, typeVariable); - inferiority--; - } - } - else if (source.flags & 196608) { - var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; - inferFromTypes(sourceType, target); - } - } - else { - source = getApparentType(source); - if (source.flags & 32768) { - var key = source.id + "," + target.id; - if (visited && visited.get(key)) { - return; - } - (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); - } - } - } - } - function inferFromObjectTypes(source, target) { - if (getObjectFlags(target) & 32) { - var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144) { - var index = ts.indexOf(typeVariables, constraintType.type); - if (index >= 0 && !typeInferences[index].isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - inferiority++; - inferFromTypes(inferredType, typeVariables[index]); - inferiority--; - } - } - return; - } - if (constraintType.flags & 16384) { - inferFromTypes(getIndexType(source), constraintType); - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); - return; - } - } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target); - } - function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.name); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - } - } - function inferFromSignatures(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - var sourceLen = sourceSignatures.length; - var targetLen = targetSignatures.length; - var len = sourceLen < targetLen ? sourceLen : targetLen; - for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); - } - } - function inferFromParameterTypes(source, target) { - return inferFromTypes(source, target); - } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromParameterTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - } - function inferFromIndexTypes(source, target) { - var targetStringIndexType = getIndexTypeOfType(target, 0); - if (targetStringIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 0); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetStringIndexType); - } - } - var targetNumberIndexType = getIndexTypeOfType(target, 1); - if (targetNumberIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 1) || - getIndexTypeOfType(source, 0) || - getImplicitIndexTypeOfType(source, 1); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetNumberIndexType); - } - } - } - } - function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function removeTypesFromUnionOrIntersection(type, typesToRemove) { - var reducedTypes = []; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!typeIdenticalToSomeType(t, typesToRemove)) { - reducedTypes.push(t); - } - } - return type.flags & 65536 ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); - } - function getInferenceCandidates(context, index) { - var inferences = context.inferences[index]; - return inferences.primary || inferences.secondary || emptyArray; - } - function hasPrimitiveConstraint(type) { - var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 | 262144); - } - function getInferredType(context, index) { - var inferredType = context.inferredTypes[index]; - var inferenceSucceeded; - if (!inferredType) { - var inferences = getInferenceCandidates(context, index); - if (inferences.length) { - var signature = context.signature; - var widenLiteralTypes = context.inferences[index].topLevel && - !hasPrimitiveConstraint(signature.typeParameters[index]) && - (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; - var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, true) : getCommonSupertype(baseInferences); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; - } - else { - var defaultType = getDefaultFromTypeParameter(context.signature.typeParameters[index]); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), getInferenceMapper(context))); - } - else { - inferredType = context.useAnyForNoInferences ? anyType : emptyObjectType; - } - inferenceSucceeded = true; - } - context.inferredTypes[index] = inferredType; - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - context.inferredTypes[index] = inferredType = instantiatedConstraint; - } - } - } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - context.failedTypeParameterIndex = index; - } - } - return inferredType; - } - function getInferredTypes(context) { - for (var i = 0; i < context.inferredTypes.length; i++) { - getInferredType(context, i); - } - return context.inferredTypes; - } - 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, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; - } - return links.resolvedSymbol; - } - function isInTypeQuery(node) { - return !!ts.findAncestor(node, function (n) { return n.kind === 162 ? true : n.kind === 71 || n.kind === 143 ? false : "quit"; }); - } - function getFlowCacheKey(node) { - if (node.kind === 71) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 99) { - return "0"; - } - if (node.kind === 179) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + node.name.text; - } - return undefined; - } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71: - case 99: - return node; - case 179: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } - function isMatchingReference(source, target) { - switch (source.kind) { - case 71: - return target.kind === 71 && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 || target.kind === 176) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99: - return target.kind === 99; - case 97: - return target.kind === 97; - case 179: - return target.kind === 179 && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } - return false; - } - function containsMatchingReference(source, target) { - while (source.kind === 179) { - source = source.expression; - if (isMatchingReference(source, target)) { - return true; - } - } - return false; - } - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 179) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } - function isOrContainsMatchingReference(source, target) { - return isMatchingReference(source, target) || containsMatchingReference(source, target); - } - function hasMatchingArgument(callExpression, reference) { - if (callExpression.arguments) { - for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isOrContainsMatchingReference(reference, argument)) { - return true; - } - } - } - if (callExpression.expression.kind === 179 && - isOrContainsMatchingReference(reference, callExpression.expression.expression)) { - return true; - } - return false; - } - function getFlowNodeId(flow) { - if (!flow.id) { - flow.id = nextFlowId; - nextFlowId++; - } - return flow.id; - } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } - function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 8192) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192)) { - return reducedType; - } - } - return declaredType; - } - function getTypeFactsOfTypes(types) { - var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); - } - function getTypeFacts(type) { - var flags = type.flags; - if (flags & 2) { - return strictNullChecks ? 4079361 : 4194049; - } - if (flags & 32) { - var isEmpty = type.value === ""; - return strictNullChecks ? - isEmpty ? 3030785 : 1982209 : - isEmpty ? 3145473 : 4194049; - } - if (flags & (4 | 16)) { - return strictNullChecks ? 4079234 : 4193922; - } - if (flags & 64) { - var isZero = type.value === 0; - return strictNullChecks ? - isZero ? 3030658 : 1982082 : - isZero ? 3145346 : 4193922; - } - if (flags & 8) { - return strictNullChecks ? 4078980 : 4193668; - } - if (flags & 136) { - return strictNullChecks ? - type === falseType ? 3030404 : 1981828 : - type === falseType ? 3145092 : 4193668; - } - if (flags & 32768) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 : 8376288 : - strictNullChecks ? 6166480 : 8378320; - } - if (flags & (1024 | 2048)) { - return 2457472; - } - if (flags & 4096) { - return 2340752; - } - if (flags & 512) { - return strictNullChecks ? 1981320 : 4193160; - } - if (flags & 16777216) { - return strictNullChecks ? 6166480 : 8378320; - } - if (flags & 540672) { - return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); - } - if (flags & 196608) { - return getTypeFactsOfTypes(type.types); - } - return 8388607; - } - function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); - } - function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072), defaultType]); - } - return type; - } - function getTypeOfDestructuredProperty(type, name) { - var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || - isNumericLiteralName(text) && getIndexTypeOfType(type, 1) || - getIndexTypeOfType(type, 0) || - unknownType; - } - function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || - checkIteratedTypeOrElementType(type, undefined, false, false) || - unknownType; - } - function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, undefined, false, false) || unknownType); - } - function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 && isDestructuringAssignmentTarget(node.parent.parent); - return isDestructuringDefaultAssignment ? - getTypeWithDefault(getAssignedType(node), node.right) : - getTypeOfExpression(node.right); - } - function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 && parent.parent.left === parent || - parent.parent.kind === 216 && parent.parent.initializer === parent; - } - function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); - } - function getAssignedTypeOfSpreadExpression(node) { - return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); - } - function getAssignedTypeOfPropertyAssignment(node) { - return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); - } - function getAssignedTypeOfShorthandPropertyAssignment(node) { - return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); - } - function getAssignedType(node) { - var parent = node.parent; - switch (parent.kind) { - case 215: - return stringType; - case 216: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194: - return getAssignedTypeOfBinaryExpression(parent); - case 188: - return undefinedType; - case 177: - return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198: - return getAssignedTypeOfSpreadExpression(parent); - case 261: - return getAssignedTypeOfPropertyAssignment(parent); - case 262: - return getAssignedTypeOfShorthandPropertyAssignment(parent); - } - return unknownType; - } - function getInitialTypeOfBindingElement(node) { - var pattern = node.parent; - var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 ? - getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : - !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadExpression(parentType); - return getTypeWithDefault(type, node.initializer); - } - function getTypeOfInitializer(node) { - var links = getNodeLinks(node); - return links.resolvedType || getTypeOfExpression(node); - } - function getInitialTypeOfVariableDeclaration(node) { - if (node.initializer) { - return getTypeOfInitializer(node.initializer); - } - if (node.parent.parent.kind === 215) { - return stringType; - } - if (node.parent.parent.kind === 216) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; - } - return unknownType; - } - function getInitialType(node) { - return node.kind === 226 ? - getInitialTypeOfVariableDeclaration(node) : - getInitialTypeOfBindingElement(node); - } - function getInitialOrAssignedType(node) { - return node.kind === 226 || node.kind === 176 ? - getInitialType(node) : - getAssignedType(node); - } - function isEmptyArrayAssignment(node) { - return node.kind === 226 && node.initializer && - isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 && node.parent.kind === 194 && - isEmptyArrayLiteral(node.parent.right); - } - function getReferenceCandidate(node) { - switch (node.kind) { - case 185: - return getReferenceCandidate(node.expression); - case 194: - switch (node.operatorToken.kind) { - case 58: - return getReferenceCandidate(node.left); - case 26: - return getReferenceCandidate(node.right); - } - } - return node; - } - function getReferenceRoot(node) { - var parent = node.parent; - return parent.kind === 185 || - parent.kind === 194 && parent.operatorToken.kind === 58 && parent.left === node || - parent.kind === 194 && parent.operatorToken.kind === 26 && parent.right === node ? - getReferenceRoot(parent) : node; - } - function getTypeOfSwitchClause(clause) { - if (clause.kind === 257) { - var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); - return isUnitType(caseType) ? caseType : undefined; - } - return neverType; - } - function getSwitchClauseTypes(switchStatement) { - var links = getNodeLinks(switchStatement); - if (!links.switchTypes) { - var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; - } - return links.switchTypes; - } - function eachTypeContainedIn(source, types) { - return source.flags & 65536 ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 && getBaseTypeOfEnumLiteralType(source) === target) { - return true; - } - return containsType(target.types, source); - } - function forEachType(type, f) { - return type.flags & 65536 ? ts.forEach(type.types, f) : f(type); - } - function filterType(type, f) { - if (type.flags & 65536) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; - } - function mapType(type, mapper) { - if (!(type.flags & 65536)) { - return mapper(type); - } - var types = type.types; - var mappedType; - var mappedTypes; - 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) { - mappedType = t; - } - else if (!mappedTypes) { - mappedTypes = [mappedType, t]; - } - else { - mappedTypes.push(t); - } - } - } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; - } - function extractTypesOfKind(type, kind) { - return filterType(type, function (t) { return (t.flags & kind) !== 0; }); - } - function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { - return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : - t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : - t; - }); - } - return typeWithPrimitives; - } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - function createEvolvingArrayType(elementType) { - var result = createObjectType(256); - result.elementType = elementType; - return result; - } - function getEvolvingArrayType(elementType) { - return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); - } - function addEvolvingArrayElementType(evolvingArrayType, node) { - var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); - return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); - } - function createFinalArrayType(elementType) { - return elementType.flags & 8192 ? - autoArrayType : - createArrayType(elementType.flags & 65536 ? - getUnionType(elementType.types, true) : - elementType); - } - function getFinalArrayType(evolvingArrayType) { - return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); - } - function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? getFinalArrayType(type) : type; - } - function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 ? type.elementType : neverType; - } - function isEvolvingArrayTypeList(types) { - var hasEvolvingArrayType = false; - 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; - } - hasEvolvingArrayType = true; - } - } - return hasEvolvingArrayType; - } - function getUnionOrEvolvingArrayType(types, subtypeReduction) { - return isEvolvingArrayTypeList(types) ? - getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : - getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); - } - function isEvolvingArrayOperationTarget(node) { - var root = getReferenceRoot(node); - var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 && (parent.name.text === "length" || - parent.parent.kind === 181 && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 && - parent.expression === root && - parent.parent.kind === 194 && - parent.parent.operatorToken.kind === 58 && - parent.parent.left === parent && - !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 | 2048); - return isLengthPushOrUnshift || isElementAssignment; - } - function maybeTypePredicateCall(node) { - var links = getNodeLinks(node); - if (links.maybeTypePredicate === undefined) { - links.maybeTypePredicate = getMaybeTypePredicate(node); - } - return links.maybeTypePredicate; - } - function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97) { - var funcType = checkNonNullExpression(node.expression); - if (funcType !== silentNeverType) { - var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } - } - } - return false; - } - function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { - if (initialType === void 0) { initialType = declaredType; } - var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175)) { - return declaredType; - } - var visitedFlowStart = visitedFlowCount; - var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; - var resultType = getObjectFlags(evolvedType) & 256 && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 && getTypeWithFacts(resultType, 524288).flags & 8192) { - return declaredType; - } - return resultType; - function getTypeAtFlowNode(flow) { - while (true) { - if (flow.flags & 1024) { - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; - } - } - } - var type = void 0; - if (flow.flags & 4096) { - flow.locked = true; - type = getTypeAtFlowNode(flow.antecedent); - flow.locked = false; - } - else if (flow.flags & 2048) { - flow = flow.antecedent; - continue; - } - else if (flow.flags & 16) { - type = getTypeAtFlowAssignment(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 96) { - type = getTypeAtFlowCondition(flow); - } - else if (flow.flags & 128) { - type = getTypeAtSwitchClause(flow); - } - else if (flow.flags & 12) { - if (flow.antecedents.length === 1) { - flow = flow.antecedents[0]; - continue; - } - type = flow.flags & 4 ? - getTypeAtFlowBranchLabel(flow) : - getTypeAtFlowLoopLabel(flow); - } - else if (flow.flags & 256) { - type = getTypeAtFlowArrayMutation(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 2) { - var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 && reference.kind !== 99) { - flow = container.flowNode; - continue; - } - type = initialType; - } - else { - type = convertAutoToAny(declaredType); - } - if (flow.flags & 1024) { - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; - } - return type; - } - } - function getTypeAtFlowAssignment(flow) { - var node = flow.node; - if (isMatchingReference(reference, node)) { - if (ts.getAssignmentTargetKind(node) === 2) { - var flowType = getTypeAtFlowNode(flow.antecedent); - return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); - } - if (declaredType === autoType || declaredType === autoArrayType) { - if (isEmptyArrayAssignment(node)) { - return getEvolvingArrayType(neverType); - } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); - return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; - } - if (declaredType.flags & 65536) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); - } - return declaredType; - } - if (containsMatchingReference(reference, node)) { - return declaredType; - } - return undefined; - } - function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256) { - var evolvedType_1 = type; - if (node.kind === 181) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); - } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 | 2048)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); - } - } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); - } - return flowType; - } - return undefined; - } - function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (type.flags & 8192) { - return flowType; - } - var assumeTrue = (flow.flags & 32) !== 0; - var nonEvolvingType = finalizeEvolvingArrayType(type); - var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); - if (narrowedType === nonEvolvingType) { - return flowType; - } - var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 ? silentNeverType : narrowedType; - return createFlowType(resultType, incomplete); - } - function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); - } - function getTypeAtFlowBranchLabel(flow) { - var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - if (antecedent.flags & 2048 && antecedent.lock.locked) { - continue; - } - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); - if (type === declaredType && declaredType === initialType) { - return type; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } - } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); - } - function getTypeAtFlowLoopLabel(flow) { - var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); - if (!key) { - key = getFlowCacheKey(reference); - } - var cached = cache.get(key); - if (cached) { - return cached; - } - for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), true); - } - } - var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; - flowLoopNodes[flowLoopCount] = flow; - flowLoopKeys[flowLoopCount] = key; - flowLoopTypes[flowLoopCount] = antecedentTypes; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); - flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); - var cached_1 = cache.get(key); - if (cached_1) { - return cached_1; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (type === declaredType) { - break; - } - } - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, true); - } - cache.set(key, result); - return result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 179 && - declaredType.flags & 65536 && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); - } - function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 : 2097152); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 : 2097152); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; - } - function narrowTypeByBinaryExpression(type, expr, assumeTrue) { - switch (expr.operatorToken.kind) { - case 58: - return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32: - case 33: - case 34: - case 35: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 && right_1.kind === 9) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); - } - if (right_1.kind === 189 && left_1.kind === 9) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); - } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); - } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); - } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); - } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; - } - break; - case 93: - return narrowTypeByInstanceof(type, expr, assumeTrue); - case 26: - return narrowType(type, expr.right, assumeTrue); - } - return type; - } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1) { - return type; - } - if (operator === 33 || operator === 35) { - assumeTrue = !assumeTrue; - } - var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 32 || operator === 33; - var facts = doubleEquals ? - assumeTrue ? 65536 : 524288 : - value.kind === 95 ? - assumeTrue ? 32768 : 262144 : - assumeTrue ? 16384 : 131072; - return getTypeWithFacts(type, facts); - } - if (type.flags & 16810497) { - return type; - } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); - } - if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); - } - return type; - } - function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - var target = getReferenceCandidate(typeOfExpr.expression); - if (!isMatchingReference(reference, target)) { - if (containsMatchingReference(reference, target)) { - return declaredType; - } - return type; - } - if (operator === 33 || operator === 35) { - assumeTrue = !assumeTrue; - } - if (assumeTrue && !(type.flags & 65536)) { - var targetType = typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & 540672) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } - } - } - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 : - typeofNEFacts.get(literal.text) || 8192; - return getTypeWithFacts(type, facts); - } - function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - var switchTypes = getSwitchClauseTypes(switchStatement); - if (!switchTypes.length) { - return type; - } - var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); - if (!hasDefaultClause) { - return caseType; - } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 ? defaultType : getUnionType([caseType, defaultType]); - } - function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); - if (!isMatchingReference(reference, left)) { - if (containsMatchingReference(reference, left)) { - return declaredType; - } - return type; - } - var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { - return type; - } - var targetType; - var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (prototypeProperty) { - var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (!isTypeAny(prototypePropertyType)) { - targetType = prototypePropertyType; - } - } - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } - if (!targetType) { - var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (getObjectFlags(rightType) & 16) { - constructSignatures = getSignaturesOfType(rightType, 1); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } - } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); - } - return type; - } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { - if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); - } - if (type.flags & 65536) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192)) { - return assignableType; - } - } - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); - } - function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { - return type; - } - var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; - if (!predicate) { - return type; - } - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; - if (predicateArgument) { - if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } - } - } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 || invokedExpression.kind === 179) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } - return type; - } - function narrowType(type, expr, assumeTrue) { - switch (expr.kind) { - case 71: - case 99: - case 97: - case 179: - return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181: - return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185: - return narrowType(type, expr.expression, assumeTrue); - case 194: - return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192: - if (expr.operator === 51) { - return narrowType(type, expr.operand, !assumeTrue); - } - break; - } - return type; - } - } - function getTypeOfSymbolAtLocation(symbol, location) { - if (location.kind === 71) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { - location = location.parent; - } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { - var type = getTypeOfExpression(location); - if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { - return type; - } - } - } - return getTypeOfSymbol(symbol); - } - function getControlFlowContainer(node) { - return ts.findAncestor(node.parent, function (node) { - return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 || - node.kind === 265 || - node.kind === 149; - }); - } - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304)) { - links.flags |= 4194304; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304); }); - } - function markParameterAssignments(node) { - if (node.kind === 71) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); - } - } - function isConstVariable(symbol) { - return symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; - } - function removeOptionalityFromDeclaredType(declaredType, declaration) { - var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 && - declaration.initializer && - getFalsyFlags(declaredType) & 2048 && - !(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) { - return unknownType; - } - if (symbol === argumentsSymbol) { - var container = ts.getContainingFunction(node); - if (languageVersion < 2) { - if (container.kind === 187) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); - } - else if (ts.hasModifier(container, 256)) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); - } - } - getNodeLinks(container).flags |= 8192; - return getTypeOfSymbol(symbol); - } - if (symbol.flags & 8388608 && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); - } - var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (localOrExportSymbol.flags & 32) { - var declaration_1 = localOrExportSymbol.valueDeclaration; - if (declaration_1.kind === 229 - && ts.nodeIsDecorated(declaration_1)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === declaration_1 && container.name !== node) { - getNodeLinks(declaration_1).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; - break; - } - container = ts.getContainingClass(container); - } - } - else if (declaration_1.kind === 199) { - var container = ts.getThisContainer(node, false); - while (container !== undefined) { - if (container.parent === declaration_1) { - if (container.kind === 149 && ts.hasModifier(container, 32)) { - getNodeLinks(declaration_1).flags |= 8388608; - getNodeLinks(node).flags |= 16777216; - } - break; - } - container = ts.getThisContainer(container, false); - } - } - } - checkCollisionWithCapturedSuperVariable(node, node); - checkCollisionWithCapturedThisVariable(node, node); - checkCollisionWithCapturedNewTargetVariable(node, node); - checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); - var declaration = localOrExportSymbol.valueDeclaration; - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); - return unknownType; - } - if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); - return unknownType; - } - } - if (!(localOrExportSymbol.flags & 3) || assignmentKind === 1 || !declaration) { - return type; - } - var isParameter = ts.getRootDeclaration(declaration).kind === 146; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 || - flowContainer.kind === 187 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && - (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - var assumeInitialized = isParameter || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 246) || - ts.isInAmbientContext(declaration); - var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : - type === autoType || type === autoArrayType ? undefinedType : - getNullableType(type, 2048); - var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized); - if (type === autoType || type === autoArrayType) { - if (flowType === autoType || flowType === autoArrayType) { - if (noImplicitAny) { - 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); - } - } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - return type; - } - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); - } - function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 || - (symbol.flags & (2 | 32)) === 0 || - symbol.valueDeclaration.parent.kind === 260) { - return; - } - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { - getNodeLinks(current).flags |= 65536; - } - if (container.kind === 214 && - ts.getAncestor(symbol.valueDeclaration, 227).parent === container && - isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152; - } - getNodeLinks(symbol.valueDeclaration).flags |= 262144; - } - if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072; - } - } - function isAssignedInBodyOfForStatement(node, container) { - var current = node; - while (current.parent.kind === 185) { - current = current.parent; - } - var isAssigned = false; - if (ts.isAssignmentTarget(current)) { - isAssigned = true; - } - else if ((current.parent.kind === 192 || current.parent.kind === 193)) { - var expr = current.parent; - isAssigned = expr.operator === 43 || expr.operator === 44; - } - if (!isAssigned) { - return false; - } - return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); - } - function captureLexicalThis(node, container) { - getNodeLinks(node).flags |= 2; - if (container.kind === 149 || container.kind === 152) { - var classNode = container.parent; - getNodeLinks(classNode).flags |= 4; - } - else { - getNodeLinks(container).flags |= 4; - } - } - function findFirstSuperCall(n) { - if (ts.isSuperCall(n)) { - return n; - } - else if (ts.isFunctionLike(n)) { - return undefined; - } - return ts.forEachChild(n, findFirstSuperCall); - } - function getSuperCallInConstructor(constructor) { - var links = getNodeLinks(constructor); - if (links.hasSuperCall === undefined) { - links.superCall = findFirstSuperCall(constructor.body); - links.hasSuperCall = links.superCall ? true : false; - } - return links.superCall; - } - function classDeclarationExtendsNull(classDecl) { - var classSymbol = getSymbolOfNode(classDecl); - var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); - return baseConstructorType === nullWideningType; - } - function checkThisBeforeSuper(node, container, diagnosticMessage) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - if (!superCall || superCall.end > node.pos) { - error(node, diagnosticMessage); - } - } - } - function checkThisExpression(node) { - var container = ts.getThisContainer(node, true); - var needToCaptureLexicalThis = false; - if (container.kind === 152) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - if (container.kind === 187) { - container = ts.getThisContainer(container, false); - needToCaptureLexicalThis = (languageVersion < 2); - } - switch (container.kind) { - case 233: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); - break; - case 232: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - break; - case 152: - if (isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); - } - break; - case 149: - case 148: - if (ts.getModifierFlags(container) & 32) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); - } - break; - case 144: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); - break; - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node, container); - } - if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - if (container.kind === 186 && - container.parent.kind === 194 && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { - var className = container.parent - .left - .expression - .expression; - var classSymbol = checkExpression(className).symbol; - if (classSymbol && classSymbol.members && (classSymbol.flags & 16)) { - return getInferredClassType(classSymbol); - } - } - var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); - if (thisType) { - return thisType; - } - } - if (ts.isClassLike(container.parent)) { - var symbol = getSymbolOfNode(container.parent); - var type = ts.hasModifier(container, 32) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type); - } - if (ts.isInJavaScriptFile(node)) { - var type = getTypeForThisExpressionFromJSDoc(container); - if (type && type !== unknownType) { - return type; - } - } - if (noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; - } - function getTypeForThisExpressionFromJSDoc(node) { - var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 279) { - var jsDocFunctionType = jsdocType; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 282) { - return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); - } - } - } - function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146; }); - } - function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 && node.parent.expression === node; - var container = ts.getSuperContainer(node, true); - var needToCaptureLexicalThis = false; - if (!isCallExpression) { - while (container && container.kind === 187) { - container = ts.getSuperContainer(container, true); - needToCaptureLexicalThis = languageVersion < 2; - } - } - var canUseSuperExpression = isLegalUsageOfSuperExpression(container); - var nodeCheckFlag = 0; - if (!canUseSuperExpression) { - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144; }); - if (current && current.kind === 144) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); - } - else if (isCallExpression) { - error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); - } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); - } - else { - error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); - } - return unknownType; - } - if (!isCallExpression && container.kind === 152) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); - } - if ((ts.getModifierFlags(container) & 32) || isCallExpression) { - nodeCheckFlag = 512; - } - else { - nodeCheckFlag = 256; - } - getNodeLinks(node).flags |= nodeCheckFlag; - if (container.kind === 151 && ts.getModifierFlags(container) & 256) { - if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096; - } - else { - getNodeLinks(container).flags |= 2048; - } - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node.parent, container); - } - if (container.parent.kind === 178) { - if (languageVersion < 2) { - error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); - return unknownType; - } - else { - return anyType; - } - } - var classLikeDeclaration = container.parent; - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } - if (container.kind === 152 && isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); - return unknownType; - } - return nodeCheckFlag === 512 - ? getBaseConstructorTypeOfClass(classType) - : getTypeWithThisArgument(baseClassType, classType.thisType); - function isLegalUsageOfSuperExpression(container) { - if (!container) { - return false; - } - if (isCallExpression) { - return container.kind === 152; - } - else { - if (ts.isClassLike(container.parent) || container.parent.kind === 178) { - if (ts.getModifierFlags(container) & 32) { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154; - } - else { - return container.kind === 151 || - container.kind === 150 || - container.kind === 153 || - container.kind === 154 || - container.kind === 149 || - container.kind === 148 || - container.kind === 152; - } - } - } - return false; - } - } - function getContainingObjectLiteral(func) { - return (func.kind === 151 || - func.kind === 153 || - func.kind === 154) && func.parent.kind === 178 ? func.parent : - func.kind === 186 && func.parent.kind === 261 ? func.parent.parent : - undefined; - } - function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 && type.target === globalThisType ? type.typeArguments[0] : undefined; - } - function getThisTypeFromContextualType(type) { - return mapType(type, function (t) { - return t.flags & 131072 ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); - }); - } - function getContextualThisParameterType(func) { - if (func.kind === 187) { - return undefined; - } - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var thisParameter = contextualSignature.thisParameter; - if (thisParameter) { - return getTypeOfSymbol(thisParameter); - } - } - } - if (noImplicitThis) { - var containingLiteral = getContainingObjectLiteral(func); - if (containingLiteral) { - var contextualType = getApparentTypeOfContextualType(containingLiteral); - var literal = containingLiteral; - var type = contextualType; - while (type) { - var thisType = getThisTypeFromContextualType(type); - if (thisType) { - return instantiateType(thisType, getContextualMapper(containingLiteral)); - } - if (literal.parent.kind !== 261) { - break; - } - literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); - } - return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); - } - if (func.parent.kind === 194 && func.parent.operatorToken.kind === 58) { - var target = func.parent.left; - if (target.kind === 179 || target.kind === 180) { - return checkExpressionCached(target.expression); - } - } - } - return undefined; - } - function getContextuallyTypedParameterType(parameter) { - var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; - } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; - } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } - } - } - return undefined; - } - function getContextualTypeForInitializerExpression(node) { - var declaration = node.parent; - if (node === declaration.initializer) { - if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.kind === 146) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, true, false); - } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176 && - parentDeclaration.type && - !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); - } - } - } - } - return undefined; - } - function getContextualTypeForReturnExpression(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return undefined; - } - var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) - : contextualReturnType; - } - return undefined; - } - function getContextualTypeForYieldOperand(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); - if (contextualReturnType) { - return node.asteriskToken - ? contextualReturnType - : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2) !== 0); - } - } - return undefined; - } - function isInParameterInitializerBeforeContainingFunction(node) { - while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } - function getContextualReturnType(functionDecl) { - if (functionDecl.type || - functionDecl.kind === 152 || - functionDecl.kind === 153 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 154))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); - } - var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { - return getReturnTypeOfSignature(signature); - } - return undefined; - } - function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); - if (argIndex >= 0) { - var signature = getResolvedOrAnySignature(callTarget); - return getTypeAtPosition(signature, argIndex); - } - return undefined; - } - function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183) { - return getContextualTypeForArgument(template.parent, substitutionExpression); - } - return undefined; - } - function getContextualTypeForBinaryOperand(node) { - var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (operator >= 58 && operator <= 70) { - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0) { - return undefined; - } - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } - } - else if (operator === 54) { - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); - } - return type; - } - else if (operator === 53 || operator === 26) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } - } - return undefined; - } - function getTypeOfPropertyOfContextualType(type, name) { - return mapType(type, function (t) { - var prop = t.flags & 229376 ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; - }); - } - function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); - } - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } - function getContextualTypeForObjectLiteralMethod(node) { - ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { - return undefined; - } - return getContextualTypeForObjectLiteralElement(node); - } - function getContextualTypeForObjectLiteralElement(element) { - var objectLiteral = element.parent; - var type = getApparentTypeOfContextualType(objectLiteral); - if (type) { - if (!ts.hasDynamicName(element)) { - var symbolName = getSymbolOfNode(element).name; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); - if (propertyType) { - return propertyType; - } - } - return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1) || - getIndexTypeOfContextualType(type, 0); - } - return undefined; - } - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1) - || getIteratedTypeOrElementType(type, undefined, false, false, false); - } - return undefined; - } - function getContextualTypeForConditionalOperand(node) { - var conditional = node.parent; - return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; - } - function getContextualTypeForJsxExpression(node) { - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - node.parent.openingElement.attributes; - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - return getTypeOfPropertyOfType(attributesType, node.parent.name.text); - } - else if (node.parent.kind === 249) { - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - return attributesType; - } - } - function getContextualTypeForJsxAttribute(attribute) { - var attributesType = getContextualType(attribute.parent); - if (ts.isJsxAttribute(attribute)) { - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - return getTypeOfPropertyOfType(attributesType, attribute.name.text); - } - else { - return attributesType; - } - } - function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); - } - function getContextualType(node) { - if (isInsideWithStatementBody(node)) { - return undefined; - } - if (node.contextualType) { - return node.contextualType; - } - var parent = node.parent; - switch (parent.kind) { - case 226: - case 146: - case 149: - case 148: - case 176: - return getContextualTypeForInitializerExpression(node); - case 187: - case 219: - return getContextualTypeForReturnExpression(node); - case 197: - return getContextualTypeForYieldOperand(parent); - case 181: - case 182: - return getContextualTypeForArgument(parent, node); - case 184: - case 202: - return getTypeFromTypeNode(parent.type); - case 194: - return getContextualTypeForBinaryOperand(node); - case 261: - case 262: - return getContextualTypeForObjectLiteralElement(parent); - case 263: - return getApparentTypeOfContextualType(parent.parent); - case 177: - return getContextualTypeForElementExpression(node); - case 195: - return getContextualTypeForConditionalOperand(node); - case 205: - ts.Debug.assert(parent.parent.kind === 196); - return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185: - return getContextualType(parent); - case 256: - return getContextualTypeForJsxExpression(parent); - case 253: - case 255: - return getContextualTypeForJsxAttribute(parent); - case 251: - case 250: - return getAttributesTypeFromJsxOpeningLikeElement(parent); - } - return undefined; - } - function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; - } - function getNonGenericSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!signature.typeParameters && !isAritySmaller(signature, node)) { - return signature; - } - } - } - function isAritySmaller(signature, target) { - var targetParameterCount = 0; - for (; targetParameterCount < target.parameters.length; targetParameterCount++) { - var param = target.parameters[targetParameterCount]; - if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { - break; - } - } - if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { - targetParameterCount--; - } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; - } - function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 || node.kind === 187; - } - function getContextualSignatureForFunctionLikeDeclaration(node) { - return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) - ? getContextualSignature(node) - : undefined; - } - function getContextualTypeForFunctionLikeDeclaration(node) { - return ts.isObjectLiteralMethod(node) ? - getContextualTypeForObjectLiteralMethod(node) : - getApparentTypeOfContextualType(node); - } - function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); - if (!type) { - return undefined; - } - if (!(type.flags & 65536)) { - return getNonGenericSignature(type, node); - } - var signatureList; - var types = type.types; - 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) { - signatureList = [signature]; - } - else if (!compareSignaturesIdentical(signatureList[0], signature, false, true, true, compareTypesIdentical)) { - return undefined; - } - else { - signatureList.push(signature); - } - } - } - var result; - if (signatureList) { - result = cloneSignature(signatureList[0]); - result.resolvedReturnType = undefined; - result.unionSignatures = signatureList; - } - return result; - } - function checkSpreadExpression(node, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 1536); - } - var arrayOrIterableType = checkExpression(node.expression, checkMode); - return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, false, false); - } - function hasDefaultValue(node) { - return (node.kind === 176 && !!node.initializer) || - (node.kind === 194 && node.operatorToken.kind === 58); - } - function checkArrayLiteral(node, checkMode) { - var elements = node.elements; - var hasSpreadElement = false; - var elementTypes = []; - var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 198) { - var restArrayType = checkExpression(e.expression, checkMode); - var restElementType = getIndexTypeOfType(restArrayType, 1) || - getIteratedTypeOrElementType(restArrayType, undefined, false, false, false); - if (restElementType) { - elementTypes.push(restElementType); - } - } - else { - var type = checkExpressionForMutableLocation(e, checkMode); - elementTypes.push(type); - } - hasSpreadElement = hasSpreadElement || e.kind === 198; - } - if (!hasSpreadElement) { - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); - type.pattern = node; - return type; - } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - if (pattern && (pattern.kind === 175 || pattern.kind === 177)) { - var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else { - if (patternElement.kind !== 200) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(unknownType); - } - } - } - if (elementTypes.length) { - return createTupleType(elementTypes); - } - } - } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, true) : - strictNullChecks ? neverType : undefinedWideningType); - } - function isNumericName(name) { - return name.kind === 144 ? isNumericComputedName(name) : isNumericLiteralName(name.text); - } - function isNumericComputedName(name) { - return isTypeAnyOrAllConstituentTypesHaveKind(checkComputedPropertyName(name), 84); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); - } - function isInfinityOrNaNString(name) { - return name === "Infinity" || name === "-Infinity" || name === "NaN"; - } - function isNumericLiteralName(name) { - return (+name).toString() === name; - } - function checkComputedPropertyName(node) { - var links = getNodeLinks(node.expression); - if (!links.resolvedType) { - links.resolvedType = checkExpression(node.expression); - 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 { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, true); - } - } - return links.resolvedType; - } - function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { - var propTypes = []; - for (var i = 0; i < properties.length; i++) { - if (kind === 0 || isNumericName(propertyNodes[i + offset].name)) { - propTypes.push(getTypeOfSymbol(properties[i])); - } - } - var unionType = propTypes.length ? getUnionType(propTypes, true) : undefinedType; - return createIndexInfo(unionType, false); - } - function checkObjectLiteral(node, checkMode) { - var inDestructuringPattern = ts.isAssignmentTarget(node); - checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); - var propertiesArray = []; - var spread = emptyObjectType; - var propagatedFlags = 0; - var contextualType = getApparentTypeOfContextualType(node); - var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 || contextualType.pattern.kind === 178); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); - var typeFlags = 0; - var patternWithComputedProperties = false; - var hasComputedStringProperty = false; - var hasComputedNumberProperty = false; - var offset = 0; - for (var i = 0; i < node.properties.length; i++) { - var memberDecl = node.properties[i]; - var member = memberDecl.symbol; - if (memberDecl.kind === 261 || - memberDecl.kind === 262 || - ts.isObjectLiteralMethod(memberDecl)) { - var type = void 0; - if (memberDecl.kind === 261) { - type = checkPropertyAssignment(memberDecl, checkMode); - } - else if (memberDecl.kind === 151) { - type = checkObjectLiteralMethod(memberDecl, checkMode); - } - else { - ts.Debug.assert(memberDecl.kind === 262); - type = checkExpressionForMutableLocation(memberDecl.name, checkMode); - } - typeFlags |= type.flags; - var prop = createSymbol(4 | member.flags, member.name); - if (inDestructuringPattern) { - var isOptional = (memberDecl.kind === 261 && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 && memberDecl.objectAssignmentInitializer); - if (isOptional) { - prop.flags |= 67108864; - } - if (ts.hasDynamicName(memberDecl)) { - patternWithComputedProperties = true; - } - } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { - var impliedProp = getPropertyOfType(contextualType, member.name); - if (impliedProp) { - prop.flags |= impliedProp.flags & 67108864; - } - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { - error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); - } - } - prop.declarations = member.declarations; - prop.parent = member.parent; - if (member.valueDeclaration) { - prop.valueDeclaration = member.valueDeclaration; - } - prop.type = type; - prop.target = member; - member = prop; - } - else if (memberDecl.kind === 263) { - if (languageVersion < 2) { - checkExternalEmitHelpers(memberDecl, 2); - } - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - propertiesArray = []; - propertiesTable = ts.createMap(); - hasComputedStringProperty = false; - hasComputedNumberProperty = false; - typeFlags = 0; - } - var type = checkExpression(memberDecl.expression); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return unknownType; - } - spread = getSpreadType(spread, type); - offset = i + 1; - continue; - } - else { - ts.Debug.assert(memberDecl.kind === 153 || memberDecl.kind === 154); - checkNodeDeferred(memberDecl); - } - if (ts.hasDynamicName(memberDecl)) { - if (isNumericName(memberDecl.name)) { - hasComputedNumberProperty = true; - } - else { - hasComputedStringProperty = true; - } - } - else { - propertiesTable.set(member.name, member); - } - propertiesArray.push(member); - } - if (contextualTypeHasPattern) { - for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 67108864)) { - error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - propertiesTable.set(prop.name, prop); - propertiesArray.push(prop); - } - } - } - if (spread !== emptyObjectType) { - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768) { - spread.flags |= propagatedFlags; - spread.flags |= 1048576; - spread.objectFlags |= 128; - spread.symbol = node.symbol; - } - return spread; - } - return createObjectLiteralType(); - function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 4194304 | freshObjectLiteralFlag | (typeFlags & 14680064); - result.objectFlags |= 128; - if (patternWithComputedProperties) { - result.objectFlags |= 512; - } - if (inDestructuringPattern) { - result.pattern = node; - } - if (!(result.flags & 6144)) { - propagatedFlags |= (result.flags & 14680064); - } - return result; - } - } - function isValidSpreadType(type) { - return !!(type.flags & (1 | 4096 | 2048 | 16777216) || - type.flags & 32768 && !isGenericMappedType(type) || - type.flags & 196608 && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); - } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); - return getJsxGlobalElementType() || anyType; - } - function checkJsxElement(node) { - checkJsxOpeningLikeElement(node.openingElement); - if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { - getIntrinsicTagSymbol(node.closingElement); - } - else { - checkExpression(node.closingElement.tagName); - } - return getJsxGlobalElementType() || anyType; - } - function isUnhyphenatedJsxName(name) { - return name.indexOf("-") < 0; - } - function isJsxIntrinsicIdentifier(tagName) { - if (tagName.kind === 179 || tagName.kind === 99) { - return false; - } - else { - return ts.isIntrinsicJsxName(tagName.text); - } - } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { - var attributes = openingLikeElement.attributes; - 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; - if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; - var attributeSymbol = createSymbol(4 | 134217728 | member.flags, member.name); - attributeSymbol.declarations = member.declarations; - attributeSymbol.parent = member.parent; - if (member.valueDeclaration) { - attributeSymbol.valueDeclaration = member.valueDeclaration; - } - attributeSymbol.type = exprType; - 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); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - var exprType = checkExpression(attributeDecl.expression); - if (isTypeAny(exprType)) { - hasSpreadAnyType = true; - } - if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); - } - else { - typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; - } - } - } - if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - } - attributesArray = getPropertiesOfType(spread); - } - 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 _c = 0, _d = parent.children; _c < _d.length; _c++) { - var child = _d[_c]; - if (child.kind === 10) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } - 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); - childrenPropSymbol.type = childrenTypes.length === 1 ? - childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); - } - } - 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); - result.flags |= 33554432 | 4194304; - result.objectFlags |= 128; - return result; - } - } - function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, undefined, checkMode); - } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; - } - function getIntrinsicTagSymbol(node) { - var links = getNodeLinks(node); - if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); - if (intrinsicProp) { - links.jsxFlags |= 1; - return links.resolvedSymbol = intrinsicProp; - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - links.jsxFlags |= 2; - return links.resolvedSymbol = intrinsicElementsType.symbol; - } - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return links.resolvedSymbol = unknownSymbol; - } - else { - if (noImplicitAny) { - error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); - } - return links.resolvedSymbol = unknownSymbol; - } - } - return links.resolvedSymbol; - } - function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536)); - if (isTypeAny(valueType)) { - return anyType; - } - var signatures = getSignaturesOfType(valueType, 1); - if (signatures.length === 0) { - signatures = getSignaturesOfType(valueType, 0); - if (signatures.length === 0) { - error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); - return unknownType; - } - } - 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); - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064); - var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); - var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); - if (propertiesOfJsxElementAttribPropInterface) { - if (propertiesOfJsxElementAttribPropInterface.length === 0) { - return ""; - } - else if (propertiesOfJsxElementAttribPropInterface.length === 1) { - return propertiesOfJsxElementAttribPropInterface[0].name; - } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { - error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, nameOfAttribPropContainer); - } - } - return undefined; - } - function getJsxElementPropertiesName() { - if (!_hasComputedJsxElementPropertiesName) { - _hasComputedJsxElementPropertiesName = true; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; - } - function getJsxElementChildrenPropertyname() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - 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)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, undefined); - 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) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - 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++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.text) && - !getPropertyOfType(paramType, attribute.name.text)) { - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - if (!result) { - result = allMatchingAttributesType; - } - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttributes !== unknownType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } - if (elementType.flags & 65536) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), true); - } - if (elementType.flags & 2) { - return anyType; - } - else if (elementType.flags & 32) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - return anyType; - } - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - return anyType; - } - else if (propsName === "") { - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - return attributesType; - } - else { - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } - } - function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { - ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var symbol = getIntrinsicTagSymbol(node); - if (links.jsxFlags & 1) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); - } - else if (links.jsxFlags & 2) { - return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0).type; - } - else { - return links.resolvedJsxElementAttributesType = unknownType; - } - } - return links.resolvedJsxElementAttributesType; - } - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, undefined, elemClassType); - } - return links.resolvedJsxElementAttributesType; - } - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, true); - } - } - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, false); - } - } - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.text); - return prop || unknownSymbol; - } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; - } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; - } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } - } - return deferredJsxStatelessElementType; - } - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); - return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; - } - function checkJsxPreconditions(errorNode) { - if ((compilerOptions.jsx || 0) === 0) { - error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); - } - if (getJsxGlobalElementType() === undefined) { - if (noImplicitAny) { - error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); - } - } - } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); - checkJsxPreconditions(node); - var reactRefErr = compilerOptions.jsx === 2 ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455, reactRefErr, reactNamespace); - if (reactSym) { - reactSym.isReferenced = true; - if (reactSym.flags & 8388608 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { - markAliasSymbolAsReferenced(reactSym); - } - } - 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) : - getCustomJsxElementAttributesType(openingLikeElement, false); - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.name) || !!(getPropertyOfType(targetAttributesType, attribute.name)); - }); - if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); - } - else { - 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) { - if (node.expression) { - var type = checkExpression(node.expression, checkMode); - if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); - } - return type; - } - else { - return unknownType; - } - } - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149; - } - function getDeclarationNodeFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; - } - function isMethodLike(symbol) { - return !!(symbol.flags & 8192 || ts.getCheckFlags(symbol) & 4); - } - function checkPropertyAccessibility(node, left, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 || node.kind === 226 ? - node.name : - node.right; - 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; - } - if (left.kind === 97) { - if (languageVersion < 2) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 && propKind !== 150; - }); - if (hasNonMethodDeclaration) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - return false; - } - } - if (flags & 128) { - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - } - if (!(flags & 24)) { - return true; - } - if (flags & 8) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - return true; - } - if (left.kind === 97) { - return true; - } - var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { - var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; - }); - if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); - return false; - } - if (flags & 32) { - return true; - } - if (type.flags & 16384 && type.isThisType) { - type = getConstraintOfTypeParameter(type); - } - if (!(getObjectFlags(getTargetType(type)) & 3 && hasBaseType(type, enclosingClass))) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); - return false; - } - return true; - } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); - } - function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144; - if (kind) { - error(errorNode, kind & 2048 ? kind & 4096 ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); - var t = getNonNullableType(type); - return t.flags & (6144 | 8192) ? unknownType : t; - } - return type; - } - function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); - } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); - } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 && isTypeAny(apparentType))) { - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 && - node.parent && node.parent.kind !== 159 && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - if (node.kind !== 179 || assignmentKind === 1 || - !(prop.flags & (3 | 4 | 98304)) && - !(prop.flags & 8192 && propType.flags & 65536)) { - return propType; - } - 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 - : node.left; - var type = checkExpression(left); - if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop) { - return checkPropertyAccessibility(node, left, type, prop); - } - } - return true; - } - function getForInVariableSymbol(node) { - var initializer = node.initializer; - if (initializer.kind === 227) { - var variable = initializer.declarations[0]; - if (variable && !ts.isBindingPattern(variable.name)) { - return getSymbolOfNode(variable); - } - } - else if (initializer.kind === 71) { - return getResolvedSymbol(initializer); - } - return undefined; - } - function hasNumericPropertyNames(type) { - return getIndexTypeOfType(type, 1) && !getIndexTypeOfType(type, 0); - } - function isForInVariableForNumericPropertyNames(expr) { - var e = ts.skipParentheses(expr); - if (e.kind === 71) { - var symbol = getResolvedSymbol(e); - if (symbol.flags & 3) { - var child = expr; - var node = expr.parent; - while (node) { - if (node.kind === 215 && - child === node.statement && - getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(getTypeOfExpression(node.expression))) { - return true; - } - child = node; - node = node.parent; - } - } - } - return false; - } - function checkIndexedAccess(node) { - var objectType = checkNonNullExpression(node.expression); - var indexExpression = node.argumentExpression; - if (!indexExpression) { - var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 && node.parent.expression === node) { - var start = ts.skipTrivia(sourceFile.text, node.expression.end); - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); - } - else { - var start = node.end - "]".length; - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); - } - return unknownType; - } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); - if (objectType === unknownType || objectType === silentNeverType) { - return objectType; - } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9) { - error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); - return unknownType; - } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === unknownType) { - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - if ((expressionType.flags & 512) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(true); - if (!globalESSymbol) { - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - 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); - } - else if (node.kind !== 147) { - ts.forEach(node.arguments, function (argument) { - checkExpression(argument); - }); - } - return anySignature; - } - function resolveErrorCall(node) { - resolveUntypedCall(node); - return unknownSignature; - } - function reorderCandidates(signatures, result) { - var lastParent; - var lastSymbol; - var cutoffIndex = 0; - var index; - var specializedIndex = -1; - var spliceIndex; - ts.Debug.assert(!result.length); - 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) { - if (lastParent && parent === lastParent) { - index++; - } - else { - lastParent = parent; - index = cutoffIndex; - } - } - else { - index = cutoffIndex = result.length; - lastParent = parent; - } - lastSymbol = symbol; - if (signature.hasLiteralTypes) { - specializedIndex++; - spliceIndex = specializedIndex; - cutoffIndex++; - } - else { - spliceIndex = index; - } - result.splice(spliceIndex, 0, signature); - } - } - function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 198) { - return i; - } - } - return -1; - } - function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; - var typeArguments; - var callIsIncomplete; - var isDecorator; - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - return true; - } - if (node.kind === 183) { - var tagExpression = node; - argCount = args.length; - typeArguments = undefined; - if (tagExpression.template.kind === 196) { - var templateExpression = tagExpression.template; - var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); - ts.Debug.assert(lastSpan !== undefined); - callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; - } - else { - var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 13); - callIsIncomplete = !!templateLiteral.isUnterminated; - } - } - else if (node.kind === 147) { - isDecorator = true; - typeArguments = undefined; - argCount = getEffectiveArgumentCount(node, undefined, signature); - } - else { - var callExpression = node; - if (!callExpression.arguments) { - ts.Debug.assert(callExpression.kind === 182); - return signature.minArgumentCount === 0; - } - argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; - callIsIncomplete = callExpression.arguments.end === callExpression.end; - typeArguments = callExpression.typeArguments; - spreadArgIndex = getSpreadArgumentIndex(args); - } - var numTypeParameters = ts.length(signature.typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { - return false; - } - if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || spreadArgIndex >= signature.minArgumentCount; - } - if (!signature.hasRestParameter && argCount > signature.parameters.length) { - return false; - } - var hasEnoughArguments = argCount >= signature.minArgumentCount; - return callIsIncomplete || hasEnoughArguments; - } - function getSingleCallSignature(type) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - return resolved.callSignatures[0]; - } - } - return undefined; - } - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, true, false); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - inferTypesWithContext(context, instantiateType(source, contextualMapper), target); - }); - return getSignatureInstantiation(signature, getInferredTypes(context)); - } - function inferTypeArguments(node, signature, args, excludeArgument, context) { - var typeParameters = signature.typeParameters; - var inferenceMapper = getInferenceMapper(context); - for (var i = 0; i < typeParameters.length; i++) { - if (!context.inferences[i].isFixed) { - context.inferredTypes[i] = undefined; - } - } - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } - var thisType = getThisTypeOfSignature(signature); - if (thisType) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypesWithContext(context, thisArgumentType, thisType); - } - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } - inferTypesWithContext(context, argType, paramType); - } - } - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); - } - } - } - getInferredTypes(context); - } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { - var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; - var mapper; - for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } - } - } - return typeArgumentsAreAssignable; - } - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - var callIsIncomplete = node.attributes.end === node.end; - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.name) && isUnhyphenatedJsxName(arg.name)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, undefined, headMessage); - } - function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); - } - var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; - var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { - return false; - } - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - if (arg === undefined || arg.kind !== 200) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - } - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { - return false; - } - } - } - return true; - } - function getThisArgumentOfCall(node) { - if (node.kind === 181) { - var callee = node.expression; - if (callee.kind === 179) { - return callee.expression; - } - else if (callee.kind === 180) { - return callee.expression; - } - } - } - function getEffectiveCallArguments(node) { - var args; - if (node.kind === 183) { - var template = node.template; - args = [undefined]; - if (template.kind === 196) { - ts.forEach(template.templateSpans, function (span) { - args.push(span.expression); - }); - } - } - else if (node.kind === 147) { - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - args = node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; - } - else { - args = node.arguments || emptyArray; - } - return args; - } - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147) { - switch (node.parent.kind) { - case 229: - case 199: - return 1; - case 149: - return 2; - case 151: - case 153: - case 154: - if (languageVersion === 0) { - return 2; - } - return signature.parameters.length >= 3 ? 3 : 2; - case 146: - return 3; - } - } - else { - return args.length; - } - } - function getEffectiveDecoratorFirstArgumentType(node) { - if (node.kind === 229) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 146) { - node = node.parent; - if (node.kind === 152) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorSecondArgumentType(node) { - if (node.kind === 229) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return unknownType; - } - if (node.kind === 146) { - node = node.parent; - if (node.kind === 152) { - return anyType; - } - } - if (node.kind === 149 || - node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - var element = node; - switch (element.name.kind) { - case 71: - case 8: - case 9: - return getLiteralType(element.name.text); - case 144: - var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return unknownType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorThirdArgumentType(node) { - if (node.kind === 229) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 146) { - return numberType; - } - if (node.kind === 149) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 151 || - node.kind === 153 || - node.kind === 154) { - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return unknownType; - } - function getEffectiveArgumentType(node, argIndex) { - if (node.kind === 147) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 183) { - return getGlobalTemplateStringsArrayType(); - } - return undefined; - } - function getEffectiveArgument(node, args, argIndex) { - if (node.kind === 147 || - (argIndex === 0 && node.kind === 183)) { - return undefined; - } - return args[argIndex]; - } - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147) { - return node.expression; - } - else if (argIndex === 0 && node.kind === 183) { - return node.template; - } - else { - return arg; - } - } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183; - var isDecorator = node.kind === 147; - var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); - var typeArguments; - if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { - typeArguments = node.typeArguments; - if (node.expression.kind !== 97) { - ts.forEach(typeArguments, checkSourceElement); - } - } - if (signatures.length === 1) { - var declaration = signatures[0].declaration; - if (declaration && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration)) { - if (containsArgumentsReference(declaration)) { - var signatureWithRest = cloneSignature(signatures[0]); - var syntheticArgsSymbol = createSymbol(3, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - signatureWithRest.parameters = ts.concatenate(signatureWithRest.parameters, [syntheticArgsSymbol]); - signatureWithRest.hasRestParameter = true; - signatures = [signatureWithRest]; - } - } - } - var candidates = candidatesOutArray || []; - reorderCandidates(signatures, candidates); - if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); - return resolveErrorCall(node); - } - var args = getEffectiveCallArguments(node); - var excludeArgument; - if (!isDecorator) { - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - } - } - } - var candidateForArgumentError; - var candidateForTypeArgumentError; - var resultOfFailedInference; - var result; - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; - if (candidates.length > 1) { - result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); - } - if (!result) { - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; - result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); - } - if (result) { - return result; - } - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - return candidateForArgumentError; - } - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); - } - else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - 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 (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } - } - 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 _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)); - } - return candidate; - } - } - } - return resolveErrorCall(node); - function chooseOverload(candidates, relation, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { - var originalCandidate = candidates_2[_i]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { - continue; - } - var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, false, ts.isInJavaScriptFile(node)) - : undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); - } - else { - inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentTypes = inferenceContext.inferredTypes; - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; - } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { - break; - } - var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; - if (index < 0) { - return candidate; - } - excludeArgument[index] = false; - } - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } - } - return undefined; - } - } - function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 97) { - var superType = checkSuperExpression(node.expression); - if (superType !== unknownType) { - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - if (baseTypeNode) { - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); - } - } - return resolveUntypedCall(node); - } - var funcType = checkNonNullExpression(node.expression); - if (funcType === silentNeverType) { - return silentNeverSignature; - } - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - if (funcType !== unknownType && node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - if (constructSignatures.length) { - error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); - } - else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - } - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - if (funcType.flags & 65536) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } - function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 1) { - var spreadIndex = getSpreadArgumentIndex(node.arguments); - if (spreadIndex >= 0) { - error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); - } - } - var expressionType = checkNonNullExpression(node.expression); - if (expressionType === silentNeverType) { - return silentNeverSignature; - } - expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { - return resolveErrorCall(node); - } - 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(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } - if (isTypeAny(expressionType)) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - var constructSignatures = getSignaturesOfType(expressionType, 1); - if (constructSignatures.length) { - if (!isConstructorAccessible(node, constructSignatures[0])) { - return resolveErrorCall(node); - } - return resolveCall(node, constructSignatures, candidatesOutArray); - } - var callSignatures = getSignaturesOfType(expressionType, 0); - if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); - } - return signature; - } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); - return resolveErrorCall(node); - } - function isConstructorAccessible(node, signature) { - if (!signature || !signature.declaration) { - return true; - } - var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - if (!(modifiers & 24)) { - return true; - } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); - var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); - } - } - if (modifiers & 8) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - if (modifiers & 16) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - return false; - } - return true; - } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { - var tagType = checkExpression(node.tag); - var apparentType = getApparentType(tagType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - function getDiagnosticHeadMessageForDecoratorResolution(node) { - switch (node.parent.kind) { - case 229: - case 199: - return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146: - return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151: - case 153: - case 154: - return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; - } - } - function resolveDecorator(node, candidatesOutArray) { - var funcType = checkExpression(node.expression); - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0); - var constructSignatures = getSignaturesOfType(apparentType, 1); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); - } - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; - } - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - if (elementType.flags & 65536) { - var types = elementType.types; - var result = void 0; - 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; - } - var callSignatures = elementType && getSignaturesOfType(elementType, 0); - if (callSignatures && callSignatures.length > 0) { - var callSignature = void 0; - callSignature = resolveCall(openingLikeElement, callSignatures, candidatesOutArray); - return callSignature; - } - return undefined; - } - function resolveSignature(node, candidatesOutArray) { - switch (node.kind) { - case 181: - return resolveCallExpression(node, candidatesOutArray); - case 182: - return resolveNewExpression(node, candidatesOutArray); - case 183: - return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147: - return resolveDecorator(node, candidatesOutArray); - case 251: - case 250: - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); - } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); - } - function getResolvedSignature(node, candidatesOutArray) { - var links = getNodeLinks(node); - var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { - return cached; - } - links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); - links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; - return result; - } - function getResolvedOrAnySignature(node) { - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); - } - function getInferredClassType(symbol) { - var links = getSymbolLinks(symbol); - if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, undefined, undefined); - } - return links.inferredClassType; - } - function checkCallExpression(node) { - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - var signature = getResolvedSignature(node); - if (node.expression.kind === 97) { - return voidType; - } - if (node.kind === 182) { - var declaration = signature.declaration; - if (declaration && - declaration.kind !== 152 && - declaration.kind !== 156 && - declaration.kind !== 161 && - !ts.isJSDocConstructSignature(declaration)) { - var funcSymbol = node.expression.kind === 71 ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.members && funcSymbol.flags & 16) { - return getInferredClassType(funcSymbol); - } - else if (noImplicitAny) { - error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); - } - return anyType; - } - } - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { - return resolveExternalModuleTypeByLiteral(node.arguments[0]); - } - return getReturnTypeOfSignature(signature); - } - function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, true)) { - return false; - } - var resolvedRequire = resolveName(node.expression, node.expression.text, 107455, undefined, undefined); - if (!resolvedRequire) { - return true; - } - if (resolvedRequire.flags & 8388608) { - return false; - } - var targetDeclarationKind = resolvedRequire.flags & 16 - ? 228 - : resolvedRequire.flags & 3 - ? 226 - : 0; - if (targetDeclarationKind !== 0) { - var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - return ts.isInAmbientContext(decl); - } - return false; - } - function checkTaggedTemplateExpression(node) { - return getReturnTypeOfSignature(getResolvedSignature(node)); - } - function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); - checkSourceElement(node.type); - var targetType = getTypeFromTypeNode(node.type); - if (produceDiagnostics && targetType !== unknownType) { - var widenedType = getWidenedType(exprType); - if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, node, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); - } - } - return targetType; - } - function checkNonNullAssertion(node) { - return getNonNullableType(checkExpression(node.expression)); - } - function checkMetaProperty(node) { - checkGrammarMetaProperty(node); - var container = ts.getNewTargetContainer(node); - if (!container) { - error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); - return unknownType; - } - else if (container.kind === 152) { - var symbol = getSymbolOfNode(container.parent); - return getTypeOfSymbol(symbol); - } - else { - var symbol = getSymbolOfNode(container); - return getTypeOfSymbol(symbol); - } - } - function getTypeOfParameter(symbol) { - var type = getTypeOfSymbol(symbol); - if (strictNullChecks) { - var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { - return getNullableType(type, 2048); - } - } - return type; - } - function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; - } - function getTypeOfFirstParameterOfSignature(signature) { - return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; - } - function assignContextualParameterTypes(signature, context, mapper, checkMode) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (checkMode === 2) { - for (var i = 0; i < len; i++) { - var declaration = signature.parameters[i].valueDeclaration; - if (declaration.type) { - inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); - } - } - } - if (context.thisParameter) { - var parameter = signature.thisParameter; - if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { - if (!parameter) { - signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper, checkMode); - } - } - for (var i = 0; i < len; i++) { - var parameter = signature.parameters[i]; - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - var parameter = ts.lastOrUndefined(signature.parameters); - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - } - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); - } - } - } - } - function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper, checkMode) { - var links = getSymbolLinks(parameter); - if (!links.type) { - links.type = instantiateType(contextualType, mapper); - var name = ts.getNameOfDeclaration(parameter.valueDeclaration); - if (links.type === emptyObjectType && - (name.kind === 174 || name.kind === 175)) { - links.type = getTypeFromBindingPattern(name); - } - assignBindingElementTypes(parameter.valueDeclaration); - } - else if (checkMode === 2) { - inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); - } - } - function getReturnTypeFromJSDocComment(func) { - var returnTag = ts.getJSDocReturnTag(func); - if (returnTag && returnTag.typeExpression) { - return getTypeFromTypeNode(returnTag.typeExpression.type); - } - return undefined; - } - function createPromiseType(promisedType) { - var globalPromiseType = getGlobalPromiseType(true); - if (globalPromiseType !== emptyGenericType) { - promisedType = getAwaitedType(promisedType) || emptyObjectType; - return createTypeReference(globalPromiseType, [promisedType]); - } - return emptyObjectType; - } - function createPromiseReturnType(func, promisedType) { - var promiseType = createPromiseType(promisedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); - return unknownType; - } - else if (!getGlobalPromiseConstructorSymbol(true)) { - error(func, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - return promiseType; - } - function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!func.body) { - return unknownType; - } - var functionFlags = ts.getFunctionFlags(func); - var type; - if (func.body.kind !== 207) { - type = checkExpressionCached(func.body, checkMode); - if (functionFlags & 2) { - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - } - else { - var types = void 0; - if (functionFlags & 1) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); - if (!types || types.length === 0) { - var iterableIteratorAny = functionFlags & 2 - ? createAsyncIterableIteratorType(anyType) - : createIterableIteratorType(anyType); - if (noImplicitAny) { - error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); - } - return iterableIteratorAny; - } - } - else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (!types) { - return functionFlags & 2 - ? createPromiseReturnType(func, neverType) - : neverType; - } - if (types.length === 0) { - return functionFlags & 2 - ? createPromiseReturnType(func, voidType) - : voidType; - } - } - type = getUnionType(types, true); - if (functionFlags & 1) { - type = functionFlags & 2 - ? createAsyncIterableIteratorType(type) - : createIterableIteratorType(type); - } - } - if (!contextualSignature) { - reportErrorsFromWidening(func, type); - } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); - } - var widenedType = getWidenedType(type); - return (functionFlags & 3) === 2 - ? createPromiseReturnType(func, widenedType) - : widenedType; - } - function checkAndAggregateYieldOperandTypes(func, checkMode) { - var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); - ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, false, (functionFlags & 2) !== 0); - } - if (functionFlags & 2) { - type = checkAwaitedType(type, expr, yieldExpression.asteriskToken - ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - }); - return aggregatedTypes; - } - function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { - return false; - } - var type = getTypeOfExpression(node.expression); - if (!isLiteralType(type)) { - return false; - } - var switchTypes = getSwitchClauseTypes(node); - if (!switchTypes.length) { - return false; - } - return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); - } - function functionHasImplicitReturn(func) { - if (!(func.flags & 128)) { - return false; - } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 && isExhaustiveSwitchStatement(lastStatement)) { - return false; - } - return true; - } - function checkAndAggregateReturnExpressionTypes(func, checkMode) { - var functionFlags = ts.getFunctionFlags(func); - var aggregatedTypes = []; - var hasReturnWithNoExpression = functionHasImplicitReturn(func); - var hasReturnOfTypeNever = false; - ts.forEachReturnStatement(func.body, function (returnStatement) { - var expr = returnStatement.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (functionFlags & 2) { - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (type.flags & 8192) { - hasReturnOfTypeNever = true; - } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - else { - hasReturnWithNoExpression = true; - } - }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 || func.kind === 187)) { - return undefined; - } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } - } - return aggregatedTypes; - } - function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { - if (!produceDiagnostics) { - return; - } - if (returnType && maybeTypeOfKind(returnType, 1 | 1024)) { - return; - } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 || !functionHasImplicitReturn(func)) { - return; - } - var hasExplicitReturn = func.flags & 256; - if (returnType && returnType.flags & 8192) { - error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); - } - else if (returnType && !hasExplicitReturn) { - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); - } - else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { - error(func.type, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); - } - else if (compilerOptions.noImplicitReturns) { - if (!returnType) { - if (!hasExplicitReturn) { - return; - } - var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { - return; - } - } - error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186) { - checkGrammarForGenerator(node); - } - if (checkMode === 1 && isContextSensitive(node)) { - checkNodeDeferred(node); - return anyFunctionType; - } - var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); - var contextSensitive = isContextSensitive(node); - var mightFixTypeParameters = contextSensitive && checkMode === 2; - if (mightFixTypeParameters || !(links.flags & 1024)) { - var contextualSignature = getContextualSignature(node); - var contextChecked = !!(links.flags & 1024); - if (mightFixTypeParameters || !contextChecked) { - links.flags |= 1024; - if (contextualSignature) { - var signature = getSignaturesOfType(type, 0)[0]; - if (contextSensitive) { - assignContextualParameterTypes(signature, contextualSignature, getContextualMapper(node), checkMode); - } - if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { - var returnType = getReturnTypeFromBody(node, checkMode); - if (!signature.resolvedReturnType) { - signature.resolvedReturnType = returnType; - } - } - } - if (!contextChecked) { - checkSignatureDeclaration(node); - checkNodeDeferred(node); - } - } - } - if (produceDiagnostics && node.kind !== 151) { - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - } - return type; - } - function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 || ts.isObjectLiteralMethod(node)); - var functionFlags = ts.getFunctionFlags(node); - var returnOrPromisedType = node.type && - ((functionFlags & 3) === 2 ? - checkAsyncFunctionReturnType(node) : - getTypeFromTypeNode(node.type)); - if ((functionFlags & 1) === 0) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (node.body) { - if (!node.type) { - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - if (node.body.kind === 207) { - checkSourceElement(node.body); - } - else { - var exprType = checkExpression(node.body); - if (returnOrPromisedType) { - if ((functionFlags & 3) === 2) { - 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); - } - else { - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); - } - } - } - registerForUnusedIdentifiersCheck(node); - } - } - function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84)) { - error(operand, diagnostic); - return false; - } - return true; - } - function isReadonlySymbol(symbol) { - 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); - } - function isReferenceToReadonlyEntity(expr, symbol) { - if (isReadonlySymbol(symbol)) { - if (symbol.flags & 4 && - (expr.kind === 179 || expr.kind === 180) && - expr.expression.kind === 99) { - var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152)) - return true; - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); - } - return true; - } - return false; - } - function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 || expr.kind === 180) { - var node = ts.skipParentheses(expr.expression); - if (node.kind === 71) { - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol.flags & 8388608) { - var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240; - } - } - } - return false; - } - function checkReferenceExpression(expr, invalidReferenceMessage) { - var node = ts.skipParentheses(expr); - if (node.kind !== 71 && node.kind !== 179 && node.kind !== 180) { - error(expr, invalidReferenceMessage); - return false; - } - return true; - } - function checkDeleteExpression(node) { - checkExpression(node.expression); - var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 && expr.kind !== 180) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); - return booleanType; - } - var links = getNodeLinks(expr); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); - } - return booleanType; - } - function checkTypeOfExpression(node) { - checkExpression(node.expression); - return typeofType; - } - function checkVoidExpression(node) { - checkExpression(node.expression); - return undefinedWideningType; - } - function checkAwaitExpression(node) { - if (produceDiagnostics) { - if (!(node.flags & 16384)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - var operandType = checkExpression(node.expression); - return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkPrefixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - if (node.operator === 38 && node.operand.kind === 8) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - switch (node.operator) { - case 37: - case 38: - case 52: - checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512)) { - error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); - } - return numberType; - case 51: - var facts = getTypeFacts(operandType) & (1048576 | 2097152); - return facts === 1048576 ? falseType : - facts === 2097152 ? trueType : - booleanType; - case 43: - case 44: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - return unknownType; - } - function checkPostfixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - function maybeTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 196608) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (maybeTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 65536) { - var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; - } - if (type.flags & 131072) { - var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 && type.symbol && isConstEnumSymbol(type.symbol); - } - function isConstEnumSymbol(symbol) { - return (symbol.flags & 128) !== 0; - } - function checkInstanceOfExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (isTypeOfKind(leftType, 8190)) { - error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0).length || - getSignaturesOfType(rightType, 1).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); - } - return booleanType; - } - function checkInExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - 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)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - return booleanType; - } - function checkObjectLiteralAssignment(node, sourceType) { - var properties = node.properties; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); - } - return sourceType; - } - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 || property.kind === 262) { - var name = property.name; - if (name.kind === 144) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1) || - getIndexTypeOfType(objectLiteralType, 0); - if (type) { - if (property.kind === 262) { - return checkDestructuringAssignment(property, type); - } - else { - return checkDestructuringAssignment(property.initializer, type); - } - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); - } - } - else if (property.kind === 263) { - if (languageVersion < 5) { - checkExternalEmitHelpers(property, 4); - } - var nonRestNames = []; - if (allProperties) { - for (var i = 0; i < allProperties.length - 1; i++) { - nonRestNames.push(allProperties[i].name); - } - } - var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); - return checkDestructuringAssignment(property.expression, type); - } - else { - error(property, ts.Diagnostics.Property_assignment_expected); - } - } - function checkArrayLiteralAssignment(node, sourceType, checkMode) { - if (languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); - } - var elementType = checkIteratedTypeOrElementType(sourceType, node, false, false) || unknownType; - var elements = node.elements; - for (var i = 0; i < elements.length; i++) { - checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); - } - return sourceType; - } - function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { - var elements = node.elements; - var element = elements[elementIndex]; - if (element.kind !== 200) { - if (element.kind !== 198) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; - if (type) { - return checkDestructuringAssignment(element, type, checkMode); - } - else { - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } - } - } - else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - else { - var restExpression = element.expression; - if (restExpression.kind === 194 && restExpression.operatorToken.kind === 58) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); - } - } - } - } - return undefined; - } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { - var target; - if (exprOrAssignment.kind === 262) { - var prop = exprOrAssignment; - if (prop.objectAssignmentInitializer) { - if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048)) { - sourceType = getTypeWithFacts(sourceType, 131072); - } - checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); - } - target = exprOrAssignment.name; - } - else { - target = exprOrAssignment; - } - if (target.kind === 194 && target.operatorToken.kind === 58) { - checkBinaryExpression(target, checkMode); - target = target.left; - } - if (target.kind === 178) { - return checkObjectLiteralAssignment(target, sourceType); - } - if (target.kind === 177) { - return checkArrayLiteralAssignment(target, sourceType, checkMode); - } - return checkReferenceAssignment(target, sourceType, checkMode); - } - function checkReferenceAssignment(target, sourceType, checkMode) { - var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 ? - ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : - ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, undefined); - } - return sourceType; - } - function isSideEffectFree(node) { - node = ts.skipParentheses(node); - switch (node.kind) { - case 71: - case 9: - case 12: - case 183: - case 196: - case 13: - case 8: - case 101: - case 86: - case 95: - case 139: - case 186: - case 199: - case 187: - case 177: - case 178: - case 189: - case 203: - case 250: - case 249: - return true; - case 195: - return isSideEffectFree(node.whenTrue) && - isSideEffectFree(node.whenFalse); - case 194: - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return false; - } - return isSideEffectFree(node.left) && - isSideEffectFree(node.right); - case 192: - case 193: - switch (node.operator) { - case 51: - case 37: - case 38: - case 52: - return true; - } - return false; - case 190: - case 184: - case 202: - default: - return false; - } - } - function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], true); - } - function checkBinaryExpression(node, checkMode) { - return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); - } - function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { - var operator = operatorToken.kind; - if (operator === 58 && (left.kind === 178 || left.kind === 177)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); - } - var leftType = checkExpression(left, checkMode); - var rightType = checkExpression(right, checkMode); - switch (operator) { - case 39: - case 40: - case 61: - case 62: - case 41: - case 63: - case 42: - case 64: - case 38: - case 60: - case 45: - case 65: - case 46: - case 66: - case 47: - case 67: - case 49: - case 69: - case 50: - case 70: - case 48: - case 68: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - var suggestedOperator = void 0; - if ((leftType.flags & 136) && - (rightType.flags & 136) && - (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { - error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); - } - else { - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); - } - } - return numberType; - case 37: - case 59: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (!isTypeOfKind(leftType, 1 | 262178) && !isTypeOfKind(rightType, 1 | 262178)) { - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - } - var resultType = void 0; - if (isTypeOfKind(leftType, 84) && isTypeOfKind(rightType, 84)) { - resultType = numberType; - } - else { - if (isTypeOfKind(leftType, 262178) || isTypeOfKind(rightType, 262178)) { - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } - } - if (!resultType) { - reportOperatorError(); - return anyType; - } - if (operator === 59) { - checkAssignmentOperator(resultType); - } - return resultType; - case 27: - case 29: - case 30: - case 31: - if (checkForDisallowedESSymbolOperand(operator)) { - leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); - rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { - reportOperatorError(); - } - } - return booleanType; - case 32: - case 33: - case 34: - case 35: - var leftIsLiteral = isLiteralType(leftType); - var rightIsLiteral = isLiteralType(rightType); - if (!leftIsLiteral || !rightIsLiteral) { - leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; - rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; - } - if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { - reportOperatorError(); - } - return booleanType; - case 93: - return checkInstanceOfExpression(left, right, leftType, rightType); - case 92: - return checkInExpression(left, right, leftType, rightType); - case 53: - return getTypeFacts(leftType) & 1048576 ? - getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : - leftType; - case 54: - return getTypeFacts(leftType) & 2097152 ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; - case 58: - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); - case 26: - if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { - error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); - } - return rightType; - } - function isEvalNode(node) { - return node.kind === 71 && node.text === "eval"; - } - function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512) ? left : - maybeTypeOfKind(rightType, 512) ? right : - undefined; - if (offendingSymbolOperand) { - error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); - return false; - } - return true; - } - function getSuggestedBooleanOperator(operator) { - switch (operator) { - case 49: - case 69: - return 54; - case 50: - case 70: - return 35; - case 48: - case 68: - return 53; - default: - return undefined; - } - } - function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 58 && operator <= 70) { - if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { - checkTypeAssignableTo(valueType, leftType, left, undefined); - } - } - } - function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); - } - } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } - function checkYieldExpression(node) { - if (produceDiagnostics) { - if (!(node.flags & 4096) || isYieldExpressionInClass(node)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - if (node.expression) { - var func = ts.getContainingFunction(node); - var functionFlags = func && ts.getFunctionFlags(func); - if (node.asteriskToken) { - if ((functionFlags & 3) === 3 && - languageVersion < 5) { - checkExternalEmitHelpers(node, 26624); - } - if ((functionFlags & 3) === 1 && - languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256); - } - } - if (functionFlags & 1) { - var expressionType = checkExpressionCached(node.expression, undefined); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, false, (functionFlags & 2) !== 0); - } - if (func.type) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(func.type), (functionFlags & 2) !== 0) || anyType; - if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 - ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionElementType, signatureElementType, node.expression, undefined); - } - else { - checkTypeAssignableTo(functionFlags & 2 - ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionType, signatureElementType, node.expression, undefined); - } - } - } - } - return anyType; - } - function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); - var type1 = checkExpression(node.whenTrue, checkMode); - var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); - } - function checkLiteralExpression(node) { - if (node.kind === 8) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8: - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101: - return trueType; - case 86: - return falseType; - } - } - function checkTemplateExpression(node) { - ts.forEach(node.templateSpans, function (templateSpan) { - checkExpression(templateSpan.expression); - }); - return stringType; - } - function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; - var checkMode = contextualMapper === identityMapper ? 1 : - contextualMapper ? 2 : 0; - var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; - return result; - } - function checkExpressionCached(node, checkMode) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var saveFlowLoopStart = flowLoopStart; - flowLoopStart = flowLoopCount; - links.resolvedType = checkExpression(node, checkMode); - flowLoopStart = saveFlowLoopStart; - } - return links.resolvedType; - } - function isTypeAssertion(node) { - node = ts.skipParentheses(node); - return node.kind === 184 || node.kind === 202; - } - function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, true); - return ts.getCombinedNodeFlags(declaration) & 2 || - ts.getCombinedModifierFlags(declaration) & 64 && !ts.isParameterPropertyDeclaration(declaration) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); - } - function isLiteralContextualType(contextualType) { - if (contextualType) { - if (contextualType.flags & 540672) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - if (constraint.flags & (2 | 4 | 8 | 16)) { - return true; - } - contextualType = constraint; - } - return maybeTypeOfKind(contextualType, (224 | 262144)); - } - return false; - } - function checkExpressionForMutableLocation(node, checkMode) { - var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); - } - function checkPropertyAssignment(node, checkMode) { - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - return checkExpressionForMutableLocation(node.initializer, checkMode); - } - function checkObjectLiteralMethod(node, checkMode) { - checkGrammarMethod(node); - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { - if (checkMode === 2) { - var signature = getSingleCallSignature(type); - if (signature && signature.typeParameters) { - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType) { - var contextualSignature = getSingleCallSignature(contextualType); - if (contextualSignature && !contextualSignature.typeParameters) { - return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); - } - } - } - } - return type; - } - function getTypeOfExpression(node, cache) { - if (node.kind === 181 && node.expression.kind !== 97 && !ts.isRequireCall(node, true)) { - var funcType = checkNonNullExpression(node.expression); - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return getReturnTypeOfSignature(signature); - } - } - return cache ? checkExpressionCached(node) : checkExpression(node); - } - function getContextFreeTypeOfExpression(node) { - var saveContextualType = node.contextualType; - node.contextualType = anyType; - var type = getTypeOfExpression(node); - node.contextualType = saveContextualType; - return type; - } - function checkExpression(node, checkMode) { - var type; - if (node.kind === 143) { - type = checkQualifiedName(node); - } - else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); - type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - if (isConstEnumObjectType(type)) { - var ok = (node.parent.kind === 179 && node.parent.expression === node) || - (node.parent.kind === 180 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 143) && isInRightSideOfImportOrExportAssignment(node)); - if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); - } - } - return type; - } - function checkExpressionWorker(node, checkMode) { - switch (node.kind) { - case 71: - return checkIdentifier(node); - case 99: - return checkThisExpression(node); - case 97: - return checkSuperExpression(node); - case 95: - return nullWideningType; - case 9: - case 8: - case 101: - case 86: - return checkLiteralExpression(node); - case 196: - return checkTemplateExpression(node); - case 13: - return stringType; - case 12: - return globalRegExpType; - case 177: - return checkArrayLiteral(node, checkMode); - case 178: - return checkObjectLiteral(node, checkMode); - case 179: - return checkPropertyAccessExpression(node); - case 180: - return checkIndexedAccess(node); - case 181: - case 182: - return checkCallExpression(node); - case 183: - return checkTaggedTemplateExpression(node); - case 185: - return checkExpression(node.expression, checkMode); - case 199: - return checkClassExpression(node); - case 186: - case 187: - return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189: - return checkTypeOfExpression(node); - case 184: - case 202: - return checkAssertion(node); - case 203: - return checkNonNullAssertion(node); - case 204: - return checkMetaProperty(node); - case 188: - return checkDeleteExpression(node); - case 190: - return checkVoidExpression(node); - case 191: - return checkAwaitExpression(node); - case 192: - return checkPrefixUnaryExpression(node); - case 193: - return checkPostfixUnaryExpression(node); - case 194: - return checkBinaryExpression(node, checkMode); - case 195: - return checkConditionalExpression(node, checkMode); - case 198: - return checkSpreadExpression(node, checkMode); - case 200: - return undefinedWideningType; - case 197: - return checkYieldExpression(node); - case 256: - return checkJsxExpression(node, checkMode); - case 249: - return checkJsxElement(node); - case 250: - return checkJsxSelfClosingElement(node); - case 254: - return checkJsxAttributes(node, checkMode); - case 251: - ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); - } - return unknownType; - } - function checkTypeParameter(node) { - if (node.expression) { - grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); - } - checkSourceElement(node.constraint); - checkSourceElement(node.default); - var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); - } - var constraintType = getConstraintOfTypeParameter(typeParameter); - var defaultType = getDefaultFromTypeParameter(typeParameter); - if (constraintType && defaultType) { - checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); - } - } - function checkParameter(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkVariableLikeDeclaration(node); - var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 && ts.nodeIsPresent(func.body))) { - error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); - } - } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { - error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); - } - if (node.name.text === "this") { - if (ts.indexOf(func.parameters, node) !== 0) { - error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); - } - if (func.kind === 152 || func.kind === 156 || func.kind === 161) { - error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); - } - } - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { - error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); - } - } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 && - param.name.text === parameter.text) { - return i; - } - } - } - return -1; - } - function checkTypePredicate(node) { - var parent = getTypePredicateParent(node); - if (!parent) { - error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - return; - } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; - if (!typePredicate) { - return; - } - var parameterName = node.parameterName; - if (ts.isThisTypePredicate(typePredicate)) { - getTypeFromThisTypeNode(parameterName); - } - else { - if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { - error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); - } - else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); - } - } - else if (parameterName) { - var hasReportedError = false; - for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name = _a[_i].name; - if (ts.isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { - hasReportedError = true; - break; - } - } - if (!hasReportedError) { - error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); - } - } - } - } - function getTypePredicateParent(node) { - switch (node.parent.kind) { - case 187: - case 155: - case 228: - case 186: - case 160: - case 151: - case 150: - var parent = node.parent; - if (node === parent.type) { - return parent; - } - } - } - function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (ts.isOmittedExpression(element)) { - continue; - } - var name = element.name; - if (name.kind === 71 && - name.text === predicateVariableName) { - error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); - return true; - } - else if (name.kind === 175 || - name.kind === 174) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { - return true; - } - } - } - } - function checkSignatureDeclaration(node) { - if (node.kind === 157) { - checkGrammarIndexSignature(node); - } - else if (node.kind === 160 || node.kind === 228 || node.kind === 161 || - node.kind === 155 || node.kind === 152 || - node.kind === 156) { - checkGrammarFunctionLikeDeclaration(node); - } - var functionFlags = ts.getFunctionFlags(node); - if (!(functionFlags & 4)) { - if ((functionFlags & 3) === 3 && languageVersion < 5) { - checkExternalEmitHelpers(node, 6144); - } - if ((functionFlags & 3) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - } - if ((functionFlags & 3) !== 0 && languageVersion < 2) { - checkExternalEmitHelpers(node, 128); - } - } - checkTypeParameters(node.typeParameters); - ts.forEach(node.parameters, checkParameter); - if (node.type) { - checkSourceElement(node.type); - } - if (produceDiagnostics) { - checkCollisionWithArgumentsInGeneratedCode(node); - if (noImplicitAny && !node.type) { - switch (node.kind) { - case 156: - error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - case 155: - error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - } - } - if (node.type) { - var functionFlags_1 = ts.getFunctionFlags(node); - 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); - } - else { - var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2) !== 0) || anyType; - var iterableIteratorInstantiation = functionFlags_1 & 2 - ? createAsyncIterableIteratorType(generatorElementType) - : createIterableIteratorType(generatorElementType); - checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); - } - } - else if ((functionFlags_1 & 3) === 2) { - checkAsyncFunctionReturnType(node); - } - } - if (noUnusedIdentifiers && !node.body) { - checkUnusedTypeParameters(node); - } - } - } - 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++) { - var member = _a[_i]; - if (member.kind === 152) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var param = _c[_b]; - if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3); - } - } - } - else { - var isStatic = ts.getModifierFlags(member) & 32; - var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { - switch (member.kind) { - case 153: - addName(names, member.name, memberName, 1); - break; - case 154: - addName(names, member.name, memberName, 2); - break; - case 149: - addName(names, member.name, memberName, 3); - break; - case 151: - addName(names, member.name, memberName, 4); - break; - } - } - } - } - function addName(names, location, name, meaning) { - var prev = names.get(name); - if (prev) { - if (prev & 4) { - if (meaning !== 4) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - else { - names.set(name, prev | meaning); - } - } - else { - names.set(name, meaning); - } - } - } - function checkClassForStaticPropertyNameConflicts(node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32; - if (isStatic && memberNameNode) { - var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); - switch (memberName) { - case "name": - case "length": - case "caller": - case "arguments": - case "prototype": - var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); - error(memberNameNode, message, memberName, className); - break; - } - } - } - } - function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148) { - var memberName = void 0; - switch (member.name.kind) { - case 9: - case 8: - case 71: - memberName = member.name.text; - break; - default: - continue; - } - if (names.get(memberName)) { - error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); - error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); - } - else { - names.set(memberName, true); - } - } - } - } - function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230) { - var nodeSymbol = getSymbolOfNode(node); - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { - return; - } - } - var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { - var seenNumericIndexer = false; - var seenStringIndexer = false; - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var declaration = decl; - if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type.kind) { - case 136: - if (!seenStringIndexer) { - seenStringIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_string_index_signature); - } - break; - case 133: - if (!seenNumericIndexer) { - seenNumericIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_number_index_signature); - } - break; - } - } - } - } - } - function checkPropertyDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); - checkVariableLikeDeclaration(node); - } - function checkMethodDeclaration(node) { - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - checkFunctionOrMethodDeclaration(node); - if (ts.getModifierFlags(node) & 128 && node.body) { - error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); - } - } - function checkConstructorDeclaration(node) { - checkSignatureDeclaration(node); - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - var symbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(symbol); - } - if (ts.nodeIsMissing(node.body)) { - return; - } - if (!produceDiagnostics) { - return; - } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } - function markThisReferencesAsErrors(n) { - if (n.kind === 99) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 && n.kind !== 228) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } - function isInstancePropertyWithInitializer(n) { - return n.kind === 149 && - !(ts.getModifierFlags(n) & 32) && - !!n.initializer; - } - var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - captureLexicalThis(node.parent, containingClassDecl); - var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); - var superCall = getSuperCallInConstructor(node); - if (superCall) { - if (classExtendsNull) { - error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); - } - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92; }); - if (superCallShouldBeFirst) { - var statements = node.body.statements; - var superCallStatement = void 0; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (statement.kind === 210 && ts.isSuperCall(statement.expression)) { - superCallStatement = statement; - break; - } - if (!ts.isPrologueDirective(statement)) { - break; - } - } - if (!superCallStatement) { - error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); - } - } - } - else if (!classExtendsNull) { - error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); - } - } - } - function checkAccessorDeclaration(node) { - if (produceDiagnostics) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - checkDecorators(node); - checkSignatureDeclaration(node); - if (node.kind === 153) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128)) { - if (!(node.flags & 256)) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); - } - } - } - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - var otherKind = node.kind === 153 ? 154 : 153; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); - if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28) !== (ts.getModifierFlags(otherAccessor) & 28)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); - } - if (ts.hasModifier(node, 128) !== ts.hasModifier(otherAccessor, 128)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); - } - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); - } - } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } - } - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } - } - function checkMissingDeclaration(node) { - checkDecorators(node); - } - function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var typeArguments; - var mapper; - var result = true; - for (var i = 0; i < typeParameters.length; i++) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); - mapper = createTypeMapper(typeParameters, typeArguments); - } - var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - } - return result; - } - function checkTypeReferenceNode(node) { - checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReference(node); - if (type !== unknownType) { - if (node.typeArguments) { - ts.forEach(node.typeArguments, checkSourceElement); - if (produceDiagnostics) { - var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; - checkTypeArgumentConstraints(typeParameters, node.typeArguments); - } - } - 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)); - } - } - } - function checkTypeQuery(node) { - getTypeFromTypeQueryNode(node); - } - function checkTypeLiteral(node) { - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - checkObjectTypeForDuplicateDeclarations(node); - } - } - function checkArrayType(node) { - checkSourceElement(node.elementType); - } - function checkTupleType(node) { - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); - } - ts.forEach(node.elementTypes, checkSourceElement); - } - function checkUnionOrIntersectionType(node) { - ts.forEach(node.types, checkSourceElement); - } - function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288)) { - return type; - } - var objectType = type.objectType; - var indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - return type; - } - if (maybeTypeOfKind(objectType, 540672) && isTypeOfKind(indexType, 84)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1)) { - return type; - } - } - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); - return type; - } - function checkIndexedAccessType(node) { - checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); - } - function checkMappedType(node) { - checkSourceElement(node.typeParameter); - checkSourceElement(node.type); - var type = getTypeFromMappedTypeNode(node); - var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); - } - function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8) && ts.isInAmbientContext(node); - } - function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedModifierFlags(n); - if (n.parent.kind !== 230 && - n.parent.kind !== 229 && - n.parent.kind !== 199 && - ts.isInAmbientContext(n)) { - if (!(flags & 2)) { - flags |= 1; - } - flags |= 2; - } - return flags & flagsToCheck; - } - function checkFunctionOrConstructorSymbol(symbol) { - if (!produceDiagnostics) { - return; - } - function getCanonicalOverload(overloads, implementation) { - var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; - return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; - } - function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { - var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; - if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); - ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; - if (deviation & 1) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - } - else if (deviation & 2) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - } - else if (deviation & (8 | 16)) { - error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - } - else if (deviation & 128) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); - } - }); - } - } - function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { - if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); - ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; - if (deviation) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); - } - }); - } - } - var flagsToCheck = 1 | 2 | 8 | 16 | 128; - var someNodeFlags = 0; - var allNodeFlags = flagsToCheck; - var someHaveQuestionToken = false; - var allHaveQuestionToken = true; - var hasOverloads = false; - var bodyDeclaration; - var lastSeenNonAmbientDeclaration; - var previousDeclaration; - var declarations = symbol.declarations; - var isConstructor = (symbol.flags & 16384) !== 0; - function reportImplementationExpectedError(node) { - if (node.name && ts.nodeIsMissing(node.name)) { - return; - } - var seen = false; - var subsequentNode = ts.forEachChild(node.parent, function (c) { - if (seen) { - return c; - } - else { - seen = c === node; - } - }); - if (subsequentNode && subsequentNode.pos === node.end) { - if (subsequentNode.kind === node.kind) { - var errorNode_1 = subsequentNode.name || subsequentNode; - if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 151 || node.kind === 150) && - (ts.getModifierFlags(node) & 32) !== (ts.getModifierFlags(subsequentNode) & 32); - if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); - } - return; - } - else if (ts.nodeIsPresent(subsequentNode.body)) { - error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); - return; - } - } - } - var errorNode = node.name || node; - if (isConstructor) { - error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); - } - else { - if (ts.getModifierFlags(node) & 128) { - error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); - } - else { - error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); - } - } - } - var duplicateFunctionDeclaration = false; - var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; - var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 || node.parent.kind === 163 || inAmbientContext; - if (inAmbientContextOrInterface) { - previousDeclaration = undefined; - } - if (node.kind === 228 || node.kind === 151 || node.kind === 150 || node.kind === 152) { - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - if (ts.nodeIsPresent(node.body) && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; - } - else { - duplicateFunctionDeclaration = true; - } - } - else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (ts.nodeIsPresent(node.body)) { - if (!bodyDeclaration) { - bodyDeclaration = node; - } - } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } - } - } - if (multipleConstructorImplementation) { - ts.forEach(declarations, function (declaration) { - error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); - }); - } - if (duplicateFunctionDeclaration) { - ts.forEach(declarations, function (declaration) { - error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); - }); - } - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128) && !lastSeenNonAmbientDeclaration.questionToken) { - reportImplementationExpectedError(lastSeenNonAmbientDeclaration); - } - if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); - if (bodyDeclaration) { - var signatures = getSignaturesOfSymbol(symbol); - var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - 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; - } - } - } - } - } - function checkExportsOnMergedDeclarations(node) { - if (!produceDiagnostics) { - return; - } - var symbol = node.localSymbol; - if (!symbol) { - symbol = getSymbolOfNode(node); - if (!(symbol.flags & 7340032)) { - return; - } - } - if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { - return; - } - var exportedDeclarationSpaces = 0; - var nonExportedDeclarationSpaces = 0; - var defaultExportedDeclarationSpaces = 0; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var d = _a[_i]; - var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 512); - if (effectiveDeclarationFlags & 1) { - if (effectiveDeclarationFlags & 512) { - defaultExportedDeclarationSpaces |= declarationSpaces; - } - else { - exportedDeclarationSpaces |= declarationSpaces; - } - } - else { - nonExportedDeclarationSpaces |= declarationSpaces; - } - } - var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; - var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; - var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; - if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { - 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); - } - } - } - function getDeclarationSpaces(d) { - switch (d.kind) { - case 230: - return 2097152; - case 233: - return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 - ? 4194304 | 1048576 - : 4194304; - case 229: - case 232: - return 2097152 | 1048576; - case 237: - var result_3 = 0; - var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - default: - return 1048576; - } - } - } - function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { - var promisedType = getPromisedTypeOfPromise(type, errorNode); - return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); - } - function getPromisedTypeOfPromise(promise, errorNode) { - if (isTypeAny(promise)) { - return undefined; - } - var typeAsPromise = promise; - if (typeAsPromise.promisedTypeOfPromise) { - return typeAsPromise.promisedTypeOfPromise; - } - if (isReferenceToType(promise, getGlobalPromiseType(false))) { - return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; - } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (isTypeAny(thenFunction)) { - return undefined; - } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0) : emptyArray; - if (thenSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); - } - return undefined; - } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288); - if (isTypeAny(onfulfilledParameterType)) { - return undefined; - } - var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0); - if (onfulfilledParameterSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); - } - return undefined; - } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), true); - } - function checkAwaitedType(type, errorNode, diagnosticMessage) { - return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; - } - function getAwaitedType(type, errorNode, diagnosticMessage) { - var typeAsAwaitable = type; - if (typeAsAwaitable.awaitedTypeOfType) { - return typeAsAwaitable.awaitedTypeOfType; - } - if (isTypeAny(type)) { - return typeAsAwaitable.awaitedTypeOfType = type; - } - if (type.flags & 65536) { - var types = void 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituentType = _a[_i]; - types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); - } - if (!types) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, true); - } - var promisedType = getPromisedTypeOfPromise(type); - if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); - } - return undefined; - } - awaitedTypeStack.push(type.id); - var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); - awaitedTypeStack.pop(); - if (!awaitedType) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = awaitedType; - } - var thenFunction = getTypeOfPropertyOfType(type, "then"); - if (thenFunction && getSignaturesOfType(thenFunction, 0).length > 0) { - if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); - error(errorNode, diagnosticMessage); - } - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = type; - } - function checkAsyncFunctionReturnType(node) { - var returnType = getTypeFromTypeNode(node.type); - if (languageVersion >= 2) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(true); - if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { - error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return unknownType; - } - } - else { - markTypeNodeAsReferenced(node.type); - if (returnType === unknownType) { - return unknownType; - } - var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); - if (promiseConstructorName === undefined) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return unknownType; - } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455, true); - var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; - if (promiseConstructorType === unknownType) { - if (promiseConstructorName.kind === 71 && promiseConstructorName.text === "Promise" && getTargetType(returnType) === getGlobalPromiseType(false)) { - error(node.type, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - else { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - } - return unknownType; - } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(true); - if (globalPromiseConstructorLikeType === emptyObjectType) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return unknownType; - } - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.text, 107455); - if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - } - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkDecorator(node) { - var signature = getResolvedSignature(node); - var returnType = getReturnTypeOfSignature(signature); - if (returnType.flags & 1) { - return; - } - var expectedReturnType; - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - var errorInfo; - switch (node.parent.kind) { - case 229: - var classSymbol = getSymbolOfNode(node.parent); - var classConstructorType = getTypeOfSymbol(classSymbol); - expectedReturnType = getUnionType([classConstructorType, voidType]); - break; - case 146: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); - break; - case 149: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); - break; - case 151: - case 153: - case 154: - var methodType = getTypeOfNode(node.parent); - var descriptorType = createTypedPropertyDescriptorType(methodType); - expectedReturnType = getUnionType([descriptorType, voidType]); - break; - } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); - } - function markTypeNodeAsReferenced(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 - && rootSymbol.flags & 8388608 - && symbolIsValue(rootSymbol) - && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - 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; - } - function checkDecorators(node) { - if (!node.decorators) { - return; - } - if (!ts.nodeCanBeDecorated(node)) { - return; - } - if (!compilerOptions.experimentalDecorators) { - error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); - } - var firstDecorator = node.decorators[0]; - checkExternalEmitHelpers(firstDecorator, 8); - if (node.kind === 146) { - checkExternalEmitHelpers(firstDecorator, 32); - } - if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16); - switch (node.kind) { - case 229: - var constructor = ts.getFirstConstructorWithBody(node); - if (constructor) { - for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - } - break; - case 151: - case 153: - case 154: - for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - case 149: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); - break; - case 146: - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - } - } - ts.forEach(node.decorators, checkDecorator); - } - function checkFunctionDeclaration(node) { - if (produceDiagnostics) { - checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function checkFunctionOrMethodDeclaration(node) { - checkDecorators(node); - checkSignatureDeclaration(node); - var functionFlags = ts.getFunctionFlags(node); - if (node.name && node.name.kind === 144) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - var symbol = getSymbolOfNode(node); - var localSymbol = node.localSymbol || symbol; - var firstDeclaration = ts.forEach(localSymbol.declarations, function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? - declaration : undefined; }); - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(localSymbol); - } - if (symbol.parent) { - if (ts.getDeclarationOfKind(symbol, node.kind) === node) { - checkFunctionOrConstructorSymbol(symbol); - } - } - } - checkSourceElement(node.body); - if ((functionFlags & 1) === 0) { - var returnOrPromisedType = node.type && (functionFlags & 2 - ? checkAsyncFunctionReturnType(node) - : getTypeFromTypeNode(node.type)); - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (produceDiagnostics && !node.type) { - if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); - } - if (functionFlags & 1 && ts.nodeIsPresent(node.body)) { - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - } - registerForUnusedIdentifiersCheck(node); - } - function registerForUnusedIdentifiersCheck(node) { - if (deferredUnusedIdentifierNodes) { - deferredUnusedIdentifierNodes.push(node); - } - } - function checkUnusedIdentifiers() { - if (deferredUnusedIdentifierNodes) { - for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { - var node = deferredUnusedIdentifierNodes_1[_i]; - switch (node.kind) { - case 265: - case 233: - checkUnusedModuleMembers(node); - break; - case 229: - case 199: - checkUnusedClassMembers(node); - checkUnusedTypeParameters(node); - break; - case 230: - checkUnusedTypeParameters(node); - break; - case 207: - case 235: - case 214: - case 215: - case 216: - checkUnusedLocalsAndParameters(node); - break; - case 152: - case 186: - case 228: - case 187: - case 151: - case 153: - case 154: - if (node.body) { - checkUnusedLocalsAndParameters(node); - } - checkUnusedTypeParameters(node); - break; - case 150: - case 155: - case 156: - case 157: - case 160: - case 161: - checkUnusedTypeParameters(node); - break; - } - } - } - } - function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - 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(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(ts.getNameOfDeclaration(d) || d, local.name); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } - function errorUnusedLocal(node, name) { - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 && - (declaration.parent.parent.kind === 215 || - declaration.parent.parent.kind === 216)) { - return; - } - } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); - } - } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 && node.text.charCodeAt(0) === 95; - } - function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 151 || member.kind === 149) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); - } - } - else if (member.kind === 152) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); - } - } - } - } - } - } - } - function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.typeParameters) { - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } - for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { - var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); - } - } - } - } - } - function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); - } - } - } - }); - } - } - function checkBlock(node) { - if (node.kind === 207) { - checkGrammarStatementInAmbientContext(node); - } - ts.forEach(node.statements, checkSourceElement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { - return; - } - ts.forEach(node.parameters, function (p) { - if (p.name && !ts.isBindingPattern(p.name) && p.name.text === argumentsSymbol.name) { - error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); - } - }); - } - function needCollisionCheckForIdentifier(node, identifier, name) { - if (!(identifier && identifier.text === name)) { - return false; - } - if (node.kind === 149 || - node.kind === 148 || - node.kind === 151 || - node.kind === 150 || - node.kind === 153 || - node.kind === 154) { - return false; - } - if (ts.isInAmbientContext(node)) { - return false; - } - var root = ts.getRootDeclaration(node); - if (root.kind === 146 && ts.nodeIsMissing(root.parent.body)) { - return false; - } - return true; - } - function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { - potentialThisCollisions.push(node); - } - } - function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { - potentialNewTargetCollisions.push(node); - } - } - function checkIfThisIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 4) { - var isDeclaration_1 = node.kind !== 71; - if (isDeclaration_1) { - 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); - } - return true; - } - }); - } - function checkIfNewTargetIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 8) { - var isDeclaration_2 = node.kind !== 71; - if (isDeclaration_2) { - 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); - } - return true; - } - }); - } - function checkCollisionWithCapturedSuperVariable(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "_super")) { - return; - } - var enclosingClass = ts.getContainingClass(node); - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { - return; - } - if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71; - if (isDeclaration_3) { - error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); - } - else { - error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); - } - } - } - function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - if (modulekind >= ts.ModuleKind.ES2015) { - return; - } - if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { - return; - } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { - return; - } - var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent)) { - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 || !needCollisionCheckForIdentifier(node, name, "Promise")) { - return; - } - if (node.kind === 233 && ts.getModuleInstanceState(node) !== 1) { - return; - } - var parent = getDeclarationContainer(node); - if (parent.kind === 265 && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024) { - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 3) !== 0 || ts.isParameterDeclaration(node)) { - return; - } - if (node.kind === 226 && !node.initializer) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol.flags & 1) { - var localDeclarationSymbol = resolveName(node, node.name.text, 3, undefined, undefined); - if (localDeclarationSymbol && - localDeclarationSymbol !== symbol && - localDeclarationSymbol.flags & 2) { - if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227); - var container = varDeclList.parent.kind === 208 && varDeclList.parent.parent - ? varDeclList.parent.parent - : undefined; - var namesShareScope = container && - (container.kind === 207 && ts.isFunctionLike(container.parent) || - container.kind === 234 || - container.kind === 233 || - container.kind === 265); - if (!namesShareScope) { - var name = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); - } - } - } - } - } - function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146) { - return; - } - var func = ts.getContainingFunction(node); - visit(node.initializer); - function visit(n) { - if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { - return; - } - if (n.kind === 179) { - return visit(n.expression); - } - else if (n.kind === 71) { - var symbol = resolveName(n, n.text, 107455 | 8388608, undefined, undefined); - if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { - return; - } - if (symbol.valueDeclaration === node) { - error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); - return; - } - var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 || - symbol.valueDeclaration.kind === 176) { - if (symbol.valueDeclaration.pos < node.pos) { - return; - } - if (ts.findAncestor(n, function (current) { - if (current === node.initializer) { - return "quit"; - } - return ts.isFunctionLike(current.parent) || - (current.parent.kind === 149 && - !(ts.hasModifier(current.parent, 32)) && - ts.isClassLike(current.parent.parent)); - })) { - return; - } - } - error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); - } - } - else { - return ts.forEachChild(n, visit); - } - } - } - function convertAutoToAny(type) { - return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; - } - function checkVariableLikeDeclaration(node) { - checkDecorators(node); - checkSourceElement(node.type); - if (node.name.kind === 144) { - checkComputedPropertyName(node.name); - if (node.initializer) { - checkExpressionCached(node.initializer); - } - } - if (node.kind === 176) { - if (node.parent.kind === 174 && languageVersion < 5) { - checkExternalEmitHelpers(node, 4); - } - if (node.propertyName && node.propertyName.kind === 144) { - checkComputedPropertyName(node.propertyName); - } - var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); - var name = node.propertyName || node.name; - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); - } - } - if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 && languageVersion < 2 && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512); - } - ts.forEach(node.name.elements, checkSourceElement); - } - if (node.initializer && ts.getRootDeclaration(node).kind === 146 && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { - error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); - return; - } - if (ts.isBindingPattern(node.name)) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); - checkParameterInitializer(node); - } - return; - } - var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); - if (node === symbol.valueDeclaration) { - if (node.initializer && node.parent.parent.kind !== 215) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); - checkParameterInitializer(node); - } - } - else { - var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.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(node.name), typeToString(type), typeToString(declarationType)); - } - if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); - } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - 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)); - } - } - if (node.kind !== 149 && node.kind !== 148) { - checkExportsOnMergedDeclarations(node); - if (node.kind === 226 || node.kind === 176) { - checkVarDeclaredNamesNotShadowed(node); - } - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 && right.kind === 226) || - (left.kind === 226 && right.kind === 146)) { - return true; - } - if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { - return false; - } - var interestingFlags = 8 | - 16 | - 256 | - 128 | - 64 | - 32; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); - } - function checkVariableDeclaration(node) { - checkGrammarVariableDeclaration(node); - return checkVariableLikeDeclaration(node); - } - function checkBindingElement(node) { - checkGrammarBindingElement(node); - return checkVariableLikeDeclaration(node); - } - function checkVariableStatement(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); - ts.forEach(node.declarationList.declarations, checkSourceElement); - } - function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - if (node.modifiers && node.parent.kind === 178) { - if (ts.getFunctionFlags(node) & 2) { - if (node.modifiers.length > 1) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - } - function checkExpressionStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - } - function checkIfStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209) { - error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); - } - checkSourceElement(node.elseStatement); - } - function checkDoStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkSourceElement(node.statement); - checkExpression(node.expression); - } - function checkWhileStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.statement); - } - function checkForStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227) { - checkGrammarVariableDeclarationList(node.initializer); - } - } - if (node.initializer) { - if (node.initializer.kind === 227) { - ts.forEach(node.initializer.declarations, checkVariableDeclaration); - } - else { - checkExpression(node.initializer); - } - } - if (node.condition) - checkExpression(node.condition); - if (node.incrementor) - checkExpression(node.incrementor); - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForOfStatement(node) { - checkGrammarForInOrForOfStatement(node); - if (node.kind === 216) { - if (node.awaitModifier) { - var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { - checkExternalEmitHelpers(node, 16384); - } - } - else if (compilerOptions.downlevelIteration && languageVersion < 2) { - checkExternalEmitHelpers(node, 256); - } - } - if (node.initializer.kind === 227) { - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - if (varExpr.kind === 177 || varExpr.kind === 178) { - checkDestructuringAssignment(varExpr, iteratedType || unknownType); - } - else { - var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); - if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, undefined); - } - } - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInStatement(node) { - checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); - if (node.initializer.kind === 227) { - var variable = node.initializer.declarations[0]; - if (variable && ts.isBindingPattern(variable.name)) { - error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 || varExpr.kind === 178) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); - } - else { - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); - } - } - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 | 540672 | 16777216)) { - error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInOrForOfVariableDeclaration(iterationStatement) { - var variableDeclarationList = iterationStatement.initializer; - if (variableDeclarationList.declarations.length >= 1) { - var decl = variableDeclarationList.declarations[0]; - checkVariableDeclaration(decl); - } - } - function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { - var expressionType = checkNonNullExpression(rhsExpression); - return checkIteratedTypeOrElementType(expressionType, rhsExpression, true, awaitModifier !== undefined); - } - function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable) { - if (isTypeAny(inputType)) { - return inputType; - } - return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, true) || anyType; - } - function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, checkAssignability) { - var uplevelIteration = languageVersion >= 2; - var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; - if (uplevelIteration || downlevelIteration || allowAsyncIterable) { - var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterable, allowAsyncIterable, checkAssignability); - if (iteratedType || uplevelIteration) { - return iteratedType; - } - } - var arrayType = inputType; - var reportedError = false; - var hasStringConstituent = false; - if (allowStringInput) { - if (arrayType.flags & 65536) { - var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178); }); - if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, true); - } - } - else if (arrayType.flags & 262178) { - arrayType = neverType; - } - hasStringConstituent = arrayType !== inputType; - if (hasStringConstituent) { - if (languageVersion < 1) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); - reportedError = true; - } - } - if (arrayType.flags & 8192) { - return stringType; - } - } - } - if (!isArrayLikeType(arrayType)) { - if (errorNode && !reportedError) { - var diagnostic = !allowStringInput || hasStringConstituent - ? downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type - : downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; - error(errorNode, diagnostic, typeToString(arrayType)); - } - return hasStringConstituent ? stringType : undefined; - } - var arrayElementType = getIndexTypeOfType(arrayType, 1); - if (hasStringConstituent && arrayElementType) { - if (arrayElementType.flags & 262178) { - return stringType; - } - return getUnionType([arrayElementType, stringType], true); - } - return arrayElementType; - } - function getIteratedTypeOfIterable(type, errorNode, isAsyncIterable, allowNonAsyncIterables, checkAssignability) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterable = type; - if (isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable) { - return isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable; - } - if (isAsyncIterable) { - if (isReferenceToType(type, getGlobalAsyncIterableType(false)) || - isReferenceToType(type, getGlobalAsyncIterableIteratorType(false))) { - return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; - } - } - if (!isAsyncIterable || allowNonAsyncIterables) { - if (isReferenceToType(type, getGlobalIterableType(false)) || - isReferenceToType(type, getGlobalIterableIteratorType(false))) { - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0] - : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; - } - } - var iteratorMethodSignatures; - var isNonAsyncIterable = false; - if (isAsyncIterable) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0); - } - if (!isAsyncIterable || (allowNonAsyncIterables && !ts.some(iteratorMethodSignatures))) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0); - isNonAsyncIterable = true; - } - if (ts.some(iteratorMethodSignatures)) { - var iteratorMethodReturnType = getUnionType(ts.map(iteratorMethodSignatures, getReturnTypeOfSignature), true); - var iteratedType = getIteratedTypeOfIterator(iteratorMethodReturnType, errorNode, !isNonAsyncIterable); - if (checkAssignability && errorNode && iteratedType) { - checkTypeAssignableTo(type, isNonAsyncIterable - ? createIterableType(iteratedType) - : createAsyncIterableType(iteratedType), errorNode); - } - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; - } - if (errorNode) { - error(errorNode, isAsyncIterable - ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); - } - return undefined; - } - function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterator = type; - if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { - return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; - } - var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; - if (isReferenceToType(type, getIteratorType(false))) { - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] - : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; - } - var nextMethod = getTypeOfPropertyOfType(type, "next"); - if (isTypeAny(nextMethod)) { - return undefined; - } - var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0) : emptyArray; - if (nextMethodSignatures.length === 0) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.An_async_iterator_must_have_a_next_method - : ts.Diagnostics.An_iterator_must_have_a_next_method); - } - return undefined; - } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), true); - if (isTypeAny(nextResult)) { - return undefined; - } - if (isAsyncIterator) { - nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); - if (isTypeAny(nextResult)) { - return undefined; - } - } - var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); - if (!nextValue) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property - : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue - : typeAsIterator.iteratedTypeOfIterator = nextValue; - } - function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { - if (isTypeAny(returnType)) { - return undefined; - } - return getIteratedTypeOfIterable(returnType, undefined, isAsyncGenerator, false, false) - || getIteratedTypeOfIterator(returnType, undefined, isAsyncGenerator); - } - function checkBreakOrContinueStatement(node) { - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); - } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 153 && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154))); - } - function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3) === 2 - ? getPromisedTypeOfPromise(returnType) - : returnType; - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 | 1); - } - function checkReturnStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } - } - var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1) { - return; - } - if (func.kind === 154) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } - } - else if (func.kind === 152) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); - } - } - } - else if (func.kind !== 152 && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - } - function checkWithStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 16384) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); - } - } - checkExpression(node.expression); - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; - var end = node.statement.pos; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); - } - } - function checkSwitchStatement(node) { - checkGrammarStatementInAmbientContext(node); - var firstDefaultClause; - var hasDuplicateDefaultClause = false; - var expressionType = checkExpression(node.expression); - var expressionIsLiteral = isLiteralType(expressionType); - ts.forEach(node.caseBlock.clauses, function (clause) { - if (clause.kind === 258 && !hasDuplicateDefaultClause) { - if (firstDefaultClause === undefined) { - firstDefaultClause = clause; - } - else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); - hasDuplicateDefaultClause = true; - } - } - if (produceDiagnostics && clause.kind === 257) { - var caseClause = clause; - var caseType = checkExpression(caseClause.expression); - var caseIsLiteral = isLiteralType(caseType); - var comparedExpressionType = expressionType; - if (!caseIsLiteral || !expressionIsLiteral) { - caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; - comparedExpressionType = getBaseTypeOfLiteralType(expressionType); - } - if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { - checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, undefined); - } - } - ts.forEach(clause.statements, checkSourceElement); - }); - if (node.caseBlock.locals) { - registerForUnusedIdentifiersCheck(node.caseBlock); - } - } - function checkLabeledStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - ts.findAncestor(node.parent, function (current) { - if (ts.isFunctionLike(current)) { - return "quit"; - } - if (current.kind === 222 && current.label.text === node.label.text) { - var sourceFile = ts.getSourceFileOfNode(node); - grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); - return true; - } - }); - } - checkSourceElement(node.statement); - } - function checkThrowStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.expression === undefined) { - grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); - } - } - if (node.expression) { - checkExpression(node.expression); - } - } - function checkTryStatement(node) { - checkGrammarStatementInAmbientContext(node); - checkBlock(node.tryBlock); - var catchClause = node.catchClause; - if (catchClause) { - if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.type) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); - } - else if (catchClause.variableDeclaration.initializer) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); - } - else { - var blockLocals_1 = catchClause.block.locals; - if (blockLocals_1) { - ts.forEachKey(catchClause.locals, function (caughtName) { - var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2) !== 0) { - grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); - } - }); - } - } - } - checkBlock(catchClause.block); - } - if (node.finallyBlock) { - checkBlock(node.finallyBlock); - } - } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0); - var stringIndexType = getIndexTypeOfType(type, 0); - var numberIndexType = getIndexTypeOfType(type, 1); - if (stringIndexType || numberIndexType) { - ts.forEach(getPropertiesOfObjectType(type), function (prop) { - var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1); - }); - if (getObjectFlags(type) & 1 && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (!(ts.getModifierFlags(member) & 32) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); - } - } - } - } - var errorNode; - if (stringIndexType && numberIndexType) { - errorNode = declaredNumberIndexer || declaredStringIndexer; - if (!errorNode && (getObjectFlags(type) & 2)) { - var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0) && getIndexTypeOfType(base, 1); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; - } - } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { - error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); - } - function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { - return; - } - var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { - return; - } - var errorNode; - if (propDeclaration && - (propDeclaration.kind === 194 || - ts.getNameOfDeclaration(propDeclaration).kind === 144 || - prop.parent === containingType.symbol)) { - errorNode = propDeclaration; - } - else if (indexDeclaration) { - errorNode = indexDeclaration; - } - else if (getObjectFlags(containingType) & 2) { - var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; - } - if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 - ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 - : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; - error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); - } - } - } - function checkTypeNameIsReserved(name, message) { - switch (name.text) { - case "any": - case "number": - case "boolean": - case "string": - case "symbol": - case "void": - case "object": - error(name, message, name.text); - } - } - function checkTypeParameters(typeParameterDeclarations) { - if (typeParameterDeclarations) { - var seenDefault = false; - for (var i = 0; i < typeParameterDeclarations.length; i++) { - var node = typeParameterDeclarations[i]; - checkTypeParameter(node); - if (produceDiagnostics) { - if (node.default) { - seenDefault = true; - } - else if (seenDefault) { - error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); - } - for (var j = 0; j < i; j++) { - if (typeParameterDeclarations[j].symbol === node.symbol) { - error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); - } - } - } - } - } - } - function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { - return; - } - var links = getSymbolLinks(symbol); - if (!links.typeParametersChecked) { - links.typeParametersChecked = true; - var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { - return; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { - var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); - } - } - } - } - function areTypeParametersIdentical(declarations, typeParameters) { - var maxTypeArgumentCount = ts.length(typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - var numTypeParameters = ts.length(declaration.typeParameters); - if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { - return false; - } - for (var i = 0; i < numTypeParameters; i++) { - var source = declaration.typeParameters[i]; - var target = typeParameters[i]; - if (source.name.text !== target.symbol.name) { - return false; - } - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; - } - var sourceDefault = source.default && getTypeFromTypeNode(source.default); - var targetDefault = getDefaultFromTypeParameter(target); - if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { - return false; - } - } - } - return true; - } - function checkClassExpression(node) { - checkClassLikeDeclaration(node); - checkNodeDeferred(node); - return getTypeOfSymbol(getSymbolOfNode(node)); - } - function checkClassExpressionDeferred(node) { - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); - } - checkClassLikeDeclaration(node); - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassLikeDeclaration(node) { - checkGrammarClassLikeDeclaration(node); - checkDecorators(node); - if (node.name) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkTypeParameters(node.typeParameters); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - var staticType = getTypeOfSymbol(symbol); - checkTypeParameterListsIdentical(symbol); - checkClassForDuplicateDeclarations(node); - if (!ts.isInAmbientContext(node)) { - checkClassForStaticPropertyNameConflicts(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - if (languageVersion < 2) { - checkExternalEmitHelpers(baseTypeNode.parent, 1); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length && produceDiagnostics) { - var baseType_1 = baseTypes[0]; - var baseConstructorType = getBaseConstructorTypeOfClass(type); - var staticBaseType = getApparentType(baseConstructorType); - checkBaseTypeAccessibility(staticBaseType, baseTypeNode); - checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { - ts.forEach(baseTypeNode.typeArguments, checkSourceElement); - for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { - var constructor = _a[_i]; - if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { - break; - } - } - } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 && !isMixinConstructorType(staticType)) { - error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); - } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32) && !(baseConstructorType.flags & 540672)) { - var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); - } - } - checkKindsOfPropertyMemberOverrides(type, baseType_1); - } - } - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); - if (implementedTypeNodes) { - for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { - var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { - error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(typeRefNode); - if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); - if (t !== unknownType) { - if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); - } - else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); - } - } - } - } - } - if (produceDiagnostics) { - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - } - } - function checkBaseTypeAccessibility(type, node) { - var signatures = getSignaturesOfType(type, 1); - if (signatures.length) { - var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); - } - } - } - } - function getTargetSymbol(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; }); - } - function getClassOrInterfaceDeclarationsOfSymbol(symbol) { - return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 || d.kind === 230; - }); - } - function checkKindsOfPropertyMemberOverrides(type, baseType) { - var baseProperties = getPropertiesOfType(baseType); - for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; - var base = getTargetSymbol(baseProperty); - if (base.flags & 16777216) { - continue; - } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - 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) { - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128))) { - if (derivedClassDecl.kind === 199) { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); - } - else { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); - } - } - } - else { - var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 8 || derivedDeclarationFlags & 8) { - continue; - } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 && derived.flags & 98308) { - continue; - } - var errorMessage = void 0; - if (isMethodLike(base)) { - if (derived.flags & 98304) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; - } - } - else if (base.flags & 4) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; - } - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); - } - } - } - } - function isAccessor(kind) { - return kind === 153 || kind === 154; - } - function checkInheritedPropertiesAreIdentical(type, typeNode) { - var baseTypes = getBaseTypes(type); - if (baseTypes.length < 2) { - return true; - } - var seen = ts.createMap(); - ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.name, { prop: p, containingType: type }); }); - var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; - var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; - var existing = seen.get(prop.name); - if (!existing) { - seen.set(prop.name, { prop: prop, containingType: base }); - } - else { - var isInheritedProperty = existing.containingType !== type; - if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { - ok = false; - var typeName1 = typeToString(existing.containingType); - var typeName2 = typeToString(base); - var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); - } - } - } - } - return ok; - } - function checkInterfaceDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); - checkTypeParameters(node.typeParameters); - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - checkTypeParameterListsIdentical(symbol); - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230); - if (node === firstInterfaceDecl) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - if (checkInheritedPropertiesAreIdentical(type, node.name)) { - for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { - var baseType = _a[_i]; - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); - } - checkIndexConstraints(type); - } - } - checkObjectTypeForDuplicateDeclarations(node); - } - ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { - error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(heritageElement); - }); - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); - } - } - function checkTypeAliasDeclaration(node) { - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); - checkTypeParameters(node.typeParameters); - checkSourceElement(node.type); - } - function computeEnumMemberValues(node) { - var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 16384)) { - nodeLinks.flags |= 16384; - var autoValue = 0; - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var value = computeMemberValue(member, autoValue); - getNodeLinks(member).enumMemberValue = value; - autoValue = typeof value === "number" ? value + 1 : undefined; - } - } - } - 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); - } - } - 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; - } - } - 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; - case 47: return left >>> right; - case 45: return left << right; - case 50: return left ^ right; - case 39: return left * right; - case 41: return left / right; - case 37: return left + right; - case 38: return left - right; - case 42: return left % right; - } - } - 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); - } - } - 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; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkExportsOnMergedDeclarations(node); - computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); - } - var enumSymbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); - if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { - ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); - } - }); - } - var seenEnumMissingInitialInitializer_1 = false; - ts.forEach(enumSymbol.declarations, function (declaration) { - if (declaration.kind !== 232) { - return false; - } - var enumDeclaration = declaration; - if (!enumDeclaration.members.length) { - return false; - } - var firstEnumMember = enumDeclaration.members[0]; - if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer_1) { - error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); - } - else { - seenEnumMissingInitialInitializer_1 = true; - } - } - }); - } - } - function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 229 || - (declaration.kind === 228 && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { - return declaration; - } - } - return undefined; - } - function inSameLexicalScope(node1, node2) { - var container1 = ts.getEnclosingBlockScopeContainer(node1); - var container2 = ts.getEnclosingBlockScopeContainer(node2); - if (isGlobalSourceFile(container1)) { - return isGlobalSourceFile(container2); - } - else if (isGlobalSourceFile(container2)) { - return false; - } - else { - return container1 === container2; - } - } - function checkModuleDeclaration(node) { - if (produceDiagnostics) { - var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); - if (isGlobalAugmentation && !inAmbientContext) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); - } - var isAmbientExternalModule = ts.isAmbientModule(node); - var contextErrorMessage = isAmbientExternalModule - ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file - : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; - if (checkGrammarModuleElementContext(node, contextErrorMessage)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9) { - grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - } - if (ts.isIdentifier(node.name)) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - if (symbol.flags & 512 - && symbol.declarations.length > 1 - && !inAmbientContext - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { - var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); - if (firstNonAmbientClassOrFunc) { - if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); - } - else if (node.pos < firstNonAmbientClassOrFunc.pos) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); - } - } - var mergedClass = ts.getDeclarationOfKind(symbol, 229); - if (mergedClass && - inSameLexicalScope(node, mergedClass)) { - getNodeLinks(node).flags |= 32768; - } - } - if (isAmbientExternalModule) { - if (ts.isExternalModuleAugmentation(node)) { - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728); - if (checkBody && node.body) { - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - checkModuleAugmentationElement(statement, isGlobalAugmentation); - } - } - } - else if (isGlobalSourceFile(node.parent)) { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); - } - } - else { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else { - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); - } - } - } - } - if (node.body) { - checkSourceElement(node.body); - if (!ts.isGlobalScopeAugmentation(node)) { - registerForUnusedIdentifiersCheck(node); - } - } - } - function checkModuleAugmentationElement(node, isGlobalAugmentation) { - switch (node.kind) { - case 208: - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - checkModuleAugmentationElement(decl, isGlobalAugmentation); - } - break; - case 243: - case 244: - grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); - break; - case 237: - case 238: - grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); - break; - case 176: - case 226: - var name = node.name; - if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; - checkModuleAugmentationElement(el, isGlobalAugmentation); - } - break; - } - case 229: - case 232: - case 228: - case 230: - case 233: - case 231: - if (isGlobalAugmentation) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol) { - var reportError = !(symbol.flags & 134217728); - if (!reportError) { - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } - break; - } - } - function getFirstIdentifier(node) { - switch (node.kind) { - case 71: - return node; - case 143: - do { - node = node.left; - } while (node.kind !== 71); - return node; - case 179: - do { - node = node.expression; - } while (node.kind !== 71); - return node; - } - } - function checkExternalImportOrExportDeclaration(node) { - var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9) { - error(moduleName, ts.Diagnostics.String_literal_expected); - return false; - } - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 ? - ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : - ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); - return false; - } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - if (!isTopLevelInExternalModuleAugmentation(node)) { - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; - } - } - return true; - } - function checkAliasSymbol(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target !== unknownSymbol) { - var excludedMeanings = (symbol.flags & (107455 | 1048576) ? 107455 : 0) | - (symbol.flags & 793064 ? 793064 : 0) | - (symbol.flags & 1920 ? 1920 : 0); - if (target.flags & excludedMeanings) { - var message = node.kind === 246 ? - ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : - 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) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkAliasSymbol(node); - } - function checkImportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); - } - if (checkExternalImportOrExportDeclaration(node)) { - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - checkImportBinding(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240) { - checkImportBinding(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, checkImportBinding); - } - } - } - } - } - function checkImportEqualsDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - return; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { - checkImportBinding(node); - if (ts.getModifierFlags(node) & 1) { - markExportAsReferenced(node); - } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveAlias(getSymbolOfNode(node)); - if (target !== unknownSymbol) { - if (target.flags & 107455) { - var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 | 1920).flags & 1920)) { - error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); - } - } - if (target.flags & 793064) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); - } - } - } - else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - grammarErrorOnNode(node, ts.Diagnostics.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); - } - } - } - } - function checkExportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); - } - if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { - ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { - error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); - } - } - else { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); - } - } - } - } - function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 || node.parent.kind === 234 || node.parent.kind === 233; - if (!isInAppropriateContext) { - grammarErrorOnFirstToken(node, errorMessage); - } - return !isInAppropriateContext; - } - function checkExportSpecifier(node) { - checkAliasSymbol(node); - if (!node.parent.parent.moduleSpecifier) { - var exportedName = node.propertyName || node.name; - var symbol = resolveName(exportedName, exportedName.text, 107455 | 793064 | 1920 | 8388608, undefined, undefined); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); - } - else { - markExportAsReferenced(node); - } - } - } - function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { - return; - } - var container = node.parent.kind === 265 ? node.parent : node.parent.parent; - if (container.kind === 233 && !ts.isAmbientModule(container)) { - if (node.isExportEquals) { - error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); - } - else { - error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); - } - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); - } - if (node.expression.kind === 71) { - markExportAsReferenced(node); - } - else { - checkExpressionCached(node.expression); - } - checkExternalModuleExports(container); - if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); - } - else if (modulekind === ts.ModuleKind.System) { - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); - } - } - } - function hasExportedMembers(moduleSymbol) { - return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); - } - function checkExternalModuleExports(node) { - var moduleSymbol = getSymbolOfNode(node); - var links = getSymbolLinks(moduleSymbol); - if (!links.exportsChecked) { - var exportEqualsSymbol = moduleSymbol.exports.get("export="); - if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { - var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration)) { - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); - } - } - var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - if (flags & (1920 | 64 | 384)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); - if (flags & 524288 && exportedDeclarationsCount <= 2) { - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); - } - } - } - }); - links.exportsChecked = true; - } - function isNotOverload(declaration) { - return (declaration.kind !== 228 && declaration.kind !== 151) || - !!declaration.body; - } - } - function checkSourceElement(node) { - if (!node) { - return; - } - var kind = node.kind; - if (cancellationToken) { - switch (kind) { - case 233: - case 229: - case 230: - case 228: - cancellationToken.throwIfCancellationRequested(); - } - } - switch (kind) { - case 145: - return checkTypeParameter(node); - case 146: - return checkParameter(node); - case 149: - case 148: - return checkPropertyDeclaration(node); - case 160: - case 161: - case 155: - case 156: - return checkSignatureDeclaration(node); - case 157: - return checkSignatureDeclaration(node); - case 151: - case 150: - return checkMethodDeclaration(node); - case 152: - return checkConstructorDeclaration(node); - case 153: - case 154: - return checkAccessorDeclaration(node); - case 159: - return checkTypeReferenceNode(node); - case 158: - return checkTypePredicate(node); - case 162: - return checkTypeQuery(node); - case 163: - return checkTypeLiteral(node); - case 164: - return checkArrayType(node); - case 165: - return checkTupleType(node); - case 166: - case 167: - return checkUnionOrIntersectionType(node); - case 168: - case 170: - return checkSourceElement(node.type); - case 171: - return checkIndexedAccessType(node); - case 172: - return checkMappedType(node); - case 228: - return checkFunctionDeclaration(node); - case 207: - case 234: - return checkBlock(node); - case 208: - return checkVariableStatement(node); - case 210: - return checkExpressionStatement(node); - case 211: - return checkIfStatement(node); - case 212: - return checkDoStatement(node); - case 213: - return checkWhileStatement(node); - case 214: - return checkForStatement(node); - case 215: - return checkForInStatement(node); - case 216: - return checkForOfStatement(node); - case 217: - case 218: - return checkBreakOrContinueStatement(node); - case 219: - return checkReturnStatement(node); - case 220: - return checkWithStatement(node); - case 221: - return checkSwitchStatement(node); - case 222: - return checkLabeledStatement(node); - case 223: - return checkThrowStatement(node); - case 224: - return checkTryStatement(node); - case 226: - return checkVariableDeclaration(node); - case 176: - return checkBindingElement(node); - case 229: - return checkClassDeclaration(node); - case 230: - return checkInterfaceDeclaration(node); - case 231: - return checkTypeAliasDeclaration(node); - case 232: - return checkEnumDeclaration(node); - case 233: - return checkModuleDeclaration(node); - case 238: - return checkImportDeclaration(node); - case 237: - return checkImportEqualsDeclaration(node); - case 244: - return checkExportDeclaration(node); - case 243: - return checkExportAssignment(node); - case 209: - checkGrammarStatementInAmbientContext(node); - return; - case 225: - checkGrammarStatementInAmbientContext(node); - return; - case 247: - return checkMissingDeclaration(node); - } - } - function checkNodeDeferred(node) { - if (deferredNodes) { - deferredNodes.push(node); - } - } - function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; - switch (node.kind) { - case 186: - case 187: - case 151: - case 150: - checkFunctionExpressionOrObjectLiteralMethodDeferred(node); - break; - case 153: - case 154: - checkAccessorDeclaration(node); - break; - case 199: - checkClassExpressionDeferred(node); - break; - } - } - } - function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); - checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); - } - function checkSourceFileWorker(node) { - var links = getNodeLinks(node); - if (!(links.flags & 1)) { - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { - return; - } - checkGrammarSourceFile(node); - potentialThisCollisions.length = 0; - potentialNewTargetCollisions.length = 0; - deferredNodes = []; - deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; - ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); - if (ts.isExternalModule(node)) { - registerForUnusedIdentifiersCheck(node); - } - if (!node.isDeclarationFile) { - checkUnusedIdentifiers(); - } - deferredNodes = undefined; - deferredUnusedIdentifierNodes = undefined; - if (ts.isExternalOrCommonJsModule(node)) { - checkExternalModuleExports(node); - } - if (potentialThisCollisions.length) { - ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); - potentialThisCollisions.length = 0; - } - if (potentialNewTargetCollisions.length) { - ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); - potentialNewTargetCollisions.length = 0; - } - links.flags |= 1; - } - } - function getDiagnostics(sourceFile, ct) { - try { - cancellationToken = ct; - return getDiagnosticsWorker(sourceFile); - } - finally { - cancellationToken = undefined; - } - } - function getDiagnosticsWorker(sourceFile) { - throwIfNonDiagnosticsProducing(); - if (sourceFile) { - var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; - checkSourceFile(sourceFile); - var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); - var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { - var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); - return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); - } - else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { - return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); - } - return semanticDiagnostics; - } - ts.forEach(host.getSourceFiles(), checkSourceFile); - return diagnostics.getDiagnostics(); - } - function getGlobalDiagnostics() { - throwIfNonDiagnosticsProducing(); - return diagnostics.getGlobalDiagnostics(); - } - function throwIfNonDiagnosticsProducing() { - if (!produceDiagnostics) { - throw new Error("Trying to get diagnostics from a type checker that does not produce them."); - } - } - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } - function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { - return []; - } - var symbols = ts.createMap(); - var memberFlags = 0; - populateSymbols(); - return symbolsToArray(symbols); - function populateSymbols() { - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 265: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - case 233: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931); - break; - case 232: - copySymbols(getSymbolOfNode(location).exports, meaning & 8); - break; - case 199: - var className = location.name; - if (className) { - copySymbol(location.symbol, meaning); - } - case 229: - case 230: - if (!(memberFlags & 32)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064); - } - break; - case 186: - var funcName = location.name; - if (funcName) { - copySymbol(location.symbol, meaning); - } - break; - } - if (ts.introducesArgumentsExoticObject(location)) { - copySymbol(argumentsSymbol, meaning); - } - memberFlags = ts.getModifierFlags(location); - location = location.parent; - } - copySymbols(globals, meaning); - } - function copySymbol(symbol, meaning) { - if (symbol.flags & meaning) { - var id = symbol.name; - if (!symbols.has(id)) { - symbols.set(id, symbol); - } - } - } - function copySymbols(source, meaning) { - if (meaning) { - source.forEach(function (symbol) { - copySymbol(symbol, meaning); - }); - } - } - } - function isTypeDeclarationName(name) { - return name.kind === 71 && - isTypeDeclaration(name.parent) && - name.parent.name === name; - } - function isTypeDeclaration(node) { - switch (node.kind) { - case 145: - case 229: - case 230: - case 231: - case 232: - return true; - } - } - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 143) { - node = node.parent; - } - return node.parent && (node.parent.kind === 159 || node.parent.kind === 277); - } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 179) { - node = node.parent; - } - return node.parent && node.parent.kind === 201; - } - function forEachEnclosingClass(node, callback) { - var result; - while (true) { - node = ts.getContainingClass(node); - if (!node) - break; - if (result = callback(node)) - break; - } - return result; - } - function isNodeWithinClass(node, classDeclaration) { - return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); - } - function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143) { - nodeOnRightSide = nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 237) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 243) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; - } - return undefined; - } - function isInRightSideOfImportOrExportAssignment(node) { - return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; - } - function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); - switch (specialPropertyAssignmentKind) { - case 1: - case 3: - return getSymbolOfNode(entityName.parent); - case 4: - case 2: - case 5: - return getSymbolOfNode(entityName.parent.parent); - } - } - function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { - if (ts.isDeclarationName(entityName)) { - return getSymbolOfNode(entityName.parent); - } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 && - entityName.parent === entityName.parent.parent.left) { - var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); - if (specialPropertyAssignmentSymbol) { - return specialPropertyAssignmentSymbol; - } - } - if (entityName.parent.kind === 243 && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, 107455 | 793064 | 1920 | 8388608); - } - if (entityName.kind !== 179 && isInRightSideOfImportOrExportAssignment(entityName)) { - var importEqualsDeclaration = ts.getAncestor(entityName, 237); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, true); - } - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = 0; - if (entityName.parent.kind === 201) { - meaning = 793064; - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455; - } - } - else { - meaning = 1920; - } - meaning |= 8388608; - var entityNameSymbol = resolveEntityName(entityName, meaning); - if (entityNameSymbol) { - return entityNameSymbol; - } - } - if (ts.isPartOfExpression(entityName)) { - if (ts.nodeIsMissing(entityName)) { - return undefined; - } - if (entityName.kind === 71) { - if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { - return getIntrinsicTagSymbol(entityName.parent); - } - return resolveEntityName(entityName, 107455, false, true); - } - else if (entityName.kind === 179) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkPropertyAccessExpression(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - else if (entityName.kind === 143) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkQualifiedName(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - } - else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 159 || entityName.parent.kind === 277) ? 793064 : 1920; - return resolveEntityName(entityName, meaning, false, true); - } - else if (entityName.parent.kind === 253) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 158) { - return resolveEntityName(entityName, 1); - } - return undefined; - } - function getSymbolAtLocation(node) { - if (node.kind === 265) { - return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; - } - if (isInsideWithStatementBody(node)) { - return undefined; - } - if (isDeclarationNameOrImportPropertyName(node)) { - return getSymbolOfNode(node.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); - } - if (node.kind === 71) { - if (isInRightSideOfImportOrExportAssignment(node)) { - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - } - else if (node.parent.kind === 176 && - node.parent.parent.kind === 174 && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); - if (propertyDeclaration) { - return propertyDeclaration; - } - } - } - switch (node.kind) { - case 71: - case 179: - case 143: - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99: - var container = ts.getThisContainer(node, false); - if (ts.isFunctionLike(container)) { - var sig = getSignatureFromDeclaration(container); - if (sig.thisParameter) { - return sig.thisParameter; - } - } - case 97: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; - case 169: - return getTypeFromTypeNode(node).symbol; - case 123: - var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152) { - return constructorDeclaration.parent.symbol; - } - return undefined; - case 9: - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { - return resolveExternalModuleName(node, node); - } - case 8: - if (node.parent.kind === 180 && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); - } - break; - } - return undefined; - } - function getShorthandAssignmentValueSymbol(location) { - if (location && location.kind === 262) { - return resolveEntityName(location.name, 107455 | 8388608); - } - return undefined; - } - function getExportSpecifierLocalTargetSymbol(node) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 | 793064 | 1920 | 8388608); - } - function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { - return unknownType; - } - if (ts.isPartOfTypeNode(node)) { - var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; - } - if (ts.isPartOfExpression(node)) { - return getRegularTypeOfExpression(node); - } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); - } - if (isTypeDeclaration(node)) { - var symbol = getSymbolOfNode(node); - return getDeclaredTypeOfSymbol(symbol); - } - if (isTypeDeclarationName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - } - if (ts.isDeclaration(node)) { - var symbol = getSymbolOfNode(node); - return getTypeOfSymbol(symbol); - } - if (isDeclarationNameOrImportPropertyName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); - } - if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, true); - } - if (isInRightSideOfImportOrExportAssignment(node)) { - var symbol = getSymbolAtLocation(node); - var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); - return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); - } - return unknownType; - } - function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 || expr.kind === 177); - if (expr.parent.kind === 216) { - var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - if (expr.parent.kind === 194) { - var iteratedType = getTypeOfExpression(expr.parent.right); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - if (expr.parent.kind === 261) { - var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); - } - ts.Debug.assert(expr.parent.kind === 177); - var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); - } - function getPropertySymbolOfDestructuringAssignment(location) { - var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); - return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); - } - function getRegularTypeOfExpression(expr) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { - expr = expr.parent; - } - return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); - } - function getParentTypeOfClassElement(node) { - var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 - ? getTypeOfSymbol(classSymbol) - : getDeclaredTypeOfSymbol(classSymbol); - } - function getAugmentedPropertiesOfType(type) { - type = getApparentType(type); - var propsByName = createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0).length || getSignaturesOfType(type, 1).length) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName.has(p.name)) { - propsByName.set(p.name, p); - } - }); - } - return getNamedMembers(propsByName); - } - function getRootSymbols(symbol) { - 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_4.push(symbol); - } - }); - return symbols_4; - } - else if (symbol.flags & 134217728) { - if (symbol.leftSpread) { - var links = symbol; - return getRootSymbols(links.leftSpread).concat(getRootSymbols(links.rightSpread)); - } - if (symbol.syntheticOrigin) { - return getRootSymbols(symbol.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } - } - return [symbol]; - } - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var isPropertyName_1 = node.parent.kind === 179 && node.parent.name === node; - return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; - } - } - return false; - } - function moduleExportsSomeValue(moduleReferenceExpression) { - var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return true; - } - var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - var symbolLinks = getSymbolLinks(moduleSymbol); - if (symbolLinks.exportsSomeValue === undefined) { - symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455) - : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); - } - return symbolLinks.exportsSomeValue; - function isValue(s) { - s = resolveSymbol(s); - return s && !!(s.flags & 107455); - } - } - function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; - } - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node, isNameOfModuleOrEnumDeclaration(node)); - if (symbol) { - if (symbol.flags & 1048576) { - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol_1 = getParentOfSymbol(symbol); - if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 && parentSymbol_1.valueDeclaration.kind === 265) { - var symbolFile = parentSymbol_1.valueDeclaration; - var referenceFile = ts.getSourceFileOfNode(node); - var symbolIsUmdExport = symbolFile !== referenceFile; - return symbolIsUmdExport ? undefined : symbolFile; - } - return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); - } - } - } - } - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && symbol.flags & 8388608) { - return getDeclarationOfAliasSymbol(symbol); - } - } - return undefined; - } - function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418) { - var links = getSymbolLinks(symbol); - if (links.isDeclarationWithCollidingName === undefined) { - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (ts.isStatementWithLocals(container)) { - var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.name, 107455, undefined, undefined)) { - links.isDeclarationWithCollidingName = true; - } - else if (nodeLinks_1.flags & 131072) { - var isDeclaredInLoop = nodeLinks_1.flags & 262144; - var inLoopInitializer = ts.isIterationStatement(container, false); - var inLoopBodyBlock = container.kind === 207 && ts.isIterationStatement(container.parent, false); - links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); - } - else { - links.isDeclarationWithCollidingName = false; - } - } - } - return links.isDeclarationWithCollidingName; - } - return false; - } - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { - return symbol.valueDeclaration; - } - } - } - return undefined; - } - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); - if (node) { - var symbol = getSymbolOfNode(node); - if (symbol) { - return isSymbolOfDeclarationWithCollidingName(symbol); - } - } - return false; - } - function isValueAliasDeclaration(node) { - switch (node.kind) { - case 237: - case 239: - case 240: - case 242: - case 246: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244: - var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243: - return node.expression - && node.expression.kind === 71 - ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) - : true; - } - return false; - } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 || !ts.isInternalModuleImportEqualsDeclaration(node)) { - return false; - } - var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); - return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); - } - function isAliasResolvedToValue(symbol) { - var target = resolveAlias(symbol); - if (target === unknownSymbol) { - return true; - } - return target.flags & 107455 && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); - } - function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; - } - function isReferencedAliasDeclaration(node, checkChildren) { - if (ts.isAliasSymbolDeclaration(node)) { - var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { - return true; - } - } - if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); - } - return false; - } - function isImplementationOfOverload(node) { - if (ts.nodeIsPresent(node.body)) { - var symbol = getSymbolOfNode(node); - var signaturesOfSymbol = getSignaturesOfSymbol(symbol); - return signaturesOfSymbol.length > 1 || - (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); - } - return false; - } - function isRequiredInitializedParameter(parameter) { - return strictNullChecks && - !isOptionalParameter(parameter) && - parameter.initializer && - !(ts.getModifierFlags(parameter) & 92); - } - function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; - } - function getEnumMemberValue(node) { - computeEnumMemberValues(node.parent); - return getNodeLinks(node).enumMemberValue; - } - function canHaveConstantValue(node) { - switch (node.kind) { - case 264: - case 179: - case 180: - return true; - } - return false; - } - function getConstantValue(node) { - if (node.kind === 264) { - return getEnumMemberValue(node); - } - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol && (symbol.flags & 8)) { - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); - } - } - return undefined; - } - function isFunctionType(type) { - return type.flags & 32768 && getSignaturesOfType(type, 0).length > 0; - } - function getTypeReferenceSerializationKind(typeName, location) { - var valueSymbol = resolveEntityName(typeName, 107455, true, false, location); - var typeSymbol = resolveEntityName(typeName, 793064, true, false, location); - if (valueSymbol && valueSymbol === typeSymbol) { - var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(false); - if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { - return ts.TypeReferenceSerializationKind.Promise; - } - var constructorType = getTypeOfSymbol(valueSymbol); - if (constructorType && isConstructorType(constructorType)) { - return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; - } - } - if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - var type = getDeclaredTypeOfSymbol(typeSymbol); - if (type === unknownType) { - return ts.TypeReferenceSerializationKind.Unknown; - } - else if (type.flags & 1) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - else if (isTypeOfKind(type, 1024 | 6144 | 8192)) { - return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; - } - else if (isTypeOfKind(type, 136)) { - return ts.TypeReferenceSerializationKind.BooleanType; - } - else if (isTypeOfKind(type, 84)) { - return ts.TypeReferenceSerializationKind.NumberLikeType; - } - else if (isTypeOfKind(type, 262178)) { - return ts.TypeReferenceSerializationKind.StringLikeType; - } - else if (isTupleType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else if (isTypeOfKind(type, 512)) { - return ts.TypeReferenceSerializationKind.ESSymbolType; - } - else if (isFunctionType(type)) { - return ts.TypeReferenceSerializationKind.TypeWithCallSignature; - } - else if (isArrayType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else { - return ts.TypeReferenceSerializationKind.ObjectType; - } - } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { - var symbol = getSymbolOfNode(declaration); - var type = symbol && !(symbol.flags & (2048 | 131072)) - ? getWidenedLiteralType(getTypeOfSymbol(symbol)) - : unknownType; - if (flags & 4096) { - type = getNullableType(type, 2048); - } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { - var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); - } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name) { - return globals.has(name); - } - function getReferencedValueSymbol(reference, startInDeclarationContainer) { - var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; - if (resolvedSymbol) { - return resolvedSymbol; - } - var location = reference; - if (startInDeclarationContainer) { - var parent = reference.parent; - if (ts.isDeclaration(parent) && reference === parent.name) { - location = getDeclarationContainer(parent); - } - } - return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); - } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); - if (reference) { - var symbol = getReferencedValueSymbol(reference); - if (symbol) { - return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; - } - } - } - return undefined; - } - function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 && type.flags & 1048576); - } - return false; - } - function writeLiteralConstValue(node, writer) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); - } - function createResolver() { - var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); - var fileToDirective; - if (resolvedTypeReferenceDirectives) { - fileToDirective = ts.createFileMap(); - resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { - if (!resolvedDirective) { - return; - } - var file = host.getSourceFile(resolvedDirective.resolvedFileName); - fileToDirective.set(file.path, key); - }); - } - return { - getReferencedExportContainer: getReferencedExportContainer, - getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, - isDeclarationWithCollidingName: isDeclarationWithCollidingName, - isValueAliasDeclaration: function (node) { - node = ts.getParseTreeNode(node); - return node ? isValueAliasDeclaration(node) : true; - }, - hasGlobalName: hasGlobalName, - isReferencedAliasDeclaration: function (node, checkChildren) { - node = ts.getParseTreeNode(node); - return node ? isReferencedAliasDeclaration(node, checkChildren) : true; - }, - getNodeCheckFlags: function (node) { - node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; - }, - isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, - isDeclarationVisible: isDeclarationVisible, - isImplementationOfOverload: isImplementationOfOverload, - isRequiredInitializedParameter: isRequiredInitializedParameter, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, - isSymbolAccessible: isSymbolAccessible, - isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - collectLinkedAliases: collectLinkedAliases, - getReferencedValueDeclaration: getReferencedValueDeclaration, - getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, - isOptionalParameter: isOptionalParameter, - moduleExportsSomeValue: moduleExportsSomeValue, - isArgumentsLocalBinding: isArgumentsLocalBinding, - getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, - getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, - isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } - }; - function getTypeReferenceDirectivesForEntityName(node) { - if (!fileToDirective) { - return undefined; - } - var meaning = (node.kind === 179) || (node.kind === 71 && isInTypeQuery(node)) - ? 107455 | 1048576 - : 793064 | 1920; - var symbol = resolveEntityName(node, meaning, true); - return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; - } - function getTypeReferenceDirectivesForSymbol(symbol, meaning) { - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { - return undefined; - } - var typeReferenceDirectives; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); - if (typeReferenceDirective) { - (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); - } - else { - return undefined; - } - } - } - return typeReferenceDirectives; - } - function isSymbolFromTypeDeclarationFile(symbol) { - if (!symbol.declarations) { - return false; - } - var current = symbol; - while (true) { - var parent = getParentOfSymbol(current); - if (parent) { - current = parent; - } - else { - break; - } - } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 && current.flags & 512) { - return false; - } - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.contains(file.path)) { - return true; - } - } - return false; - } - } - function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, undefined); - if (!moduleSymbol) { - return undefined; - } - return ts.getDeclarationOfKind(moduleSymbol, 265); - } - function initializeTypeChecker() { - for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); - } - var augmentations; - for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); - } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); - } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); - } - if (file.symbol && file.symbol.globalExports) { - var source = file.symbol.globalExports; - source.forEach(function (sourceSymbol, id) { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); - } - }); - } - } - if (augmentations) { - for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { - var list = augmentations_1[_d]; - for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { - var augmentation = list_1[_e]; - mergeModuleAugmentation(augmentation); - } - } - } - addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); - getSymbolLinks(undefinedSymbol).type = undefinedWideningType; - getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", 0, true); - getSymbolLinks(unknownSymbol).type = unknownType; - globalArrayType = getGlobalType("Array", 1, true); - globalObjectType = getGlobalType("Object", 0, true); - globalFunctionType = getGlobalType("Function", 0, true); - globalStringType = getGlobalType("String", 0, true); - globalNumberType = getGlobalType("Number", 0, true); - globalBooleanType = getGlobalType("Boolean", 0, true); - globalRegExpType = getGlobalType("RegExp", 0, true); - anyArrayType = createArrayType(anyType); - autoArrayType = createArrayType(autoType); - globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", 1); - anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined("ThisType", 1); - } - function checkExternalEmitHelpers(location, helpers) { - if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { - var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { - var helpersModule = resolveHelpersModule(sourceFile, location); - if (helpersModule !== unknownSymbol) { - var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 16384; helper <<= 1) { - if (uncheckedHelpers & helper) { - var name = getHelperName(helper); - var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); - if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); - } - } - } - } - requestedExternalEmitHelpers |= helpers; - } - } - } - function getHelperName(helper) { - switch (helper) { - case 1: return "__extends"; - case 2: return "__assign"; - case 4: return "__rest"; - case 8: return "__decorate"; - case 16: return "__metadata"; - case 32: return "__param"; - case 64: return "__awaiter"; - case 128: return "__generator"; - case 256: return "__values"; - case 512: return "__read"; - case 1024: return "__spread"; - case 2048: return "__await"; - case 4096: return "__asyncGenerator"; - case 8192: return "__asyncDelegator"; - case 16384: return "__asyncValues"; - default: ts.Debug.fail("Unrecognized helper."); - } - } - function resolveHelpersModule(node, errorNode) { - if (!externalHelpersModule) { - externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; - } - return externalHelpersModule; - } - function checkGrammarDecorators(node) { - if (!node.decorators) { - return false; - } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 && !ts.nodeIsPresent(node.body)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); - } - } - else if (node.kind === 153 || node.kind === 154) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); - } - } - return false; - } - function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; - } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; - var flags = 0; - for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { - var modifier = _a[_i]; - if (modifier.kind !== 131) { - if (node.kind === 148 || node.kind === 150) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); - } - if (node.kind === 157) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); - } - } - switch (modifier.kind) { - case 76: - if (node.kind !== 232 && node.parent.kind === 229) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76)); - } - break; - case 114: - case 113: - case 112: - var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113) { - lastProtected = modifier; - } - else if (modifier.kind === 112) { - lastPrivate = modifier; - } - if (flags & 28) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); - } - else if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); - } - else if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); - } - else if (node.parent.kind === 234 || node.parent.kind === 265) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); - } - else if (flags & 128) { - if (modifier.kind === 112) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); - } - else { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); - } - } - flags |= ts.modifierToFlag(modifier.kind); - break; - case 115: - if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); - } - else if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); - } - else if (node.parent.kind === 234 || node.parent.kind === 265) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); - } - else if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - flags |= 32; - lastStatic = modifier; - break; - case 131: - if (flags & 64) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); - } - else if (node.kind !== 149 && node.kind !== 148 && node.kind !== 157 && node.kind !== 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); - } - flags |= 64; - lastReadonly = modifier; - break; - case 84: - if (flags & 1) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); - } - else if (flags & 2) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); - } - else if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); - } - else if (node.parent.kind === 229) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); - } - flags |= 1; - break; - case 124: - if (flags & 2) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); - } - else if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.parent.kind === 229) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); - } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234) { - return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); - } - flags |= 2; - lastDeclare = modifier; - break; - case 117: - if (flags & 128) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); - } - if (node.kind !== 229) { - if (node.kind !== 151 && - node.kind !== 149 && - node.kind !== 153 && - node.kind !== 154) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); - } - if (!(node.parent.kind === 229 && ts.getModifierFlags(node.parent) & 128)) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); - } - if (flags & 32) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - if (flags & 8) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); - } - } - flags |= 128; - break; - case 120: - if (flags & 256) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); - } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.kind === 146) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); - } - flags |= 256; - lastAsync = modifier; - break; - } - } - if (node.kind === 152) { - if (flags & 32) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); - } - if (flags & 128) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); - } - else if (flags & 256) { - return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); - } - else if (flags & 64) { - return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); - } - return; - } - else if ((node.kind === 238 || node.kind === 237) && flags & 2) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); - } - else if (node.kind === 146 && (flags & 92) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); - } - else if (node.kind === 146 && (flags & 92) && node.dotDotDotToken) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); - } - if (flags & 256) { - return checkGrammarAsyncModifier(node, lastAsync); - } - } - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 153: - case 154: - case 152: - case 149: - case 148: - case 151: - case 150: - case 157: - case 233: - case 238: - case 237: - case 244: - case 243: - case 186: - case 187: - case 146: - return false; - default: - if (node.parent.kind === 234 || node.parent.kind === 265) { - return false; - } - switch (node.kind) { - case 228: - return nodeHasAnyModifiersExcept(node, 120); - case 229: - return nodeHasAnyModifiersExcept(node, 117); - case 230: - case 208: - case 231: - return true; - case 232: - return nodeHasAnyModifiersExcept(node, 76); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } - function checkGrammarAsyncModifier(node, asyncModifier) { - switch (node.kind) { - case 151: - case 228: - case 186: - case 187: - return false; - } - return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); - } - function checkGrammarForDisallowedTrailingComma(list) { - if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } - if (typeParameters && typeParameters.length === 0) { - var start = typeParameters.pos - "<".length; - var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; - return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); - } - } - function checkGrammarParameterList(parameters) { - var seenOptionalParameter = false; - var parameterCount = parameters.length; - for (var i = 0; i < parameterCount; i++) { - var parameter = parameters[i]; - if (parameter.dotDotDotToken) { - if (i !== (parameterCount - 1)) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); - } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); - } - } - else if (parameter.questionToken) { - seenOptionalParameter = true; - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); - } - } - else if (seenOptionalParameter && !parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); - } - } - } - function checkGrammarFunctionLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); - } - function checkGrammarClassLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); - } - function checkGrammarArrowFunction(node, file) { - if (node.kind === 187) { - var arrowFunction = node; - var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; - var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; - if (startLine !== endLine) { - return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); - } - } - return false; - } - function checkGrammarIndexSignatureParameters(node) { - var parameter = node.parameters[0]; - if (node.parameters.length !== 1) { - if (parameter) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - else { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - } - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); - } - if (ts.getModifierFlags(parameter) !== 0) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); - } - if (!parameter.type) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); - } - if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); - } - if (!node.type) { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); - } - } - function checkGrammarIndexSignature(node) { - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); - } - function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { - if (typeArguments && typeArguments.length === 0) { - var sourceFile = ts.getSourceFileOfNode(node); - var start = typeArguments.pos - "<".length; - var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function checkGrammarTypeArguments(node, typeArguments) { - return checkGrammarForDisallowedTrailingComma(typeArguments) || - checkGrammarForAtLeastOneTypeArgument(node, typeArguments); - } - function checkGrammarForOmittedArgument(node, args) { - if (args) { - var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { - var arg = args_4[_i]; - if (arg.kind === 200) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); - } - } - } - } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); - } - function checkGrammarHeritageClause(node) { - var types = node.types; - if (checkGrammarForDisallowedTrailingComma(types)) { - return true; - } - if (types && types.length === 0) { - var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); - } - } - function checkGrammarClassDeclarationHeritageClauses(node) { - var seenExtendsClause = false; - var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); - } - if (heritageClause.types.length > 1) { - return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108); - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); - } - seenImplementsClause = true; - } - checkGrammarHeritageClause(heritageClause); - } - } - } - function checkGrammarInterfaceDeclaration(node) { - var seenExtendsClause = false; - if (node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108); - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); - } - checkGrammarHeritageClause(heritageClause); - } - } - return false; - } - function checkGrammarComputedPropertyName(node) { - if (node.kind !== 144) { - return false; - } - var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 && computedPropertyName.expression.operatorToken.kind === 26) { - return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); - } - } - function checkGrammarForGenerator(node) { - if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 || - node.kind === 186 || - node.kind === 151); - if (ts.isInAmbientContext(node)) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); - } - if (!node.body) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); - } - } - } - function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } - } - function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 263) { - continue; - } - var name = prop.name; - if (name.kind === 144) { - checkGrammarComputedPropertyName(name); - } - if (prop.kind === 262 && !inDestructuring && prop.objectAssignmentInitializer) { - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); - } - if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { - var mod = _c[_b]; - if (mod.kind !== 120 || prop.kind !== 151) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); - } - } - } - var currentKind = void 0; - if (prop.kind === 261 || prop.kind === 262) { - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151) { - currentKind = Property; - } - else if (prop.kind === 153) { - currentKind = GetAccessor; - } - else if (prop.kind === 154) { - currentKind = SetAccessor; - } - else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); - } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name); - if (effectiveName === undefined) { - continue; - } - var existingKind = seen.get(effectiveName); - if (!existingKind) { - seen.set(effectiveName, currentKind); - } - else { - if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); - } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen.set(effectiveName, currentKind | existingKind); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); - } - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); - } - } - } - } - function checkGrammarJsxElement(node) { - var seen = ts.createMap(); - for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { - var attr = _a[_i]; - if (attr.kind === 255) { - continue; - } - var jsxAttr = attr; - var name = jsxAttr.name; - if (!seen.get(name.text)) { - seen.set(name.text, true); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); - } - var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 && !initializer.expression) { - return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); - } - } - } - function checkGrammarForInOrForOfStatement(forInOrOfStatement) { - if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { - return true; - } - if (forInOrOfStatement.kind === 216 && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 16384) === 0) { - return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - } - } - if (forInOrOfStatement.initializer.kind === 227) { - var variableList = forInOrOfStatement.initializer; - if (!checkGrammarVariableDeclarationList(variableList)) { - var declarations = variableList.declarations; - if (!declarations.length) { - return false; - } - if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement - : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; - return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); - } - var firstDeclaration = declarations[0]; - if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer - : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; - return grammarErrorOnNode(firstDeclaration.name, diagnostic); - } - if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 - ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation - : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; - return grammarErrorOnNode(firstDeclaration, diagnostic); - } - } - } - return false; - } - function checkGrammarAccessor(accessor) { - var kind = accessor.kind; - if (languageVersion < 1) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); - } - else if (ts.isInAmbientContext(accessor)) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); - } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - else if (accessor.body && ts.getModifierFlags(accessor) & 128) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); - } - else if (accessor.typeParameters) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); - } - else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 ? - ts.Diagnostics.A_get_accessor_cannot_have_parameters : - ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); - } - else if (kind === 154) { - if (accessor.type) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); - } - else { - var parameter = accessor.parameters[0]; - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); - } - else if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); - } - else if (parameter.initializer) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); - } - } - } - } - function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 ? 0 : 1); - } - function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 ? 1 : 2)) { - return ts.getThisParameter(accessor); - } - } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { - return grammarErrorOnNode(node, message); - } - } - function checkGrammarMethod(node) { - if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || - checkGrammarFunctionLikeDeclaration(node) || - checkGrammarForGenerator(node)) { - return true; - } - if (node.parent.kind === 178) { - if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { - return true; - } - else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - } - if (ts.isClassLike(node.parent)) { - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); - } - else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); - } - } - else if (node.parent.kind === 230) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); - } - else if (node.parent.kind === 163) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); - } - } - function checkGrammarBreakOrContinueStatement(node) { - var current = node; - while (current) { - if (ts.isFunctionLike(current)) { - return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); - } - switch (current.kind) { - case 222: - if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 217 - && !ts.isIterationStatement(current.statement, true); - if (isMisplacedContinueLabel) { - return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); - } - return false; - } - break; - case 221: - if (node.kind === 218 && !node.label) { - return false; - } - break; - default: - if (ts.isIterationStatement(current, false) && !node.label) { - return false; - } - break; - } - current = current.parent; - } - if (node.label) { - var message = node.kind === 218 - ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement - : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - else { - var message = node.kind === 218 - ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement - : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - } - function checkGrammarBindingElement(node) { - if (node.dotDotDotToken) { - var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - if (node.name.kind === 175 || node.name.kind === 174) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (node.initializer) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - } - } - function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 || expr.kind === 8 || - expr.kind === 192 && expr.operator === 38 && - expr.operand.kind === 8; - } - function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 && node.parent.parent.kind !== 216) { - if (ts.isInAmbientContext(node)) { - if (node.initializer) { - if (ts.isConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - else if (!node.initializer) { - if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); - } - if (ts.isConst(node)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); - } - } - } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { - checkESModuleMarker(node.name); - } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); - return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); - } - function checkESModuleMarker(name) { - if (name.kind === 71) { - if (ts.unescapeIdentifier(name.text) === "__esModule") { - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; - if (!ts.isOmittedExpression(element)) { - return checkESModuleMarker(element.name); - } - } - } - } - function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71) { - if (name.originalKeywordKind === 110) { - return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; - if (!ts.isOmittedExpression(element)) { - checkGrammarNameInLetOrConstDeclarations(element.name); - } - } - } - } - function checkGrammarVariableDeclarationList(declarationList) { - var declarations = declarationList.declarations; - if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { - return true; - } - if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); - } - } - function allowLetAndConstDeclarations(parent) { - switch (parent.kind) { - case 211: - case 212: - case 213: - case 220: - case 214: - case 215: - case 216: - return false; - case 222: - return allowLetAndConstDeclarations(parent.parent); - } - return true; - } - function checkGrammarForDisallowedLetOrConstStatement(node) { - if (!allowLetAndConstDeclarations(node.parent)) { - if (ts.isLet(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); - } - else if (ts.isConst(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); - } - } - } - function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94) { - if (node.name.text !== "target") { - return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.text, ts.tokenToString(node.keywordToken), "target"); - } - } - } - function hasParseDiagnostics(sourceFile) { - return sourceFile.parseDiagnostics.length > 0; - } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorOnNode(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); - return true; - } - } - function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarProperty(node) { - if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - } - else if (node.parent.kind === 230) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); - } - } - else if (node.parent.kind === 163) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); - } - } - if (ts.isInAmbientContext(node) && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - if (node.kind === 230 || - node.kind === 231 || - node.kind === 238 || - node.kind === 237 || - node.kind === 244 || - node.kind === 243 || - node.kind === 236 || - ts.getModifierFlags(node) & (2 | 1 | 512)) { - return false; - } - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); - } - function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { - for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208) { - if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { - return true; - } - } - } - } - function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); - } - function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { - if (isAccessor(node.parent.kind)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = true; - } - var links = getNodeLinks(node); - if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); - } - if (node.parent.kind === 207 || node.parent.kind === 234 || node.parent.kind === 265) { - var links_1 = getNodeLinks(node.parent); - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); - } - } - else { - } - } - } - function checkGrammarNumericLiteral(node) { - if (node.numericLiteralFlags & 4) { - var diagnosticMessage = void 0; - if (languageVersion >= 1) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 173)) { - diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 264)) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; - } - if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38; - var literal = (withMinus ? "-" : "") + "0o" + node.text; - return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); - } - } - } - function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), 0, message, arg0, arg1, arg2)); - return true; - } - } - function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(global); - } - }); - return result; - } - } - 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) { @@ -42690,11 +43975,11 @@ var ts; 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)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), 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 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)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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: @@ -42702,9 +43987,9 @@ var ts; 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)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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: @@ -42712,9 +43997,9 @@ var ts; 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)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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: @@ -42734,7 +44019,7 @@ var ts; case 171: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); case 172: - 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)); + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), 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 174: @@ -42762,9 +44047,9 @@ var ts; case 185: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 186: - return ts.updateFunctionExpression(node, 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)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 188: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189: @@ -42788,7 +44073,7 @@ var ts; case 198: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); case 199: - return ts.updateClassExpression(node, 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)); + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 201: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 202: @@ -42838,13 +44123,13 @@ var ts; case 227: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 228: - 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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: @@ -42911,9 +44196,9 @@ var ts; return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); case 265: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); - case 296: + case 288: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297: + case 289: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: return node; @@ -42951,7 +44236,7 @@ var ts; case 209: case 200: case 225: - case 295: + case 287: break; case 143: result = reduceNode(node.left, cbNode, result); @@ -43111,9 +44396,6 @@ var ts; result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 203: - result = reduceNode(node.expression, cbNode, result); - break; case 205: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); @@ -43312,10 +44594,10 @@ var ts; case 265: result = reduceNodes(node.statements, cbNodes, result); break; - case 296: + case 288: result = reduceNode(node.expression, cbNode, result); break; - case 297: + case 289: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -43381,38 +44663,207 @@ var ts; } var Debug; (function (Debug) { + var isDebugInfoEnabled = false; Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } : ts.noop; Debug.assertEachNode = Debug.shouldAssert(1) - ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; Debug.assertNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } : ts.noop; Debug.assertOptionalNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } : ts.noop; Debug.assertOptionalToken = Debug.shouldAssert(1) - ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } : ts.noop; Debug.assertMissingNode = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; - function getFunctionName(func) { - if (typeof func !== "function") { - return ""; + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, + "__debugObjectFlags": { get: function () { return this.flags & 32768 ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, + "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + "__debugGetText": { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } } - else if (func.hasOwnProperty("name")) { - return func.name; - } - else { - var text = Function.prototype.toString.call(func); - var match = /^function\s+([\w\$]+)\s*\(/.exec(text); - return match ? match[1] : ""; + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 238: + externalImports.push(node); + break; + case 237: + if (node.moduleReference.kind === 248) { + externalImports.push(node); + } + break; + case 244: + if (node.moduleSpecifier) { + if (!node.exportClause) { + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + externalImports.push(node); + } + } + else { + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 243: + if (node.isExportEquals && !exportEquals) { + exportEquals = node; + } + break; + case 208: + if (ts.hasModifier(node, 1)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 228: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 229: + if (ts.hasModifier(node, 1)) { + if (ts.hasModifier(node, 512)) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; } } - })(Debug = ts.Debug || (ts.Debug = {})); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { + uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -43665,11 +45116,11 @@ var ts; } else if (ts.isStringOrNumericLiteral(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); - argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); return ts.createPropertyAccess(value, name); } } @@ -43746,6 +45197,22 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports"; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -43926,6 +45393,7 @@ var ts; case 147: case 231: case 149: + case 236: return undefined; case 152: return visitConstructor(node); @@ -43997,32 +45465,71 @@ var ts; function shouldEmitDecorateCallForParameter(parameter) { return parameter.decorators !== undefined && parameter.decorators.length > 0; } + function getClassFacts(node, staticProperties) { + var facts = 0; + if (ts.some(staticProperties)) + facts |= 1; + if (ts.getClassExtendsHeritageClauseElement(node)) + facts |= 64; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2; + if (ts.childIsDecorated(node)) + facts |= 4; + if (isExportOfNamespace(node)) + facts |= 8; + else if (isDefaultExternalModuleExport(node)) + facts |= 32; + else if (isNamedExternalModuleExport(node)) + facts |= 16; + if (languageVersion <= 1 && (facts & 7)) + facts |= 128; + return facts; + } function visitClassDeclaration(node) { var staticProperties = getInitializedProperties(node, true); - var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; - var isDecoratedClass = shouldEmitDecorateCallForClass(node); - var name = node.name; - if (!name && (staticProperties.length > 0 || ts.childIsDecorated(node))) { - name = ts.getGeneratedNameForNode(node); + var facts = getClassFacts(node, staticProperties); + if (facts & 128) { + context.startLexicalEnvironment(); } - var classStatement = isDecoratedClass - ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) - : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var name = node.name || (facts & 5 ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; - if (staticProperties.length) { - addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); + if (facts & 1) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 ? ts.getInternalName(node) : ts.getLocalName(node)); } addClassElementDecorationStatements(statements, node, false); addClassElementDecorationStatements(statements, node, true); addConstructorDecorationStatement(statements, node); - if (isNamespaceExport(node)) { + if (facts & 128) { + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18); + var localName = ts.getInternalName(node); + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 | 384); + statements.push(statement); + ts.addRange(statements, context.endLexicalEnvironment()); + var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, false, false), undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } + if (facts & 8) { addExportMemberAssignment(statements, node); } - else if (isDecoratedClass) { - if (isDefaultExternalModuleExport(node)) { + else if (facts & 128 || facts & 2) { + if (facts & 32) { statements.push(ts.createExportDefault(ts.getLocalName(node, false, true))); } - else if (isNamedExternalModuleExport(node)) { + else if (facts & 16) { statements.push(ts.createExternalModuleExport(ts.getLocalName(node, false, true))); } } @@ -44032,10 +45539,13 @@ var ts; } return ts.singleOrMany(statements); } - function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { - var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause)); + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { + var modifiers = !(facts & 128) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; + var classDeclaration = ts.createClassDeclaration(undefined, modifiers, name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64) !== 0)); var emitFlags = ts.getEmitFlags(node); - if (hasStaticProperties) { + if (facts & 1) { emitFlags |= 32; } ts.setTextRange(classDeclaration, node); @@ -44043,12 +45553,12 @@ var ts; ts.setEmitFlags(classDeclaration, emitFlags); return classDeclaration; } - function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { + function createClassDeclarationHeadWithDecorators(node, name, facts) { var location = ts.moveRangePastDecorators(node); var classAlias = getClassAliasIfNeeded(node); var declName = ts.getLocalName(node, false, true); var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, hasExtendsClause); + var members = transformClassMembers(node, (facts & 64) !== 0); var classExpression = ts.createClassExpression(undefined, name, undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -44302,8 +45812,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -44457,7 +45967,7 @@ var ts; var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { continue; } if (parameter.dotDotDotToken) { @@ -44557,13 +46067,13 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { return serializedIndividual; } else if (serializedUnion) { if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || - serializedUnion.text !== serializedIndividual.text) { + serializedUnion.escapedText !== serializedIndividual.escapedText) { return ts.createIdentifier("Object"); } } @@ -44644,7 +46154,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeIdentifier(name.text)); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.getSynthesizedClone(name); @@ -44725,7 +46235,7 @@ var ts; return ts.createNotEmittedStatement(node); } var updated = ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var statements = [updated]; addExportMemberAssignment(statements, node); return statements; @@ -44756,7 +46266,7 @@ var ts; return parameter; } function visitVariableStatement(node) { - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); if (variables.length === 0) { return undefined; @@ -44873,16 +46383,16 @@ var ts; return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } function hasNamespaceQualifiedExportName(node) { - return isNamespaceExport(node) + return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System); } function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createMap(); + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); } if (!currentScopeFirstDeclarationsOfName.has(name)) { currentScopeFirstDeclarationsOfName.set(name, node); @@ -44891,7 +46401,7 @@ var ts; } function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { return currentScopeFirstDeclarationsOfName.get(name) === node; } @@ -45067,7 +46577,7 @@ var ts; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); ts.setEmitFlags(moduleReference, 1536 | 2048); - if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.setOriginalNode(ts.createVariableDeclaration(node.name, undefined, moduleReference), node) ])), node), node); @@ -45076,7 +46586,7 @@ var ts; return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node); } } - function isNamespaceExport(node) { + function isExportOfNamespace(node) { return currentNamespace !== undefined && ts.hasModifier(node, 1); } function isExternalModuleExport(node) { @@ -45095,7 +46605,7 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, false, true), ts.getLocalName(node)); - ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); var statement = ts.createStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); @@ -45120,7 +46630,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeIdentifier(node.name.text) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -45224,10 +46734,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_2 = ts.getSynthesizedClone(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; } } } @@ -45501,7 +47011,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -45791,8 +47301,10 @@ 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 createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 + ? ts.createYield(undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); @@ -45811,7 +47323,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ 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); + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, createDownlevelAwait(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -45820,7 +47332,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -45998,7 +47510,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -46256,8 +47768,8 @@ var ts; } else { var name = node.tagName; - if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.text)) { - return ts.createLiteral(name.text); + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.createExpressionFromEntityName(name); @@ -46266,11 +47778,11 @@ var ts; } function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(name.text)) { + if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { return name; } else { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } } function visitJsxExpression(node) { @@ -46707,11 +48219,58 @@ var ts; && node.kind === 219 && !node.expression; } + function isClassLikeVariableStatement(node) { + if (!ts.isVariableStatement(node)) + return false; + var variable = ts.singleOrUndefined(node.declarationList.declarations); + return variable + && variable.initializer + && ts.isIdentifier(variable.name) + && (ts.isClassLike(variable.initializer) + || (ts.isAssignmentExpression(variable.initializer) + && ts.isIdentifier(variable.initializer.left) + && ts.isClassLike(variable.initializer.right))); + } + function isTypeScriptClassWrapper(node) { + var call = ts.tryCast(node, ts.isCallExpression); + if (!call || ts.isParseTreeNode(call) || + ts.some(call.typeArguments) || + ts.some(call.arguments)) { + return false; + } + var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + if (!func || ts.isParseTreeNode(func) || + ts.some(func.typeParameters) || + ts.some(func.parameters) || + func.type || + !func.body) { + return false; + } + var statements = func.body.statements; + if (statements.length < 2) { + return false; + } + var firstStatement = statements[0]; + if (ts.isParseTreeNode(firstStatement) || + !ts.isClassLike(firstStatement) && + !isClassLikeVariableStatement(firstStatement)) { + return false; + } + var lastStatement = ts.elementAt(statements, -1); + var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); + if (!returnStatement || + !returnStatement.expression || + !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { + return false; + } + return true; + } function shouldVisitNode(node) { return (node.transformFlags & 128) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 && ts.isStatement(node)) - || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)); + || (ts.isIterationStatement(node, false) && shouldConvertIterationStatementBody(node)) + || isTypeScriptClassWrapper(node); } function visitor(node) { if (shouldVisitNode(node)) { @@ -46896,7 +48455,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return node; } - if (node.text !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { return node; } return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); @@ -46904,7 +48463,7 @@ var ts; function visitBreakOrContinueStatement(node) { if (convertedLoopState) { var jump = node.kind === 218 ? 2 : 4; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(node.label.text)) || + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; @@ -46920,12 +48479,12 @@ var ts; } else { if (node.kind === 218) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, true, node.label.text, labelMarker); + labelMarker = "break-" + node.label.escapedText; + setLabeledJump(convertedLoopState, true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, false, node.label.text, labelMarker); + labelMarker = "continue-" + node.label.escapedText; + setLabeledJump(convertedLoopState, false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -47568,9 +49127,9 @@ var ts; if (node.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 + var declarations = ts.flatMap(node.declarations, node.flags & 1 ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); + : visitVariableDeclaration); var declarationList = ts.createVariableDeclarationList(declarations); ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); @@ -47608,9 +49167,9 @@ var ts; return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_3 = ts.getMutableClone(node); - clone_3.initializer = ts.createVoidZero(); - return clone_3; + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; } return ts.visitEachChild(node, visitor, context); } @@ -47627,10 +49186,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(node.label.text, node.label.text); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); } function resetLabel(node) { - convertedLoopState.labels.set(node.label.text, undefined); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -47949,13 +49508,13 @@ var ts; loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); } else { - var clone_4 = ts.getMutableClone(node); - clone_4.statement = undefined; - clone_4 = ts.visitEachChild(clone_4, visitor, context); - clone_4.statement = ts.createBlock(convertedLoopBodyStatements, true); - clone_4.transformFlags = 0; - ts.aggregateTransformFlags(clone_4); - loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + var clone_3 = ts.getMutableClone(node); + clone_3.statement = undefined; + clone_3 = ts.visitEachChild(clone_3, visitor, context); + clone_3.statement = ts.createBlock(convertedLoopBodyStatements, true); + clone_3.transformFlags = 0; + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -48057,7 +49616,7 @@ var ts; else { loopParameters.push(ts.createParameter(undefined, undefined, undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeIdentifier(name.text)); + var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -48187,11 +49746,49 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitCallExpression(node) { + if (isTypeScriptClassWrapper(node)) { + return visitTypeScriptClassWrapper(node); + } if (node.transformFlags & 64) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } + function visitTypeScriptClassWrapper(node) { + var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); + var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + ts.addRange(statements, remainingStatements); + ts.addRange(statements, classStatements, 1); + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, undefined, undefined, undefined, undefined, func.parameters, undefined, ts.updateBlock(func.body, statements))), undefined, call.arguments)))); + } function visitImmediateSuperCallInBody(node) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } @@ -48235,7 +49832,7 @@ var ts; if (ts.isCallExpression(firstSegment) && ts.isIdentifier(firstSegment.expression) && (ts.getEmitFlags(firstSegment.expression) & 4096) - && firstSegment.expression.text === "___spread") { + && firstSegment.expression.escapedText === "___spread") { return segments[0]; } } @@ -48244,7 +49841,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 177 + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -48252,7 +49849,7 @@ var ts; } } function partitionSpread(node) { - return ts.isSpreadExpression(node) + return ts.isSpreadElement(node) ? visitSpanOfSpreads : visitSpanOfNonSpreads; } @@ -48354,7 +49951,7 @@ var ts; : ts.createIdentifier("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 && node.name.text === "target") { + if (node.keywordToken === 94 && node.name.escapedText === "target") { if (hierarchyFacts & 8192) { hierarchyFacts |= 32768; } @@ -48455,8 +50052,7 @@ var ts; return false; } if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { - return currentNode.kind !== 149 - || (ts.getModifierFlags(currentNode) & 32) === 0; + return true; } currentNode = currentNode.parent; } @@ -48498,7 +50094,7 @@ var ts; return false; } var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression.text === "arguments"; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; } } ts.transformES2015 = transformES2015; @@ -48826,7 +50422,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } function visitBinaryExpression(node) { @@ -48892,10 +50488,10 @@ var ts; else if (node.operatorToken.kind === 26) { return visitCommaExpression(node); } - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -49022,10 +50618,10 @@ var ts; } function visitElementAccessExpression(node) { if (containsYield(node.argumentExpression)) { - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -49141,7 +50737,7 @@ var ts; return undefined; } function transformInitializedVariable(node) { - return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); } function transformAndEmitIfStatement(node) { if (containsYield(node)) { @@ -49328,13 +50924,13 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? node.label.text : undefined); + var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); emitBreak(label, node); } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && node.label.text); + var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, node); } @@ -49342,13 +50938,13 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? node.label.text : undefined); + var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); emitBreak(label, node); } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && node.label.text); + var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, node); } @@ -49443,7 +51039,7 @@ var ts; } function transformAndEmitLabeledStatement(node) { if (containsYield(node)) { - beginLabeledBlock(node.label.text); + beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -49453,7 +51049,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(node.label.text); + beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -49508,17 +51104,17 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(node.text)) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_7 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_7, node); - ts.setCommentRange(clone_7, node); - return clone_7; + var clone_6 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -49625,7 +51221,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = variable.name.text; + var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -49689,7 +51285,7 @@ var ts; kind: 3, isScript: false, breakLabel: breakLabel, - continueLabel: continueLabel + continueLabel: continueLabel, }); return breakLabel; } @@ -49713,7 +51309,7 @@ var ts; beginBlock({ kind: 2, isScript: false, - breakLabel: breakLabel + breakLabel: breakLabel, }); return breakLabel; } @@ -50251,7 +51847,7 @@ var ts; return node; } function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); if (token >= 72 && token <= 107) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -50291,9 +51887,10 @@ var ts; var currentSourceFile; var currentModuleInfo; var noSubstitution; + var needUMDDynamicImportHelper; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864)) { return node; } currentSourceFile = node; @@ -50303,6 +51900,7 @@ var ts; var updated = transformModule(node); currentSourceFile = undefined; currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; return ts.aggregateTransformFlags(updated); } function shouldEmitUnderscoreUnderscoreESModule() { @@ -50324,9 +51922,10 @@ var ts; addExportEqualsIfNeeded(statements, false); ts.addRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); } + ts.addEmitHelpers(updated, context.readEmitHelpers()); return updated; } function transformAMDModule(node) { @@ -50419,9 +52018,12 @@ var ts; addExportEqualsIfNeeded(statements, true); ts.addRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } return body; } function addExportEqualsIfNeeded(statements, emitAsReturn) { @@ -50456,14 +52058,49 @@ var ts; return visitFunctionDeclaration(node); case 229: return visitClassDeclaration(node); - case 298: + case 290: return visitMergeDeclarationMarker(node); - case 299: + case 291: return visitEndOfDeclarationMarker(node); default: - return node; + return ts.visitEachChild(node, importCallExpressionVisitor, context); } } + function importCallExpressionVisitor(node) { + if (!(node.transformFlags & 67108864)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else { + return ts.visitEachChild(node, importCallExpressionVisitor, context); + } + } + function visitImportCallExpression(node) { + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return transformImportCallExpressionAMD(node); + case ts.ModuleKind.UMD: + return transformImportCallExpressionUMD(node); + case ts.ModuleKind.CommonJS: + default: + return transformImportCallExpressionCommonJS(node); + } + } + function transformImportCallExpressionUMD(node) { + needUMDDynamicImportHelper = true; + return ts.createConditional(ts.createIdentifier("__syncRequire"), transformImportCallExpressionCommonJS(node), transformImportCallExpressionAMD(node)); + } + function transformImportCallExpressionAMD(node) { + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + return ts.createNew(ts.createIdentifier("Promise"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, resolve), + ts.createParameter(undefined, undefined, undefined, reject)], undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + } + function transformImportCallExpressionCommonJS(node) { + return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []), "then"), undefined, [ts.createFunctionExpression(undefined, undefined, undefined, undefined, undefined, undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), undefined, node.arguments))]))]); + } function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); @@ -50554,11 +52191,7 @@ var ts; return ts.singleOrMany(statements); } else { - return ts.setTextRange(ts.createStatement(ts.createCall(ts.createIdentifier("__export"), undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ])), node); + return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } function visitExportAssignment(node) { @@ -50579,10 +52212,10 @@ var ts; function visitFunctionDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, node.parameters, undefined, node.body), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -50596,10 +52229,10 @@ var ts; function visitClassDeclaration(node) { var statements; if (ts.hasModifier(node, 1)) { - statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, node.heritageClauses, node.members), node), node)); + statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -50636,7 +52269,7 @@ var ts; } } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -50649,10 +52282,10 @@ var ts; } function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(node, undefined, context, 0, false, createExportExpression); + return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), undefined, context, 0, false, createExportExpression); } else { - return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), node.initializer); + return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); } } function visitMergeDeclarationMarker(node) { @@ -50749,7 +52382,7 @@ var ts; } function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -50930,7 +52563,18 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), undefined, [module]); + } + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; })(ts || (ts = {})); var ts; @@ -50962,7 +52606,7 @@ var ts; var noSubstitution; return transformSourceFile; function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864)) { return node; } var id = ts.getOriginalNodeId(node); @@ -51067,7 +52711,7 @@ var ts; if (moduleInfo.exportedNames) { for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { var exportedLocalName = _c[_b]; - if (exportedLocalName.text === "default") { + if (exportedLocalName.escapedText === "default") { continue; } exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue())); @@ -51084,7 +52728,7 @@ var ts; } for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -51141,7 +52785,7 @@ var ts; var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, undefined, [ts.createObjectLiteral(properties, true)]))); } @@ -51200,7 +52844,7 @@ var ts; if (node.isExportEquals) { return undefined; } - var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { var id = ts.getOriginalNodeId(node); @@ -51212,10 +52856,10 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, true, true), undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); } else { - hoistedStatements = ts.append(hoistedStatements, node); + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); @@ -51230,7 +52874,7 @@ var ts; var statements; var name = ts.getLocalName(node); hoistVariableDeclaration(name); - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement)), node))), node)); + statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(undefined, node.name, undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); @@ -51242,7 +52886,7 @@ var ts; } function visitVariableStatement(node) { if (!shouldHoistVariableDeclarationList(node.declarationList)) { - return ts.visitNode(node, destructuringVisitor, ts.isStatement); + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); } var expressions; var isExportedDeclaration = ts.hasModifier(node, 1); @@ -51290,8 +52934,8 @@ var ts; function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) - ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, false, createAssignment) + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); } function createExportedVariableAssignment(name, value, location) { return createVariableAssignment(name, value, location, true); @@ -51386,7 +53030,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = decl.name.text; + excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -51400,7 +53044,7 @@ var ts; if (ts.hasModifier(decl, 1)) { var exportName = ts.hasModifier(decl, 512) ? ts.createLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); - excludeName = exportName.text; + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); } if (decl.name) { statements = appendExportsOfDeclaration(statements, decl, excludeName); @@ -51412,11 +53056,11 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; - if (exportSpecifier.name.text !== excludeName) { + if (exportSpecifier.name.escapedText !== excludeName) { statements = appendExportStatement(statements, exportSpecifier.name, name); } } @@ -51475,32 +53119,32 @@ var ts; return visitCatchClause(node); case 207: return visitBlock(node); - case 298: + case 290: return visitMergeDeclarationMarker(node); - case 299: + case 291: return visitEndOfDeclarationMarker(node); default: - return destructuringVisitor(node); + return destructuringAndImportCallVisitor(node); } } function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -51525,19 +53169,19 @@ var ts; } } function visitDoStatement(node) { - return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } function visitWhileStatement(node) { - return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitLabeledStatement(node) { return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitWithStatement(node) { - return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } function visitSwitchStatement(node) { - return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); } function visitCaseBlock(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; @@ -51547,7 +53191,7 @@ var ts; return node; } function visitCaseClause(node) { - return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); } function visitDefaultClause(node) { return ts.visitEachChild(node, nestedElementVisitor, context); @@ -51569,29 +53213,35 @@ var ts; enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } - function destructuringVisitor(node) { + function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 && node.kind === 194) { return visitDestructuringAssignment(node); } - else if (node.transformFlags & 2048) { - return ts.visitEachChild(node, destructuringVisitor, context); + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048) || (node.transformFlags & 67108864)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { return node; } } + function visitImportCallExpression(node) { + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), undefined, node.arguments); + } function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { - return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0, true); + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0, true); } - return ts.visitEachChild(node, destructuringVisitor, context); + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } function hasExportedReferenceInDestructuringTarget(node) { if (ts.isAssignmentExpression(node, true)) { return hasExportedReferenceInDestructuringTarget(node.left); } - else if (ts.isSpreadExpression(node)) { + else if (ts.isSpreadElement(node)) { return hasExportedReferenceInDestructuringTarget(node.expression); } else if (ts.isObjectLiteralExpression(node)) { @@ -51831,6 +53481,7 @@ var ts; (function (ts) { function getModuleTransformer(moduleKind) { switch (moduleKind) { + case ts.ModuleKind.ESNext: case ts.ModuleKind.ES2015: return ts.transformES2015Module; case ts.ModuleKind.System: @@ -51883,7 +53534,7 @@ var ts; } ts.getTransformers = getTransformers; function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(300); + var enabledSyntaxKindFeatures = new Array(292); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -51977,7 +53628,7 @@ var ts; function hoistVariableDeclaration(name) { ts.Debug.assert(state > 0, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2, "Cannot modify the lexical environment after transformation has completed."); - var decl = ts.createVariableDeclaration(name); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64); if (!lexicalEnvironmentVariableDeclarations) { lexicalEnvironmentVariableDeclarations = [decl]; } @@ -52203,7 +53854,7 @@ var ts; var writer = ts.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; @@ -52300,10 +53951,10 @@ var ts; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } - function reportIllegalExtends() { + function reportPrivateInBaseOfClassExpression(propertyName) { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleThisError() { @@ -52316,14 +53967,17 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); var shouldUseResolverType = declaration.kind === 146 && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { emitType(type); } else { errorNameNode = declaration.name; - var format = 2 | 1024 | - (shouldUseResolverType ? 4096 : 0); + var format = 4 | + 16384 | + 2048 | + (shouldUseResolverType ? 8192 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -52336,7 +53990,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 2048 | 16384, writer); errorNameNode = undefined; } } @@ -52566,7 +54220,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 2048 | 16384, writer); write(";"); writeLine(); return tempVarName; @@ -53031,7 +54685,7 @@ var ts; if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { tempVarName = baseTypeNode.expression.kind === 95 ? "null" : - emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name @@ -53659,7 +55313,7 @@ var ts; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSourceFile; + var currentSource; var currentSourceText; var sourceMapDir; var sourceMapSourceIndex; @@ -53679,6 +55333,9 @@ var ts; getText: getText, getSourceMappingURL: getSourceMappingURL, }; + function skipSourceTrivia(pos) { + return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); + } function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { if (disabled) { return; @@ -53686,7 +55343,7 @@ var ts; if (sourceMapData) { reset(); } - currentSourceFile = undefined; + currentSource = undefined; currentSourceText = undefined; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; @@ -53729,7 +55386,7 @@ var ts; if (disabled) { return; } - currentSourceFile = undefined; + currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; lastRecordedSourceMapSpan = undefined; @@ -53772,7 +55429,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("beforeSourcemap"); } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); sourceLinePos.line++; sourceLinePos.character++; var emittedLine = writer.getLine(); @@ -53809,12 +55466,21 @@ var ts; if (node) { var emitNode = node.emitNode; var emitFlags = emitNode && emitNode.flags; - var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; - if (node.kind !== 295 + var range = emitNode && emitNode.sourceMapRange; + var _a = range || node, pos = _a.pos, end = _a.end; + var source = range && range.source; + var oldSource = currentSource; + if (source === oldSource) + source = undefined; + if (source) + setSourceFile(source); + if (node.kind !== 287 && (emitFlags & 16) === 0 && pos >= 0) { - emitPos(ts.skipTrivia(currentSourceText, pos)); + emitPos(skipSourceTrivia(pos)); } + if (source) + setSourceFile(oldSource); if (emitFlags & 64) { disabled = true; emitCallback(hint, node); @@ -53823,11 +55489,15 @@ var ts; else { emitCallback(hint, node); } - if (node.kind !== 295 + if (source) + setSourceFile(source); + if (node.kind !== 287 && (emitFlags & 32) === 0 && end >= 0) { emitPos(end); } + if (source) + setSourceFile(oldSource); } } function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { @@ -53837,7 +55507,7 @@ var ts; var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128) === 0 && tokenPos >= 0) { emitPos(tokenPos); } @@ -53853,17 +55523,17 @@ var ts; if (disabled) { return; } - currentSourceFile = sourceFile; - currentSourceText = currentSourceFile.text; + currentSource = sourceFile; + currentSourceText = currentSource.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); - sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSource.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSource.text); } } } @@ -53963,9 +55633,9 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295; - var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0; + var isEmittedNode = node.kind !== 287; + var skipLeadingComments = pos < 0 || (emitFlags & 512) !== 0 || node.kind === 10; + var skipTrailingComments = end < 0 || (emitFlags & 1024) !== 0 || node.kind === 10; if (!skipLeadingComments) { emitLeadingComments(pos, isEmittedNode); } @@ -54256,6 +55926,50 @@ var ts; (function (ts) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + function getOutputExtension(sourceFile, options) { + if (options.jsx === 1) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { + return ".jsx"; + } + } + else if (sourceFile.languageVariant === 1) { + return ".jsx"; + } + } + return ".js"; + } + function getOriginalSourceFileOrBundle(sourceFileOrBundle) { + if (sourceFileOrBundle.kind === 266) { + return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); + } + return ts.getOriginalSourceFile(sourceFileOrBundle); + } function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -54282,7 +55996,7 @@ var ts; onSetSourceFile: setSourceFile, }); ts.performance.mark("beforePrint"); - ts.forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); transform.dispose(); return { @@ -54302,7 +56016,7 @@ var ts; emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -54698,6 +56412,8 @@ var ts; return emitModuleBlock(node); case 235: return emitCaseBlock(node); + case 236: + return emitNamespaceExportDeclaration(node); case 237: return emitImportEqualsDeclaration(node); case 238: @@ -54777,6 +56493,7 @@ var ts; case 97: case 101: case 99: + case 91: writeTokenNode(node); return; case 177: @@ -54837,9 +56554,9 @@ var ts; return emitJsxElement(node); case 250: return emitJsxSelfClosingElement(node); - case 296: + case 288: return emitPartiallyEmittedExpression(node); - case 297: + case 289: return emitCommaList(node); } } @@ -54916,6 +56633,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -54935,6 +56653,7 @@ var ts; emitModifiers(node, node.modifiers); writeIfPresent(node.asteriskToken, "*"); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -54994,7 +56713,7 @@ var ts; function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); - emitParametersForArrow(node, node.parameters); + emitParameters(node, node.parameters); write(" => "); emit(node.type); } @@ -55082,7 +56801,7 @@ var ts; } else { write("{"); - emitList(node, elements, ts.getEmitFlags(node) & 1 ? 272 : 432); + emitList(node, elements, 432); write("}"); } } @@ -55754,6 +57473,11 @@ var ts; } write(";"); } + function emitNamespaceExportDeclaration(node) { + write("export as namespace "); + emit(node.name); + write(";"); + } function emitNamedExports(node) { emitNamedImportsOrExports(node); } @@ -55853,6 +57577,9 @@ var ts; (ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile)); + if (statements.length > 0) { + emitTrailingCommentsOfPosition(statements.pos); + } if (emitAsSingleStatement) { write(" "); emit(statements[0]); @@ -55942,7 +57669,7 @@ var ts; } emit(statement); if (seenPrologueDirectives) { - seenPrologueDirectives.set(statement.expression.text, statement.expression.text); + seenPrologueDirectives.set(statement.expression.text, true); } } } @@ -55986,7 +57713,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 256); + emitList(node, modifiers, 131328); write(" "); } } @@ -56032,11 +57759,24 @@ var ts; function emitParameters(parentNode, parameters) { emitList(parentNode, parameters, 1360); } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos + && !(ts.isArrowFunction(parentNode) && parentNode.type) + && !ts.some(parentNode.decorators) + && !ts.some(parentNode.modifiers) + && !ts.some(parentNode.typeParameters) + && !ts.some(parameter.decorators) + && !ts.some(parameter.modifiers) + && !parameter.dotDotDotToken + && !parameter.questionToken + && !parameter.type + && !parameter.initializer + && ts.isIdentifier(parameter.name); + } function emitParametersForArrow(parentNode, parameters) { - if (parameters && - parameters.length === 1 && - parameters[0].type === undefined && - parameters[0].pos === parentNode.pos) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { emit(parameters[0]); } else { @@ -56351,7 +58091,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeIdentifier(node.text); + return ts.unescapeLeadingUnderscores(node.escapedText); } else if (node.kind === 9 && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -56389,12 +58129,12 @@ var ts; } else { var autoGenerateId = name.autoGenerateId; - return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(makeName(name))); + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } function generateNameCached(node) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); } function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) @@ -56404,8 +58144,8 @@ var ts; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { - var local = node.locals.get(name); - if (local && local.flags & (107455 | 1048576 | 8388608)) { + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); + if (local && local.flags & (107455 | 1048576 | 2097152)) { return false; } } @@ -56441,7 +58181,7 @@ var ts; while (true) { var generatedName = baseName + i; if (isUniqueName(generatedName)) { - generatedNames.set(generatedName, generatedName); + generatedNames.set(generatedName, true); return generatedName; } i++; @@ -56453,8 +58193,8 @@ var ts; } function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); } function generateNameForExportDefault() { @@ -56500,7 +58240,7 @@ var ts; case 2: return makeTempVariableName(268435456); case 3: - return makeUniqueName(ts.unescapeIdentifier(name.text)); + return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -56579,15 +58319,14 @@ var ts; ListFormat[ListFormat["PreferNewLine"] = 32768] = "PreferNewLine"; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; - ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 131328] = "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["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; @@ -56620,7 +58359,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var emptyArray = []; var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -56833,9 +58571,9 @@ var ts; 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 start = diagnostic.start, length_6 = 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 _b = ts.getLineAndCharacterOfPosition(file, start + length_6), 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; @@ -56878,6 +58616,7 @@ var ts; 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); + output += ts.sys.newLine; } return output; } @@ -56946,11 +58685,12 @@ var ts; var programDiagnostics = ts.createDiagnosticCollection(); var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); - var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { if (!resolved || resolved.extension !== undefined) { return resolved; } @@ -56962,18 +58702,18 @@ var ts; else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); }; } else { var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } - var filesByName = ts.createFileMap(); - var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; + var filesByName = ts.createMap(); + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); @@ -56998,6 +58738,7 @@ var ts; } } } + var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); moduleResolutionCache = undefined; oldProgram = undefined; program = { @@ -57005,6 +58746,7 @@ var ts; getSourceFile: getSourceFile, getSourceFileByPath: getSourceFileByPath, getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, getOptionsDiagnostics: getOptionsDiagnostics, @@ -57031,6 +58773,9 @@ var ts; ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function getCommonSourceDirectory() { if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); @@ -57049,7 +58794,7 @@ var ts; function getClassifiableNames() { if (!classifiableNames) { getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); @@ -57105,7 +58850,7 @@ var ts; } var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) - : emptyArray; + : ts.emptyArray; if (!result) { ts.Debug.assert(resolutions.length === moduleNames.length); return resolutions; @@ -57190,6 +58935,9 @@ var ts; if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { oldProgram.structureIsReused = 1; } + if ((oldSourceFile.flags & 524288) !== (newSourceFile.flags & 524288)) { + oldProgram.structureIsReused = 1; + } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { oldProgram.structureIsReused = 1; } @@ -57233,13 +58981,20 @@ var ts; if (oldProgram.structureIsReused !== 2) { return oldProgram.structureIsReused; } + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 1; + } + for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { + var p = _e[_d]; + filesByName.set(p, undefined); + } for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { - var modifiedFile = modifiedSourceFiles_2[_d]; + for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { + var modifiedFile = modifiedSourceFiles_2[_f]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -57276,7 +59031,7 @@ var ts; return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); } function isEmitBlocked(emitFileName) { - return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; @@ -57306,7 +59061,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return getSourceFileByPath(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { return filesByName.get(path); @@ -57315,14 +59070,12 @@ var ts; if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } - var allDiagnostics = []; - ts.forEach(program.getSourceFiles(), function (sourceFile) { + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } - ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); - }); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return getDiagnostics(sourceFile, cancellationToken); + })); } function getSyntacticDiagnostics(sourceFile, cancellationToken) { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); @@ -57343,6 +59096,9 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + if (ts.isCheckJsEnabledForFile(sourceFile, options)) { + sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); + } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -57366,13 +59122,13 @@ var ts; function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(function () { if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { - return emptyArray; + return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var bindDiagnostics = sourceFile.bindDiagnostics; - var includeCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); - var checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : []; + var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); @@ -57422,7 +59178,6 @@ var ts; case 186: case 228: case 187: - case 228: case 226: if (parent.type === node) { diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); @@ -57458,10 +59213,14 @@ var ts; case 232: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 184: - var typeAssertionExpression = node; - diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + case 203: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; + case 202: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 184: + ts.Debug.fail(); } var prevParent = parent; parent = node; @@ -57482,7 +59241,6 @@ var ts; case 186: case 228: case 187: - case 228: if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return; @@ -57570,10 +59328,10 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; if (sourceFile) { if (!cache.perFile) { - cache.perFile = ts.createFileMap(); + cache.perFile = ts.createMap(); } cache.perFile.set(sourceFile.path, result); } @@ -57586,15 +59344,10 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); - ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); } function getGlobalDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { processSourceFile(ts.normalizePath(fileName), isDefaultLib); @@ -57629,13 +59382,13 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, false); - if (isJavaScriptFile) { - collectRequireCalls(node); + if ((file.flags & 524288) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(node); } } - file.imports = imports || emptyArray; - file.moduleAugmentations = moduleAugmentations || emptyArray; - file.ambientModuleNames = ambientModules || emptyArray; + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { @@ -57643,7 +59396,7 @@ var ts; case 237: case 244: var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || moduleNameExpr.kind !== 9) { + if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; } if (!moduleNameExpr.text) { @@ -57656,12 +59409,13 @@ var ts; case 233: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2) || file.isDeclarationFile)) { var moduleName = node.name; - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { if (file.isDeclarationFile) { - (ambientModules || (ambientModules = [])).push(moduleName.text); + (ambientModules || (ambientModules = [])).push(nameText); } var body = node.body; if (body) { @@ -57674,17 +59428,20 @@ var ts; } } } - function collectRequireCalls(node) { + function collectDynamicImportOrRequireCalls(node) { if (ts.isRequireCall(node, true)) { (imports || (imports = [])).push(node.arguments[0]); } + else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9) { + (imports || (imports = [])).push(node.arguments[0]); + } else { - ts.forEachChild(node, collectRequireCalls); + ts.forEachChild(node, collectDynamicImportOrRequireCalls); } } } function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -57719,7 +59476,7 @@ var ts; } } 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) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -57737,7 +59494,7 @@ var ts; } } function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(path)) { + if (filesByName.has(path)) { var file_1 = filesByName.get(path); if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); @@ -57772,12 +59529,13 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { - var existingFile = filesByNameIgnoreCase.get(path); + var pathLowerCase = path.toLowerCase(); + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(path, file); + filesByNameIgnoreCase.set(pathLowerCase, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -57885,7 +59643,7 @@ var ts; modulesWithElidedImports.set(file.path, true); } else if (shouldAddFile) { - var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); findSourceFile(resolvedFileName, path, false, file, pos, file.imports[i].end); } @@ -57928,28 +59686,28 @@ var ts; function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); } if (options.noEmitOnError) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); } if (options.out) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); } if (options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); } } if (options.inlineSourceMap) { if (options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); } if (options.mapRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); } } if (options.paths && options.baseUrl === undefined) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } if (options.paths) { for (var key in options.paths) { @@ -57957,64 +59715,65 @@ var ts; continue; } if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + createDiagnosticForOptionPaths(true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); } - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var subst = _a[_i]; + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); } } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); + createDiagnosticForOptionPaths(false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); } } } if (!options.sourceMap && !options.inlineSourceMap) { if (options.inlineSources) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); } if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); } } if (options.out && options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } if (options.mapRoot && !options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); } if (options.declarationDir) { if (!options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); } if (options.out || options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.lib && options.noLib) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; 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)); + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { @@ -58028,7 +59787,7 @@ var ts; } if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); @@ -58040,33 +59799,33 @@ var ts; options.mapRoot) { var dir = getCommonSourceDirectory(); if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } if (!options.noEmit && options.allowJs && options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } if (options.jsxFactory) { if (options.reactNamespace) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); } if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); } } else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); } if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); @@ -58074,8 +59833,8 @@ var ts; } function verifyEmitFilePath(emitFileName, emitFilesSeen) { if (emitFileName) { - var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); - if (filesByName.contains(emitFilePath)) { + var emitFilePath = toPath(emitFileName); + if (filesByName.has(emitFilePath)) { var chain_1; if (!options.configFilePath) { chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); @@ -58083,17 +59842,96 @@ var ts; chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } - if (emitFilesSeen.contains(emitFilePath)) { + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + if (emitFilesSeen.has(emitFileKey)) { blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { - emitFilesSeen.set(emitFilePath, true); + emitFilesSeen.set(emitFileKey, true); } } } } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + if (ts.isArrayLiteralExpression(keyProps.initializer) && + keyProps.initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionPathsSyntax() { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + } + return ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2) { + createDiagnosticForOption(true, option1, option2, message, option1, option2); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(false, option1, undefined, message, arg0); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; + if (options.configFile && options.configFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + } + return !!props.length; + } function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } } @@ -58101,14 +59939,14 @@ var ts; function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { - case ts.Extension.Ts: - case ts.Extension.Dts: + case ".ts": + case ".d.ts": return undefined; - case ts.Extension.Tsx: + case ".tsx": return needJsx(); - case ts.Extension.Jsx: + case ".jsx": return needJsx() || needAllowJs(); - case ts.Extension.Js: + case ".js": return needAllowJs(); } function needJsx() { @@ -58119,6 +59957,10 @@ var ts; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; + function checkAllDefined(names) { + ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); + return names; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -58154,10 +59996,10 @@ var ts; ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); var IndentStyle; (function (IndentStyle) { @@ -58220,80 +60062,77 @@ var ts; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); var ScriptElementKind; (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; - ScriptElementKind.keyword = "keyword"; - ScriptElementKind.scriptElement = "script"; - ScriptElementKind.moduleElement = "module"; - ScriptElementKind.classElement = "class"; - ScriptElementKind.localClassElement = "local class"; - ScriptElementKind.interfaceElement = "interface"; - ScriptElementKind.typeElement = "type"; - ScriptElementKind.enumElement = "enum"; - ScriptElementKind.enumMemberElement = "enum member"; - ScriptElementKind.variableElement = "var"; - ScriptElementKind.localVariableElement = "local var"; - ScriptElementKind.functionElement = "function"; - ScriptElementKind.localFunctionElement = "local function"; - ScriptElementKind.memberFunctionElement = "method"; - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; - ScriptElementKind.memberVariableElement = "property"; - ScriptElementKind.constructorImplementationElement = "constructor"; - ScriptElementKind.callSignatureElement = "call"; - ScriptElementKind.indexSignatureElement = "index"; - ScriptElementKind.constructSignatureElement = "construct"; - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; - ScriptElementKind.jsxAttribute = "JSX attribute"; + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; + ScriptElementKind["keyword"] = "keyword"; + ScriptElementKind["scriptElement"] = "script"; + ScriptElementKind["moduleElement"] = "module"; + ScriptElementKind["classElement"] = "class"; + ScriptElementKind["localClassElement"] = "local class"; + ScriptElementKind["interfaceElement"] = "interface"; + ScriptElementKind["typeElement"] = "type"; + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; + ScriptElementKind["variableElement"] = "var"; + ScriptElementKind["localVariableElement"] = "local var"; + ScriptElementKind["functionElement"] = "function"; + ScriptElementKind["localFunctionElement"] = "local function"; + ScriptElementKind["memberFunctionElement"] = "method"; + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; + ScriptElementKind["memberVariableElement"] = "property"; + ScriptElementKind["constructorImplementationElement"] = "constructor"; + ScriptElementKind["callSignatureElement"] = "call"; + ScriptElementKind["indexSignatureElement"] = "index"; + ScriptElementKind["constructSignatureElement"] = "construct"; + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; + ScriptElementKind["jsxAttribute"] = "JSX attribute"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - return ClassificationTypeNames; - }()); - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - ts.ClassificationTypeNames = ClassificationTypeNames; + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); var ClassificationType; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -58325,7 +60164,6 @@ var ts; var ts; (function (ts) { ts.scanner = ts.createScanner(5, true); - ts.emptyArray = []; var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -58359,11 +60197,11 @@ var ts; case 231: case 163: return 2; + case 283: + return node.name === undefined ? 1 | 2 : 2; case 264: case 229: return 1 | 2; - case 232: - return 7; case 233: if (ts.isAmbientModule(node)) { return 4 | 1; @@ -58374,6 +60212,7 @@ var ts; else { return 4; } + case 232: case 241: case 242: case 237: @@ -58384,7 +60223,7 @@ var ts; case 265: return 4 | 1; } - return 1 | 2 | 4; + return 7; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { @@ -58392,9 +60231,9 @@ var ts; return 1; } else if (node.parent.kind === 243) { - return 1 | 2 | 4; + return 7; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -58406,6 +60245,10 @@ var ts; else if (isNamespaceReference(node)) { return 4; } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); + return 2; + } else { return 1; } @@ -58420,12 +60263,13 @@ var ts; } return 4; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -58460,10 +60304,19 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 159 || - (node.parent.kind === 201 && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 99 && !ts.isPartOfExpression(node)) || - node.kind === 169; + switch (node.kind) { + case 99: + return !ts.isPartOfExpression(node); + case 169: + return true; + } + switch (node.parent.kind) { + case 159: + return true; + case 201: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; } function isCallExpressionTarget(node) { return isCallOrNewExpressionTarget(node, 181); @@ -58483,7 +60336,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 && referenceNode.label.text === labelName) { + if (referenceNode.kind === 222 && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -58551,6 +60404,9 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { + if (node.kind === 283) { + node = node.parent.parent; + } while (true) { node = node.parent; if (!node) { @@ -58576,15 +60432,15 @@ var ts; function getNodeKind(node) { switch (node.kind) { case 265: - return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + return ts.isExternalModule(node) ? "module" : "script"; case 233: - return ts.ScriptElementKind.moduleElement; + return "module"; case 229: case 199: - return ts.ScriptElementKind.classElement; - case 230: return ts.ScriptElementKind.interfaceElement; - case 231: return ts.ScriptElementKind.typeElement; - case 232: return ts.ScriptElementKind.enumElement; + return "class"; + case 230: return "interface"; + case 231: return "type"; + case 232: return "enum"; case 226: return getKindOfVariableDeclaration(node); case 176: @@ -58592,39 +60448,39 @@ var ts; case 187: case 228: case 186: - return ts.ScriptElementKind.functionElement; - case 153: return ts.ScriptElementKind.memberGetAccessorElement; - case 154: return ts.ScriptElementKind.memberSetAccessorElement; + return "function"; + case 153: return "getter"; + case 154: return "setter"; case 151: case 150: - return ts.ScriptElementKind.memberFunctionElement; + return "method"; case 149: case 148: - return ts.ScriptElementKind.memberVariableElement; - case 157: return ts.ScriptElementKind.indexSignatureElement; - case 156: return ts.ScriptElementKind.constructSignatureElement; - case 155: return ts.ScriptElementKind.callSignatureElement; - case 152: return ts.ScriptElementKind.constructorImplementationElement; - case 145: return ts.ScriptElementKind.typeParameterElement; - case 264: return ts.ScriptElementKind.enumMemberElement; - case 146: return ts.hasModifier(node, 92) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + return "property"; + case 157: return "index"; + case 156: return "construct"; + case 155: return "call"; + case 152: return "constructor"; + case 145: return "type parameter"; + case 264: return "enum member"; + case 146: return ts.hasModifier(node, 92) ? "property" : "parameter"; case 237: case 242: case 239: case 246: case 240: - return ts.ScriptElementKind.alias; - case 290: - return ts.ScriptElementKind.typeElement; + return "alias"; + case 283: + return "type"; default: - return ts.ScriptElementKind.unknown; + return ""; } function getKindOfVariableDeclaration(v) { return ts.isConst(v) - ? ts.ScriptElementKind.constElement + ? "const" : ts.isLet(v) - ? ts.ScriptElementKind.letElement - : ts.ScriptElementKind.variableElement; + ? "let" + : "var"; } } ts.getNodeKind = getNodeKind; @@ -58820,7 +60676,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 294 && c.pos <= node.pos && c.end >= node.end) { + if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -58829,27 +60685,22 @@ var ts; } ts.findContainingList = findContainingList; function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, false, includeItemAtEndPosition, includeJsDocComment); + function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, false, includePrecedingTokenAtEndPosition, false, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeJsDocComment); + function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, true, undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { @@ -58857,21 +60708,21 @@ var ts; } for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; - if (ts.isJSDocNode(child) && !includeJsDocComment) { + if (!includeJsDocComment && ts.isJSDocNode(child)) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); if (start > position) { - continue; + break; } var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1)) { + if (position < end || (position === end && (child.kind === 1 || includeEndPosition))) { current = child; continue outer; } - else if (includeItemAtEndPosition && end === position) { + else if (includePrecedingTokenAtEndPosition && end === position) { var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { return previousToken; } } @@ -58880,7 +60731,7 @@ var ts; } } function findTokenOnLeftOfPosition(file, position) { - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -58906,7 +60757,7 @@ var ts; } } ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { + function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { return find(startNode || sourceFile); function findRightmostToken(n) { if (ts.isToken(n)) { @@ -58924,7 +60775,7 @@ var ts; for (var i = 0; i < children.length; i++) { var child = children[i]; if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { - var start = child.getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 && start === child.end); if (lookInPreviousChild) { @@ -58936,7 +60787,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265); + ts.Debug.assert(startNode !== undefined || n.kind === 265 || ts.isJSDocCommentContainingNode(n)); if (children.length) { var candidate = findRightmostChildNodeWithTokens(children, children.length); return candidate && findRightmostToken(candidate); @@ -58953,7 +60804,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9) { + if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); if (start < position && position < end) { @@ -58967,7 +60818,7 @@ var ts; } ts.isInString = isInString; function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); if (!token) { return false; } @@ -58990,12 +60841,12 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, false); } return position <= tokenAtPosition.getStart(sourceFile) && (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); @@ -59018,7 +60869,7 @@ var ts; } } function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, false); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); function jsDocPrefix(c) { @@ -59027,38 +60878,6 @@ var ts; } } ts.hasDocComment = hasDocComment; - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (ts.isToken(node)) { - switch (node.kind) { - case 104: - case 110: - case 76: - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (jsDoc.tags) { - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } - } - } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; function nodeHasTokens(n) { return n.getWidth() !== 0; } @@ -59066,20 +60885,20 @@ var ts; var flags = ts.getCombinedModifierFlags(node); var result = []; if (flags & 8) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); + result.push("private"); if (flags & 16) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + result.push("protected"); if (flags & 4) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); + result.push("public"); if (flags & 32) - result.push(ts.ScriptElementKindModifier.staticModifier); + result.push("static"); if (flags & 128) - result.push(ts.ScriptElementKindModifier.abstractModifier); + result.push("abstract"); if (flags & 1) - result.push(ts.ScriptElementKindModifier.exportedModifier); + result.push("export"); if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + result.push("declare"); + return result.length > 0 ? result.join(",") : ""; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { @@ -59131,6 +60950,12 @@ var ts; return false; } ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; function compareDataObjects(dst, src) { if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { return false; @@ -59253,7 +61078,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop + reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { if (lineStart) { @@ -59325,7 +61150,7 @@ var ts; else if (flags & 524288) { return ts.SymbolDisplayPartKind.aliasName; } - else if (flags & 8388608) { + else if (flags & 2097152) { return ts.SymbolDisplayPartKind.aliasName; } return ts.SymbolDisplayPartKind.text; @@ -59333,10 +61158,7 @@ var ts; } ts.symbolPart = symbolPart; function displayPart(text, kind) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] - }; + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; } ts.displayPart = displayPart; function spacePart() { @@ -59376,10 +61198,13 @@ var ts; } ts.lineBreakPart = lineBreakPart; function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { @@ -59402,7 +61227,7 @@ var ts; ts.signatureToDisplayParts = signatureToDisplayParts; function getDeclaredName(typeChecker, symbol, location) { if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144) { - return location.text; + return ts.getTextOfIdentifierOrLiteral(location); } var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); return typeChecker.symbolToString(localExportDefaultSymbol || symbol); @@ -59434,38 +61259,9 @@ var ts; } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - var trimmedOutput = outputText.trim(); - 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; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -59478,7 +61274,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -59490,7 +61286,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, false); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); @@ -60003,7 +61799,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_7 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -60011,8 +61807,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_7, classification: convertClassification(type) }); + lastEnd = start + length_7; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -60366,7 +62162,7 @@ var ts; checkForClassificationCancellation(cancellationToken, kind); if (kind === 71 && !ts.nodeIsMissing(node)) { var identifier = node; - if (classifiableNames.get(identifier.text)) { + if (classifiableNames.has(identifier.escapedText)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); @@ -60383,29 +62179,29 @@ var ts; ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; function getClassificationTypeName(type) { switch (type) { - case 1: return ts.ClassificationTypeNames.comment; - case 2: return ts.ClassificationTypeNames.identifier; - case 3: return ts.ClassificationTypeNames.keyword; - case 4: return ts.ClassificationTypeNames.numericLiteral; - case 5: return ts.ClassificationTypeNames.operator; - case 6: return ts.ClassificationTypeNames.stringLiteral; - case 8: return ts.ClassificationTypeNames.whiteSpace; - case 9: return ts.ClassificationTypeNames.text; - case 10: return ts.ClassificationTypeNames.punctuation; - case 11: return ts.ClassificationTypeNames.className; - case 12: return ts.ClassificationTypeNames.enumName; - case 13: return ts.ClassificationTypeNames.interfaceName; - case 14: return ts.ClassificationTypeNames.moduleName; - case 15: return ts.ClassificationTypeNames.typeParameterName; - case 16: return ts.ClassificationTypeNames.typeAliasName; - case 17: return ts.ClassificationTypeNames.parameterName; - case 18: return ts.ClassificationTypeNames.docCommentTagName; - case 19: return ts.ClassificationTypeNames.jsxOpenTagName; - case 20: return ts.ClassificationTypeNames.jsxCloseTagName; - case 21: return ts.ClassificationTypeNames.jsxSelfClosingTagName; - case 22: return ts.ClassificationTypeNames.jsxAttribute; - case 23: return ts.ClassificationTypeNames.jsxText; - case 24: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + case 1: return "comment"; + case 2: return "identifier"; + case 3: return "keyword"; + case 4: return "number"; + case 5: return "operator"; + case 6: return "string"; + case 8: return "whitespace"; + case 9: return "text"; + case 10: return "punctuation"; + case 11: return "class name"; + case 12: return "enum name"; + case 13: return "interface name"; + case 14: return "module name"; + case 15: return "type parameter name"; + case 16: return "type alias name"; + case 17: return "parameter name"; + case 18: return "doc comment tag name"; + case 19: return "jsx open tag name"; + case 20: return "jsx close tag name"; + case 21: return "jsx self closing tag name"; + case 22: return "jsx attribute"; + case 23: return "jsx text"; + case 24: return "jsx attribute string literal value"; } } function convertClassifications(classifications) { @@ -60465,7 +62261,7 @@ var ts; pushClassification(start, width, 1); continue; } - ts.Debug.assert(ch === 61); + ts.Debug.assert(ch === 124 || ch === 61); classifyDisabledMergeCode(text, start, end); } } @@ -60496,16 +62292,16 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18); pos = tag.tagName.end; switch (tag.kind) { - case 286: + case 279: processJSDocParameterTag(tag); break; - case 289: + case 282: processJSDocTemplateTag(tag); break; - case 288: + case 281: processElement(tag.typeExpression); break; - case 287: + case 280: processElement(tag.typeExpression); break; } @@ -60517,20 +62313,20 @@ var ts; } return; function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17); - pos = tag.preParameterName.end; + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17); + pos = tag.name.end; } if (tag.typeExpression) { pushCommentRange(pos, tag.typeExpression.pos - pos); processElement(tag.typeExpression); pos = tag.typeExpression.end; } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17); - pos = tag.postParameterName.end; + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17); + pos = tag.name.end; } } } @@ -60563,7 +62359,7 @@ var ts; } } function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { + if (ts.isJSDoc(node)) { return true; } if (ts.nodeIsMissing(node)) { @@ -60741,14 +62537,9 @@ var ts; PathCompletions.getStringLiteralCompletionEntriesFromModuleNames = getStringLiteralCompletionEntriesFromModuleNames; function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase) { rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); - var relativeDirectory; - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDirectory = rootDirs_1[_i]; - if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { - relativeDirectory = scriptPath.substr(rootDirectory.length); - break; - } - } + var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + }); return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); } function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { @@ -60792,7 +62583,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + result.push(createCompletionEntryForModule(foundFile, "script", span)); }); } var directories = tryGetDirectories(host, baseDirectory); @@ -60800,7 +62591,7 @@ var ts; for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { var directory = directories_2[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + result.push(createCompletionEntryForModule(directoryName, "directory", span)); } } } @@ -60823,7 +62614,7 @@ var ts; var pattern = _a[_i]; for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { var match = _c[_b]; - result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(match, "external module name", span)); } } } @@ -60831,7 +62622,7 @@ var ts; else if (ts.startsWith(path, fragment)) { var entry = paths[path] && paths[path].length === 1 && paths[path][0]; if (entry) { - result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(path, "external module name", span)); } } } @@ -60844,7 +62635,7 @@ var ts; getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { var moduleName = _e[_d]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } return result; } @@ -60871,8 +62662,8 @@ var ts; continue; } var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); + var length_8 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); } return result; } @@ -60884,21 +62675,18 @@ var ts; var isNestedModule = fragment.indexOf(ts.directorySeparator) !== -1; var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); - var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); if (isNestedModule) { var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { - if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { - return moduleName.substr(moduleNameWithSeperator_1.length); - } - return moduleName; + nonRelativeModuleNames = ts.map(nonRelativeModuleNames, function (nonRelativeModuleName) { + return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); } if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { var visibleModule = _a[_i]; if (!isNestedModule) { - nonRelativeModules.push(visibleModule.moduleName); + nonRelativeModuleNames.push(visibleModule.moduleName); } else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, undefined, ["./*"]); @@ -60907,16 +62695,16 @@ var ts; var f = nestedFiles_1[_b]; f = ts.normalizePath(f); var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); - nonRelativeModules.push(nestedModule); + nonRelativeModuleNames.push(nestedModule); } } } } } - return ts.deduplicate(nonRelativeModules); + return ts.deduplicate(nonRelativeModuleNames); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, false); if (!token) { return undefined; } @@ -60958,7 +62746,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } } else if (host.getDirectories) { @@ -60990,7 +62778,7 @@ var ts; for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { var typeDirectory = directories_3[_i]; typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name", span)); } } } @@ -61061,7 +62849,7 @@ var ts; } } function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + return { name: name, kind: kind, kindModifiers: "", sortText: name, replacementSpan: replacementSpan }; } function getDirectoryFragmentTextSpan(text, textStart) { var index = text.lastIndexOf(ts.directorySeparator); @@ -61118,6 +62906,12 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var KeywordCompletionFilters; + (function (KeywordCompletionFilters) { + KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); @@ -61129,70 +62923,66 @@ 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, hasFilteredClassMemberKeywords = completionData.hasFilteredClassMemberKeywords; - if (requestJsDocTagName) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagNameCompletions() }; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + if (sourceFile.languageVariant === 1 && + location && location.parent && location.parent.kind === 252) { + var tagName = location.parent.parent.openingElement.tagName; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, + entries: [{ + name: tagName.getFullText(), + kind: "class", + kindModifiers: undefined, + sortText: "0", + }] }; } - if (requestJsDocTag) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagCompletions() }; + if (request) { + var entries_2 = request.kind === "JsDocTagName" + ? ts.JsDoc.getJSDocTagNameCompletions() + : request.kind === "JsDocTag" + ? ts.JsDoc.getJSDocTagCompletions() + : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target)); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 && - location.parent && location.parent.kind === 252) { - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0", - }); - } - else if (!hasFilteredClassMemberKeywords) { - return undefined; - } + if ((!symbols || symbols.length === 0) && keywordFilters === 0) { + return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log); } - if (hasFilteredClassMemberKeywords) { - ts.addRange(entries, classMemberKeywordCompletions); - } - else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { - ts.addRange(entries, keywordCompletions); + if (keywordFilters !== 0 || !isMemberCompletion) { + ts.addRange(entries, getKeywordCompletions(keywordFilters)); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target) { - var entries = []; - var nameTable = ts.getNameTable(sourceFile); - nameTable.forEach(function (pos, name) { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { if (pos === position) { return; } - if (!uniqueNames.get(name)) { - uniqueNames.set(name, name); - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name), target, true); - if (displayName) { - var entry = { - name: displayName, - kind: ts.ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } + var realName = ts.unescapeLeadingUnderscores(name); + if (uniqueNames.has(realName)) { + return; + } + uniqueNames.set(realName, true); + var displayName = getCompletionEntryDisplayName(realName, target, true); + if (displayName) { + entries.push({ + name: displayName, + kind: "warning", + kindModifiers: "", + sortText: "1" + }); } }); - return entries; } function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { - var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); if (!displayName) { return undefined; } @@ -61211,10 +63001,10 @@ var ts; var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!uniqueNames.get(id)) { + var id = entry.name; + if (!uniqueNames.has(id)) { entries.push(entry); - uniqueNames.set(id, id); + uniqueNames.set(id, true); } } } @@ -61266,9 +63056,9 @@ var ts; 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]; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { @@ -61317,8 +63107,8 @@ var ts; uniques.set(name, true); result.push({ name: name, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, + kindModifiers: "", + kind: "var", sortText: "0" }); } @@ -61327,10 +63117,10 @@ var ts; function getCompletionEntryDetails(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_1 = completionData.location; - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_1) === entryName ? s : undefined; }); + var symbols = completionData.symbols, location = completionData.location; + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_1, location_1, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -61341,12 +63131,12 @@ var ts; }; } } - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0), function (c) { return c.name === entryName; }); if (keywordCompletion) { return { name: entryName, - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "keyword", + kindModifiers: "", displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, tags: undefined @@ -61357,72 +63147,71 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, false, location_2) === entryName ? s : undefined; }); - } - return undefined; + return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - var requestJsDocTagName = false; - var requestJsDocTag = false; + var request; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, false); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64) { - requestJsDocTagName = true; + request = { kind: "JsDocTagName" }; } else { var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); - requestJsDocTag = !(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/)); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + request = { kind: "JsDocTag" }; + } } } - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); + var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - requestJsDocTagName = true; + request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 288: - case 286: - case 287: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267) { + currentToken = ts.getTokenAtPosition(sourceFile, position, true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 284 || + currentToken.parent.name !== currentToken))) { + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } - if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; + if (request) { + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile); + var previousToken = ts.findPrecedingToken(position, sourceFile, undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + var start_4 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, undefined, insideJsDocTagTypeExpression); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } var node = currentToken; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); if (contextToken) { if (isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); @@ -61473,7 +63262,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; - var hasFilteredClassMemberKeywords = false; + var keywordFilters = 0; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -61481,7 +63270,7 @@ var ts; else if (isRightOfOpenTag) { var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 8388608)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 | 2097152)); })); } else { symbols = tagSymbols; @@ -61504,42 +63293,64 @@ 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, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 277: + case 279: + case 284: + case 280: + case 281: + case 283: + return true; + } + } function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 71 || node.kind === 143 || node.kind === 179) { + var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); - if (symbol && symbol.flags & 8388608) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952) { - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 | 384)) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isRhsOfImportDeclaration ? + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var symbol_2 = exportedSymbols_1[_i]; + if (isValidAccess(symbol_2)) { + symbols.push(symbol_2); + } } - }); + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 && d.kind !== 233 && d.kind !== 232; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } } function addTypeProperties(type) { - if (type) { - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); } - if (isJavaScriptFile && type.flags & 65536) { - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } + } + if (isJavaScriptFile && type.flags & 65536) { + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); } } } @@ -61554,6 +63365,12 @@ var ts; if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (tryGetConstructorLikeCompletionContainer(contextToken)) { + isMemberCompletion = false; + isNewIdentifierLocation = true; + keywordFilters = 2; + return true; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { getGetClassLikeCompletionSymbols(classLikeContainer); return true; @@ -61586,10 +63403,64 @@ var ts; scopeNode.kind === 256 || ts.isStatement(scopeNode); } - var symbolMeanings = 793064 | 107455 | 1920 | 8388608; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + var symbolMeanings = 793064 | 107455 | 1920 | 2097152; + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + if (ts.isExportAssignment(location.parent)) { + return true; + } + if (symbol && symbol.flags & 2097152) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + return symbolCanBeReferencedAtTypeLocation(symbol); + } + } + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 && + contextToken.parent.kind === 162; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56: + return parentKind === 149 || + parentKind === 148 || + parentKind === 146 || + parentKind === 226 || + ts.isFunctionLikeKind(parentKind); + case 58: + return parentKind === 231; + case 118: + return parentKind === 202; + } + } + } + function symbolCanBeReferencedAtTypeLocation(symbol) { + symbol = symbol.exportSymbol || symbol; + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & 793064) { + return true; + } + if (symbol.flags & 1536) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); + } + } function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { @@ -61673,9 +63544,9 @@ var ts; if (contextToken.kind === 9 || contextToken.kind === 12 || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_3 = contextToken.getStart(); + var start_5 = contextToken.getStart(); var end = contextToken.getEnd(); - if (start_3 < position && position < end) { + if (start_5 < position && position < end) { return true; } if (position === end) { @@ -61697,34 +63568,29 @@ var ts; typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 174) { + else { + ts.Debug.assert(objectLikeContainer.kind === 174); isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 146) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 151 || rootDeclaration.parent.kind === 154) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } + if (!ts.isVariableLike(rootDeclaration)) + throw ts.Debug.fail("Root declaration is not variable-like."); + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216; + if (!canGetType && rootDeclaration.kind === 146) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - if (canGetType) { - var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - if (!typeForObject) - return false; - typeMembers = typeChecker.getPropertiesOfType(typeForObject); - existingMembers = objectLikeContainer.elements; + else if (rootDeclaration.parent.kind === 151 || rootDeclaration.parent.kind === 154) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } - else { - ts.Debug.fail("Root declaration is not variable-like."); + if (canGetType) { + var typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); + if (!typeForObject) + return false; + typeMembers = typeChecker.getPropertiesOfType(typeForObject); + existingMembers = objectLikeContainer.elements; } } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } if (typeMembers && typeMembers.length > 0) { symbols = filterObjectMembersList(typeMembers, existingMembers); } @@ -61753,7 +63619,7 @@ var ts; function getGetClassLikeCompletionSymbols(classLikeDeclaration) { isMemberCompletion = true; isNewIdentifierLocation = true; - hasFilteredClassMemberKeywords = true; + keywordFilters = 1; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); if (baseTypeNode || implementsTypeNodes) { @@ -61778,11 +63644,11 @@ var ts; } } var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32) ? - undefined : - ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + ts.emptyArray : + ts.flatMap(implementsTypeNodes || ts.emptyArray, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); symbols = filterClassMembersList(baseClassTypeToGetPropertiesFrom ? typeChecker.getPropertiesOfType(baseClassTypeToGetPropertiesFrom) : - undefined, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); + ts.emptyArray, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); } } } @@ -61792,7 +63658,7 @@ var ts; case 17: case 26: var parent = contextToken.parent; - if (parent && (parent.kind === 178 || parent.kind === 174)) { + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; @@ -61817,6 +63683,14 @@ var ts; function isFromClassElementDeclaration(node) { return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); } + function isParameterOfConstructorDeclaration(node) { + return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); + } + function isConstructorParameterCompletion(node) { + return node.parent && + isParameterOfConstructorDeclaration(node.parent) && + (isConstructorParameterCompletionKeyword(node.kind) || ts.isDeclarationName(node)); + } function tryGetClassLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { @@ -61826,6 +63700,10 @@ var ts; } break; case 26: + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; case 25: case 18: if (ts.isClassLike(location)) { @@ -61840,11 +63718,25 @@ var ts; } } } - if (location && location.kind === 294 && ts.isClassLike(location.parent)) { + if (location && location.kind === 286 && ts.isClassLike(location.parent)) { return location.parent; } return undefined; } + function tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 19: + case 26: + return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + default: + if (isConstructorParameterCompletion(contextToken)) { + return contextToken.parent.parent; + } + } + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -61882,19 +63774,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152: - case 161: - case 160: - return false; - default: - return true; - } - } function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { @@ -61903,12 +63782,13 @@ var ts; containingNodeKind === 227 || containingNodeKind === 208 || containingNodeKind === 232 || - isFunction(containingNodeKind) || - containingNodeKind === 229 || - containingNodeKind === 199 || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 230 || containingNodeKind === 175 || - containingNodeKind === 231; + containingNodeKind === 231 || + (ts.isClassLike(contextToken.parent) && + contextToken.parent.typeParameters && + contextToken.parent.typeParameters.end >= contextToken.pos); case 23: return containingNodeKind === 175; case 56: @@ -61917,7 +63797,7 @@ var ts; return containingNodeKind === 175; case 19: return containingNodeKind === 260 || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17: return containingNodeKind === 232 || containingNodeKind === 230 || @@ -61932,7 +63812,7 @@ var ts; containingNodeKind === 199 || containingNodeKind === 230 || containingNodeKind === 231 || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115: return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: @@ -61942,7 +63822,7 @@ var ts; case 114: case 112: case 113: - return containingNodeKind === 146; + return containingNodeKind === 146 && !ts.isConstructorDeclaration(contextToken.parent.parent); case 118: return containingNodeKind === 242 || containingNodeKind === 246 || @@ -61968,6 +63848,13 @@ var ts; isFromClassElementDeclaration(contextToken)) { return false; } + if (isConstructorParameterCompletion(contextToken)) { + if (!ts.isIdentifier(contextToken) || + isConstructorParameterCompletionKeywordText(contextToken.getText()) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } switch (contextToken.getText()) { case "abstract": case "async": @@ -61986,7 +63873,10 @@ var ts; case "yield": return true; } - return false; + return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8) { @@ -61996,25 +63886,25 @@ var ts; return false; } function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = ts.createMap(); + var existingImportsOrExports = ts.createUnderscoreEscapedMap(); for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { var element = namedImportsOrExports_1[_i]; if (isCurrentlyEditingNode(element)) { continue; } var name = element.propertyName || element.name; - existingImportsOrExports.set(name.text, true); + existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports.get(e.name); }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); } function filterObjectMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; } - var existingMemberNames = ts.createMap(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; if (m.kind !== 261 && @@ -62031,18 +63921,19 @@ var ts; var existingName = void 0; if (m.kind === 176 && m.propertyName) { if (m.propertyName.kind === 71) { - existingName = m.propertyName.text; + existingName = m.propertyName.escapedText; } } else { - existingName = ts.getNameOfDeclaration(m).text; + var name = ts.getNameOfDeclaration(m); + existingName = ts.getEscapedTextOfIdentifierOrLiteral(name); } existingMemberNames.set(existingName, true); } - return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.escapedName); }); } function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { - var existingMemberNames = ts.createMap(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; if (m.kind !== 149 && @@ -62068,63 +63959,91 @@ var ts; 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); })); + var result = []; + addPropertySymbols(baseSymbols, 8); + addPropertySymbols(implementingTypeSymbols, 24); + return result; + function addPropertySymbols(properties, inValidModifierFlags) { + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; + if (isValidProperty(property, inValidModifierFlags)) { + result.push(property); + } + } + } function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.name) && + return !existingMemberNames.get(propertySymbol.escapedName) && propertySymbol.getDeclarations() && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); } } function filterJsxAttributes(symbols, attributes) { - var seenNames = ts.createMap(); + var seenNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { var attr = attributes_1[_i]; if (isCurrentlyEditingNode(attr)) { continue; } if (attr.kind === 253) { - seenNames.set(attr.name.text, true); + seenNames.set(attr.name.escapedText, true); } } - return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); + return ts.filter(symbols, function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(typeChecker, symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - if ((symbol.flags & 1920) && (firstCharCode === 39 || firstCharCode === 34)) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + var name = symbol.name; + if (!name) + return undefined; + if (symbol.flags & 1920) { + var firstCharCode = name.charCodeAt(0); + if (firstCharCode === 39 || firstCharCode === 34) { return undefined; } } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks); } function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { + if (performCharacterChecks && !ts.isIdentifierText(name, target)) { return undefined; } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } - if (performCharacterChecks) { - if (!ts.isIdentifierText(name, target)) { - return undefined; - } - } return name; } - var keywordCompletions = []; - for (var i = 72; i <= 142; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, - sortText: "0" - }); + var _keywordCompletions = []; + function getKeywordCompletions(keywordFilter) { + var completions = _keywordCompletions[keywordFilter]; + if (completions) { + return completions; + } + return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); + function generateKeywordCompletions(keywordFilter) { + switch (keywordFilter) { + case 0: + return getAllKeywordCompletions(); + case 1: + return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + case 2: + return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + } + } + function getAllKeywordCompletions() { + var allKeywordsCompletions = []; + for (var i = 72; i <= 142; i++) { + allKeywordsCompletions.push({ + name: ts.tokenToString(i), + kind: "keyword", + kindModifiers: "", + sortText: "0" + }); + } + return allKeywordsCompletions; + } + function getFilteredKeywordCompletions(filterFn) { + return ts.filter(getKeywordCompletions(0), function (entry) { return filterFn(entry.name); }); + } } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -62144,9 +64063,18 @@ var ts; function isClassMemberCompletionKeywordText(text) { return isClassMemberCompletionKeyword(ts.stringToToken(text)); } - var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { - return isClassMemberCompletionKeywordText(entry.name); - }); + function isConstructorParameterCompletionKeyword(kind) { + switch (kind) { + case 114: + case 112: + case 113: + case 131: + return true; + } + } + function isConstructorParameterCompletionKeywordText(text) { + return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); + } function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -62156,6 +64084,34 @@ var ts; kind === 34 || kind === 35; } + function getJsDocTagAtPosition(node, position) { + var jsDoc = getJsDocHavingNode(node).jsDoc; + if (!jsDoc) + return undefined; + for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) { + var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags; + if (!tags || position < pos || position > end) + continue; + for (var i = tags.length - 1; i >= 0; i--) { + var tag = tags[i]; + if (position >= tag.pos) { + return tag; + } + } + } + } + function getJsDocHavingNode(node) { + if (!ts.isToken(node)) + return node; + switch (node.kind) { + case 104: + case 110: + case 76: + return node.parent.parent; + default: + return node.parent; + } + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); var ts; @@ -62163,17 +64119,26 @@ var ts; var DocumentHighlights; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + var node = ts.getTouchingWord(sourceFile, position, true); + if (node === sourceFile) + return undefined; + ts.Debug.assert(node.parent !== undefined); + if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var end = node.getEnd(); return { fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: ts.HighlightSpanKind.none + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" }; } function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { @@ -62407,7 +64372,7 @@ var ts; case 234: case 265: if (modifierFlag & 128) { - nodes = declaration.members.concat(declaration); + nodes = declaration.members.concat([declaration]); } else { nodes = container.statements; @@ -62428,7 +64393,7 @@ var ts; } } else if (modifierFlag & 128) { - nodes = nodes.concat(container); + nodes = nodes.concat([container]); } break; default: @@ -62620,7 +64585,7 @@ var ts; result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: ts.HighlightSpanKind.reference + kind: "reference" }); i++; continue; @@ -62632,7 +64597,7 @@ var ts; } function isLabeledBy(node, labelName) { for (var owner = node.parent; owner.kind === 222; owner = owner.parent) { - if (owner.label.text === labelName) { + if (owner.label.escapedText === labelName) { return true; } } @@ -62652,7 +64617,7 @@ var ts; function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createFileMap()); + buckets.set(key, bucket = ts.createMap()); } return bucket; } @@ -62660,9 +64625,9 @@ var ts; var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); var sourceFiles = []; - entries.forEachValue(function (key, entry) { + entries.forEach(function (entry, name) { sourceFiles.push({ - name: key, + name: name, refCount: entry.languageServiceRefCount, references: entry.owners.slice(0) }); @@ -62726,7 +64691,7 @@ var ts; entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(path); + bucket.delete(path); } } return { @@ -62788,7 +64753,7 @@ var ts; } function handleDirectImports(exportingModuleSymbol) { var theseDirectImports = getDirectImports(exportingModuleSymbol); - if (theseDirectImports) + if (theseDirectImports) { for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { var direct = theseDirectImports_1[_i]; if (!markSeenDirectImport(direct)) { @@ -62831,6 +64796,7 @@ var ts; break; } } + } } function handleNamespaceImport(importDeclaration, name, isReExport) { if (exportKind === 2) { @@ -62862,28 +64828,30 @@ var ts; var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); ts.Debug.assert(!!(moduleSymbol.flags & 1536)); var directImports = getDirectImports(moduleSymbol); - if (directImports) + if (directImports) { for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { var directImport = directImports_1[_i]; addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); } + } } function getDirectImports(moduleSymbol) { return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); } } function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.name; + var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { importSearches.push([location, symbol]); } - if (directImports) + if (directImports) { for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { var decl = directImports_2[_i]; handleImport(decl); } + } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { if (decl.kind === 237) { @@ -62917,7 +64885,7 @@ var ts; } else { var name = importClause.name; - if (name && (!isForRename || name.text === symbolName(exportSymbol))) { + if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { var defaultImportAlias = checker.getSymbolAtLocation(name); addSearch(name, defaultImportAlias); } @@ -62928,16 +64896,16 @@ var ts; } } function handleNamespaceImportLike(importName) { - if (exportKind === 2 && (!isForRename || importName.text === exportName)) { + if (exportKind === 2 && (!isForRename || importName.escapedText === exportName)) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) + if (namedBindings) { for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var element = _a[_i]; var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).text !== exportName) { + if ((propertyName || name).escapedText !== exportName) { continue; } if (propertyName) { @@ -62953,6 +64921,7 @@ var ts; addSearch(name, localSymbol); } } + } } } function findNamespaceReExports(sourceFileLike, name, checker) { @@ -63074,22 +65043,20 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; - if (symbol.flags & 7340032) { + if (symbol.exportSymbol) { if (parent.kind === 179) { - return symbol.declarations.some(function (d) { return d === parent; }) && parent.parent.kind === 194 + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) ? getSpecialPropertyExport(parent.parent, false) : undefined; } else { - var exportSymbol = symbol.exportSymbol; - ts.Debug.assert(!!exportSymbol); - return exportInfo(exportSymbol, getExportKindForDeclaration(parent)); + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); } } else { - var exportNode = getExportNode(parent); + var exportNode = getExportNode(parent, node); if (exportNode && ts.hasModifier(exportNode, 1)) { - if (exportNode.kind === 237 && exportNode.moduleReference === node) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { if (comingFromExport) { return undefined; } @@ -63100,18 +65067,24 @@ var ts; return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } } - else if (parent.kind === 243) { - var exportingModuleSymbol = parent.symbol.parent; - ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 } }; + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); } - else if (parent.kind === 194) { + else if (ts.isExportAssignment(parent.parent)) { + return getExportAssignmentExport(parent.parent); + } + else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, true); } - else if (parent.parent.kind === 194) { + else if (ts.isBinaryExpression(parent.parent)) { return getSpecialPropertyExport(parent.parent, true); } } + function getExportAssignmentExport(ex) { + var exportingModuleSymbol = ex.symbol.parent; + ts.Debug.assert(!!exportingModuleSymbol); + return { kind: 1, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 } }; + } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; switch (ts.getSpecialPropertyAssignmentKind(node)) { @@ -63131,16 +65104,16 @@ var ts; function getImport() { var isImport = isNodeImport(node); if (!isImport) - return; + return undefined; var importedSymbol = checker.getImmediateAliasedSymbol(symbol); - if (importedSymbol) { - importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); - if (importedSymbol.name === "export=") { - importedSymbol = checker.getImmediateAliasedSymbol(importedSymbol); - } - if (symbolName(importedSymbol) === symbol.name) { - return __assign({ kind: 0, symbol: importedSymbol }, isImport); - } + if (!importedSymbol) + return undefined; + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + if (symbolName(importedSymbol) === symbol.escapedName) { + return __assign({ kind: 0, symbol: importedSymbol }, isImport); } } function exportInfo(symbol, kind) { @@ -63152,10 +65125,24 @@ var ts; } } FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; - function getExportNode(parent) { + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152) { + return checker.getImmediateAliasedSymbol(importedSymbol); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { + return decl.expression.symbol; + } + else if (ts.isBinaryExpression(decl)) { + return decl.right.symbol; + } + ts.Debug.fail(); + } + function getExportNode(parent, node) { if (parent.kind === 226) { var p = parent; - return p.parent.kind === 260 ? undefined : p.parent.parent.kind === 208 ? p.parent.parent : undefined; + return p.name !== node ? undefined : + p.parent.kind === 260 ? undefined : p.parent.parent.kind === 208 ? p.parent.parent : undefined; } else { return parent; @@ -63184,25 +65171,26 @@ var ts; } FindAllReferences.getExportInfo = getExportInfo; function symbolName(symbol) { - if (symbol.name !== "default") { - return symbol.name; + if (symbol.escapedName !== "default") { + return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; } var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 && name.text; + return name && name.kind === 71 && name.escapedText; }); } function skipExportSpecifierSymbol(symbol, checker) { - if (symbol.declarations) + if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { return checker.getExportSpecifierLocalTargetSymbol(declaration); } } + } return symbol; } function getContainingModuleSymbol(importer, checker) { @@ -63253,13 +65241,16 @@ var ts; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, false); 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(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265) { + return undefined; + } var checker = program.getTypeChecker(); if (node.parent.kind === 262) { var result_5 = []; @@ -63302,22 +65293,22 @@ var ts; } case "label": { var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: ts.ScriptElementKind.label, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + return { node: node_3, name: node_3.text, kind: "label", displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: ts.ScriptElementKind.keyword, displayParts: [{ text: name_4, kind: ts.ScriptElementKind.keyword }] }; + return { node: node_4, name: name_4, kind: "keyword", displayParts: [{ text: name_4, kind: "keyword" }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: ts.ScriptElementKind.variableElement, displayParts: displayParts_2 }; + return { node: node_5, name: "this", kind: "var", displayParts: displayParts_2 }; } case "string": { var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: ts.ScriptElementKind.variableElement, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + return { node: node_6, name: node_6.text, kind: "var", displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -63349,7 +65340,7 @@ var ts; fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -63360,7 +65351,7 @@ var ts; } else { var textSpan = entry.textSpan, fileName = entry.fileName; - return { textSpan: textSpan, fileName: fileName, kind: ts.ScriptElementKind.unknown, displayParts: [] }; + return { textSpan: textSpan, fileName: fileName, kind: "", displayParts: [] }; } } function implementationKindDisplayParts(node, checker) { @@ -63370,13 +65361,13 @@ var ts; } else if (node.kind === 178) { return { - kind: ts.ScriptElementKind.interfaceElement, + kind: "interface", displayParts: [ts.punctuationPart(19), ts.textPart("object literal"), ts.punctuationPart(20)] }; } else if (node.kind === 199) { return { - kind: ts.ScriptElementKind.localClassElement, + kind: "local class", displayParts: [ts.punctuationPart(19), ts.textPart("anonymous local class"), ts.punctuationPart(20)] }; } @@ -63387,14 +65378,14 @@ var ts; function toHighlightSpan(entry) { if (entry.type === "span") { var fileName_1 = entry.fileName, textSpan = entry.textSpan; - return { fileName: fileName_1, span: { textSpan: textSpan, kind: ts.HighlightSpanKind.reference } }; + return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" } }; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; var writeAccess = isWriteAccess(node); var span = { textSpan: getTextSpan(node), - kind: writeAccess ? ts.HighlightSpanKind.writtenReference : ts.HighlightSpanKind.reference, + kind: writeAccess ? "writtenReference" : "reference", isInString: isInString }; return { fileName: fileName, span: span }; @@ -63410,20 +65401,19 @@ var ts; return ts.createTextSpanFromBounds(start, end); } function isWriteAccess(node) { - if (node.kind === 71 && ts.isDeclarationName(node)) { + if (ts.isAnyDeclarationName(node)) { return true; } var parent = node.parent; - if (parent) { - if (parent.kind === 193 || parent.kind === 192) { + switch (parent && parent.kind) { + case 193: + case 192: return true; - } - else if (parent.kind === 194 && parent.left === node) { - var operator = parent.operatorToken.kind; - return 58 <= operator && operator <= 70; - } + case 194: + return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); + default: + return false; } - return false; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -63468,7 +65458,7 @@ var ts; case 244: return true; case 181: - return ts.isRequireCall(node.parent, false); + return ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent); default: return false; } @@ -63529,7 +65519,7 @@ var ts; symbol = skipPastExportOrImportSpecifier(symbol, node, checker); var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; - var state = createState(sourceFiles, node, checker, cancellationToken, searchMeaning, options, result); + var state = new State(sourceFiles, node.kind === 123, checker, cancellationToken, searchMeaning, options, result); var search = state.createSearch(node, symbol, undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); var scope = getSymbolScope(symbol); if (scope) { @@ -63554,51 +65544,59 @@ var ts; } return symbol; } - function createState(sourceFiles, originalLocation, checker, cancellationToken, searchMeaning, options, result) { - var symbolIdToReferences = []; - var inheritsFromCache = ts.createMap(); - var sourceFileToSeenSymbols = []; - var isForConstructor = originalLocation.kind === 123; - var importTracker; - return __assign({}, options, { sourceFiles: sourceFiles, isForConstructor: isForConstructor, checker: checker, cancellationToken: cancellationToken, searchMeaning: searchMeaning, inheritsFromCache: inheritsFromCache, getImportSearches: getImportSearches, createSearch: createSearch, referenceAdder: referenceAdder, addStringOrCommentReference: addStringOrCommentReference, - markSearchedSymbol: markSearchedSymbol, markSeenContainingTypeReference: ts.nodeSeenTracker(), markSeenReExportRHS: ts.nodeSeenTracker() }); - function getImportSearches(exportSymbol, exportInfo) { - if (!importTracker) - importTracker = FindAllReferences.createImportTracker(sourceFiles, checker, cancellationToken); - return importTracker(exportSymbol, exportInfo, options.isForRename); + var State = (function () { + function State(sourceFiles, isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.isForConstructor = isForConstructor; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + this.inheritsFromCache = ts.createMap(); + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + this.sourceFileToSeenSymbols = []; } - function createSearch(location, symbol, comingFrom, searchOptions) { + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + }; + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; - var escapedText = ts.escapeIdentifier(text); - var parents = options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, checker); - return { location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: includes }; - function includes(referenceSymbol) { - return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; - } - } - function referenceAdder(referenceSymbol, searchLocation) { - var symbolId = ts.getSymbolId(referenceSymbol); - var references = symbolIdToReferences[symbolId]; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + return { + location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, + }; + }; + State.prototype.referenceAdder = function (searchSymbol, searchLocation) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; if (!references) { - references = symbolIdToReferences[symbolId] = []; - result.push({ definition: { type: "symbol", symbol: referenceSymbol, node: searchLocation }, references: references }); + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; - } - function addStringOrCommentReference(fileName, textSpan) { - result.push({ + }; + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ definition: undefined, references: [{ type: "span", fileName: fileName, textSpan: textSpan }] }); - } - function markSearchedSymbol(sourceFile, symbol) { + }; + State.prototype.markSearchedSymbol = function (sourceFile, symbol) { var sourceId = ts.getNodeId(sourceFile); var symbolId = ts.getSymbolId(symbol); - var seenSymbols = sourceFileToSeenSymbols[sourceId] || (sourceFileToSeenSymbols[sourceId] = []); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []); return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true); - } - } + }; + return State; + }()); function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; if (singleReferences.length) { @@ -63619,7 +65617,7 @@ var ts; indirectSearch = state.createSearch(exportLocation, exportSymbol, 1); break; case 1: - indirectSearch = state.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1, { text: "default" }); + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1, { text: "default" }); break; case 2: break; @@ -63647,15 +65645,17 @@ var ts; return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && checker.getPropertySymbolOfDestructuringAssignment(location); } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { + function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 176); - return bindingElement && + if (bindingElement && bindingElement.parent.kind === 174 && - !bindingElement.propertyName; + !bindingElement.propertyName) { + return bindingElement; + } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176); + var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); + if (bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } @@ -63670,20 +65670,18 @@ var ts; return undefined; } if (flags & (4 | 8192)) { - var privateDeclaration = ts.find(declarations, function (d) { return !!(ts.getModifierFlags(d) & 8); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8); }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 229); } + return undefined; } - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + if (getObjectBindingElementWithoutPropertyName(symbol)) { return undefined; } if (parent && !((parent.flags & 1536) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } - if ((flags & 134217728 && symbol.checkFlags & 6)) { - return undefined; - } var scope; for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var declaration = declarations_10[_i]; @@ -63698,11 +65696,8 @@ var ts; } return parent ? scope.getSourceFile() : scope; } - function getPossibleSymbolReferencePositions(sourceFile, symbolName, container, fullStart) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { 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; @@ -63710,9 +65705,9 @@ var ts; var text = sourceFile.text; var sourceLength = text.length; var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); + var position = text.indexOf(symbolName, container.pos); while (position >= 0) { - if (position > end) + if (position > container.end) break; var endPosition = position + symbolNameLength; if ((position === 0 || !ts.isIdentifierPart(text.charCodeAt(position - 1), 5)) && @@ -63730,7 +65725,7 @@ var ts; 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); + var node = ts.getTouchingWord(sourceFile, position, false); if (node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); } @@ -63740,7 +65735,7 @@ var ts; function isValidReferencePosition(node, searchSymbolName) { switch (node && node.kind) { case 71: - return ts.unescapeIdentifier(node.text).length === searchSymbolName.length; + return node.text.length === searchSymbolName.length; case 9: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && node.text.length === searchSymbolName.length; @@ -63760,10 +65755,10 @@ var ts; return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -63777,15 +65772,15 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, state.findInComments); _i < _a.length; _i++) { + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, true); if (!isValidReferencePosition(referenceLocation, search.text)) { - if (!state.implementations && (state.findInStrings && ts.isInString(sourceFile, position) || state.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { state.addStringOrCommentReference(sourceFile.fileName, ts.createTextSpan(position, search.text.length)); } return; @@ -63833,7 +65828,7 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.isForRename && state.markSeenReExportRHS(name)) { + if (!state.options.isForRename && state.markSeenReExportRHS(name)) { addReference(name, referenceSymbol, name, state); } } @@ -63842,7 +65837,7 @@ var ts; addRef(); } } - if (!(referenceLocation === propertyName && state.isForRename)) { + if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 ? 1 : 0; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); ts.Debug.assert(!!exportInfo); @@ -63874,7 +65869,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0) { - if (!state.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename || importOrExport.isNamedImport) { searchForImportedSymbol(symbol, state); } } @@ -63885,13 +65880,13 @@ var ts; function getReferenceForShorthandProperty(_a, search, state) { var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); - if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { + if (!(flags & 33554432) && search.includes(shorthandValueSymbol)) { addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { var addRef = state.referenceAdder(relatedSymbol, searchLocation); - if (state.implementations) { + if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { @@ -63980,15 +65975,16 @@ var ts; addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { - if (parent.body.kind === 207) { - ts.forEachReturnStatement(parent.body, function (returnStatement) { + var body = parent.body; + if (body.kind === 207) { + ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); } }); } - else if (isImplementationExpression(parent.body)) { - addReference(parent.body); + else if (isImplementationExpression(body)) { + addReference(body); } } else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { @@ -64119,7 +66115,7 @@ var ts; 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); + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || node.kind !== 97) { continue; } @@ -64177,7 +66173,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, false); if (!node || !ts.isThis(node)) { return; } @@ -64225,7 +66221,7 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + var node_7 = ts.getTouchingWord(sourceFile, position, false); if (node_7 && node_7.kind === 9 && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, true)); } @@ -64264,7 +66260,7 @@ var ts; result.push(rootSymbol); } if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 | 64)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap(), checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), checker); } } return result; @@ -64273,7 +66269,7 @@ var ts; if (!symbol) { return; } - if (previousIterationSymbolsCache.has(symbol.name)) { + if (previousIterationSymbolsCache.has(symbol.escapedName)) { return; } if (symbol.flags & (32 | 64)) { @@ -64296,7 +66292,7 @@ var ts; if (propertySymbol) { result.push.apply(result, checker.getRootSymbols(propertySymbol)); } - previousIterationSymbolsCache.set(symbol.name, symbol); + previousIterationSymbolsCache.set(symbol.escapedName, symbol); getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); } } @@ -64332,7 +66328,7 @@ var ts; return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, ts.createMap(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, ts.createSymbolTable(), state.checker); return ts.find(result, search.includes); } return undefined; @@ -64346,7 +66342,7 @@ var ts; } return undefined; } - return node.name.text; + return ts.getTextOfIdentifierOrLiteral(node.name); } function getPropertySymbolsFromContextualType(node, checker) { var objectLiteral = node.parent; @@ -64479,7 +66475,6 @@ var ts; if (referenceFile) { return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; } - return undefined; } var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { @@ -64487,14 +66482,14 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } if (ts.isJumpStatementTarget(node)) { var labelName = node.text; - var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, ts.ScriptElementKind.label, labelName, undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, labelName); + return label ? [createDefinitionInfoFromName(label, "label", labelName, undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -64505,7 +66500,7 @@ var ts; if (!symbol) { return undefined; } - if (symbol.flags & 8388608 && shouldSkipAlias(node, symbol.declarations[0])) { + if (symbol.flags & 2097152 && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = typeChecker.getAliasedSymbol(symbol); if (aliased.declarations) { symbol = aliased; @@ -64532,7 +66527,7 @@ var ts; } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -64677,7 +66672,7 @@ var ts; return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ts.ScriptElementKind.scriptElement, + kind: "script", name: name, containerName: undefined, containerKind: undefined @@ -64754,19 +66749,14 @@ var ts; function getJsDocCommentsFromDeclarations(declarations) { var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getCommentsFromJSDoc(declaration); - if (!comments) { - return; - } - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var comment = comments_3[_i]; - if (comment) { + ts.forEach(ts.getAllJSDocs(declaration), function (doc) { + if (doc.comment) { if (documentationComment.length) { documentationComment.push(ts.lineBreakPart()); } - documentationComment.push(ts.textPart(comment)); + documentationComment.push(ts.textPart(doc.comment)); } - } + }); }); return documentationComment; } @@ -64774,20 +66764,10 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { var tags = []; forEachUnique(declarations, function (declaration) { - var jsDocs = ts.getJSDocs(declaration); - if (!jsDocs) { - return; - } - for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { - var doc = jsDocs_1[_i]; - var tagsForDoc = doc.tags; - if (tagsForDoc) { - tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 284; }).map(function (jsDocTag) { - return { - name: jsDocTag.tagName.text, - text: jsDocTag.comment - }; - })); + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 276) { + tags.push({ name: tag.tagName.text, text: tag.comment }); } } }); @@ -64811,7 +66791,7 @@ var ts; return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword", kindModifiers: "", sortText: "0", }; @@ -64822,18 +66802,39 @@ var ts; return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: "@" + tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword", kindModifiers: "", sortText: "0" }; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter", kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; function getDocCommentTemplateAtPosition(newLine, sourceFile, position) { if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -64868,7 +66869,7 @@ var ts; for (var i = 0; i < parameters.length; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 71 ? - currentName.text : + currentName.escapedText : "param" + i; if (isJavaScriptFile) { docParams += indentationStr + " * @param {any} " + paramName + newLine; @@ -64924,8 +66925,6 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - var safeList; - var EmptySafeList = ts.createMap(); JsTyping.nodeCoreModuleList = [ "buffer", "querystring", "events", "http", "cluster", "zlib", "os", "https", "punycode", "repl", "readline", @@ -64935,58 +66934,53 @@ var ts; "constants", "process", "v8", "timers", "console" ]; var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { - var inferredTypings = ts.createMap(); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 || kind === 2; + var inferredTypings = ts.createMap(); + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMapFromTemplate(result.config) : EmptySafeList; - } var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typeAcquisition.include); - exclude = typeAcquisition.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { var packageJsonPath = ts.combinePaths(searchDir, "package.json"); getTypingNamesFromJson(packageJsonPath, filesToWatch); var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); getTypingNamesFromJson(bowerJsonPath, filesToWatch); var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath); - } + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); getTypingNamesFromSourceFileNames(fileNames); if (unresolvedImports) { - for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { - var moduleId = unresolvedImports_1[_a]; - var typingName = nodeCoreModules.has(moduleId) ? "node" : moduleId; - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } + var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + addInferredTypings(module, "Inferred typings from unresolved imports"); } packageNameToTypingLocation.forEach(function (typingLocation, name) { if (inferredTypings.has(name) && inferredTypings.get(name) === undefined) { inferredTypings.set(name, typingLocation); } }); - for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { - var excludeTypingName = exclude_1[_b]; - inferredTypings.delete(excludeTypingName); + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); } var newTypingNames = []; var cachedTypingPaths = []; @@ -64998,58 +66992,56 @@ var ts; newTypingNames.push(typing); } }); - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!inferredTypings.has(typing)) { - inferredTypings.set(typing, undefined); - } + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); } } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (host.fileExists(jsonPath)) { - filesToWatch.push(jsonPath); - } - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } + if (!host.fileExists(jsonPath)) { + return; } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); } function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return safeList.has(f); })); + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx"); }); if (hasJsxFile) { - mergeTypings(["react"]); + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); } } - function getTypingNamesFromPackagesFolder(packagesFolderPath) { + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { filesToWatch.push(packagesFolderPath); if (!host.directoryExists(packagesFolderPath)) { return; } - var typingNames = []; var fileNames = host.readDirectory(packagesFolderPath, [".json"], undefined, undefined, 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -65057,11 +67049,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; + var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_8.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -65069,15 +67058,18 @@ var ts; if (!packageJson.name) { continue; } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); inferredTypings.set(packageJson.name, absolutePath); } else { - typingNames.push(packageJson.name); + packageNames.push(packageJson.name); } } - mergeTypings(typingNames); + addInferredTypings(packageNames, " Found package names"); } } JsTyping.discoverTypings = discoverTypings; @@ -65090,7 +67082,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { return "continue"; @@ -65122,14 +67114,14 @@ var ts; }; for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_6(sourceFile); } rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; if (decl.kind === 239 || decl.kind === 242 || decl.kind === 237) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); - return importer.name !== imported.name; + return importer.escapedName !== imported.escapedName; } else { return true; @@ -65151,21 +67143,11 @@ var ts; } return true; } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 || - node.kind === 9 || - node.kind === 8) { - return node.text; - } - } - return undefined; - } function tryAddSingleDeclarationName(declaration, containers) { if (declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var text = getTextOfIdentifierOrLiteral(name); + var text = ts.getTextOfIdentifierOrLiteral(name); if (text !== undefined) { containers.unshift(text); } @@ -65180,7 +67162,7 @@ var ts; return true; } function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = getTextOfIdentifierOrLiteral(expression); + var text = ts.getTextOfIdentifierOrLiteral(expression); if (text !== undefined) { if (includeLastPortion) { containers.unshift(text); @@ -65446,7 +67428,7 @@ var ts; default: ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 290) { + if (tag.kind === 283) { addLeafNode(tag); } }); @@ -65538,14 +67520,14 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.getPropertyNameForPropertyNameNode(declName); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { case 186: case 187: case 199: return getFunctionOrClassName(node); - case 290: + case 283: return getJSDocTypedefTagName(node); default: return undefined; @@ -65585,7 +67567,7 @@ var ts; return "()"; case 157: return "[]"; - case 290: + case 283: return getJSDocTypedefTagName(node); default: return ""; @@ -65632,7 +67614,7 @@ var ts; case 233: case 265: case 231: - case 290: + case 283: return true; case 152: case 151: @@ -65717,10 +67699,10 @@ var ts; return ts.getTextOfNode(moduleDeclaration.name); } var result = []; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); while (moduleDeclaration.body && moduleDeclaration.body.kind === 233) { moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } return result.join("."); } @@ -65780,7 +67762,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_13); } @@ -65791,7 +67773,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_14); } @@ -65803,8 +67785,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { - var currentComment = comments_4[_i]; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var currentComment = comments_3[_i]; cancellationToken.throwIfCancellationRequested(); if (currentComment.kind === 2) { if (isFirstSingleLineComment) { @@ -66370,13 +68352,9 @@ var ts; }); } function getFileReference() { - var file = ts.scanner.getTokenValue(); + var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; + return { fileName: fileName, pos: pos, end: pos + fileName.length }; } function recordAmbientExternalModule() { if (!ambientExternalModules) { @@ -66411,7 +68389,14 @@ var ts; var token = ts.scanner.getToken(); if (token === 91) { token = nextToken(); - if (token === 9) { + if (token === 19) { + token = nextToken(); + if (token === 9) { + recordModuleName(); + return true; + } + } + else if (token === 9) { recordModuleName(); return true; } @@ -66660,7 +68645,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } var displayName = ts.stripQuotes(node.text); - return getRenameInfoSuccess(displayName, displayName, ts.ScriptElementKind.variableElement, ts.ScriptElementKindModifier.none, node, sourceFile); + return getRenameInfoSuccess(displayName, displayName, "var", "", node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -66706,7 +68691,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var emptyArray = []; var ArgumentListKind; (function (ArgumentListKind) { ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; @@ -66721,13 +68705,12 @@ var ts; return undefined; } var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); - cancellationToken.throwIfCancellationRequested(); - if (!argumentInfo) { + if (!argumentInfo) return undefined; - } + cancellationToken.throwIfCancellationRequested(); var call = argumentInfo.invocation; var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates); + var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { if (ts.isSourceFileJavaScript(sourceFile)) { @@ -66749,7 +68732,7 @@ var ts; : expression.kind === 179 ? expression.name : undefined; - if (!name || !name.text) { + if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -66776,36 +68759,25 @@ var ts; } function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { if (ts.isCallOrNewExpression(node.parent)) { - var callExpression = node.parent; - if (node.kind === 27 || - node.kind === 19) { - var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + var invocation = node.parent; + var list = void 0; + var argumentIndex = void 0; + if (node.kind === 27 || node.kind === 19) { + list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); ts.Debug.assert(list !== undefined); - return { - kind: isTypeArgList ? 0 : 1, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: 0, - argumentCount: getArgumentCount(list) - }; + argumentIndex = 0; } - var listItemInfo = ts.findListItemInfo(node); - if (listItemInfo) { - var list = listItemInfo.list; - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; - var argumentIndex = getArgumentIndex(list, node); - var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - kind: isTypeArgList ? 0 : 1, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + else { + list = ts.findContainingList(node); + if (!list) + return undefined; + argumentIndex = getArgumentIndex(list, node); } - return undefined; + var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 : 1; + var argumentCount = getArgumentCount(list); + ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (node.kind === 13 && node.parent.kind === 183) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -66929,25 +68901,9 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } - function selectBestInvalidOverloadIndex(candidates, argumentCount) { - var maxParamsSignatureIndex = -1; - var maxParams = -1; - for (var i = 0; i < candidates.length; i++) { - var candidate = candidates[i]; - if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { - return i; - } - if (candidate.parameters.length > maxParams) { - maxParams = candidate.parameters.length; - maxParamsSignatureIndex = i; - } - } - return maxParamsSignatureIndex; - } - function createSignatureHelpItems(candidates, bestSignature, argumentListInfo, typeChecker) { - var applicableSpan = argumentListInfo.argumentsSpan; + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0; - var invocation = argumentListInfo.invocation; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, undefined, undefined); @@ -66962,8 +68918,8 @@ var ts; if (isTypeParameterList) { isVariadic = false; prefixDisplayParts.push(ts.punctuationPart(27)); - var typeParameters = candidateSignature.typeParameters; - signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; + var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); @@ -66977,8 +68933,7 @@ var ts; }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19)); - var parameters = candidateSignature.parameters; - signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; + signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); suffixDisplayParts.push(ts.punctuationPart(20)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { @@ -66995,20 +68950,10 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - var argumentIndex = argumentListInfo.argumentIndex; - var argumentCount = argumentListInfo.argumentCount; - var selectedItemIndex = candidates.indexOf(bestSignature); - if (selectedItemIndex < 0) { - selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount); - } ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - items: items, - applicableSpan: applicableSpan, - selectedItemIndex: selectedItemIndex, - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); @@ -67026,7 +68971,7 @@ var ts; }); return { name: typeParameter.symbol.name, - documentation: emptyArray, + documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; @@ -67039,94 +68984,95 @@ var ts; var SymbolDisplay; (function (SymbolDisplay) { function getSymbolKind(typeChecker, symbol, location) { - var flags = symbol.flags; - if (flags & 32) + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32) { return ts.getDeclarationOfKind(symbol, 199) ? - ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + "local class" : "class"; + } if (flags & 384) - return ts.ScriptElementKind.enumElement; + return "enum"; if (flags & 524288) - return ts.ScriptElementKind.typeElement; + return "type"; if (flags & 64) - return ts.ScriptElementKind.interfaceElement; + return "interface"; if (flags & 262144) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter"; var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - if (result === ts.ScriptElementKind.unknown) { + if (result === "") { if (flags & 262144) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter"; if (flags & 8) - return ts.ScriptElementKind.enumMemberElement; - if (flags & 8388608) - return ts.ScriptElementKind.alias; + return "enum member"; + if (flags & 2097152) + return "alias"; if (flags & 1536) - return ts.ScriptElementKind.moduleElement; + return "module"; } return result; } SymbolDisplay.getSymbolKind = getSymbolKind; function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { if (typeChecker.isUndefinedSymbol(symbol)) { - return ts.ScriptElementKind.variableElement; + return "var"; } if (typeChecker.isArgumentsSymbol(symbol)) { - return ts.ScriptElementKind.localVariableElement; + return "local var"; } if (location.kind === 99 && ts.isExpression(location)) { - return ts.ScriptElementKind.parameterElement; + return "parameter"; } - var flags = symbol.flags; + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 3) { if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ts.ScriptElementKind.parameterElement; + return "parameter"; } else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ts.ScriptElementKind.constElement; + return "const"; } else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ts.ScriptElementKind.letElement; + return "let"; } - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + return isLocalVariableOrFunction(symbol) ? "local var" : "var"; } if (flags & 16) - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + return isLocalVariableOrFunction(symbol) ? "local function" : "function"; if (flags & 32768) - return ts.ScriptElementKind.memberGetAccessorElement; + return "getter"; if (flags & 65536) - return ts.ScriptElementKind.memberSetAccessorElement; + return "setter"; if (flags & 8192) - return ts.ScriptElementKind.memberFunctionElement; + return "method"; if (flags & 16384) - return ts.ScriptElementKind.constructorImplementationElement; + return "constructor"; if (flags & 4) { - if (flags & 134217728 && symbol.checkFlags & 6) { + if (flags & 33554432 && symbol.checkFlags & 6) { var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (98308 | 3)) { - return ts.ScriptElementKind.memberVariableElement; + return "property"; } ts.Debug.assert(!!(rootSymbolFlags & 8192)); }); if (!unionPropertyKind) { var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { - return ts.ScriptElementKind.memberFunctionElement; + return "method"; } - return ts.ScriptElementKind.memberVariableElement; + return "property"; } return unionPropertyKind; } if (location.parent && ts.isJsxAttribute(location.parent)) { - return ts.ScriptElementKind.jsxAttribute; + return "JSX attribute"; } - return ts.ScriptElementKind.memberVariableElement; + return "property"; } - return ts.ScriptElementKind.unknown; + return ""; } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) - : ts.ScriptElementKindModifier.none; + : ""; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { @@ -67134,17 +69080,17 @@ var ts; var displayParts = []; var documentation; var tags; - var symbolFlags = symbol.flags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 && ts.isExpression(location); var type; - if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 || symbolFlags & 8388608) { - if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { - symbolKind = ts.ScriptElementKind.memberVariableElement; + if (symbolKind !== "" || symbolFlags & 32 || symbolFlags & 2097152) { + if (symbolKind === "getter" || symbolKind === "setter") { + symbolKind = "property"; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); if (type) { if (location.parent && location.parent.kind === 179) { var right = location.parent.name; @@ -67175,11 +69121,11 @@ var ts; } if (signature) { if (useConstructSignatures && (symbolFlags & 32)) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor"; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - else if (symbolFlags & 8388608) { - symbolKind = ts.ScriptElementKind.alias; + else if (symbolFlags & 2097152) { + symbolKind = "alias"; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { @@ -67192,13 +69138,13 @@ var ts; addPrefixForAnyFunctionOrVar(symbol, symbolKind); } switch (symbolKind) { - case ts.ScriptElementKind.jsxAttribute: - case ts.ScriptElementKind.memberVariableElement: - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.parameterElement: - case ts.ScriptElementKind.localVariableElement: + case "JSX attribute": + case "property": + case "var": + case "const": + case "let": + case "parameter": + case "local var": displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); if (useConstructSignatures) { @@ -67208,7 +69154,7 @@ var ts; if (!(type.flags & 32768 && type.objectFlags & 16) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); } - addSignatureDisplayParts(signature, allSignatures, 8); + addSignatureDisplayParts(signature, allSignatures, 16); break; default: addSignatureDisplayParts(signature, allSignatures); @@ -67216,7 +69162,7 @@ var ts; hasAddedSymbolInfo = true; } } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304)) || + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304)) || (location.kind === 123 && location.parent.kind === 152)) { var functionDeclaration_1 = location.parent; var locationIsSymbolDeclaration = ts.findDeclaration(symbol, function (declaration) { @@ -67231,7 +69177,7 @@ var ts; signature = allSignatures[0]; } if (functionDeclaration_1.kind === 152) { - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor"; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { @@ -67246,7 +69192,7 @@ var ts; } if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { if (ts.getDeclarationOfKind(symbol, 199)) { - pushTypePart(ts.ScriptElementKind.localClassElement); + pushTypePart("local class"); } else { displayParts.push(ts.keywordPart(75)); @@ -67271,7 +69217,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024)); } if (symbolFlags & 384) { addNewLineIfDisplayPartsExist(); @@ -67318,7 +69264,7 @@ var ts; else if (declaration.kind !== 155 && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64)); } else if (declaration.kind === 231) { addInPrefix(); @@ -67331,7 +69277,7 @@ var ts; } } if (symbolFlags & 8) { - symbolKind = ts.ScriptElementKind.enumMemberElement; + symbolKind = "enum member"; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; if (declaration.kind === 264) { @@ -67344,7 +69290,7 @@ var ts; } } } - if (symbolFlags & 8388608) { + if (symbolFlags & 2097152) { addNewLineIfDisplayPartsExist(); if (symbol.declarations[0].kind === 236) { displayParts.push(ts.keywordPart(84)); @@ -67382,7 +69328,7 @@ var ts; }); } if (!hasAddedSymbolInfo) { - if (symbolKind !== ts.ScriptElementKind.unknown) { + if (symbolKind !== "") { if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); @@ -67391,10 +69337,10 @@ var ts; else { addPrefixForAnyFunctionOrVar(symbol, symbolKind); } - if (symbolKind === ts.ScriptElementKind.memberVariableElement || - symbolKind === ts.ScriptElementKind.jsxAttribute || + if (symbolKind === "property" || + symbolKind === "JSX attribute" || symbolFlags & 3 || - symbolKind === ts.ScriptElementKind.localVariableElement || + symbolKind === "local var" || isThisExpression) { displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); @@ -67413,7 +69359,7 @@ var ts; symbolFlags & 16384 || symbolFlags & 131072 || symbolFlags & 98304 || - symbolKind === ts.ScriptElementKind.memberFunctionElement) { + symbolKind === "method") { var allSignatures = type.getNonNullableType().getCallSignatures(); addSignatureDisplayParts(allSignatures[0], allSignatures); } @@ -67426,7 +69372,7 @@ var ts; if (!documentation) { documentation = symbol.getDocumentationComment(); tags = symbol.getJsDocTags(); - if (documentation.length === 0 && symbol.flags & 4) { + if (documentation.length === 0 && symbolFlags & 4) { if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 265; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -67471,11 +69417,11 @@ var ts; } function pushTypePart(symbolKind) { switch (symbolKind) { - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.functionElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.constructorImplementationElement: + case "var": + case "function": + case "let": + case "const": + case "constructor": displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: @@ -67486,7 +69432,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19)); @@ -67602,8 +69548,8 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); - options = ts.clone(options); - var _loop_5 = function (opt) { + options = ts.cloneCompilerOptions(options); + var _loop_7 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -67619,7 +69565,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_7(opt); } return options; } @@ -67823,11 +69769,7 @@ var ts; break; } } - lastTokenInfo = { - leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia, - token: token - }; + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } function isOnToken() { @@ -67944,7 +69886,8 @@ var ts; FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -68074,9 +70017,9 @@ var ts; } return true; }; + RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); - RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -68104,11 +70047,11 @@ var ts; 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); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71, 3, 75, 84, 91]); - 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.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 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.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2), 1); 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)); @@ -68300,6 +70243,9 @@ var ts; Rules.IsOptionDisabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; }; + Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + }; Rules.IsOptionEnabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; }; @@ -68343,8 +70289,8 @@ var ts; Rules.IsConditionalOperatorContext = function (context) { return context.contextNode.kind === 195; }; - Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { - return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); + Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { + return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); }; Rules.IsBraceWrappedContext = function (context) { return context.contextNode.kind === 174 || Rules.IsSingleLineBlockContext(context); @@ -68890,11 +70836,27 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 25, sourceFile, options, rulesProvider, 3); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3); } formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, options, rulesProvider, 4); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 18, sourceFile, options, rulesProvider, 4); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -68908,33 +70870,22 @@ var ts; function formatSelection(start, end, sourceFile, rulesProvider, options) { var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), - end: end + end: end, }; return formatSpan(span, sourceFile, options, rulesProvider, 1); } formatting.formatSelection = formatSelection; - function formatOutermostParent(position, expectedLastToken, sourceFile, options, rulesProvider, requestKind) { - var parent = findOutermostParent(position, expectedLastToken, sourceFile); - if (!parent) { - return []; - } - var span = { - pos: ts.getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile), - end: parent.end - }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; } - function findOutermostParent(position, expectedTokenKind, sourceFile) { - var precedingToken = ts.findPrecedingToken(position, sourceFile); - if (!precedingToken || - precedingToken.kind !== expectedTokenKind || - position !== precedingToken.getEnd()) { - return undefined; - } - var current = precedingToken; + function findOutermostNodeWithinListLevel(node) { + var current = node; while (current && current.parent && - current.parent.end === precedingToken.end && + current.parent.end === node.end && !isListElement(current.parent, current)) { current = current.parent; } @@ -69031,11 +70982,21 @@ var ts; } return 0; } - function formatNode(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1, function (_) { return false; }, sourceFileLike); } - formatting.formatNode = formatNode; + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + } function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { var enclosingNode = findEnclosingNode(originalRange, sourceFile); 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); @@ -70177,7 +72138,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, false); if (nextToken && isSeparator(node, nextToken)) { var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), false, true); var nextElement = containingList[index + 1]; @@ -70186,7 +72147,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -70254,7 +72215,7 @@ var ts; } var end = after.getEnd(); if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, false); if (nextToken && isSeparator(after, nextToken)) { var lineAndCharOfNextElement = ts.getLineAndCharacterOfPosition(sourceFile, skipWhitespacesAndLineBreaks(sourceFile.text, containingList[index + 1].getFullStart())); var lineAndCharOfNextToken = ts.getLineAndCharacterOfPosition(sourceFile, nextToken.end); @@ -70328,7 +72289,7 @@ var ts; }; ChangeTracker.prototype.getChanges = function () { var _this = this; - var changesPerFile = ts.createFileMap(); + var changesPerFile = ts.createMap(); for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { var c = _a[_i]; var changesInFile = changesPerFile.get(c.sourceFile.path); @@ -70338,8 +72299,7 @@ var ts; changesInFile.push(c); } var fileChangesList = []; - changesPerFile.forEachValue(function (path) { - var changesInFile = changesPerFile.get(path); + changesPerFile.forEach(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; var fileTextChanges = { fileName: sourceFile.fileName, textChanges: [] }; for (var _i = 0, _a = ChangeTracker.normalize(changesInFile); _i < _a.length; _i++) { @@ -70407,7 +72367,7 @@ var ts; lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNode(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } textChanges.applyFormatting = applyFormatting; @@ -70581,39 +72541,46 @@ var ts; } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - var results; - var refactorList = []; - refactors.forEach(function (refactor) { - refactorList.push(refactor); + return ts.flatMapIter(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); }); - 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; + function getEditsForRefactor(context, refactorName, actionName) { var refactor = refactors.get(refactorName); - if (!refactor) { - return undefined; - } - var codeActions = refactor.getCodeActions(context); - if (codeActions) { - ts.addRange((result || (result = [])), codeActions); - } - return result; + return refactor && refactor.getEditsForAction(context, actionName); } - refactor_1.getRefactorCodeActions = getRefactorCodeActions; + refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var qualifiedName = ts.getAncestor(token, 143); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + if (!ts.isIdentifier(qualifiedName.left)) { + return undefined; + } + var leftText = qualifiedName.left.getText(sourceFile); + var rightText = qualifiedName.right.getText(sourceFile); + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -70624,7 +72591,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -70663,11 +72630,7 @@ var ts; newNodes.push(newIndexSignatureDeclaration); } function pushAction(result, newNodes, description) { - var newAction = { - description: description, - changes: codefix.newNodesToChanges(newNodes, openBrace, context) - }; - result.push(newAction); + result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -70682,90 +72645,134 @@ var ts; getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { - var sourceFile = context.sourceFile; + var tokenSourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(tokenSourceFile, start, false); if (token.kind !== 71) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent) || token.parent.expression.kind !== 99) { + if (!ts.isPropertyAccessExpression(token.parent)) { return undefined; } - var classMemberDeclaration = ts.getThisContainer(token, false); - if (!ts.isClassElement(classMemberDeclaration)) { - return undefined; + var tokenName = token.getText(tokenSourceFile); + var makeStatic = false; + var classDeclaration; + if (token.parent.expression.kind === 99) { + var containingClassMemberDeclaration = ts.getThisContainer(token, false); + if (!ts.isClassElement(containingClassMemberDeclaration)) { + return undefined; + } + classDeclaration = containingClassMemberDeclaration.parent; + makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32); + } + else { + var checker = context.program.getTypeChecker(); + var leftExpression = token.parent.expression; + var leftExpressionType = checker.getTypeAtLocation(leftExpression); + if (leftExpressionType.flags & 32768) { + var symbol = leftExpressionType.symbol; + if (symbol.flags & 32) { + classDeclaration = symbol.declarations && symbol.declarations[0]; + if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { + makeStatic = true; + } + } + } } - var classDeclaration = classMemberDeclaration.parent; if (!classDeclaration || !ts.isClassLike(classDeclaration)) { return undefined; } - var isStatic = ts.hasModifier(classMemberDeclaration, 32); - return ts.isInJavaScriptFile(sourceFile) ? getActionsForAddMissingMemberInJavaScriptFile() : getActionsForAddMissingMemberInTypeScriptFile(); - function getActionsForAddMissingMemberInJavaScriptFile() { - var memberName = token.getText(); - if (isStatic) { + var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); + var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); + return ts.isInJavaScriptFile(classDeclarationSourceFile) ? + getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : + getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); + function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(false); + if (methodCodeAction) { + actions = [methodCodeAction]; + } + if (makeStatic) { if (classDeclaration.kind === 199) { - return undefined; + return actions; } var className = classDeclaration.name.getText(); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classDeclaration.getEnd(), length: 0 }, - newText: "" + context.newLineCharacter + className + "." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + var initializeStaticAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), + changes: staticInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeStaticAction); + return actions; } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); if (!classConstructor) { - return undefined; + return actions; } - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classConstructor.body.getEnd() - 1, length: 0 }, - newText: "this." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var initializeAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), + changes: propertyInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeAction); + return actions; } } - function getActionsForAddMissingMemberInTypeScriptFile() { + function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(true); + if (methodCodeAction) { + actions = [methodCodeAction]; + } var typeNode; if (token.parent.parent.kind === 194) { var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(binaryExpression.right))); + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } typeNode = typeNode || ts.createKeywordTypeNode(119); - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); - var property = ts.createProperty(undefined, isStatic ? [ts.createToken(115)] : undefined, token.getText(sourceFile), undefined, typeNode, undefined); + var property = ts.createProperty(undefined, makeStatic ? [ts.createToken(115)] : undefined, tokenName, undefined, typeNode, undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - propertyChangeTracker.insertNodeAfter(sourceFile, openBrace, property, { suffix: context.newLineCharacter }); - var actions = [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_declaration_for_missing_property_0), [token.getText()]), - changes: propertyChangeTracker.getChanges() - }]; - if (!isStatic) { + propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); + (actions || (actions = [])).push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + changes: propertyChangeTracker.getChanges() + }); + if (!makeStatic) { var stringTypeNode = ts.createKeywordTypeNode(136); var indexingParameter = ts.createParameter(undefined, undefined, undefined, "x", undefined, stringTypeNode, undefined); var indexSignature = ts.createIndexSignature(undefined, undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); + indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_missing_property_0), [token.getText()]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: indexSignatureChangeTracker.getChanges() }); } return actions; } + function getActionForMethodDeclaration(includeTypeScriptSyntax) { + if (token.parent.parent.kind === 181) { + var callExpression = token.parent.parent; + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? + ts.Diagnostics.Declare_method_0 : + ts.Diagnostics.Declare_static_method_0), [tokenName]), + changes: methodDeclarationChangeTracker.getChanges() + }; + } + } } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -70780,10 +72787,11 @@ var ts; }); function getActionsForCorrectSpelling(context) { var sourceFile = context.sourceFile; - var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); var checker = context.program.getTypeChecker(); var suggestion; - if (node.kind === 71 && ts.isPropertyAccessExpression(node.parent)) { + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } @@ -70834,7 +72842,7 @@ var ts; function getActionForClassLikeMissingAbstractMember(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -70869,7 +72877,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 99) { return undefined; } @@ -70879,9 +72887,9 @@ var ts; return undefined; } if (superCall.expression && superCall.expression.kind === 181) { - var arguments_1 = superCall.expression.arguments; - for (var i = 0; i < arguments_1.length; i++) { - if (arguments_1[i].expression === token) { + var expressionArguments = superCall.expression.arguments; + for (var i = 0; i < expressionArguments.length; i++) { + if (expressionArguments[i].expression === token) { return undefined; } } @@ -70914,7 +72922,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 123) { return undefined; } @@ -70938,7 +72946,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 && ts.isClassLike(classDeclNode))) { return undefined; @@ -70976,7 +72984,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, false); if (token.kind !== 71) { return undefined; } @@ -71002,129 +73010,133 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); if (token.kind === 21) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, false); } switch (token.kind) { case 71: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149: case 240: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: return deleteDefault(); } function deleteDefault() { if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + return [deleteNode(token.parent)]; } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + return [deleteNode(token.parent.parent)]; } else { return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = 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); + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); + ts.Debug.assert(previousToken.kind === 27); + ts.Debug.assert(nextToken.kind === 29); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237); + return [deleteNode(importEquals)]; case 242: - var namedImports = token.parent.parent; + var namedImports = parent.parent; if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); + return deleteNamedImportBinding(namedImports); } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 239: - var importClause = token.parent; + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { - var start_4 = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + var start_6 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) })]; } else { - return deleteNode(importClause.name); + 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); - } + return deleteNamedImportBinding(parent); default: return deleteDefault(); } } - function deleteVariableDeclaration(varDecl) { + function deleteNamedImportBinding(namedBindings) { + if (namedBindings.parent.name) { + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, false); + if (previousToken && previousToken.kind === 26) { + return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; + } + return undefined; + } + else { + var importDecl = ts.getAncestor(namedBindings, 238); + return [deleteNode(importDecl)]; + } + } + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, 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); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : 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()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215: - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -71144,16 +73156,55 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], + getCodeActions: getActionsForJSDocTypes + }); + function getActionsForJSDocTypes(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false); + var decl = ts.findAncestor(node, function (n) { return n.kind === 226; }); + if (!decl) + return; + var checker = context.program.getTypeChecker(); + var jsdocType = decl.type; + var original = ts.getTextOfNode(jsdocType); + var type = checker.getTypeFromTypeNode(jsdocType); + var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, undefined, 8))]; + if (jsdocType.kind === 270) { + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048), undefined, 8); + actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); + } + return actions; + } + function createAction(declaration, fileName, original, replacement) { + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), + changes: [{ + fileName: fileName, + textChanges: [{ + span: { start: declaration.getStart(), length: declaration.getWidth() }, + newText: replacement + }] + }], + }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var codefix; (function (codefix) { @@ -71253,15 +73304,28 @@ var ts; 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 token = ts.getTokenAtPosition(sourceFile, context.span.start, false); 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 umdSymbol = checker.getSymbolAtLocation(token); + var symbol = void 0; + var symbolName = void 0; + if (umdSymbol.flags & 2097152) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = name; + } + else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { + symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455)); + symbolName = symbol.name; + } + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, symbolName, false, true); } var candidateModules = checker.getAmbientModules(); for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { @@ -71276,15 +73340,16 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, true)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, true)); } } - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + ts.Debug.assert(name !== "default"); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); } } return symbolIdActionMap.getAllActions(); @@ -71319,16 +73384,13 @@ var ts; } } function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + return ts.getSymbolId(ts.skipAlias(symbol, checker)); } 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) { + function getCodeActionForImport(moduleSymbol, symbolName, isDefault, isNamespaceImport) { var existingDeclarations = getImportDeclarations(moduleSymbol); if (existingDeclarations.length > 0) { return getCodeActionsForExistingImport(existingDeclarations); @@ -71412,10 +73474,10 @@ var ts; var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); var changeTracker = createChangeTracker(); var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), undefined) + ? ts.createImportClause(ts.createIdentifier(symbolName), undefined) : isNamespaceImport - ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(name))) - : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(name))])); + ? ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) + : ts.createImportClause(undefined, ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))])); var importDecl = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(moduleSpecifierWithoutQuotes)); if (!lastImportDeclaration) { changeTracker.insertNodeAt(sourceFile, sourceFile.getStart(), importDecl, { suffix: "" + context.newLineCharacter + context.newLineCharacter }); @@ -71423,7 +73485,7 @@ var ts; else { changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl, { suffix: context.newLineCharacter }); } - return createCodeAction(ts.Diagnostics.Import_0_from_1, [name, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -71436,8 +73498,9 @@ var ts; tryGetModuleNameFromRootDirs() || ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265) { - return moduleSymbol.name; + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; } } function tryGetModuleNameFromBaseUrl() { @@ -71504,43 +73567,90 @@ var ts; if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { return undefined; } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { 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"))); + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (context.host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); 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 mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } } - catch (e) { } + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory); + } } - return relativeFileName; } } + function getNodeModulePathParts(fullPath) { + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["PackageContent"] = 2] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1; + } + break; + case 1: + packageRootIndex = partEnd; + state = 2; + break; + case 2: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1; + } + else { + state = 2; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDir = rootDirs_1[_i]; var relativeName = getRelativePathIfInDirectory(path, rootDir); if (relativeName !== undefined) { return relativeName; @@ -71561,7 +73671,7 @@ var ts; } function getRelativePath(path, directoryPath) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; } } } @@ -71598,7 +73708,7 @@ var ts; var lineStartPosition = ts.getStartPositionOfLine(line, sourceFile); var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); if (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -71668,7 +73778,7 @@ var ts; codefix.newNodesToChanges = newNodesToChanges; function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.getName()); }); + var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); var newNodes = []; for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { var symbol = missingMembers_1[_i]; @@ -71695,7 +73805,7 @@ var ts; var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); - var optional = !!(symbol.flags & 67108864); + var optional = !!(symbol.flags & 16777216); switch (declaration.kind) { case 153: case 154: @@ -71751,6 +73861,29 @@ var ts; return signatureDeclaration; } } + function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { + var parameters = createDummyParameters(callExpression.arguments.length, undefined, undefined, includeTypeScriptSyntax); + var typeParameters; + if (includeTypeScriptSyntax) { + var typeArgCount = ts.length(callExpression.typeArguments); + for (var i = 0; i < typeArgCount; i++) { + var name = typeArgCount < 8 ? String.fromCharCode(84 + i) : "T" + i; + var typeParameter = ts.createTypeParameterDeclaration(name, undefined, undefined); + (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); + } + } + var newMethod = ts.createMethod(undefined, makeStatic ? [ts.createToken(115)] : undefined, undefined, methodName, undefined, typeParameters, parameters, includeTypeScriptSyntax ? ts.createKeywordTypeNode(119) : undefined, createStubbedMethodBody()); + return newMethod; + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter(undefined, undefined, undefined, names && names[i] || "arg" + i, minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55) : undefined, addAnyType ? ts.createKeywordTypeNode(119) : undefined, undefined); + parameters.push(newParameter); + } + return parameters; + } function createMethodImplementingSignatures(signatures, name, optional, modifiers) { var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; @@ -71766,13 +73899,8 @@ var ts; } } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); - var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.getName(); }); - var parameters = []; - for (var i = 0; i < maxNonRestArgs; i++) { - var anyType = ts.createKeywordTypeNode(119); - var newParameter = ts.createParameter(undefined, undefined, undefined, maxArgsParameterSymbolNames[i], i >= minArgumentCount ? ts.createToken(55) : undefined, anyType, undefined); - parameters.push(newParameter); - } + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, true); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119)); var restParameter = ts.createParameter(undefined, undefined, ts.createToken(24), maxArgsParameterSymbolNames[maxNonRestArgs] || "rest", maxNonRestArgs >= minArgumentCount ? ts.createToken(55) : undefined, anyArrayType, undefined); @@ -71802,34 +73930,54 @@ var ts; (function (ts) { var refactor; (function (refactor) { + var actionName = "convert"; var convertFunctionToES6Class = { name: "Convert to ES2015 class", description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getCodeActions: getCodeActions, - isApplicable: isApplicable + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions }; refactor.registerRefactor(convertFunctionToES6Class); - function isApplicable(context) { + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start); + var node = ts.getTokenAtPosition(context.file, start, false); 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; + if (symbol && (symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - function getCodeActions(context) { + function getEditsForAction(context, action) { + if (actionName !== action) { + return undefined; + } var start = context.startPosition; var sourceFile = context.file; var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, false); var ctorSymbol = checker.getSymbolAtLocation(token); var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 | 3))) { - return []; + return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -71853,17 +74001,16 @@ var ts; break; } if (!newClassDeclaration) { - return []; + return undefined; } 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() - }]; + return { + edits: changeTracker.getChanges() + }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { @@ -71915,10 +74062,13 @@ var ts; return ts.createProperty([], modifiers, symbol.name, undefined, undefined, undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186: + case 186: { var functionExpression = assignmentBinaryExpression.right; - return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); - case 187: + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, functionExpression.parameters, undefined, functionExpression.body); + copyComments(assignmentBinaryExpression, method); + return method; + } + case 187: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; @@ -71929,15 +74079,33 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - return ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); - default: + var method = ts.createMethod(undefined, modifiers, undefined, memberDeclaration.name, undefined, undefined, arrowFunction.parameters, undefined, bodyBlock); + copyComments(assignmentBinaryExpression, method); + return method; + } + default: { if (ts.isSourceFileJavaScript(sourceFile)) { return; } - return ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + var prop = ts.createProperty(undefined, modifiers, memberDeclaration.name, undefined, undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } } } } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3) { + pos += 2; + end -= 2; + } + else { + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; if (!initializer || initializer.kind !== 186) { @@ -71950,14 +74118,16 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(undefined, undefined, initializer.parameters, initializer.body)); } - return ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; } 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); + var cls = ts.createClassDeclaration(undefined, undefined, node.name, undefined, undefined, memberElements); + return cls; } } })(refactor = ts.refactor || (ts.refactor = {})); @@ -71967,7 +74137,7 @@ var ts; ts.servicesVersion = "0.5"; var ruleProvider; function createNode(kind, pos, end, parent) { - var node = kind >= 143 ? new NodeObject(kind, pos, end) : + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 ? new IdentifierObject(71, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; @@ -72012,10 +74182,11 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { + NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var token = ts.scanner.scan(); + ts.Debug.assert(token !== 1); var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -72025,7 +74196,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(294, nodes.pos, nodes.end, this); + var list = createNode(286, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -72043,43 +74214,44 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143) { - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; - var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 283 && this.kind <= 293; - var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); - } - children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } - }; - var processNodes = function (nodes) { - if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); - } - children.push(_this.createSyntaxList(nodes)); - pos_3 = nodes.end; - }; - if (this.jsDoc) { - for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - processNode(jsDocComment); - } - } - pos_3 = this.pos; - ts.forEachChild(this, processNode, processNodes); - if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); - } - ts.scanner.setText(undefined); + if (!ts.isNodeKind(this.kind)) { + this._children = ts.emptyArray; + return; } - this._children = children || ts.emptyArray; + if (ts.isJSDocCommentContainingNode(this)) { + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + return; + } + var children = []; + ts.scanner.setText((sourceFile || this.getSourceFile()).text); + var pos = this.pos; + var processNode = function (node) { + pos = _this.addSyntheticNodes(children, pos, node.pos); + children.push(node); + pos = node.end; + }; + var processNodes = function (nodes) { + if (pos < nodes.pos) { + pos = _this.addSyntheticNodes(children, pos, nodes.pos); + } + children.push(_this.createSyntaxList(nodes)); + pos = nodes.end; + }; + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + processNode(jsDocComment); + } + } + pos = this.pos; + ts.forEachChild(this, processNode, processNodes); + if (pos < this.end) { + this.addSyntheticNodes(children, pos, this.end); + } + ts.scanner.setText(undefined); + this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -72101,7 +74273,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 || kid.kind > 293; }); + var child = ts.find(children, function (kid) { return kid.kind < 267 || kid.kind > 285; }); return child.kind < 143 ? child : child.getFirstToken(sourceFile); @@ -72176,11 +74348,21 @@ var ts; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; } SymbolObject.prototype.getFlags = function () { return this.flags; }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedName); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; SymbolObject.prototype.getName = function () { return this.name; }; @@ -72215,6 +74397,13 @@ var ts; function IdentifierObject(_kind, pos, end) { return _super.call(this, pos, end) || this; } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedText); + }, + enumerable: true, + configurable: true + }); return IdentifierObject; }(TokenOrIdentifierObject)); IdentifierObject.prototype.kind = 71; @@ -72346,26 +74535,16 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_9 = ts.getTextOfIdentifierOrLiteral(name); + if (result_9 !== undefined) { + return result_9; } if (name.kind === 144) { var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } - return getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; - } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 || - node.kind === 9 || - node.kind === 8) { - return node.text; + return ts.getTextOfIdentifierOrLiteral(expr); } } return undefined; @@ -72401,7 +74580,6 @@ var ts; case 237: case 246: case 242: - case 237: case 239: case 240: case 153: @@ -72421,8 +74599,9 @@ var ts; ts.forEachChild(decl.name, visit); break; } - if (decl.initializer) + if (decl.initializer) { visit(decl.initializer); + } } case 264: case 149: @@ -72457,6 +74636,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); + var SourceMapSourceObject = (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); function getServicesObjectAllocator() { return { getNodeConstructor: function () { return NodeObject; }, @@ -72466,6 +74656,7 @@ var ts; getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, }; } function toEditorSettings(optionsAsMap) { @@ -72513,9 +74704,8 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = ts.createFileMap(); + this.fileNameToEntry = ts.createMap(); var rootFileNames = host.getScriptFileNames(); for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { var fileName = rootFileNames_1[_i]; @@ -72540,24 +74730,20 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { - return this.fileNameToEntry.contains(path); - }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); + HostCache.prototype.containsEntryByPath = function (path) { + return this.fileNameToEntry.has(path); }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (_path, value) { + this.fileNameToEntry.forEach(function (value) { if (value) { fileNames.push(value.hostFileName); } @@ -72565,11 +74751,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -72764,11 +74950,18 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -72843,7 +75036,15 @@ var ts; return false; } } - return ts.compareDataObjects(program.getCompilerOptions(), hostCache.compilationSettings()); + var currentOptions = program.getCompilerOptions(); + var newOptions = hostCache.compilationSettings(); + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; } } function getProgram() { @@ -72858,7 +75059,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } function getSyntacticDiagnostics(fileName) { synchronizeHostData(); @@ -72893,7 +75096,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { return undefined; } @@ -72913,8 +75116,8 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ts.ScriptElementKind.unknown, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "", + kindModifiers: "", textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, @@ -72974,7 +75177,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === "writtenReference", isDefinition: false, isInString: highlightSpan.isInString, }); @@ -73006,12 +75209,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; - function writeFile(fileName, data, writeByteOrderMark) { - outputFiles.push({ - name: fileName, - writeByteOrderMark: writeByteOrderMark, - text: data - }); + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); @@ -73033,7 +75232,7 @@ var ts; } function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, false); if (node === sourceFile) { return; } @@ -73113,7 +75312,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); if (matchKind) { @@ -73173,7 +75372,10 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "}") { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { @@ -73187,27 +75389,13 @@ var ts; function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var span = { start: start, length: end - start }; - var newLineChar = ts.getNewLineOrDefaultFromHost(host); - var allFixes = []; - ts.forEach(ts.deduplicate(errorCodes), function (error) { + var span = ts.createTextSpanFromBounds(start, end); + var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); + var rulesProvider = getRuleProvider(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - var context = { - errorCode: error, - sourceFile: sourceFile, - span: span, - program: program, - newLineCharacter: newLineChar, - host: host, - cancellationToken: cancellationToken, - rulesProvider: getRuleProvider(formatOptions) - }; - var fixes = ts.codefix.getFixes(context); - if (fixes) { - allFixes = allFixes.concat(fixes); - } + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); - return allFixes; } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); @@ -73226,6 +75414,12 @@ var ts; if (ts.isInTemplateString(sourceFile, position)) { return false; } + switch (openingBrace) { + case 39: + case 34: + case 96: + return !ts.isInComment(sourceFile, position); + } return true; } function getTodoComments(fileName, descriptors) { @@ -73234,7 +75428,7 @@ var ts; cancellationToken.throwIfCancellationRequested(); var fileContents = sourceFile.text; var result = []; - if (descriptors.length > 0) { + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { var regExp = getTodoCommentsRegExp(); var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { @@ -73257,11 +75451,7 @@ var ts; continue; } var message = matchArray[2]; - result.push({ - descriptor: descriptor, - message: message, - position: matchPosition - }); + result.push({ descriptor: descriptor, message: message, position: matchPosition }); } } return result; @@ -73285,6 +75475,10 @@ var ts; (char >= 65 && char <= 90) || (char >= 48 && char <= 57); } + function isNodeModulesFile(path) { + var node_modulesFolderName = "/node_modules/"; + return path.indexOf(node_modulesFolderName) !== -1; + } } function getRenameInfo(fileName, position) { synchronizeHostData(); @@ -73308,18 +75502,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); } - function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, - getApplicableRefactors: getApplicableRefactors, - getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -73357,7 +75549,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, - getProgram: getProgram + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, }; } ts.createLanguageService = createLanguageService; @@ -73369,36 +75563,26 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); - walk(sourceFile); - sourceFile.nameTable = nameTable; - function walk(node) { - switch (node.kind) { - case 71: - setNameTable(node.text, node); - break; - case 9: - case 8: - if (ts.isDeclarationName(node) || - node.parent.kind === 248 || - isArgumentOfElementAccessExpression(node) || - ts.isLiteralComputedPropertyDeclarationName(node)) { - setNameTable(node.text, node); - } - break; - default: - ts.forEachChild(node, walk); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - ts.forEachChild(jsDoc, walk); - } - } + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } - } - function setNameTable(text, node) { - nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); - } + ts.forEachChild(node, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 248 || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { @@ -73431,22 +75615,22 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.getTextOfPropertyName(node.name); + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); if (name && contextualType) { - var result_9 = []; + var result_10 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_10.push(symbol); } }); - return result_9; + return result_10; } if (symbol) { - result_9.push(symbol); - return result_9; + result_10.push(symbol); + return result_10; } } return undefined; @@ -73482,6 +75666,7 @@ var ts; Arguments.LogFile = "--logFile"; Arguments.EnableTelemetry = "--enableTelemetry"; Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.NpmLocation = "--npmLocation"; })(Arguments = server.Arguments || (server.Arguments = {})); function hasArgument(argumentName) { return ts.sys.args.indexOf(argumentName) >= 0; @@ -73507,7 +75692,7 @@ var ts; LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; LogLevel[LogLevel["verbose"] = 3] = "verbose"; })(LogLevel = server.LogLevel || (server.LogLevel = {})); - server.emptyArray = []; + server.emptyArray = createSortedArray(); var Msg; (function (Msg) { Msg.Err = "Err"; @@ -73528,7 +75713,7 @@ var ts; function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { return { projectName: project.getProjectName(), - fileNames: project.getFileNames(true), + fileNames: project.getFileNames(true, true), compilerOptions: project.getCompilerOptions(), typeAcquisition: typeAcquisition, unresolvedImports: unresolvedImports, @@ -73585,22 +75770,6 @@ var ts; } } server.mergeMapLikes = mergeMapLikes; - function removeItemFromSet(items, itemToRemove) { - if (items.length === 0) { - return; - } - var index = items.indexOf(itemToRemove); - if (index < 0) { - return; - } - if (index === items.length - 1) { - items.pop(); - } - else { - items[index] = items.pop(); - } - } - server.removeItemFromSet = removeItemFromSet; function toNormalizedPath(fileName) { return ts.normalizePath(fileName); } @@ -73640,11 +75809,46 @@ var ts; return "/dev/null/inferredProject" + counter + "*"; } server.makeInferredProjectName = makeInferredProjectName; - function toSortedReadonlyArray(arr) { - arr.sort(); + function createSortedArray() { + return []; + } + server.createSortedArray = createSortedArray; + function toSortedArray(arr, comparer) { + arr.sort(comparer); return arr; } - server.toSortedReadonlyArray = toSortedReadonlyArray; + server.toSortedArray = toSortedArray; + function enumerateInsertsAndDeletes(newItems, oldItems, inserted, deleted, compare) { + compare = compare || ts.compareValues; + var newIndex = 0; + var oldIndex = 0; + var newLen = newItems.length; + var oldLen = oldItems.length; + while (newIndex < newLen && oldIndex < oldLen) { + var newItem = newItems[newIndex]; + var oldItem = oldItems[oldIndex]; + var compareResult = compare(newItem, oldItem); + if (compareResult === -1) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1) { + deleted(oldItem); + oldIndex++; + } + else { + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + server.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; var ThrottledOperations = (function () { function ThrottledOperations(host) { this.host = host; @@ -73689,6 +75893,154 @@ var ts; return GcTimer; }()); server.GcTimer = GcTimer; + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = ts.binarySearch(array, insert, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + server.insertSorted = insertSorted; + function removeSorted(array, remove, compare) { + if (!array || array.length === 0) { + return; + } + if (array[0] === remove) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, remove, compare); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + } + server.removeSorted = removeSorted; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var protocol; + (function (protocol) { + var CommandTypes; + (function (CommandTypes) { + CommandTypes["Brace"] = "brace"; + CommandTypes["BraceFull"] = "brace-full"; + CommandTypes["BraceCompletion"] = "braceCompletion"; + CommandTypes["Change"] = "change"; + CommandTypes["Close"] = "close"; + CommandTypes["Completions"] = "completions"; + CommandTypes["CompletionsFull"] = "completions-full"; + CommandTypes["CompletionDetails"] = "completionEntryDetails"; + CommandTypes["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; + CommandTypes["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; + CommandTypes["Configure"] = "configure"; + CommandTypes["Definition"] = "definition"; + CommandTypes["DefinitionFull"] = "definition-full"; + CommandTypes["Implementation"] = "implementation"; + CommandTypes["ImplementationFull"] = "implementation-full"; + CommandTypes["Exit"] = "exit"; + CommandTypes["Format"] = "format"; + CommandTypes["Formatonkey"] = "formatonkey"; + CommandTypes["FormatFull"] = "format-full"; + CommandTypes["FormatonkeyFull"] = "formatonkey-full"; + CommandTypes["FormatRangeFull"] = "formatRange-full"; + CommandTypes["Geterr"] = "geterr"; + CommandTypes["GeterrForProject"] = "geterrForProject"; + CommandTypes["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; + CommandTypes["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; + CommandTypes["NavBar"] = "navbar"; + CommandTypes["NavBarFull"] = "navbar-full"; + CommandTypes["Navto"] = "navto"; + CommandTypes["NavtoFull"] = "navto-full"; + CommandTypes["NavTree"] = "navtree"; + CommandTypes["NavTreeFull"] = "navtree-full"; + CommandTypes["Occurrences"] = "occurrences"; + CommandTypes["DocumentHighlights"] = "documentHighlights"; + CommandTypes["DocumentHighlightsFull"] = "documentHighlights-full"; + CommandTypes["Open"] = "open"; + CommandTypes["Quickinfo"] = "quickinfo"; + CommandTypes["QuickinfoFull"] = "quickinfo-full"; + CommandTypes["References"] = "references"; + CommandTypes["ReferencesFull"] = "references-full"; + CommandTypes["Reload"] = "reload"; + CommandTypes["Rename"] = "rename"; + CommandTypes["RenameInfoFull"] = "rename-full"; + CommandTypes["RenameLocationsFull"] = "renameLocations-full"; + CommandTypes["Saveto"] = "saveto"; + CommandTypes["SignatureHelp"] = "signatureHelp"; + CommandTypes["SignatureHelpFull"] = "signatureHelp-full"; + CommandTypes["TypeDefinition"] = "typeDefinition"; + CommandTypes["ProjectInfo"] = "projectInfo"; + CommandTypes["ReloadProjects"] = "reloadProjects"; + CommandTypes["Unknown"] = "unknown"; + CommandTypes["OpenExternalProject"] = "openExternalProject"; + CommandTypes["OpenExternalProjects"] = "openExternalProjects"; + CommandTypes["CloseExternalProject"] = "closeExternalProject"; + CommandTypes["SynchronizeProjectList"] = "synchronizeProjectList"; + CommandTypes["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; + CommandTypes["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; + CommandTypes["Cleanup"] = "cleanup"; + CommandTypes["OutliningSpans"] = "outliningSpans"; + CommandTypes["TodoComments"] = "todoComments"; + CommandTypes["Indentation"] = "indentation"; + CommandTypes["DocCommentTemplate"] = "docCommentTemplate"; + CommandTypes["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; + CommandTypes["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; + CommandTypes["BreakpointStatement"] = "breakpointStatement"; + CommandTypes["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; + CommandTypes["GetCodeFixes"] = "getCodeFixes"; + CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; + CommandTypes["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; + CommandTypes["GetApplicableRefactors"] = "getApplicableRefactors"; + CommandTypes["GetEditsForRefactor"] = "getEditsForRefactor"; + CommandTypes["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; + })(CommandTypes = protocol.CommandTypes || (protocol.CommandTypes = {})); + var IndentStyle; + (function (IndentStyle) { + IndentStyle["None"] = "None"; + IndentStyle["Block"] = "Block"; + IndentStyle["Smart"] = "Smart"; + })(IndentStyle = protocol.IndentStyle || (protocol.IndentStyle = {})); + var JsxEmit; + (function (JsxEmit) { + JsxEmit["None"] = "None"; + JsxEmit["Preserve"] = "Preserve"; + JsxEmit["ReactNative"] = "ReactNative"; + JsxEmit["React"] = "React"; + })(JsxEmit = protocol.JsxEmit || (protocol.JsxEmit = {})); + var ModuleKind; + (function (ModuleKind) { + ModuleKind["None"] = "None"; + ModuleKind["CommonJS"] = "CommonJS"; + ModuleKind["AMD"] = "AMD"; + ModuleKind["UMD"] = "UMD"; + ModuleKind["System"] = "System"; + ModuleKind["ES6"] = "ES6"; + ModuleKind["ES2015"] = "ES2015"; + })(ModuleKind = protocol.ModuleKind || (protocol.ModuleKind = {})); + var ModuleResolutionKind; + (function (ModuleResolutionKind) { + ModuleResolutionKind["Classic"] = "Classic"; + ModuleResolutionKind["Node"] = "Node"; + })(ModuleResolutionKind = protocol.ModuleResolutionKind || (protocol.ModuleResolutionKind = {})); + var NewLineKind; + (function (NewLineKind) { + NewLineKind["Crlf"] = "Crlf"; + NewLineKind["Lf"] = "Lf"; + })(NewLineKind = protocol.NewLineKind || (protocol.NewLineKind = {})); + var ScriptTarget; + (function (ScriptTarget) { + ScriptTarget["ES3"] = "ES3"; + ScriptTarget["ES5"] = "ES5"; + ScriptTarget["ES6"] = "ES6"; + ScriptTarget["ES2015"] = "ES2015"; + })(ScriptTarget = protocol.ScriptTarget || (protocol.ScriptTarget = {})); + })(protocol = server.protocol || (server.protocol = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; @@ -73743,14 +76095,17 @@ var ts; source: diag.source }; } - function formatConfigFileDiag(diag) { - return { - start: undefined, - end: undefined, - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), - category: ts.DiagnosticCategory[diag.category].toLowerCase(), - source: diag.source - }; + function convertToLocation(lineAndCharacter) { + return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; + } + function formatConfigFileDiag(diag, includeFileName) { + var start = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start)); + var end = diag.file && convertToLocation(ts.getLineAndCharacterOfPosition(diag.file, diag.start + diag.length)); + var text = ts.flattenDiagnosticMessageText(diag.messageText, "\n"); + var code = diag.code, source = diag.source; + var category = ts.DiagnosticCategory[diag.category].toLowerCase(); + return includeFileName ? { start: start, end: end, text: text, code: code, category: category, source: source, fileName: diag.file && diag.file.fileName } : + { start: start, end: end, text: text, code: code, category: category, source: source }; } function allEditsBeforePos(edits, pos) { for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { @@ -73761,80 +76116,7 @@ var ts; } return true; } - var CommandNames; - (function (CommandNames) { - CommandNames.Brace = "brace"; - CommandNames.BraceFull = "brace-full"; - CommandNames.BraceCompletion = "braceCompletion"; - CommandNames.Change = "change"; - CommandNames.Close = "close"; - CommandNames.Completions = "completions"; - CommandNames.CompletionsFull = "completions-full"; - CommandNames.CompletionDetails = "completionEntryDetails"; - CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - CommandNames.Configure = "configure"; - CommandNames.Definition = "definition"; - CommandNames.DefinitionFull = "definition-full"; - CommandNames.Exit = "exit"; - CommandNames.Format = "format"; - CommandNames.Formatonkey = "formatonkey"; - CommandNames.FormatFull = "format-full"; - CommandNames.FormatonkeyFull = "formatonkey-full"; - CommandNames.FormatRangeFull = "formatRange-full"; - CommandNames.Geterr = "geterr"; - CommandNames.GeterrForProject = "geterrForProject"; - CommandNames.Implementation = "implementation"; - CommandNames.ImplementationFull = "implementation-full"; - CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - CommandNames.NavBar = "navbar"; - CommandNames.NavBarFull = "navbar-full"; - CommandNames.NavTree = "navtree"; - CommandNames.NavTreeFull = "navtree-full"; - CommandNames.Navto = "navto"; - CommandNames.NavtoFull = "navto-full"; - CommandNames.Occurrences = "occurrences"; - CommandNames.DocumentHighlights = "documentHighlights"; - CommandNames.DocumentHighlightsFull = "documentHighlights-full"; - CommandNames.Open = "open"; - CommandNames.Quickinfo = "quickinfo"; - CommandNames.QuickinfoFull = "quickinfo-full"; - CommandNames.References = "references"; - CommandNames.ReferencesFull = "references-full"; - CommandNames.Reload = "reload"; - CommandNames.Rename = "rename"; - CommandNames.RenameInfoFull = "rename-full"; - CommandNames.RenameLocationsFull = "renameLocations-full"; - CommandNames.Saveto = "saveto"; - CommandNames.SignatureHelp = "signatureHelp"; - CommandNames.SignatureHelpFull = "signatureHelp-full"; - CommandNames.TypeDefinition = "typeDefinition"; - CommandNames.ProjectInfo = "projectInfo"; - CommandNames.ReloadProjects = "reloadProjects"; - CommandNames.Unknown = "unknown"; - CommandNames.OpenExternalProject = "openExternalProject"; - CommandNames.OpenExternalProjects = "openExternalProjects"; - CommandNames.CloseExternalProject = "closeExternalProject"; - CommandNames.SynchronizeProjectList = "synchronizeProjectList"; - CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - CommandNames.Cleanup = "cleanup"; - CommandNames.OutliningSpans = "outliningSpans"; - CommandNames.TodoComments = "todoComments"; - CommandNames.Indentation = "indentation"; - CommandNames.DocCommentTemplate = "docCommentTemplate"; - CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; - CommandNames.BreakpointStatement = "breakpointStatement"; - CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - 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 = {})); + server.CommandNames = server.protocol.CommandTypes; function formatMessage(msg, logger, byteLength, newLine) { var verboseLogging = logger.hasLevel(server.LogLevel.verbose); var json = JSON.stringify(msg); @@ -73847,13 +76129,8 @@ var ts; server.formatMessage = formatMessage; var MultistepOperation = (function () { function MultistepOperation(operationHost) { - var _this = this; this.operationHost = operationHost; this.completed = true; - this.next = { - immediate: function (action) { return _this.immediate(action); }, - delay: function (ms, action) { return _this.delay(ms, action); } - }; } MultistepOperation.prototype.startNew = function (action) { this.complete(); @@ -73896,7 +76173,7 @@ var ts; stop = true; } else { - action(this.next); + action(this); } } catch (e) { @@ -73931,19 +76208,19 @@ var ts; var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, - _a[CommandNames.OpenExternalProject] = function (request) { + _a[server.CommandNames.OpenExternalProject] = function (request) { _this.projectService.openExternalProject(request.arguments, false); return _this.requiredResponse(true); }, - _a[CommandNames.OpenExternalProjects] = function (request) { + _a[server.CommandNames.OpenExternalProjects] = function (request) { _this.projectService.openExternalProjects(request.arguments.projects); return _this.requiredResponse(true); }, - _a[CommandNames.CloseExternalProject] = function (request) { + _a[server.CommandNames.CloseExternalProject] = function (request) { _this.projectService.closeExternalProject(request.arguments.projectFileName); return _this.requiredResponse(true); }, - _a[CommandNames.SynchronizeProjectList] = function (request) { + _a[server.CommandNames.SynchronizeProjectList] = function (request) { var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { return _this.requiredResponse(result); @@ -73961,220 +76238,220 @@ var ts; }); return _this.requiredResponse(converted); }, - _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _a[server.CommandNames.ApplyChangedToOpenFiles] = function (request) { _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); _this.changeSeq++; return _this.requiredResponse(true); }, - _a[CommandNames.Exit] = function () { + _a[server.CommandNames.Exit] = function () { _this.exit(); return _this.notRequired(); }, - _a[CommandNames.Definition] = function (request) { + _a[server.CommandNames.Definition] = function (request) { return _this.requiredResponse(_this.getDefinition(request.arguments, true)); }, - _a[CommandNames.DefinitionFull] = function (request) { + _a[server.CommandNames.DefinitionFull] = function (request) { return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, - _a[CommandNames.TypeDefinition] = function (request) { + _a[server.CommandNames.TypeDefinition] = function (request) { return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, - _a[CommandNames.Implementation] = function (request) { + _a[server.CommandNames.Implementation] = function (request) { return _this.requiredResponse(_this.getImplementation(request.arguments, true)); }, - _a[CommandNames.ImplementationFull] = function (request) { + _a[server.CommandNames.ImplementationFull] = function (request) { return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, - _a[CommandNames.References] = function (request) { + _a[server.CommandNames.References] = function (request) { return _this.requiredResponse(_this.getReferences(request.arguments, true)); }, - _a[CommandNames.ReferencesFull] = function (request) { + _a[server.CommandNames.ReferencesFull] = function (request) { return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, - _a[CommandNames.Rename] = function (request) { + _a[server.CommandNames.Rename] = function (request) { return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); }, - _a[CommandNames.RenameLocationsFull] = function (request) { + _a[server.CommandNames.RenameLocationsFull] = function (request) { return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); }, - _a[CommandNames.RenameInfoFull] = function (request) { + _a[server.CommandNames.RenameInfoFull] = function (request) { return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, - _a[CommandNames.Open] = function (request) { + _a[server.CommandNames.Open] = function (request) { _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName), request.arguments.projectRootPath ? server.toNormalizedPath(request.arguments.projectRootPath) : undefined); return _this.notRequired(); }, - _a[CommandNames.Quickinfo] = function (request) { + _a[server.CommandNames.Quickinfo] = function (request) { return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); }, - _a[CommandNames.QuickinfoFull] = function (request) { + _a[server.CommandNames.QuickinfoFull] = function (request) { return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); }, - _a[CommandNames.OutliningSpans] = function (request) { + _a[server.CommandNames.OutliningSpans] = function (request) { return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); }, - _a[CommandNames.TodoComments] = function (request) { + _a[server.CommandNames.TodoComments] = function (request) { return _this.requiredResponse(_this.getTodoComments(request.arguments)); }, - _a[CommandNames.Indentation] = function (request) { + _a[server.CommandNames.Indentation] = function (request) { return _this.requiredResponse(_this.getIndentation(request.arguments)); }, - _a[CommandNames.NameOrDottedNameSpan] = function (request) { + _a[server.CommandNames.NameOrDottedNameSpan] = function (request) { return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); }, - _a[CommandNames.BreakpointStatement] = function (request) { + _a[server.CommandNames.BreakpointStatement] = function (request) { return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); }, - _a[CommandNames.BraceCompletion] = function (request) { + _a[server.CommandNames.BraceCompletion] = function (request) { return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); }, - _a[CommandNames.DocCommentTemplate] = function (request) { + _a[server.CommandNames.DocCommentTemplate] = function (request) { return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, - _a[CommandNames.Format] = function (request) { + _a[server.CommandNames.Format] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, - _a[CommandNames.Formatonkey] = function (request) { + _a[server.CommandNames.Formatonkey] = function (request) { return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); }, - _a[CommandNames.FormatFull] = function (request) { + _a[server.CommandNames.FormatFull] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); }, - _a[CommandNames.FormatonkeyFull] = function (request) { + _a[server.CommandNames.FormatonkeyFull] = function (request) { return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); }, - _a[CommandNames.FormatRangeFull] = function (request) { + _a[server.CommandNames.FormatRangeFull] = function (request) { return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, - _a[CommandNames.Completions] = function (request) { + _a[server.CommandNames.Completions] = function (request) { return _this.requiredResponse(_this.getCompletions(request.arguments, true)); }, - _a[CommandNames.CompletionsFull] = function (request) { + _a[server.CommandNames.CompletionsFull] = function (request) { return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, - _a[CommandNames.CompletionDetails] = function (request) { + _a[server.CommandNames.CompletionDetails] = function (request) { return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); }, - _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + _a[server.CommandNames.CompileOnSaveAffectedFileList] = function (request) { return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); }, - _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + _a[server.CommandNames.CompileOnSaveEmitFile] = function (request) { return _this.requiredResponse(_this.emitFile(request.arguments)); }, - _a[CommandNames.SignatureHelp] = function (request) { + _a[server.CommandNames.SignatureHelp] = function (request) { return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); }, - _a[CommandNames.SignatureHelpFull] = function (request) { + _a[server.CommandNames.SignatureHelpFull] = function (request) { return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); }, - _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + _a[server.CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); }, - _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + _a[server.CommandNames.EncodedSemanticClassificationsFull] = function (request) { return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); }, - _a[CommandNames.Cleanup] = function () { + _a[server.CommandNames.Cleanup] = function () { _this.cleanup(); return _this.requiredResponse(true); }, - _a[CommandNames.SemanticDiagnosticsSync] = function (request) { + _a[server.CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); }, - _a[CommandNames.SyntacticDiagnosticsSync] = function (request) { + _a[server.CommandNames.SyntacticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSyntacticDiagnosticsSync(request.arguments)); }, - _a[CommandNames.Geterr] = function (request) { + _a[server.CommandNames.Geterr] = function (request) { _this.errorCheck.startNew(function (next) { return _this.getDiagnostics(next, request.arguments.delay, request.arguments.files); }); return _this.notRequired(); }, - _a[CommandNames.GeterrForProject] = function (request) { + _a[server.CommandNames.GeterrForProject] = function (request) { _this.errorCheck.startNew(function (next) { return _this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file); }); return _this.notRequired(); }, - _a[CommandNames.Change] = function (request) { + _a[server.CommandNames.Change] = function (request) { _this.change(request.arguments); return _this.notRequired(); }, - _a[CommandNames.Configure] = function (request) { + _a[server.CommandNames.Configure] = function (request) { _this.projectService.setHostConfiguration(request.arguments); - _this.output(undefined, CommandNames.Configure, request.seq); + _this.output(undefined, server.CommandNames.Configure, request.seq); return _this.notRequired(); }, - _a[CommandNames.Reload] = function (request) { + _a[server.CommandNames.Reload] = function (request) { _this.reload(request.arguments, request.seq); return _this.requiredResponse({ reloadFinished: true }); }, - _a[CommandNames.Saveto] = function (request) { + _a[server.CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); return _this.notRequired(); }, - _a[CommandNames.Close] = function (request) { + _a[server.CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); return _this.notRequired(); }, - _a[CommandNames.Navto] = function (request) { + _a[server.CommandNames.Navto] = function (request) { return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); }, - _a[CommandNames.NavtoFull] = function (request) { + _a[server.CommandNames.NavtoFull] = function (request) { return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, - _a[CommandNames.Brace] = function (request) { + _a[server.CommandNames.Brace] = function (request) { return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); }, - _a[CommandNames.BraceFull] = function (request) { + _a[server.CommandNames.BraceFull] = function (request) { return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, - _a[CommandNames.NavBar] = function (request) { + _a[server.CommandNames.NavBar] = function (request) { return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); }, - _a[CommandNames.NavBarFull] = function (request) { + _a[server.CommandNames.NavBarFull] = function (request) { return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); }, - _a[CommandNames.NavTree] = function (request) { + _a[server.CommandNames.NavTree] = function (request) { return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); }, - _a[CommandNames.NavTreeFull] = function (request) { + _a[server.CommandNames.NavTreeFull] = function (request) { return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, - _a[CommandNames.Occurrences] = function (request) { + _a[server.CommandNames.Occurrences] = function (request) { return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, - _a[CommandNames.DocumentHighlights] = function (request) { + _a[server.CommandNames.DocumentHighlights] = function (request) { return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); }, - _a[CommandNames.DocumentHighlightsFull] = function (request) { + _a[server.CommandNames.DocumentHighlightsFull] = function (request) { return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); }, - _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + _a[server.CommandNames.CompilerOptionsForInferredProjects] = function (request) { _this.setCompilerOptionsForInferredProjects(request.arguments); return _this.requiredResponse(true); }, - _a[CommandNames.ProjectInfo] = function (request) { + _a[server.CommandNames.ProjectInfo] = function (request) { return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, - _a[CommandNames.ReloadProjects] = function () { + _a[server.CommandNames.ReloadProjects] = function () { _this.projectService.reloadProjects(); return _this.notRequired(); }, - _a[CommandNames.GetCodeFixes] = function (request) { + _a[server.CommandNames.GetCodeFixes] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); }, - _a[CommandNames.GetCodeFixesFull] = function (request) { + _a[server.CommandNames.GetCodeFixesFull] = function (request) { return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); }, - _a[CommandNames.GetSupportedCodeFixes] = function () { + _a[server.CommandNames.GetSupportedCodeFixes] = function () { return _this.requiredResponse(_this.getSupportedCodeFixes()); }, - _a[CommandNames.GetApplicableRefactors] = function (request) { + _a[server.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[server.CommandNames.GetEditsForRefactor] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, true)); }, - _a[CommandNames.GetRefactorCodeActionsFull] = function (request) { - return _this.requiredResponse(_this.getRefactorCodeActions(request.arguments, false)); + _a[server.CommandNames.GetEditsForRefactorFull] = function (request) { + return _this.requiredResponse(_this.getEditsForRefactor(request.arguments, false)); }, _a)); this.host = opts.host; @@ -74234,13 +76511,22 @@ var ts; var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; this.configFileDiagnosticEvent(triggerFile, configFileName, diagnostics); break; - case server.ProjectLanguageServiceStateEvent: + case server.ProjectLanguageServiceStateEvent: { var eventName = "projectLanguageServiceState"; this.event({ projectName: event.data.project.getProjectName(), languageServiceEnabled: event.data.languageServiceEnabled }, eventName); break; + } + case server.ProjectInfoTelemetryEvent: { + var eventName = "telemetry"; + this.event({ + telemetryEventName: event.eventName, + payload: event.data, + }, eventName); + break; + } } }; Session.prototype.logError = function (err, cmd) { @@ -74263,7 +76549,7 @@ var ts; this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { - var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); + var bakedDiags = ts.map(diagnostics, function (diagnostic) { return formatConfigFileDiag(diagnostic, true); }); var ev = { seq: 0, type: "event", @@ -74390,9 +76676,37 @@ var ts; Session.prototype.getProject = function (projectFileName) { return projectFileName && this.projectService.findProject(projectFileName); }; + Session.prototype.getConfigFileAndProject = function (args) { + var project = this.getProject(args.projectFileName); + var file = server.toNormalizedPath(args.file); + return { + configFile: project && project.hasConfigFile(file) && file, + project: project + }; + }; + Session.prototype.getConfigFileDiagnostics = function (configFile, project, includeLinePosition) { + var projectErrors = project.getAllProjectErrors(); + var optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); + var diagnosticsForConfigFile = ts.filter(ts.concatenate(projectErrors, optionsErrors), function (diagnostic) { return diagnostic.file && diagnostic.file.fileName === configFile; }); + return includeLinePosition ? + this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : + ts.map(diagnosticsForConfigFile, function (diagnostic) { return formatConfigFileDiag(diagnostic, false); }); + }; + Session.prototype.convertToDiagnosticsWithLinePositionFromDiagnosticFile = function (diagnostics) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start)), + endLocation: d.file && convertToLocation(ts.getLineAndCharacterOfPosition(d.file, d.start + d.length)) + }); }); + }; Session.prototype.getCompilerOptionsDiagnostics = function (args) { var project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + return this.convertToDiagnosticsWithLinePosition(ts.filter(project.getLanguageService().getCompilerOptionsDiagnostics(), function (diagnostic) { return !diagnostic.file; }), undefined); }; Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { var _this = this; @@ -74505,9 +76819,17 @@ var ts; }); }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { + var configFile = this.getConfigFileAndProject(args).configFile; + if (configFile) { + return []; + } return this.getDiagnosticsWorker(args, false, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { + var _a = this.getConfigFileAndProject(args), configFile = _a.configFile, project = _a.project; + if (configFile) { + return this.getConfigFileDiagnostics(configFile, project, args.includeLinePosition); + } return this.getDiagnosticsWorker(args, true, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { @@ -74543,14 +76865,14 @@ var ts; this.projectService.setCompilerOptionsForInferredProjects(args.options); }; Session.prototype.getProjectInfo = function (args) { - return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList, false); }; - Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { configFileName: project.getProjectName(), languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames() : undefined + fileNames: needFileNameList ? project.getFileNames(false, excludeConfigFiles) : undefined }; return projectInfo; }; @@ -74619,21 +76941,22 @@ var ts; }; }); }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; + var locs = []; + for (var _i = 0, fileSpans_1 = fileSpans; _i < fileSpans_1.length; _i++) { + var cur = fileSpans_1[_i]; + var curFileAccum = void 0; + if (locs.length > 0) { + curFileAccum = locs[locs.length - 1]; if (curFileAccum.file !== cur.file) { curFileAccum = undefined; } } if (!curFileAccum) { curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + locs.push(curFileAccum); } curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); + } return { info: renameInfo, locs: locs }; } else { @@ -74846,31 +77169,28 @@ var ts; var formatOptions = this.projectService.getFormatCodeOptions(file); var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var lineInfo = scriptInfo.getLineInfo(args.line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) === " ") { - hasIndent++; - } - else if (lineText.charAt(i) === "\t") { - hasIndent += formatOptions.tabSize; - } - else { - break; - } + var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; + if (lineText && lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) === " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) - }); + else if (lineText.charAt(i) === "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = absolutePosition + i; + edits.push({ + span: ts.createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -74896,14 +77216,13 @@ var ts; return undefined; } if (simplifiedResult) { - return completions.entries.reduce(function (result, entry) { + return ts.mapDefined(completions.entries, function (entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; - result.push({ name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }; } - return result; - }, []).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); + }).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } else { return completions; @@ -74913,13 +77232,9 @@ var ts; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); - return args.entryNames.reduce(function (accum, entryName) { - var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); - if (details) { - accum.push(details); - } - return accum; - }, []); + return ts.mapDefined(args.entryNames, function (entryName) { + return project.getLanguageService().getCompletionEntryDetails(file, position, entryName); + }); }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { var info = this.projectService.getScriptInfo(args.file); @@ -74979,14 +77294,11 @@ var ts; }; Session.prototype.getDiagnostics = function (next, delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var checkList = ts.mapDefined(fileNames, function (uncheckedFileName) { var fileName = server.toNormalizedPath(uncheckedFileName); var project = _this.projectService.getDefaultProjectForFile(fileName, true); - if (project) { - accum.push({ fileName: fileName, project: project }); - } - return accum; - }, []); + return project && { fileName: fileName, project: project }; + }); if (checkList.length > 0) { this.updateErrorCheck(next, checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } @@ -75012,7 +77324,7 @@ var ts; if (project) { this.changeSeq++; if (project.reloadScript(file, tempFileName)) { - this.output(undefined, CommandNames.Reload, reqSeq); + this.output(undefined, server.CommandNames.Reload, reqSeq); } } }; @@ -75167,21 +77479,32 @@ var ts; 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) { + Session.prototype.getEditsForRefactor = 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) { + var result = project.getLanguageService().getEditsForRefactor(file, this.projectService.getFormatCodeOptions(), position || textRange, args.refactor, args.action); + if (result === undefined) { return { - actions: result.map(function (action) { return _this.mapCodeAction(action, scriptInfo); }) + edits: [] + }; + } + if (simplifiedResult) { + var file_2 = result.renameFilename; + var location = void 0; + if (file_2 !== undefined && result.renameLocation !== undefined) { + var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(file_2)); + location = renameScriptInfo.positionToLineOffset(result.renameLocation); + } + return { + renameLocation: location, + renameFilename: file_2, + edits: result.edits.map(function (change) { return _this.mapTextChangesToCodeEdits(project, change); }) }; } else { - return { - actions: result - }; + return result; } }; Session.prototype.getCodeFixes = function (args, simplifiedResult) { @@ -75232,6 +77555,14 @@ var ts; }); }) }; }; + Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { + var _this = this; + var scriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(textChanges.fileName)); + return { + fileName: textChanges.fileName, + textChanges: textChanges.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }; + }; Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { return { start: scriptInfo.positionToLineOffset(change.span.start), @@ -75253,7 +77584,7 @@ var ts; }; Session.prototype.getDiagnosticsForProject = function (next, delay, fileName) { var _this = this; - var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, true, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -75266,18 +77597,22 @@ var ts; var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; - if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) + if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { highPriorityFiles.push(fileNameInProject); + } else { var info = this.projectService.getScriptInfo(fileNameInProject); if (!info.isScriptOpen()) { - if (fileNameInProject.indexOf(".d.ts") > 0) + if (fileNameInProject.indexOf(".d.ts") > 0) { veryLowPriorityFiles.push(fileNameInProject); - else + } + else { lowPriorityFiles.push(fileNameInProject); + } } - else + else { mediumPriorityFiles.push(fileNameInProject); + } } } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); @@ -75330,7 +77665,7 @@ var ts; } else { this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); - this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); + this.output(undefined, server.CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; @@ -75369,7 +77704,7 @@ var ts; return; } this.logError(err, message); - this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); + this.output(undefined, request ? request.command : server.CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); } }; return Session; @@ -75391,32 +77726,25 @@ var ts; CharRangeSection[CharRangeSection["End"] = 4] = "End"; CharRangeSection[CharRangeSection["PostEnd"] = 5] = "PostEnd"; })(CharRangeSection = server.CharRangeSection || (server.CharRangeSection = {})); - var BaseLineIndexWalker = (function () { - function BaseLineIndexWalker() { - this.goSubtree = true; - this.done = false; - } - BaseLineIndexWalker.prototype.leaf = function (_rangeStart, _rangeLength, _ll) { - }; - return BaseLineIndexWalker; - }()); - var EditWalker = (function (_super) { - __extends(EditWalker, _super); + var EditWalker = (function () { function EditWalker() { - var _this = _super.call(this) || this; - _this.lineIndex = new LineIndex(); - _this.endBranch = []; - _this.state = CharRangeSection.Entire; - _this.initialText = ""; - _this.trailingText = ""; - _this.suppressTrailingText = false; - _this.lineIndex.root = new LineNode(); - _this.startPath = [_this.lineIndex.root]; - _this.stack = [_this.lineIndex.root]; - return _this; + this.goSubtree = true; + this.lineIndex = new LineIndex(); + this.endBranch = []; + this.state = CharRangeSection.Entire; + this.initialText = ""; + this.trailingText = ""; + this.lineIndex.root = new LineNode(); + this.startPath = [this.lineIndex.root]; + this.stack = [this.lineIndex.root]; } - EditWalker.prototype.insertLines = function (insertedText) { - if (this.suppressTrailingText) { + Object.defineProperty(EditWalker.prototype, "done", { + get: function () { return false; }, + enumerable: true, + configurable: true + }); + EditWalker.prototype.insertLines = function (insertedText, suppressTrailingText) { + if (suppressTrailingText) { this.trailingText = ""; } if (insertedText) { @@ -75429,7 +77757,7 @@ var ts; var lines = lm.lines; if (lines.length > 1) { if (lines[lines.length - 1] === "") { - lines.length--; + lines.pop(); } } var branchParent; @@ -75449,20 +77777,18 @@ var ts; if (lastZeroCount) { branchParent.remove(lastZeroCount); } - var insertionNode = this.startPath[this.startPath.length - 2]; var leafNode = this.startPath[this.startPath.length - 1]; - var len = lines.length; - if (len > 0) { + if (lines.length > 0) { leafNode.text = lines[0]; - if (len > 1) { - var insertedNodes = new Array(len - 1); + if (lines.length > 1) { + var insertedNodes = new Array(lines.length - 1); var startNode = leafNode; for (var i = 1; i < lines.length; i++) { insertedNodes[i - 1] = new LineLeaf(lines[i]); } var pathIndex = this.startPath.length - 2; while (pathIndex >= 0) { - insertionNode = this.startPath[pathIndex]; + var insertionNode = this.startPath[pathIndex]; insertedNodes = insertionNode.insertAt(startNode, insertedNodes); pathIndex--; startNode = insertionNode; @@ -75484,6 +77810,7 @@ var ts; } } else { + var insertionNode = this.startPath[this.startPath.length - 2]; insertionNode.remove(leafNode); for (var j = this.startPath.length - 2; j >= 0; j--) { this.startPath[j].updateCounts(); @@ -75495,8 +77822,7 @@ var ts; if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } - this.stack.length--; - return undefined; + this.stack.pop(); }; EditWalker.prototype.pre = function (_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { var currentNode = this.stack[this.stack.length - 1]; @@ -75527,20 +77853,20 @@ var ts; else { child = fresh(lineCollection); currentNode.add(child); - this.startPath[this.startPath.length] = child; + this.startPath.push(child); } break; case CharRangeSection.Entire: if (this.state !== CharRangeSection.End) { child = fresh(lineCollection); currentNode.add(child); - this.startPath[this.startPath.length] = child; + this.startPath.push(child); } else { if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); - this.endBranch[this.endBranch.length] = child; + this.endBranch.push(child); } } break; @@ -75555,7 +77881,7 @@ var ts; if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); - this.endBranch[this.endBranch.length] = child; + this.endBranch.push(child); } } break; @@ -75567,9 +77893,8 @@ var ts; break; } if (this.goSubtree) { - this.stack[this.stack.length] = child; + this.stack.push(child); } - return lineCollection; }; EditWalker.prototype.leaf = function (relativeStart, relativeLength, ll) { if (this.state === CharRangeSection.Start) { @@ -75584,7 +77909,7 @@ var ts; } }; return EditWalker; - }(BaseLineIndexWalker)); + }()); var TextChange = (function () { function TextChange(pos, deleteLen, insertedText) { this.pos = pos; @@ -75614,10 +77939,10 @@ var ts; return this.currentVersion % ScriptVersionCache.maxVersions; }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { - this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); - if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || - (deleteLen > ScriptVersionCache.changeLengthThreshold) || - (insertedText && (insertedText.length > ScriptVersionCache.changeLengthThreshold))) { + this.changes.push(new TextChange(pos, deleteLen, insertedText)); + if (this.changes.length > ScriptVersionCache.changeNumberThreshold || + deleteLen > ScriptVersionCache.changeLengthThreshold || + insertedText && insertedText.length > ScriptVersionCache.changeLengthThreshold) { this.getSnapshot(); } }; @@ -75630,22 +77955,14 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename) { - var content = this.host.readFile(filename); - if (!content) { - content = ""; - } - this.reload(content); - }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; - var snap = new LineIndexSnapshot(this.currentVersion, this); + var snap = new LineIndexSnapshot(this.currentVersion, this, new LineIndex()); for (var i = 0; i < this.versions.length; i++) { this.versions[i] = undefined; } this.versions[this.currentVersionToIndex()] = snap; - snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); this.minVersion = this.currentVersion; @@ -75658,9 +77975,7 @@ var ts; var change = _a[_i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); } - snap = new LineIndexSnapshot(this.currentVersion + 1, this); - snap.index = snapIndex; - snap.changesSincePreviousVersion = this.changes; + snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes); this.currentVersion = snap.version; this.versions[this.currentVersionToIndex()] = snap; this.changes = []; @@ -75678,7 +77993,7 @@ var ts; var snap = this.versions[this.versionToIndex(i)]; for (var _i = 0, _a = snap.changesSincePreviousVersion; _i < _a.length; _i++) { var textChange = _a[_i]; - textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); + textChangeRanges.push(textChange.getTextChangeRange()); } } return ts.collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges); @@ -75691,27 +78006,27 @@ var ts; return ts.unchangedTextChangeRange; } }; - ScriptVersionCache.fromString = function (host, script) { + ScriptVersionCache.fromString = function (script) { var svc = new ScriptVersionCache(); - var snap = new LineIndexSnapshot(0, svc); + var snap = new LineIndexSnapshot(0, svc, new LineIndex()); svc.versions[svc.currentVersion] = snap; - svc.host = host; - snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); return svc; }; + ScriptVersionCache.changeNumberThreshold = 8; + ScriptVersionCache.changeLengthThreshold = 256; + ScriptVersionCache.maxVersions = 8; return ScriptVersionCache; }()); - ScriptVersionCache.changeNumberThreshold = 8; - ScriptVersionCache.changeLengthThreshold = 256; - ScriptVersionCache.maxVersions = 8; server.ScriptVersionCache = ScriptVersionCache; var LineIndexSnapshot = (function () { - function LineIndexSnapshot(version, cache) { + function LineIndexSnapshot(version, cache, index, changesSincePreviousVersion) { + if (changesSincePreviousVersion === void 0) { changesSincePreviousVersion = server.emptyArray; } this.version = version; this.cache = cache; - this.changesSincePreviousVersion = []; + this.index = index; + this.changesSincePreviousVersion = changesSincePreviousVersion; } LineIndexSnapshot.prototype.getText = function (rangeStart, rangeEnd) { return this.index.getText(rangeStart, rangeEnd - rangeStart); @@ -75719,35 +78034,14 @@ var ts; LineIndexSnapshot.prototype.getLength = function () { return this.index.root.charCount(); }; - LineIndexSnapshot.prototype.getLineStartPositions = function () { - var starts = [-1]; - var count = 1; - var pos = 0; - this.index.every(function (ll) { - starts[count] = pos; - count++; - pos += ll.text.length; - return true; - }, 0); - return starts; - }; - LineIndexSnapshot.prototype.getLineMapper = function () { - var _this = this; - return function (line) { - return _this.index.lineNumberToInfo(line).offset; - }; - }; - LineIndexSnapshot.prototype.getTextChangeRangeSinceVersion = function (scriptVersion) { - if (this.version <= scriptVersion) { - return ts.unchangedTextChangeRange; - } - else { - return this.cache.getTextChangesBetweenVersions(scriptVersion, this.version); - } - }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { - return this.getTextChangeRangeSinceVersion(oldSnapshot.version); + if (this.version <= oldSnapshot.version) { + return ts.unchangedTextChangeRange; + } + else { + return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version); + } } }; return LineIndexSnapshot; @@ -75757,21 +78051,24 @@ var ts; function LineIndex() { this.checkEdits = false; } - LineIndex.prototype.charOffsetToLineNumberAndPos = function (charOffset) { - return this.root.charOffsetToLineNumberAndPos(1, charOffset); + LineIndex.prototype.absolutePositionOfStartOfLine = function (oneBasedLine) { + return this.lineNumberToInfo(oneBasedLine).absolutePosition; }; - LineIndex.prototype.lineNumberToInfo = function (lineNumber) { + LineIndex.prototype.positionToLineOffset = function (position) { + var _a = this.root.charOffsetToLineInfo(1, position), oneBasedLine = _a.oneBasedLine, zeroBasedColumn = _a.zeroBasedColumn; + return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; + }; + LineIndex.prototype.positionToColumnAndLineText = function (position) { + return this.root.charOffsetToLineInfo(1, position); + }; + LineIndex.prototype.lineNumberToInfo = function (oneBasedLine) { var lineCount = this.root.lineCount(); - if (lineNumber <= lineCount) { - var lineInfo = this.root.lineNumberToInfo(lineNumber, 0); - lineInfo.line = lineNumber; - return lineInfo; + if (oneBasedLine <= lineCount) { + var _a = this.root.lineNumberToInfo(oneBasedLine, 0), position = _a.position, leaf = _a.leaf; + return { absolutePosition: position, lineText: leaf && leaf.text }; } else { - return { - line: lineNumber, - offset: this.root.charCount() - }; + return { absolutePosition: this.root.charCount(), lineText: undefined }; } }; LineIndex.prototype.load = function (lines) { @@ -75822,11 +78119,8 @@ var ts; return !walkFns.done; }; LineIndex.prototype.edit = function (pos, deleteLength, newText) { - function editFlat(source, s, dl, nt) { - if (nt === void 0) { nt = ""; } - return source.substring(0, s) + nt + source.substring(s + dl, source.length); - } if (this.root.charCount() === 0) { + ts.Debug.assert(deleteLength === 0); if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; @@ -75835,9 +78129,11 @@ var ts; else { var checkText = void 0; if (this.checkEdits) { - checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText); + var source = this.getText(0, this.root.charCount()); + checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength); } var walker = new EditWalker(); + var suppressTrailingText = false; if (pos >= this.root.charCount()) { pos = this.root.charCount() - 1; var endString = this.getText(pos, 1); @@ -75848,88 +78144,68 @@ var ts; newText = endString; } deleteLength = 0; - walker.suppressTrailingText = true; + suppressTrailingText = true; } else if (deleteLength > 0) { var e = pos + deleteLength; - var lineInfo = this.charOffsetToLineNumberAndPos(e); - if ((lineInfo && (lineInfo.offset === 0))) { - deleteLength += lineInfo.text.length; - if (newText) { - newText = newText + lineInfo.text; - } - else { - newText = lineInfo.text; - } + var _a = this.positionToColumnAndLineText(e), zeroBasedColumn = _a.zeroBasedColumn, lineText = _a.lineText; + if (zeroBasedColumn === 0) { + deleteLength += lineText.length; + newText = newText ? newText + lineText : lineText; } } - if (pos < this.root.charCount()) { - this.root.walk(pos, deleteLength, walker); - walker.insertLines(newText); - } + this.root.walk(pos, deleteLength, walker); + walker.insertLines(newText, suppressTrailingText); if (this.checkEdits) { - var updatedText = this.getText(0, this.root.charCount()); + var updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength()); ts.Debug.assert(checkText === updatedText, "buffer edit mismatch"); } return walker.lineIndex; } }; LineIndex.buildTreeFromBottom = function (nodes) { - var nodeCount = Math.ceil(nodes.length / lineCollectionCapacity); - var interiorNodes = []; + if (nodes.length < lineCollectionCapacity) { + return new LineNode(nodes); + } + var interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity)); var nodeIndex = 0; - for (var i = 0; i < nodeCount; i++) { - interiorNodes[i] = new LineNode(); - var charCount = 0; - var lineCount = 0; - for (var j = 0; j < lineCollectionCapacity; j++) { - if (nodeIndex < nodes.length) { - interiorNodes[i].add(nodes[nodeIndex]); - charCount += nodes[nodeIndex].charCount(); - lineCount += nodes[nodeIndex].lineCount(); - } - else { - break; - } - nodeIndex++; - } - interiorNodes[i].totalChars = charCount; - interiorNodes[i].totalLines = lineCount; - } - if (interiorNodes.length === 1) { - return interiorNodes[0]; - } - else { - return this.buildTreeFromBottom(interiorNodes); + for (var i = 0; i < interiorNodes.length; i++) { + var end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length); + interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end)); + nodeIndex = end; } + return this.buildTreeFromBottom(interiorNodes); }; LineIndex.linesFromText = function (text) { - var lineStarts = ts.computeLineStarts(text); - if (lineStarts.length === 0) { - return { lines: [], lineMap: lineStarts }; + var lineMap = ts.computeLineStarts(text); + if (lineMap.length === 0) { + return { lines: [], lineMap: lineMap }; } - var lines = new Array(lineStarts.length); - var lc = lineStarts.length - 1; + var lines = new Array(lineMap.length); + var lc = lineMap.length - 1; for (var lmi = 0; lmi < lc; lmi++) { - lines[lmi] = text.substring(lineStarts[lmi], lineStarts[lmi + 1]); + lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]); } - var endText = text.substring(lineStarts[lc]); + var endText = text.substring(lineMap[lc]); if (endText.length > 0) { lines[lc] = endText; } else { - lines.length--; + lines.pop(); } - return { lines: lines, lineMap: lineStarts }; + return { lines: lines, lineMap: lineMap }; }; return LineIndex; }()); server.LineIndex = LineIndex; var LineNode = (function () { - function LineNode() { + function LineNode(children) { + if (children === void 0) { children = []; } + this.children = children; this.totalChars = 0; this.totalLines = 0; - this.children = []; + if (children.length) + this.updateCounts(); } LineNode.prototype.isLeaf = function () { return false; @@ -75966,15 +78242,13 @@ var ts; }; LineNode.prototype.walk = function (rangeStart, rangeLength, walkFns) { var childIndex = 0; - var child = this.children[0]; - var childCharCount = child.charCount(); + var childCharCount = this.children[childIndex].charCount(); var adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); adjustedStart -= childCharCount; childIndex++; - child = this.children[childIndex]; - childCharCount = child.charCount(); + childCharCount = this.children[childIndex].charCount(); } if ((adjustedStart + rangeLength) <= childCharCount) { if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, CharRangeSection.Entire)) { @@ -75987,7 +78261,7 @@ var ts; } var adjustedLength = rangeLength - (childCharCount - adjustedStart); childIndex++; - child = this.children[childIndex]; + var child = this.children[childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { @@ -75995,8 +78269,7 @@ var ts; } adjustedLength -= childCharCount; childIndex++; - child = this.children[childIndex]; - childCharCount = child.charCount(); + childCharCount = this.children[childIndex].charCount(); } if (adjustedLength > 0) { if (this.execWalk(0, adjustedLength, walkFns, childIndex, CharRangeSection.End)) { @@ -76013,97 +78286,77 @@ var ts; } } }; - LineNode.prototype.charOffsetToLineNumberAndPos = function (lineNumber, charOffset) { - var childInfo = this.childFromCharOffset(lineNumber, charOffset); + LineNode.prototype.charOffsetToLineInfo = function (lineNumberAccumulator, relativePosition) { + var childInfo = this.childFromCharOffset(lineNumberAccumulator, relativePosition); if (!childInfo.child) { return { - line: lineNumber, - offset: charOffset, + oneBasedLine: lineNumberAccumulator, + zeroBasedColumn: relativePosition, + lineText: undefined, }; } else if (childInfo.childIndex < this.children.length) { if (childInfo.child.isLeaf()) { return { - line: childInfo.lineNumber, - offset: childInfo.charOffset, - text: (childInfo.child).text, - leaf: (childInfo.child) + oneBasedLine: childInfo.lineNumberAccumulator, + zeroBasedColumn: childInfo.relativePosition, + lineText: childInfo.child.text, }; } else { var lineNode = (childInfo.child); - return lineNode.charOffsetToLineNumberAndPos(childInfo.lineNumber, childInfo.charOffset); + return lineNode.charOffsetToLineInfo(childInfo.lineNumberAccumulator, childInfo.relativePosition); } } else { var lineInfo = this.lineNumberToInfo(this.lineCount(), 0); - return { line: this.lineCount(), offset: lineInfo.leaf.charCount() }; + return { oneBasedLine: this.lineCount(), zeroBasedColumn: lineInfo.leaf.charCount(), lineText: undefined }; } }; - LineNode.prototype.lineNumberToInfo = function (lineNumber, charOffset) { - var childInfo = this.childFromLineNumber(lineNumber, charOffset); + LineNode.prototype.lineNumberToInfo = function (relativeOneBasedLine, positionAccumulator) { + var childInfo = this.childFromLineNumber(relativeOneBasedLine, positionAccumulator); if (!childInfo.child) { - return { - line: lineNumber, - offset: charOffset - }; + return { position: positionAccumulator, leaf: undefined }; } else if (childInfo.child.isLeaf()) { - return { - line: lineNumber, - offset: childInfo.charOffset, - text: (childInfo.child).text, - leaf: (childInfo.child) - }; + return { position: childInfo.positionAccumulator, leaf: childInfo.child }; } else { var lineNode = (childInfo.child); - return lineNode.lineNumberToInfo(childInfo.relativeLineNumber, childInfo.charOffset); + return lineNode.lineNumberToInfo(childInfo.relativeOneBasedLine, childInfo.positionAccumulator); } }; - LineNode.prototype.childFromLineNumber = function (lineNumber, charOffset) { + LineNode.prototype.childFromLineNumber = function (relativeOneBasedLine, positionAccumulator) { var child; - var relativeLineNumber = lineNumber; var i; - var len; - for (i = 0, len = this.children.length; i < len; i++) { + for (i = 0; i < this.children.length; i++) { child = this.children[i]; var childLineCount = child.lineCount(); - if (childLineCount >= relativeLineNumber) { + if (childLineCount >= relativeOneBasedLine) { break; } else { - relativeLineNumber -= childLineCount; - charOffset += child.charCount(); + relativeOneBasedLine -= childLineCount; + positionAccumulator += child.charCount(); } } - return { - child: child, - childIndex: i, - relativeLineNumber: relativeLineNumber, - charOffset: charOffset - }; + return { child: child, relativeOneBasedLine: relativeOneBasedLine, positionAccumulator: positionAccumulator }; }; - LineNode.prototype.childFromCharOffset = function (lineNumber, charOffset) { + LineNode.prototype.childFromCharOffset = function (lineNumberAccumulator, relativePosition) { var child; var i; var len; for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; - if (child.charCount() > charOffset) { + if (child.charCount() > relativePosition) { break; } else { - charOffset -= child.charCount(); - lineNumber += child.lineCount(); + relativePosition -= child.charCount(); + lineNumberAccumulator += child.lineCount(); } } - return { - child: child, - childIndex: i, - charOffset: charOffset, - lineNumber: lineNumber - }; + return { child: child, childIndex: i, relativePosition: relativePosition, lineNumberAccumulator: lineNumberAccumulator }; }; LineNode.prototype.splitAfter = function (childIndex) { var splitNode; @@ -76129,13 +78382,11 @@ var ts; this.children[i] = this.children[i + 1]; } } - this.children.length--; + this.children.pop(); }; LineNode.prototype.findChildIndex = function (child) { - var childIndex = 0; - var clen = this.children.length; - while ((this.children[childIndex] !== child) && (childIndex < clen)) - childIndex++; + var childIndex = this.children.indexOf(child); + ts.Debug.assert(childIndex !== -1); return childIndex; }; LineNode.prototype.insertAt = function (child, nodes) { @@ -76176,12 +78427,12 @@ var ts; } for (var i = splitNodes.length - 1; i >= 0; i--) { if (splitNodes[i].children.length === 0) { - splitNodes.length--; + splitNodes.pop(); } } } if (shiftNode) { - splitNodes[splitNodes.length] = shiftNode; + splitNodes.push(shiftNode); } this.updateCounts(); for (var i = 0; i < splitNodeCount; i++) { @@ -76191,8 +78442,8 @@ var ts; } }; LineNode.prototype.add = function (collection) { - this.children[this.children.length] = collection; - return (this.children.length < lineCollectionCapacity); + this.children.push(collection); + ts.Debug.assert(this.children.length <= lineCollectionCapacity); }; LineNode.prototype.charCount = function () { return this.totalChars; @@ -76285,33 +78536,22 @@ var ts; return ts.createTextSpanFromBounds(start, end); } var index = this.svc.getSnapshot().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); + var _a = index.lineNumberToInfo(line + 1), lineText = _a.lineText, absolutePosition = _a.absolutePosition; + var len = lineText !== undefined ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; + return ts.createTextSpan(absolutePosition, len); }; TextStorage.prototype.lineOffsetToPosition = function (line, offset) { if (!this.svc) { - return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1); + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); } - var index = this.svc.getSnapshot().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); + return this.svc.getSnapshot().index.absolutePositionOfStartOfLine(line) + (offset - 1); }; TextStorage.prototype.positionToLineOffset = function (position) { if (!this.svc) { var _a = ts.computeLineAndCharacterOfPosition(this.getLineMap(), position), line = _a.line, character = _a.character; return { line: line + 1, offset: character + 1 }; } - var index = this.svc.getSnapshot().index; - var lineOffset = index.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + return this.svc.getSnapshot().index.positionToLineOffset(position); }; TextStorage.prototype.getFileText = function (tempFileName) { return this.host.readFile(tempFileName || this.fileName) || ""; @@ -76321,7 +78561,7 @@ var ts; }; TextStorage.prototype.switchToScriptVersionCache = function (newText) { if (!this.svc) { - this.svc = server.ScriptVersionCache.fromString(this.host, newText !== undefined ? newText : this.getOrLoadText()); + this.svc = server.ScriptVersionCache.fromString(newText !== undefined ? newText : this.getOrLoadText()); this.svcVersion++; this.text = undefined; } @@ -76418,7 +78658,7 @@ var ts; } break; default: - server.removeItemFromSet(this.containingProjects, project); + ts.unorderedRemoveItem(this.containingProjects, project); break; } }; @@ -76427,7 +78667,7 @@ var ts; var p = _a[_i]; p.removeFile(this, false); } - this.containingProjects.length = 0; + ts.clear(this.containingProjects); }; ScriptInfo.prototype.getDefaultProject = function () { switch (this.containingProjects.length) { @@ -76533,8 +78773,8 @@ var ts; this.host = host; this.project = project; this.cancellationToken = cancellationToken; - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); + this.resolvedModuleNames = ts.createMap(); + this.resolvedTypeReferenceDirectives = ts.createMap(); this.cancellationToken = new ts.ThrottledCancellationToken(cancellationToken, project.projectService.throttleWaitMilliseconds); this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); if (host.trace) { @@ -76545,7 +78785,7 @@ var ts; ? _this.project.projectService.typingsInstaller.globalTypingsCacheLocation : undefined; var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); - if (ts.moduleHasNonRelativeName(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { + if (!ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension)) && globalCache !== undefined) { var _a = ts.loadModuleFromGlobalCache(moduleName, _this.project.getProjectName(), compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; if (resolvedModule) { return { resolvedModule: resolvedModule, failedLookupLocations: primaryResult.failedLookupLocations.concat(failedLookupLocations) }; @@ -76557,6 +78797,10 @@ var ts; this.realpath = function (path) { return _this.host.realpath(path); }; } } + LSHost.prototype.dispose = function () { + this.project = undefined; + this.resolveModuleName = undefined; + }; LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { this.filesWithChangedSetOfUnresolvedImports = []; }; @@ -76673,8 +78917,9 @@ var ts; LSHost.prototype.resolvePath = function (path) { return this.host.resolvePath(path); }; - LSHost.prototype.fileExists = function (path) { - return this.host.fileExists(path); + LSHost.prototype.fileExists = function (file) { + var path = ts.toPath(file, this.host.getCurrentDirectory(), this.getCanonicalFileName); + return !this.project.isWatchedMissingFile(path) && this.host.fileExists(file); }; LSHost.prototype.readFile = function (fileName) { return this.host.readFile(fileName); @@ -76682,15 +78927,15 @@ var ts; LSHost.prototype.directoryExists = function (path) { return this.host.directoryExists(path); }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); + LSHost.prototype.readDirectory = function (path, extensions, exclude, include, depth) { + return this.host.readDirectory(path, extensions, exclude, include, depth); }; LSHost.prototype.getDirectories = function (path) { return this.host.getDirectories(path); }; LSHost.prototype.notifyFileRemoved = function (info) { - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); + this.resolvedModuleNames.delete(info.path); + this.resolvedTypeReferenceDirectives.delete(info.path); }; LSHost.prototype.setCompilationSettings = function (opt) { if (ts.changesAffectModuleResolution(this.compilationSettings, opt)) { @@ -76794,7 +79039,7 @@ var ts; this.perProjectCache.set(projectName, { compilerOptions: compilerOptions, typeAcquisition: typeAcquisition, - typings: server.toSortedReadonlyArray(newTypings), + typings: server.toSortedArray(newTypings), unresolvedImports: unresolvedImports, poisoned: false }); @@ -76869,7 +79114,10 @@ var ts; this.ctor = ctor; } AbstractBuilder.prototype.getFileInfos = function () { - return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createFileMap()); + return this.fileInfos_doNotAccessDirectly || (this.fileInfos_doNotAccessDirectly = ts.createMap()); + }; + AbstractBuilder.prototype.hasFileInfos = function () { + return !!this.fileInfos_doNotAccessDirectly; }; AbstractBuilder.prototype.clear = function () { this.fileInfos_doNotAccessDirectly = undefined; @@ -76887,18 +79135,19 @@ var ts; return fileInfo; }; AbstractBuilder.prototype.getFileInfoPaths = function () { - return this.getFileInfos().getKeys(); + return ts.arrayFrom(this.getFileInfos().keys()); }; AbstractBuilder.prototype.setFileInfo = function (path, info) { this.getFileInfos().set(path, info); }; AbstractBuilder.prototype.removeFileInfo = function (path) { - this.getFileInfos().remove(path); + this.getFileInfos().delete(path); }; AbstractBuilder.prototype.forEachFileInfo = function (action) { - this.getFileInfos().forEachValue(function (_path, value) { return action(value); }); + this.getFileInfos().forEach(action); }; AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + this.ensureFileInfoIfInProject(scriptInfo); var fileInfo = this.getFileInfo(scriptInfo.path); if (!fileInfo) { return false; @@ -76923,7 +79172,20 @@ var ts; _this.project = project; return _this; } + NonModuleBuilder.prototype.ensureFileInfoIfInProject = function (scriptInfo) { + if (this.project.containsScriptInfo(scriptInfo)) { + this.getOrCreateFileInfo(scriptInfo.path); + } + }; NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + var _this = this; + if (this.hasFileInfos()) { + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + } }; NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { var info = this.getOrCreateFileInfo(scriptInfo.path); @@ -76943,50 +79205,25 @@ var ts; __extends(ModuleBuilderFileInfo, _super); function ModuleBuilderFileInfo() { var _this = _super !== null && _super.apply(this, arguments) || this; - _this.references = []; - _this.referencedBy = []; + _this.references = server.createSortedArray(); + _this.referencedBy = server.createSortedArray(); return _this; } ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { - var l = lf.scriptInfo.fileName; - var r = rf.scriptInfo.fileName; - return (l < r ? -1 : (l > r ? 1 : 0)); - }; - ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { - if (array.length === 0) { - array.push(fileInfo); - return; - } - var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (insertIndex < 0) { - array.splice(~insertIndex, 0, fileInfo); - } - }; - ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { - if (!array || array.length === 0) { - return; - } - if (array[0] === fileInfo) { - array.splice(0, 1); - return; - } - var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); - if (removeIndex >= 0) { - array.splice(removeIndex, 1); - } + return ts.compareStrings(lf.scriptInfo.fileName, rf.scriptInfo.fileName); }; ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + server.insertSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); }; ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { - ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + server.removeSorted(this.referencedBy, fileInfo, ModuleBuilderFileInfo.compareFileInfos); }; ModuleBuilderFileInfo.prototype.removeFileReferences = function () { for (var _i = 0, _a = this.references; _i < _a.length; _i++) { var reference = _a[_i]; reference.removeReferencedBy(this); } - this.references = []; + ts.clear(this.references); }; return ModuleBuilderFileInfo; }(BuilderFileInfo)); @@ -77004,16 +79241,18 @@ var ts; ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { var _this = this; if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { - return []; + return server.createSortedArray(); } var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); - if (referencedFilePaths.length > 0) { - return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); - } - return []; + return server.toSortedArray(referencedFilePaths.map(function (f) { return _this.getOrCreateFileInfo(f); }), ModuleBuilderFileInfo.compareFileInfos); + }; + ModuleBuilder.prototype.ensureFileInfoIfInProject = function (_scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); }; ModuleBuilder.prototype.onProjectUpdateGraph = function () { - this.ensureProjectDependencyGraphUpToDate(); + if (this.hasFileInfos()) { + this.ensureProjectDependencyGraphUpToDate(); + } }; ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { var _this = this; @@ -77039,31 +79278,9 @@ var ts; } var newReferences = this.getReferencedFileInfos(fileInfo); var oldReferences = fileInfo.references; - var oldIndex = 0; - var newIndex = 0; - while (oldIndex < oldReferences.length && newIndex < newReferences.length) { - var oldReference = oldReferences[oldIndex]; - var newReference = newReferences[newIndex]; - var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); - if (compare < 0) { - oldReference.removeReferencedBy(fileInfo); - oldIndex++; - } - else if (compare > 0) { - newReference.addReferencedBy(fileInfo); - newIndex++; - } - else { - oldIndex++; - newIndex++; - } - } - for (var i = oldIndex; i < oldReferences.length; i++) { - oldReferences[i].removeReferencedBy(fileInfo); - } - for (var i = newIndex; i < newReferences.length; i++) { - newReferences[i].addReferencedBy(fileInfo); - } + server.enumerateInsertsAndDeletes(newReferences, oldReferences, function (newReference) { return newReference.addReferencedBy(fileInfo); }, function (oldReference) { + oldReference.removeReferencedBy(fileInfo); + }, ModuleBuilderFileInfo.compareFileInfos); fileInfo.references = newReferences; fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); }; @@ -77128,12 +79345,6 @@ var ts; ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; ProjectKind[ProjectKind["External"] = 2] = "External"; })(ProjectKind = server.ProjectKind || (server.ProjectKind = {})); - function remove(items, item) { - var index = items.indexOf(item); - if (index >= 0) { - items.splice(index, 1); - } - } function countEachFileTypes(infos) { var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { @@ -77157,6 +79368,7 @@ var ts; } return result; } + server.countEachFileTypes = countEachFileTypes; function hasOneOrMoreJsAndNoTsFiles(project) { var counts = countEachFileTypes(project.getScriptInfos()); return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; @@ -77173,7 +79385,7 @@ var ts; server.allFilesAreJsOrDts = allFilesAreJsOrDts; var UnresolvedImportsMap = (function () { function UnresolvedImportsMap() { - this.perFileMap = ts.createFileMap(); + this.perFileMap = ts.createMap(); this.version = 0; } UnresolvedImportsMap.prototype.clear = function () { @@ -77184,7 +79396,7 @@ var ts; return this.version; }; UnresolvedImportsMap.prototype.remove = function (path) { - this.perFileMap.remove(path); + this.perFileMap.delete(path); this.version++; }; UnresolvedImportsMap.prototype.get = function (path) { @@ -77206,7 +79418,8 @@ var ts; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; this.rootFiles = []; - this.rootFilesMap = ts.createFileMap(); + this.rootFilesMap = ts.createMap(); + this.missingFilesMap = ts.createMap(); this.cachedUnresolvedImportsPerFile = new UnresolvedImportsMap(); this.languageServiceEnabled = true; this.lastReportedVersion = 0; @@ -77257,7 +79470,10 @@ var ts; this.compilerOptions.noEmitForJsFiles = true; } }; - Project.prototype.getProjectErrors = function () { + Project.prototype.getGlobalProjectErrors = function () { + return ts.filter(this.projectErrors, function (diagnostic) { return !diagnostic.file; }); + }; + Project.prototype.getAllProjectErrors = function () { return this.projectErrors; }; Project.prototype.getLanguageService = function (ensureSynchronized) { @@ -77296,7 +79512,7 @@ var ts; return this.projectName; }; Project.prototype.getExternalFiles = function () { - return []; + return server.emptyArray; }; Project.prototype.getSourceFile = function (path) { if (!this.program) { @@ -77326,7 +79542,15 @@ var ts; this.rootFiles = undefined; this.rootFilesMap = undefined; this.program = undefined; + this.builder = undefined; + this.cachedUnresolvedImportsPerFile = undefined; + this.projectErrors = undefined; + this.lsHost.dispose(); + this.lsHost = undefined; + this.missingFilesMap.forEach(function (fileWatcher) { return fileWatcher.close(); }); + this.missingFilesMap = undefined; this.languageService.dispose(); + this.languageService = undefined; }; Project.prototype.getCompilerOptions = function () { return this.compilerOptions; @@ -77377,7 +79601,7 @@ var ts; } return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); }; - Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries) { + Project.prototype.getFileNames = function (excludeFilesFromExternalLibraries, excludeConfigFiles) { if (!this.program) { return []; } @@ -77399,8 +79623,39 @@ var ts; } result.push(server.asNormalizedPath(f.fileName)); } + if (!excludeConfigFiles) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + result.push(server.asNormalizedPath(configFile.fileName)); + if (configFile.extendedSourceFiles) { + for (var _b = 0, _c = configFile.extendedSourceFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(server.asNormalizedPath(f)); + } + } + } + } return result; }; + Project.prototype.hasConfigFile = function (configFilePath) { + if (this.program && this.languageServiceEnabled) { + var configFile = this.program.getCompilerOptions().configFile; + if (configFile) { + if (configFilePath === server.asNormalizedPath(configFile.fileName)) { + return true; + } + if (configFile.extendedSourceFiles) { + for (var _i = 0, _a = configFile.extendedSourceFiles; _i < _a.length; _i++) { + var f = _a[_i]; + if (configFilePath === server.asNormalizedPath(f)) { + return true; + } + } + } + } + } + return false; + }; Project.prototype.getAllEmittableFiles = function () { if (!this.languageServiceEnabled) { return []; @@ -77426,7 +79681,7 @@ var ts; } }; Project.prototype.isRoot = function (info) { - return this.rootFilesMap && this.rootFilesMap.contains(info.path); + return this.rootFilesMap && this.rootFilesMap.has(info.path); }; Project.prototype.addRoot = function (info) { if (!this.isRoot(info)) { @@ -77449,7 +79704,7 @@ var ts; this.markAsDirty(); }; Project.prototype.registerFileUpdate = function (fileName) { - (this.updatedFileNames || (this.updatedFileNames = ts.createMap())).set(fileName, fileName); + (this.updatedFileNames || (this.updatedFileNames = ts.createMap())).set(fileName, true); }; Project.prototype.markAsDirty = function () { this.projectStateVersion++; @@ -77497,7 +79752,7 @@ var ts; var sourceFile = _b[_a]; this.extractUnresolvedImportsFromSourceFile(sourceFile, result); } - this.lastCachedUnresolvedImportsList = server.toSortedReadonlyArray(result); + this.lastCachedUnresolvedImportsList = server.toSortedArray(result); } unresolvedImports = this.lastCachedUnresolvedImportsList; var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges); @@ -77524,11 +79779,11 @@ var ts; return true; }; Project.prototype.updateGraphWorker = function () { + var _this = this; var oldProgram = this.program; this.program = this.languageService.getProgram(); - var hasChanges = false; - if (!oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2))) { - hasChanges = true; + var hasChanges = !oldProgram || (this.program !== oldProgram && !(oldProgram.structureIsReused & 2)); + if (hasChanges) { if (oldProgram) { for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var f = _a[_i]; @@ -77541,9 +79796,49 @@ var ts; } } } + var missingFilePaths = this.program.getMissingFilePaths(); + var missingFilePathsSet_1 = ts.arrayToSet(missingFilePaths); + this.missingFilesMap.forEach(function (fileWatcher, missingFilePath) { + if (!missingFilePathsSet_1.has(missingFilePath)) { + _this.missingFilesMap.delete(missingFilePath); + fileWatcher.close(); + } + }); + var _loop_8 = function (missingFilePath) { + if (!this_1.missingFilesMap.has(missingFilePath)) { + var fileWatcher_1 = this_1.projectService.host.watchFile(missingFilePath, function (_filename, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { + fileWatcher_1.close(); + _this.missingFilesMap.delete(missingFilePath); + _this.markAsDirty(); + _this.updateGraph(); + } + }); + this_1.missingFilesMap.set(missingFilePath, fileWatcher_1); + } + }; + var this_1 = this; + for (var _b = 0, missingFilePaths_1 = missingFilePaths; _b < missingFilePaths_1.length; _b++) { + var missingFilePath = missingFilePaths_1[_b]; + _loop_8(missingFilePath); + } } + var oldExternalFiles = this.externalFiles || server.emptyArray; + this.externalFiles = this.getExternalFiles(); + server.enumerateInsertsAndDeletes(this.externalFiles, oldExternalFiles, function (inserted) { + var scriptInfo = _this.projectService.getOrCreateScriptInfo(inserted, false); + scriptInfo.attachToProject(_this); + }, function (removed) { + var scriptInfoToDetach = _this.projectService.getScriptInfo(removed); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(_this); + } + }); return hasChanges; }; + Project.prototype.isWatchedMissingFile = function (path) { + return this.missingFilesMap.has(path); + }; Project.prototype.getScriptInfoLSHost = function (fileName) { var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); if (scriptInfo) { @@ -77568,7 +79863,7 @@ var ts; var strBuilder = ""; for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { var file = _a[_i]; - strBuilder += file.fileName + "\n"; + strBuilder += "\t" + file.fileName + "\n"; } return strBuilder; }; @@ -77607,13 +79902,13 @@ var ts; this.updatedFileNames = undefined; if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { if (this.projectStructureVersion === this.lastReportedVersion && !updatedFileNames) { - return { info: info, projectErrors: this.projectErrors }; + return { info: info, projectErrors: this.getGlobalProjectErrors() }; } var lastReportedFileNames_1 = this.lastReportedFileNames; - var currentFiles_1 = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var currentFiles_1 = ts.arrayToSet(this.getFileNames()); var added_1 = []; var removed_1 = []; - var updated = ts.arrayFrom(updatedFileNames.keys()); + var updated = updatedFileNames ? ts.arrayFrom(updatedFileNames.keys()) : []; ts.forEachKey(currentFiles_1, function (id) { if (!lastReportedFileNames_1.has(id)) { added_1.push(id); @@ -77626,13 +79921,13 @@ var ts; }); this.lastReportedFileNames = currentFiles_1; this.lastReportedVersion = this.projectStructureVersion; - return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.projectErrors }; + return { info: info, changes: { added: added_1, removed: removed_1, updated: updated }, projectErrors: this.getGlobalProjectErrors() }; } else { var projectFileNames = this.getFileNames(); - this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedFileNames = ts.arrayToSet(projectFileNames); this.lastReportedVersion = this.projectStructureVersion; - return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + return { info: info, files: projectFileNames, projectErrors: this.getGlobalProjectErrors() }; } }; Project.prototype.getReferencedFiles = function (path) { @@ -77681,8 +79976,8 @@ var ts; return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); }; Project.prototype.removeRoot = function (info) { - remove(this.rootFiles, info); - this.rootFilesMap.remove(info.path); + ts.orderedRemoveItem(this.rootFiles, info); + this.rootFilesMap.delete(info.path); }; return Project; }()); @@ -77702,7 +79997,7 @@ var ts; } }; InferredProject.prototype.setCompilerOptions = function (options) { - var newOptions = options ? ts.clone(options) : this.getCompilerOptions(); + var newOptions = options ? ts.cloneCompilerOptions(options) : this.getCompilerOptions(); if (!newOptions) { return; } @@ -77750,16 +80045,16 @@ var ts; exclude: [] }; }; + InferredProject.newName = (function () { + var nextId = 1; + return function () { + var id = nextId; + nextId++; + return server.makeInferredProjectName(id); + }; + })(); return InferredProject; }(Project)); - InferredProject.newName = (function () { - var nextId = 1; - return function () { - var id = nextId; - nextId++; - return server.makeInferredProjectName(id); - }; - })(); server.InferredProject = InferredProject; var ConfiguredProject = (function (_super) { __extends(ConfiguredProject, _super); @@ -77796,15 +80091,15 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_6 = function (globalPluginName) { + var _loop_9 = function (globalPluginName) { if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; - this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); + this_2.enablePlugin({ name: globalPluginName, global: true }, searchPaths); }; - var this_1 = this; + var this_2 = this; for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_6(globalPluginName); + _loop_9(globalPluginName); } } }; @@ -77857,19 +80152,17 @@ var ts; return this.typeAcquisition; }; ConfiguredProject.prototype.getExternalFiles = function () { - var items = []; - for (var _i = 0, _a = this.plugins; _i < _a.length; _i++) { - var plugin = _a[_i]; - if (typeof plugin.getExternalFiles === "function") { - try { - items.push.apply(items, plugin.getExternalFiles(this)); - } - catch (e) { - this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); - } + var _this = this; + return server.toSortedArray(ts.flatMap(this.plugins, function (plugin) { + if (typeof plugin.getExternalFiles !== "function") + return; + try { + return plugin.getExternalFiles(_this); } - } - return items; + catch (e) { + _this.projectService.logger.info("A plugin threw an exception in getExternalFiles: " + e); + } + })); }; ConfiguredProject.prototype.watchConfigFile = function (callback) { var _this = this; @@ -77920,6 +80213,7 @@ var ts; _super.prototype.close.call(this); if (this.projectFileWatcher) { this.projectFileWatcher.close(); + this.projectFileWatcher = undefined; } if (this.typeRootsWatchers) { for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { @@ -78002,6 +80296,7 @@ var ts; server.ContextEvent = "context"; server.ConfigFileDiagEvent = "configFileDiag"; server.ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; + server.ProjectInfoTelemetryEvent = "projectInfo"; function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { var map = ts.createMap(); for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { @@ -78087,17 +80382,14 @@ var ts; } server.convertScriptKindName = convertScriptKindName; function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + var result = ts.flatMap(projects, action).sort(comparer); return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; } server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (_) { return undefined; }, - hasMixedContent: function (fileName, extraFileExtensions) { - var mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, function (item) { return item.isMixedContent; }), function (item) { return item.extension; }); - return ts.forEach(mixedContentExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } + hasMixedContent: function (fileName, extraFileExtensions) { return ts.some(extraFileExtensions, function (ext) { return ext.isMixedContent && ts.fileExtensionIs(fileName, ext.extension); }); }, }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, @@ -78157,13 +80449,15 @@ var ts; }()); var ProjectService = (function () { function ProjectService(opts) { - this.filenameToScriptInfo = ts.createFileMap(); + this.filenameToScriptInfo = ts.createMap(); this.externalProjectToConfiguredProjectMap = ts.createMap(); this.externalProjects = []; this.inferredProjects = []; this.configuredProjects = []; this.openFiles = []; this.projectToSizeMap = ts.createMap(); + this.safelist = defaultTypeSafeList; + this.seenProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -78310,8 +80604,14 @@ var ts; } else { if (info && (!info.isScriptOpen())) { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); + if (info.containingProjects.length === 0) { + info.stopWatcher(); + this.filenameToScriptInfo.delete(info.path); + } + else { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } } } }; @@ -78319,7 +80619,7 @@ var ts; this.logger.info(info.fileName + " deleted"); info.stopWatcher(); if (!info.isScriptOpen()) { - this.filenameToScriptInfo.remove(info.path); + this.filenameToScriptInfo.delete(info.path); this.lastDeletedFile = info; var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); @@ -78393,15 +80693,15 @@ var ts; project.close(); switch (project.projectKind) { case server.ProjectKind.External: - server.removeItemFromSet(this.externalProjects, project); + ts.unorderedRemoveItem(this.externalProjects, project); this.projectToSizeMap.delete(project.externalProjectName); break; case server.ProjectKind.Configured: - server.removeItemFromSet(this.configuredProjects, project); + ts.unorderedRemoveItem(this.configuredProjects, project); this.projectToSizeMap.delete(project.canonicalConfigFilePath); break; case server.ProjectKind.Inferred: - server.removeItemFromSet(this.inferredProjects, project); + ts.unorderedRemoveItem(this.inferredProjects, project); break; } }; @@ -78455,7 +80755,7 @@ var ts; }; ProjectService.prototype.closeOpenFile = function (info) { info.close(); - server.removeItemFromSet(this.openFiles, info); + ts.unorderedRemoveItem(this.openFiles, info); var projectsToRemove; for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; @@ -78493,9 +80793,21 @@ var ts; } } } - if (info.containingProjects.length === 0) { - this.filenameToScriptInfo.remove(info.path); + if (this.host.fileExists(info.fileName)) { + this.watchClosedScriptInfo(info); } + else { + this.handleDeletedFile(info); + } + }; + ProjectService.prototype.deleteOrphanScriptInfoNotInAnyProject = function () { + var _this = this; + this.filenameToScriptInfo.forEach(function (info) { + if (!info.isScriptOpen() && info.containingProjects.length === 0) { + info.stopWatcher(); + _this.filenameToScriptInfo.delete(info.path); + } + }); }; ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName, projectRootPath) { var searchPath = ts.getDirectoryPath(fileName); @@ -78552,7 +80864,7 @@ var ts; this.logger.info("Open files: "); for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { var rootFile = _a[_i]; - this.logger.info(rootFile.fileName); + this.logger.info("\t" + rootFile.fileName); } this.logger.endGroup(); function printProjects(logger, projects, counter) { @@ -78582,27 +80894,27 @@ var ts; ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { configFilename = ts.normalizePath(configFilename); var configFileContent = this.host.readFile(configFilename); - var errors; - var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); - var config = result.config; - if (result.error) { - var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; - config = sanitizedConfig; - errors = diagnostics.length ? diagnostics : [result.error]; + var result = ts.parseJsonText(configFilename, configFileContent); + if (!result.endOfFileToken) { + result.endOfFileToken = { kind: 1 }; } - var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); + var errors = result.parseDiagnostics; + var parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(result, this.host, ts.getDirectoryPath(configFilename), {}, configFilename, [], this.hostConfiguration.extraFileExtensions); if (parsedCommandLine.errors.length) { - errors = ts.concatenate(errors, parsedCommandLine.errors); + errors.push.apply(errors, parsedCommandLine.errors); } ts.Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.fileNames.length === 0) { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); return { success: false, configFileErrors: errors }; } var projectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options, - configHasFilesProperty: config["files"] !== undefined, + configHasExtendsProperty: parsedCommandLine.raw["extends"] !== undefined, + configHasFilesProperty: parsedCommandLine.raw["files"] !== undefined, + configHasIncludeProperty: parsedCommandLine.raw["include"] !== undefined, + configHasExcludeProperty: parsedCommandLine.raw["exclude"] !== undefined, wildcardDirectories: ts.createMapFromTemplate(parsedCommandLine.wildcardDirectories), typeAcquisition: parsedCommandLine.typeAcquisition, compileOnSave: parsedCommandLine.compileOnSave @@ -78639,8 +80951,49 @@ var ts; var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typeAcquisition, undefined); this.externalProjects.push(project); + this.sendProjectTelemetry(project.externalProjectName, project); return project; }; + ProjectService.prototype.sendProjectTelemetry = function (projectKey, project, projectOptions) { + if (this.seenProjects.has(projectKey)) { + return; + } + this.seenProjects.set(projectKey, true); + if (!this.eventHandler) + return; + var data = { + projectId: this.host.createHash(projectKey), + fileStats: server.countEachFileTypes(project.getScriptInfos()), + compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilerOptions()), + typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), + extends: projectOptions && projectOptions.configHasExtendsProperty, + files: projectOptions && projectOptions.configHasFilesProperty, + include: projectOptions && projectOptions.configHasIncludeProperty, + exclude: projectOptions && projectOptions.configHasExcludeProperty, + compileOnSave: project.compileOnSaveEnabled, + configFileName: configFileName(), + projectType: project instanceof server.ExternalProject ? "external" : "configured", + languageServiceEnabled: project.languageServiceEnabled, + version: ts.version, + }; + this.eventHandler({ eventName: server.ProjectInfoTelemetryEvent, data: data }); + function configFileName() { + if (!(project instanceof server.ConfiguredProject)) { + return "other"; + } + var configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath(); + var base = ts.getBaseFileName(configFilePath); + return base === "tsconfig.json" || base === "jsconfig.json" ? base : "other"; + } + function convertTypeAcquisition(_a) { + var enable = _a.enable, include = _a.include, exclude = _a.exclude; + return { + enable: enable, + include: include !== undefined && include.length !== 0, + exclude: exclude !== undefined && exclude.length !== 0, + }; + } + }; ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { if (!this.eventHandler) { return; @@ -78662,6 +81015,7 @@ var ts; project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); this.configuredProjects.push(project); + this.sendProjectTelemetry(project.getConfigFilePath(), project, projectOptions); return project; }; ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { @@ -78693,12 +81047,12 @@ var ts; var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); var projectOptions = conversionResult.success ? conversionResult.projectOptions - : { files: [], compilerOptions: {}, typeAcquisition: { enable: false } }; + : { files: [], compilerOptions: {}, configHasExtendsProperty: false, configHasFilesProperty: false, configHasIncludeProperty: false, configHasExcludeProperty: false, typeAcquisition: { enable: false } }; var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); return { success: conversionResult.success, project: project, - errors: project.getProjectErrors() + errors: project.getGlobalProjectErrors() }; }; ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, configFileErrors) { @@ -78816,8 +81170,14 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; + if (!info.hasMixedContent) { + var fileName_3 = info.fileName; + info.setWatcher(this.host.watchFile(fileName_3, function (_) { return _this.onSourceFileChanged(fileName_3); })); + } + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { if (openedByClient || this.host.fileExists(fileName)) { @@ -78829,14 +81189,13 @@ var ts; } } else { - if (!hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); - } + this.watchClosedScriptInfo(info); } } } if (info) { if (openedByClient && !info.isScriptOpen()) { + info.stopWatcher(); info.open(fileContent); if (hasMixedContent) { info.registerFileUpdate(); @@ -78936,6 +81295,7 @@ var ts; } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; var _a; @@ -78948,13 +81308,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_7 = function (proj) { + var _loop_10 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_7(proj); + _loop_10(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -79057,7 +81417,7 @@ var ts; return filename.replace(this.filenameEscapeRegexp, "\\$&"); }; ProjectService.prototype.resetSafeList = function () { - ProjectService.safelist = defaultTypeSafeList; + this.safelist = defaultTypeSafeList; }; ProjectService.prototype.loadSafeList = function (fileName) { var raw = JSON.parse(this.host.readFile(fileName, "utf-8")); @@ -79065,7 +81425,7 @@ var ts; var k = _a[_i]; raw[k].match = new RegExp(raw[k].match, "i"); } - ProjectService.safelist = raw; + this.safelist = raw; }; ProjectService.prototype.applySafeList = function (proj) { var _this = this; @@ -79073,12 +81433,12 @@ var ts; var types = (typeAcquisition && typeAcquisition.include) || []; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); - var _loop_8 = function (name) { - var rule = ProjectService.safelist[name]; + var _loop_11 = function (name) { + var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; if (rule.match.test(root)) { - this_2.logger.info("Excluding files based on rule " + name); + this_3.logger.info("Excluding files based on rule " + name); if (rule.types) { for (var _a = 0, _b = rule.types; _a < _b.length; _a++) { var type = _b[_a]; @@ -79088,7 +81448,7 @@ var ts; } } if (rule.exclude) { - var _loop_9 = function (exclude) { + var _loop_12 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -79111,7 +81471,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_9(exclude); + _loop_12(exclude); } } else { @@ -79127,10 +81487,10 @@ var ts; proj.typeAcquisition.include = types; } }; - var this_2 = this; - for (var _i = 0, _a = Object.keys(ProjectService.safelist); _i < _a.length; _i++) { + var this_3 = this; + for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_8(name); + _loop_11(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); proj.rootFiles = proj.rootFiles.filter(function (_file, index) { return !excludeRegexes.some(function (re) { return re.test(normalizedNames[index]); }); }); @@ -79226,10 +81586,9 @@ var ts; this.refreshInferredProjects(); } }; + ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; return ProjectService; }()); - ProjectService.safelist = defaultTypeSafeList; - ProjectService.filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g; server.ProjectService = ProjectService; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -79400,23 +81759,8 @@ var ts; } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - try { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - } - catch (e) { - var results = []; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { - var file = _b[_a]; - if (!ts.contains(results, file)) { - results.push(file); - } - } - } - return results; - } + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -79424,9 +81768,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; - CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { - return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); - }; CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { return JSON.parse(this.shimHost.getDirectories(path)); }; @@ -79749,7 +82090,7 @@ 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) { + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" && result.resolvedModule.extension !== ".tsx" && result.resolvedModule.extension !== ".d.ts") { resolvedFileName = undefined; } return { @@ -79809,24 +82150,15 @@ var ts; var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseConfigFileTextToJson(fileName, text); - if (result.error) { - return { - options: {}, - typeAcquisition: {}, - files: [], - raw: {}, - errors: [realizeDiagnostic(result.error, "\r\n")] - }; - } + var result = ts.parseJsonText(fileName, text); var normalizedFileName = ts.normalizeSlashes(fileName); - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); return { options: configFile.options, typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, - errors: realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") }; }); }; @@ -79838,7 +82170,10 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -79884,7 +82219,7 @@ var ts; } }; TypeScriptServicesFactory.prototype.close = function () { - this._shims = []; + ts.clear(this._shims); this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { @@ -79913,6 +82248,4 @@ var TypeScript; Services.TypeScriptServicesFactory = ts.TypeScriptServicesFactory; })(Services = TypeScript.Services || (TypeScript.Services = {})); })(TypeScript || (TypeScript = {})); -var toolsVersion = "2.4"; - -//# sourceMappingURL=tsserverlibrary.js.map +var toolsVersion = "2.5"; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 5853aafb946..1ca5c4d7736 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -22,19 +22,22 @@ declare namespace ts { interface MapLike { [index: string]: T; } - /** ES6 Map interface. */ - interface Map { + /** ES6 Map interface, only read methods included. */ + interface ReadonlyMap { get(key: string): T | undefined; has(key: string): boolean; - set(key: string, value: T): this; - delete(key: string): boolean; - clear(): void; forEach(action: (value: T, key: string) => void): void; readonly size: number; keys(): Iterator; values(): Iterator; entries(): Iterator<[string, T]>; } + /** ES6 Map interface. */ + interface Map extends ReadonlyMap { + set(key: string, value: T): this; + delete(key: string): boolean; + clear(): void; + } /** ES6 Iterator type. */ interface Iterator { next(): { @@ -45,18 +48,13 @@ declare namespace ts { done: true; }; } + /** Array that is only intended to be pushed to, never read. */ + interface Push { + push(...values: T[]): void; + } type Path = string & { __pathBrand: any; }; - interface FileMap { - get(fileName: Path): T; - set(fileName: Path, value: T): void; - contains(fileName: Path): boolean; - remove(fileName: Path): void; - forEachValue(f: (key: Path, v: T) => void): void; - getKeys(): Path[]; - clear(): void; - } interface TextRange { pos: number; end: number; @@ -332,37 +330,29 @@ declare namespace ts { JSDocTypeExpression = 267, JSDocAllType = 268, JSDocUnknownType = 269, - JSDocArrayType = 270, - JSDocUnionType = 271, - JSDocTupleType = 272, - JSDocNullableType = 273, - JSDocNonNullableType = 274, - JSDocRecordType = 275, - JSDocRecordMember = 276, - JSDocTypeReference = 277, - JSDocOptionalType = 278, - JSDocFunctionType = 279, - JSDocVariadicType = 280, - JSDocConstructorType = 281, - JSDocThisType = 282, - JSDocComment = 283, - JSDocTag = 284, - JSDocAugmentsTag = 285, - JSDocParameterTag = 286, - JSDocReturnTag = 287, - JSDocTypeTag = 288, - JSDocTemplateTag = 289, - JSDocTypedefTag = 290, - JSDocPropertyTag = 291, - JSDocTypeLiteral = 292, - JSDocLiteralType = 293, - SyntaxList = 294, - NotEmittedStatement = 295, - PartiallyEmittedExpression = 296, - CommaListExpression = 297, - MergeDeclarationMarker = 298, - EndOfDeclarationMarker = 299, - Count = 300, + JSDocNullableType = 270, + JSDocNonNullableType = 271, + JSDocOptionalType = 272, + JSDocFunctionType = 273, + JSDocVariadicType = 274, + JSDocComment = 275, + JSDocTag = 276, + JSDocAugmentsTag = 277, + JSDocClassTag = 278, + JSDocParameterTag = 279, + JSDocReturnTag = 280, + JSDocTypeTag = 281, + JSDocTemplateTag = 282, + JSDocTypedefTag = 283, + JSDocPropertyTag = 284, + JSDocTypeLiteral = 285, + SyntaxList = 286, + NotEmittedStatement = 287, + PartiallyEmittedExpression = 288, + CommaListExpression = 289, + MergeDeclarationMarker = 290, + EndOfDeclarationMarker = 291, + Count = 292, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -389,9 +379,9 @@ declare namespace ts { LastBinaryOperator = 70, FirstNode = 143, FirstJSDocNode = 267, - LastJSDocNode = 293, - FirstJSDocTagNode = 283, - LastJSDocTagNode = 293, + LastJSDocNode = 285, + FirstJSDocTagNode = 276, + LastJSDocTagNode = 285, } enum NodeFlags { None = 0, @@ -414,6 +404,7 @@ declare namespace ts { JavaScriptFile = 65536, ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, + JSDoc = 1048576, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, @@ -455,7 +446,7 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } - interface NodeArray extends Array, TextRange { + interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } interface Token extends Node { @@ -476,10 +467,10 @@ declare namespace ts { 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. + * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) + * Text of identifier, but if the identifier begins with two underscores, this will begin with three. */ - text: string; + escapedText: __String; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; } @@ -562,7 +553,7 @@ declare namespace ts { initializer?: Expression; } interface PropertySignature extends TypeElement { - kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; + kind: SyntaxKind.PropertySignature; name: PropertyName; questionToken?: QuestionToken; type?: TypeNode; @@ -600,7 +591,7 @@ declare namespace ts { interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; - name: DeclarationName; + name?: DeclarationName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; @@ -622,19 +613,21 @@ declare namespace ts { type ArrayBindingElement = BindingElement | OmittedExpression; /** * Several node kinds share function-like features such as a signature, - * a name, and a body. These nodes should extend FunctionLikeDeclaration. + * a name, and a body. These nodes should extend FunctionLikeDeclarationBase. * Examples: * - FunctionDeclaration * - MethodDeclaration * - AccessorDeclaration */ - interface FunctionLikeDeclaration extends SignatureDeclaration { + interface FunctionLikeDeclarationBase extends SignatureDeclaration { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; body?: Block | Expression; } - interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; @@ -643,12 +636,12 @@ declare namespace ts { kind: SyntaxKind.MethodSignature; name: PropertyName; } - interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; @@ -658,13 +651,13 @@ declare namespace ts { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; } - interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } - interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; @@ -691,6 +684,7 @@ declare namespace ts { interface ConstructorTypeNode extends TypeNode, SignatureDeclaration { kind: SyntaxKind.ConstructorType; } + type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; interface TypeReferenceNode extends TypeNode { kind: SyntaxKind.TypeReference; typeName: EntityName; @@ -768,22 +762,24 @@ declare namespace ts { interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } - interface IncrementExpression extends UnaryExpression { - _incrementExpressionBrand: any; + /** Deprecated, please use UpdateExpression */ + type IncrementExpression = UpdateExpression; + interface UpdateExpression extends UnaryExpression { + _updateExpressionBrand: any; } type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; - interface PrefixUnaryExpression extends IncrementExpression { + interface PrefixUnaryExpression extends UpdateExpression { kind: SyntaxKind.PrefixUnaryExpression; operator: PrefixUnaryOperator; operand: UnaryExpression; } type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; - interface PostfixUnaryExpression extends IncrementExpression { + interface PostfixUnaryExpression extends UpdateExpression { kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; operator: PostfixUnaryOperator; } - interface LeftHandSideExpression extends IncrementExpression { + interface LeftHandSideExpression extends UpdateExpression { _leftHandSideExpressionBrand: any; } interface MemberExpression extends LeftHandSideExpression { @@ -804,6 +800,9 @@ declare namespace ts { interface SuperExpression extends PrimaryExpression { kind: SyntaxKind.SuperKeyword; } + interface ImportExpression extends PrimaryExpression { + kind: SyntaxKind.ImportKeyword; + } interface DeleteExpression extends UnaryExpression { kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; @@ -880,12 +879,12 @@ declare namespace ts { } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase { kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } - interface ArrowFunction extends Expression, FunctionLikeDeclaration { + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; @@ -988,6 +987,9 @@ declare namespace ts { interface SuperCall extends CallExpression { expression: SuperExpression; } + interface ImportCall extends CallExpression { + expression: ImportExpression; + } interface ExpressionWithTypeArguments extends TypeNode { kind: SyntaxKind.ExpressionWithTypeArguments; parent?: HeritageClause; @@ -1137,6 +1139,7 @@ declare namespace ts { condition?: Expression; incrementor?: Expression; } + type ForInOrOfStatement = ForInStatement | ForOfStatement; interface ForInStatement extends IterationStatement { kind: SyntaxKind.ForInStatement; initializer: ForInitializer; @@ -1210,7 +1213,7 @@ declare namespace ts { variableDeclaration: VariableDeclaration; block: Block; } - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; + type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; @@ -1379,9 +1382,9 @@ declare namespace ts { pos: -1; end: -1; } - interface JSDocTypeExpression extends Node { + interface JSDocTypeExpression extends TypeNode { kind: SyntaxKind.JSDocTypeExpression; - type: JSDocType; + type: TypeNode; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; @@ -1392,72 +1395,33 @@ declare namespace ts { interface JSDocUnknownType extends JSDocType { kind: SyntaxKind.JSDocUnknownType; } - interface JSDocArrayType extends JSDocType { - kind: SyntaxKind.JSDocArrayType; - elementType: JSDocType; - } - interface JSDocUnionType extends JSDocType { - kind: SyntaxKind.JSDocUnionType; - types: NodeArray; - } - interface JSDocTupleType extends JSDocType { - kind: SyntaxKind.JSDocTupleType; - types: NodeArray; - } interface JSDocNonNullableType extends JSDocType { kind: SyntaxKind.JSDocNonNullableType; - type: JSDocType; + type: TypeNode; } interface JSDocNullableType extends JSDocType { kind: SyntaxKind.JSDocNullableType; - type: JSDocType; - } - interface JSDocRecordType extends JSDocType { - kind: SyntaxKind.JSDocRecordType; - literal: TypeLiteralNode; - } - interface JSDocTypeReference extends JSDocType { - kind: SyntaxKind.JSDocTypeReference; - name: EntityName; - typeArguments: NodeArray; + type: TypeNode; } interface JSDocOptionalType extends JSDocType { kind: SyntaxKind.JSDocOptionalType; - type: JSDocType; + type: TypeNode; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { kind: SyntaxKind.JSDocFunctionType; - parameters: NodeArray; - type: JSDocType; } interface JSDocVariadicType extends JSDocType { kind: SyntaxKind.JSDocVariadicType; - type: JSDocType; - } - interface JSDocConstructorType extends JSDocType { - kind: SyntaxKind.JSDocConstructorType; - type: JSDocType; - } - interface JSDocThisType extends JSDocType { - kind: SyntaxKind.JSDocThisType; - type: JSDocType; - } - interface JSDocLiteralType extends JSDocType { - kind: SyntaxKind.JSDocLiteralType; - literal: LiteralTypeNode; - } - type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; - interface JSDocRecordMember extends PropertySignature { - kind: SyntaxKind.JSDocRecordMember; - name: Identifier | StringLiteral | NumericLiteral; - type?: JSDocType; + type: TypeNode; } + type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { + parent: JSDoc; atToken: AtToken; tagName: Identifier; comment: string | undefined; @@ -1469,6 +1433,9 @@ declare namespace ts { kind: SyntaxKind.JSDocAugmentsTag; typeExpression: JSDocTypeExpression; } + interface JSDocClassTag extends JSDocTag { + kind: SyntaxKind.JSDocClassTag; + } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; @@ -1482,32 +1449,32 @@ declare namespace ts { typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; - typeExpression?: JSDocTypeExpression; - jsDocTypeLiteral?: JSDocTypeLiteral; + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } - interface JSDocPropertyTag extends JSDocTag, TypeElement { - kind: SyntaxKind.JSDocPropertyTag; - name: Identifier; + interface JSDocPropertyLikeTag extends JSDocTag, Declaration { + parent: JSDoc; + name: EntityName; typeExpression: JSDocTypeExpression; + /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ + isNameFirst: boolean; + isBracketed: boolean; + } + interface JSDocPropertyTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocPropertyTag; + } + interface JSDocParameterTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocParameterTag; } interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; - jsDocPropertyTags?: NodeArray; + jsDocPropertyTags?: ReadonlyArray; jsDocTypeTag?: JSDocTypeTag; - } - interface JSDocParameterTag extends JSDocTag { - kind: SyntaxKind.JSDocParameterTag; - /** the parameter name, if provided *before* the type (TypeScript-style) */ - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - /** the parameter name, if provided *after* the type (JSDoc-standard) */ - postParameterName?: Identifier; - /** the parameter name, regardless of the location it was provided */ - parameterName: Identifier; - isBracketed: boolean; + /** If true, then this type literal represents an *array* of its type. */ + isArrayType?: boolean; } enum FlowFlags { Unreachable = 1, @@ -1600,6 +1567,10 @@ declare namespace ts { kind: SyntaxKind.Bundle; sourceFiles: SourceFile[]; } + interface JsonSourceFile extends SourceFile { + jsonObject?: ObjectLiteralExpression; + extendedSourceFiles?: string[]; + } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; getSourceFile(fileName: string): SourceFile; @@ -1608,16 +1579,16 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. */ fileExists(path: string): boolean; - readFile(path: string): string; + readFile(path: string): string | undefined; } interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray): void; } class OperationCanceledException { } @@ -1704,14 +1675,15 @@ declare 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; getReturnTypeOfSignature(signature: Signature): Type; + getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** Note that the resulting nodes cannot be checked. */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; @@ -1735,9 +1707,13 @@ declare namespace ts { getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + /** + * returns unknownSignature in the case of an error. Don't know when it returns undefined. + * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. + */ + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; + isImplementationOfOverload(node: FunctionLike): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; @@ -1800,23 +1776,25 @@ declare namespace ts { clear(): void; trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; - reportIllegalExtends(): void; + reportPrivateInBaseOfClassExpression(propertyName: string): void; } enum TypeFormatFlags { None = 0, WriteArrayAsGenericType = 1, - UseTypeOfFunction = 2, - NoTruncation = 4, - WriteArrowStyleSignature = 8, - WriteOwnNameForAnyLike = 16, - WriteTypeArgumentsOfSignature = 32, - InElementType = 64, - UseFullyQualifiedType = 128, - InFirstTypeArgument = 256, - InTypeAlias = 512, - UseTypeAliasValue = 1024, - SuppressAnyReturnType = 2048, - AddUndefined = 4096, + UseTypeOfFunction = 4, + NoTruncation = 8, + WriteArrowStyleSignature = 16, + WriteOwnNameForAnyLike = 32, + WriteTypeArgumentsOfSignature = 64, + InElementType = 128, + UseFullyQualifiedType = 256, + InFirstTypeArgument = 512, + InTypeAlias = 1024, + UseTypeAliasValue = 2048, + SuppressAnyReturnType = 4096, + AddUndefined = 8192, + WriteClassExpressionAsTypeLiteral = 16384, + InArrayType = 32768, } enum SymbolFormatFlags { None = 0, @@ -1863,13 +1841,11 @@ declare namespace ts { TypeParameter = 262144, TypeAlias = 524288, ExportValue = 1048576, - ExportType = 2097152, - ExportNamespace = 4194304, - Alias = 8388608, - Prototype = 16777216, - ExportStar = 33554432, - Optional = 67108864, - Transient = 134217728, + Alias = 2097152, + Prototype = 4194304, + ExportStar = 8388608, + Optional = 16777216, + Transient = 33554432, Enum = 384, Variable = 3, Value = 107455, @@ -1894,26 +1870,73 @@ declare namespace ts { SetAccessorExcludes = 74687, TypeParameterExcludes = 530920, TypeAliasExcludes = 793064, - AliasExcludes = 8388608, - ModuleMember = 8914931, + AliasExcludes = 2097152, + ModuleMember = 2623475, ExportHasLocal = 944, HasExports = 1952, HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - Export = 7340032, ClassMember = 106500, } interface Symbol { flags: SymbolFlags; - name: string; + escapedName: __String; declarations?: Declaration[]; valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; } - type SymbolTable = Map; + enum InternalSymbolName { + Call = "__call", + Constructor = "__constructor", + New = "__new", + Index = "__index", + ExportStar = "__export", + Global = "__global", + Missing = "__missing", + Type = "__type", + Object = "__object", + JSXAttributes = "__jsxAttributes", + Class = "__class", + Function = "__function", + Computed = "__computed", + Resolving = "__resolving__", + ExportEquals = "export=", + Default = "default", + } + /** + * This represents a string whose leading underscore have been escaped by adding extra leading underscores. + * The shape of this brand is rather unique compared to others we've used. + * Instead of just an intersection of a string and an object, it is that union-ed + * with an intersection of void and an object. This makes it wholly incompatible + * with a normal string (which is good, it cannot be misused on assignment or on usage), + * while still being comparable with a normal string via === (also good) and castable from a string. + */ + type __String = (string & { + __escapedIdentifier: void; + }) | (void & { + __escapedIdentifier: void; + }) | InternalSymbolName; + /** ReadonlyMap where keys are `__String`s. */ + interface ReadonlyUnderscoreEscapedMap { + get(key: __String): T | undefined; + has(key: __String): boolean; + forEach(action: (value: T, key: __String) => void): void; + readonly size: number; + keys(): Iterator<__String>; + values(): Iterator; + entries(): Iterator<[__String, T]>; + } + /** Map where keys are `__String`s. */ + interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap { + set(key: __String, value: T): this; + delete(key: __String): boolean; + clear(): void; + } + /** SymbolTable based on ES6 Map interface. */ + type SymbolTable = UnderscoreEscapedMap; enum TypeFlags { Any = 1, String = 2, @@ -1987,7 +2010,7 @@ declare namespace ts { interface ObjectType extends Type { objectFlags: ObjectFlags; } - /** Class and interface types (TypeFlags.Class and TypeFlags.Interface). */ + /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; outerTypeParameters: TypeParameter[]; @@ -2003,7 +2026,7 @@ declare namespace ts { declaredNumberIndexInfo: IndexInfo; } /** - * Type references (TypeFlags.Reference). When a class or interface has type parameters or + * Type references (ObjectFlags.Reference). When a class or interface has type parameters or * a "this" type, references to the class or interface are made using type references. The * typeArguments property specifies the types to substitute for the type parameters of the * class or interface and optionally includes an extra element that specifies the type to @@ -2062,6 +2085,24 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } + enum InferencePriority { + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, + } + interface InferenceInfo { + typeParameter: TypeParameter; + candidates: Type[]; + inferredType: Type; + priority: InferencePriority; + topLevel: boolean; + isFixed: boolean; + } + enum InferenceFlags { + InferUnionTypes = 1, + NoDefault = 2, + AnyDefault = 4, + } interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2143,6 +2184,7 @@ declare namespace ts { noImplicitAny?: boolean; noImplicitReturns?: boolean; noImplicitThis?: boolean; + noStrictGenericChecks?: boolean; noUnusedLocals?: boolean; noUnusedParameters?: boolean; noImplicitUseStrict?: boolean; @@ -2172,7 +2214,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; - [option: string]: CompilerOptionsValue | undefined; + [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { enableAutoDiscovery?: boolean; @@ -2197,6 +2239,7 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, + ESNext = 6, } enum JsxEmit { None = 0, @@ -2219,6 +2262,7 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, + JSON = 6, } enum ScriptTarget { ES3 = 0, @@ -2253,7 +2297,7 @@ declare namespace ts { } interface ModuleResolutionHost { fileExists(fileName: string): boolean; - readFile(fileName: string): string; + readFile(fileName: string): string | undefined; trace?(s: string): void; directoryExists?(directoryName: string): boolean; realpath?(path: string): string; @@ -2290,12 +2334,11 @@ declare namespace ts { extension: Extension; } enum Extension { - Ts = 0, - Tsx = 1, - Dts = 2, - Js = 3, - Jsx = 4, - LastTypeScriptExtension = 2, + Ts = ".ts", + Tsx = ".tsx", + Dts = ".d.ts", + Js = ".js", + Jsx = ".jsx", } interface ResolvedModuleWithFailedLookupLocations { resolvedModule: ResolvedModuleFull | undefined; @@ -2327,6 +2370,14 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string; } + interface SourceMapRange extends TextRange { + source?: SourceMapSource; + } + interface SourceMapSource { + fileName: string; + text: string; + skipTrivia?: (pos: number) => number; + } enum EmitFlags { SingleLine = 1, AdviseOnEmitNode = 2, @@ -2457,7 +2508,7 @@ declare namespace ts { * A function that accepts and possibly transforms a node. */ type Visitor = (node: Node) => VisitResult; - type VisitResult = T | T[]; + type VisitResult = T | T[] | undefined; interface Printer { /** * Print a node and its subtree as-is, without any emit transformations. @@ -2542,13 +2593,19 @@ declare namespace ts { } } declare namespace ts { + const versionMajorMinor = "2.5"; /** The version of the TypeScript compiler release */ - const version = "2.4.0"; + const version: string; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { - type FileWatcherCallback = (fileName: string, removed?: boolean) => void; + enum FileWatcherEventKind { + Created = 0, + Changed = 1, + Deleted = 2, + } + type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; interface WatchedFile { fileName: string; @@ -2560,7 +2617,7 @@ declare namespace ts { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; - readFile(path: string, encoding?: string): string; + readFile(path: string, encoding?: string): string | undefined; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** @@ -2576,8 +2633,12 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; + /** + * This should be cryptographically secure. + * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) + */ createHash?(data: string): string; getMemoryUsage?(): number; exit(exitCode?: number): void; @@ -2630,9 +2691,9 @@ declare namespace ts { scanRange(start: number, length: number, callback: () => T): T; tryScan(callback: () => T): T; } - function tokenToString(t: SyntaxKind): string; + function tokenToString(t: SyntaxKind): string | undefined; function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; + function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; function isWhiteSpaceLike(ch: number): boolean; /** Does not include line breaks. For that, see isWhiteSpaceLike. */ function isWhiteSpaceSingleLine(ch: number): boolean; @@ -2677,7 +2738,7 @@ declare namespace ts { * This function will then merge those changes into a single change range valid between V1 and * Vn. */ - function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: Node): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; @@ -2690,8 +2751,8 @@ declare namespace ts { getExecutingFilePath(): string; resolvePath(path: string): string; fileExists(fileName: string): boolean; - readFile(fileName: string): string; - }, errors?: Diagnostic[]): void; + readFile(fileName: string): string | undefined; + }, errors?: Push): void; function getOriginalNode(node: Node): Node; function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; /** @@ -2721,13 +2782,280 @@ declare namespace ts { * @param identifier The escaped identifier text. * @returns The unescaped identifier text. */ - function unescapeIdentifier(identifier: string): string; + function unescapeLeadingUnderscores(identifier: __String): string; + /** + * Remove extra underscore from escaped identifier text content. + * @deprecated Use `id.text` for the unescaped text. + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeIdentifier(id: string): string; + function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; +} +declare namespace ts { + function isNumericLiteral(node: Node): node is NumericLiteral; + function isStringLiteral(node: Node): node is StringLiteral; + function isJsxText(node: Node): node is JsxText; + function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddle(node: Node): node is TemplateMiddle; + function isTemplateTail(node: Node): node is TemplateTail; + function isIdentifier(node: Node): node is Identifier; + function isQualifiedName(node: Node): node is QualifiedName; + function isComputedPropertyName(node: Node): node is ComputedPropertyName; + function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; + function isParameter(node: Node): node is ParameterDeclaration; + function isDecorator(node: Node): node is Decorator; + function isPropertySignature(node: Node): node is PropertySignature; + function isPropertyDeclaration(node: Node): node is PropertyDeclaration; + function isMethodSignature(node: Node): node is MethodSignature; + function isMethodDeclaration(node: Node): node is MethodDeclaration; + function isConstructorDeclaration(node: Node): node is ConstructorDeclaration; + function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration; + function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration; + function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; + function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; + function isTypePredicateNode(node: Node): node is TypePredicateNode; + function isTypeReferenceNode(node: Node): node is TypeReferenceNode; + function isFunctionTypeNode(node: Node): node is FunctionTypeNode; + function isConstructorTypeNode(node: Node): node is ConstructorTypeNode; + function isTypeQueryNode(node: Node): node is TypeQueryNode; + function isTypeLiteralNode(node: Node): node is TypeLiteralNode; + function isArrayTypeNode(node: Node): node is ArrayTypeNode; + function isTupleTypeNode(node: Node): node is TupleTypeNode; + function isUnionTypeNode(node: Node): node is UnionTypeNode; + function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode; + function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode; + function isThisTypeNode(node: Node): node is ThisTypeNode; + function isTypeOperatorNode(node: Node): node is TypeOperatorNode; + function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; + function isMappedTypeNode(node: Node): node is MappedTypeNode; + function isLiteralTypeNode(node: Node): node is LiteralTypeNode; + function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; + function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; + function isBindingElement(node: Node): node is BindingElement; + function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; + function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; + function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; + function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function isCallExpression(node: Node): node is CallExpression; + function isNewExpression(node: Node): node is NewExpression; + function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; + function isTypeAssertion(node: Node): node is TypeAssertion; + function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; + function skipPartiallyEmittedExpressions(node: Expression): Expression; + function skipPartiallyEmittedExpressions(node: Node): Node; + function isFunctionExpression(node: Node): node is FunctionExpression; + function isArrowFunction(node: Node): node is ArrowFunction; + function isDeleteExpression(node: Node): node is DeleteExpression; + function isTypeOfExpression(node: Node): node is TypeOfExpression; + function isVoidExpression(node: Node): node is VoidExpression; + function isAwaitExpression(node: Node): node is AwaitExpression; + function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression; + function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression; + function isBinaryExpression(node: Node): node is BinaryExpression; + function isConditionalExpression(node: Node): node is ConditionalExpression; + function isTemplateExpression(node: Node): node is TemplateExpression; + function isYieldExpression(node: Node): node is YieldExpression; + function isSpreadElement(node: Node): node is SpreadElement; + function isClassExpression(node: Node): node is ClassExpression; + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isTemplateSpan(node: Node): node is TemplateSpan; + function isSemicolonClassElement(node: Node): node is SemicolonClassElement; + function isBlock(node: Node): node is Block; + function isVariableStatement(node: Node): node is VariableStatement; + function isEmptyStatement(node: Node): node is EmptyStatement; + function isExpressionStatement(node: Node): node is ExpressionStatement; + function isIfStatement(node: Node): node is IfStatement; + function isDoStatement(node: Node): node is DoStatement; + function isWhileStatement(node: Node): node is WhileStatement; + function isForStatement(node: Node): node is ForStatement; + function isForInStatement(node: Node): node is ForInStatement; + function isForOfStatement(node: Node): node is ForOfStatement; + function isContinueStatement(node: Node): node is ContinueStatement; + function isBreakStatement(node: Node): node is BreakStatement; + function isReturnStatement(node: Node): node is ReturnStatement; + function isWithStatement(node: Node): node is WithStatement; + function isSwitchStatement(node: Node): node is SwitchStatement; + function isLabeledStatement(node: Node): node is LabeledStatement; + function isThrowStatement(node: Node): node is ThrowStatement; + function isTryStatement(node: Node): node is TryStatement; + function isDebuggerStatement(node: Node): node is DebuggerStatement; + function isVariableDeclaration(node: Node): node is VariableDeclaration; + function isVariableDeclarationList(node: Node): node is VariableDeclarationList; + function isFunctionDeclaration(node: Node): node is FunctionDeclaration; + function isClassDeclaration(node: Node): node is ClassDeclaration; + function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration; + function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration; + function isEnumDeclaration(node: Node): node is EnumDeclaration; + function isModuleDeclaration(node: Node): node is ModuleDeclaration; + function isModuleBlock(node: Node): node is ModuleBlock; + function isCaseBlock(node: Node): node is CaseBlock; + function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration; + function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; + function isImportDeclaration(node: Node): node is ImportDeclaration; + function isImportClause(node: Node): node is ImportClause; + function isNamespaceImport(node: Node): node is NamespaceImport; + function isNamedImports(node: Node): node is NamedImports; + function isImportSpecifier(node: Node): node is ImportSpecifier; + function isExportAssignment(node: Node): node is ExportAssignment; + function isExportDeclaration(node: Node): node is ExportDeclaration; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; + function isMissingDeclaration(node: Node): node is MissingDeclaration; + function isExternalModuleReference(node: Node): node is ExternalModuleReference; + function isJsxElement(node: Node): node is JsxElement; + function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; + function isJsxOpeningElement(node: Node): node is JsxOpeningElement; + function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxAttribute(node: Node): node is JsxAttribute; + function isJsxAttributes(node: Node): node is JsxAttributes; + function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; + function isJsxExpression(node: Node): node is JsxExpression; + function isCaseClause(node: Node): node is CaseClause; + function isDefaultClause(node: Node): node is DefaultClause; + function isHeritageClause(node: Node): node is HeritageClause; + function isCatchClause(node: Node): node is CatchClause; + function isPropertyAssignment(node: Node): node is PropertyAssignment; + function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; + function isSpreadAssignment(node: Node): node is SpreadAssignment; + function isEnumMember(node: Node): node is EnumMember; + function isSourceFile(node: Node): node is SourceFile; + function isBundle(node: Node): node is Bundle; + function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; + function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; + function isJSDocUnknownType(node: Node): node is JSDocUnknownType; + function isJSDocNullableType(node: Node): node is JSDocNullableType; + function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType; + function isJSDocOptionalType(node: Node): node is JSDocOptionalType; + function isJSDocFunctionType(node: Node): node is JSDocFunctionType; + function isJSDocVariadicType(node: Node): node is JSDocVariadicType; + function isJSDoc(node: Node): node is JSDoc; + function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocParameterTag(node: Node): node is JSDocParameterTag; + function isJSDocReturnTag(node: Node): node is JSDocReturnTag; + function isJSDocTypeTag(node: Node): node is JSDocTypeTag; + function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag; + function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag; + function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; + function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; } declare namespace ts { /** - * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. */ - function createNodeArray(elements?: T[], hasTrailingComma?: boolean): NodeArray; + function isToken(n: Node): boolean; + function isLiteralExpression(node: Node): node is LiteralExpression; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isStringTextContainingNode(node: Node): boolean; + function isModifier(node: Node): node is Modifier; + function isEntityName(node: Node): node is EntityName; + function isPropertyName(node: Node): node is PropertyName; + function isBindingName(node: Node): node is BindingName; + function isFunctionLike(node: Node): node is FunctionLike; + function isClassElement(node: Node): node is ClassElement; + function isClassLike(node: Node): node is ClassLikeDeclaration; + function isAccessor(node: Node): node is AccessorDeclaration; + function isTypeElement(node: Node): node is TypeElement; + function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node: Node): node is TypeNode; + function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; + function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; + function isCallLikeExpression(node: Node): node is CallLikeExpression; + function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; + function isTemplateLiteral(node: Node): node is TemplateLiteral; + function isAssertionExpression(node: Node): node is AssertionExpression; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; + function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; + function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node: Node): boolean; +} +declare namespace ts { + function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; + function isExternalModule(file: SourceFile): boolean; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + /** + * Cached module resolutions per containing directory. + * This assumes that any module id will have the same resolution for sibling files located in the same folder. + */ + interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { + getOrCreateCacheForDirectory(directoryName: string): Map; + } + /** + * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory + * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. + */ + interface NonRelativeModuleNameResolutionCache { + getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + } + interface PerModuleNameCache { + get(directory: string): ResolvedModuleWithFailedLookupLocations; + set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; + } + function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; function createLiteral(value: string): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; @@ -2755,36 +3083,36 @@ 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 createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - 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 createParameter(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + function updateParameter(node: ParameterDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | 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 createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createPropertySignature(modifiers: ReadonlyArray | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: ReadonlyArray | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function createProperty(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function updateProperty(node: PropertyDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function createMethodSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, 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; - function createGetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - 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 createMethod(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function updateMethod(node: MethodDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createConstructor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function updateConstructor(node: ConstructorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function createGetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function updateGetAccessor(node: GetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function createSetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function updateSetAccessor(node: SetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, 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 createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, 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 createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | 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; @@ -2792,17 +3120,17 @@ declare namespace ts { 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 createTypeLiteralNode(members: ReadonlyArray): 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 createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): 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 createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray): UnionOrIntersectionTypeNode; function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; @@ -2814,34 +3142,34 @@ declare namespace ts { 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; - function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ArrayBindingElement[]): ArrayBindingPattern; + function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; + function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; + function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; + function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ReadonlyArray): ArrayBindingPattern; function createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; - function createArrayLiteral(elements?: Expression[], multiLine?: boolean): ArrayLiteralExpression; - function updateArrayLiteral(node: ArrayLiteralExpression, elements: Expression[]): ArrayLiteralExpression; - function createObjectLiteral(properties?: ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; - function updateObjectLiteral(node: ObjectLiteralExpression, properties: ObjectLiteralElementLike[]): ObjectLiteralExpression; + function createArrayLiteral(elements?: ReadonlyArray, multiLine?: boolean): ArrayLiteralExpression; + function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; + function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; + function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; function createPropertyAccess(expression: Expression, name: string | Identifier): PropertyAccessExpression; function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - function createCall(expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]): CallExpression; - function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]): CallExpression; - function createNew(expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[] | undefined): NewExpression; - function updateNew(node: NewExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[] | undefined): NewExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; function createParen(expression: Expression): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - function createArrowFunction(modifiers: Modifier[] | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; - function updateArrowFunction(node: ArrowFunction, modifiers: Modifier[] | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: ConciseBody): ArrowFunction; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; function createTypeOf(expression: Expression): TypeOfExpression; @@ -2859,18 +3187,18 @@ declare namespace ts { 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; - function createTemplateExpression(head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; - function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; function createYield(expression?: Expression): YieldExpression; function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function createSpread(expression: Expression): SpreadElement; function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; - function createClassExpression(modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; - function updateClassExpression(node: ClassExpression, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; function createOmittedExpression(): OmittedExpression; - function createExpressionWithTypeArguments(typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; function createAsExpression(expression: Expression, type: TypeNode): AsExpression; function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; @@ -2880,10 +3208,10 @@ declare namespace ts { 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 createBlock(statements: ReadonlyArray, multiLine?: boolean): Block; + function updateBlock(node: Block, statements: ReadonlyArray): Block; + function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement; + function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2918,50 +3246,50 @@ declare namespace ts { 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; - function updateModuleDeclaration(node: ModuleDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; - function createModuleBlock(statements: Statement[]): ModuleBlock; - function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; - function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; - function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createVariableDeclarationList(declarations: ReadonlyArray, flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; + function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function createEnumDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, members: ReadonlyArray): EnumDeclaration; + function updateEnumDeclaration(node: EnumDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, members: ReadonlyArray): EnumDeclaration; + function createModuleDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + function updateModuleDeclaration(node: ModuleDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + function createModuleBlock(statements: ReadonlyArray): ModuleBlock; + function updateModuleBlock(node: ModuleBlock, statements: ReadonlyArray): ModuleBlock; + function createCaseBlock(clauses: ReadonlyArray): CaseBlock; + function updateCaseBlock(node: CaseBlock, clauses: ReadonlyArray): 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; - function updateImportDeclaration(node: ImportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; - function createImportClause(name: Identifier, namedBindings: NamedImportBindings): ImportClause; - function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings): ImportClause; + function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; + function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function createNamespaceImport(name: Identifier): NamespaceImport; function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; - function createNamedImports(elements: ImportSpecifier[]): NamedImports; - function updateNamedImports(node: NamedImports, elements: ImportSpecifier[]): NamedImports; + function createNamedImports(elements: ReadonlyArray): NamedImports; + function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - function createExportAssignment(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; - function updateExportAssignment(node: ExportAssignment, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, expression: Expression): ExportAssignment; - function createExportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; - function updateExportDeclaration(node: ExportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; - function createNamedExports(elements: ExportSpecifier[]): NamedExports; - function updateNamedExports(node: NamedExports, elements: ExportSpecifier[]): NamedExports; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; + function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; + function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; + function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; + function createNamedExports(elements: ReadonlyArray): NamedExports; + function updateNamedExports(node: NamedExports, elements: ReadonlyArray): NamedExports; function createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; function createExternalModuleReference(expression: Expression): ExternalModuleReference; function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; - function createJsxElement(openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement): JsxElement; - function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement): JsxElement; + function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; @@ -2970,18 +3298,18 @@ declare namespace ts { function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; 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 createJsxAttributes(properties: ReadonlyArray): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: ReadonlyArray): 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 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 createCaseClause(expression: Expression, statements: ReadonlyArray): CaseClause; + function updateCaseClause(node: CaseClause, expression: Expression, statements: ReadonlyArray): CaseClause; + function createDefaultClause(statements: ReadonlyArray): DefaultClause; + function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): 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; @@ -2992,7 +3320,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: Statement[]): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -3014,10 +3342,12 @@ 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 createCommaList(elements: ReadonlyArray): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; + function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression; + function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression): Expression; function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; @@ -3039,10 +3369,6 @@ declare namespace ts { */ function disposeEmitNodes(sourceFile: SourceFile): void; function setTextRange(range: T, location: TextRange | undefined): T; - /** - * Gets flags that control emit behavior of a node. - */ - function getEmitFlags(node: Node): EmitFlags | undefined; /** * Sets flags that control emit behavior of a node. */ @@ -3050,19 +3376,23 @@ declare namespace ts { /** * Gets a custom text range to use when emitting source maps. */ - function getSourceMapRange(node: Node): TextRange; + function getSourceMapRange(node: Node): SourceMapRange; /** * Sets a custom text range to use when emitting source maps. */ - function setSourceMapRange(node: T, range: TextRange | undefined): T; + function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; /** * Gets the TextRange to use for source maps for a token of a node. */ - function getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange | undefined; + function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; /** * Sets the TextRange to use for source maps for a token of a node. */ - function setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange | undefined): T; + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; /** * Gets a custom text range to use when emitting comments. */ @@ -3107,58 +3437,6 @@ declare namespace ts { function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; function setOriginalNode(node: T, original: Node | undefined): T; } -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 | 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 { - function moduleHasNonRelativeName(moduleName: string): boolean; - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; - /** - * Cached module resolutions per containing directory. - * This assumes that any module id will have the same resolution for sibling files located in the same folder. - */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; - } - /** - * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory - * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. - */ - interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; - } - interface PerModuleNameCache { - get(directory: string): ResolvedModuleWithFailedLookupLocations; - set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; - } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; -} declare namespace ts { /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. @@ -3256,15 +3534,28 @@ declare namespace ts { function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + /** + * 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. + */ function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { - function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; + function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; /** * Read tsconfig.json file * @param fileName The path to the config file */ - function readConfigFile(fileName: string, readFile: (path: string) => string): { + function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic; }; @@ -3273,20 +3564,35 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { + function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic; }; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse * @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; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @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 + */ + function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3312,31 +3618,36 @@ declare namespace ts { getText(sourceFile?: SourceFile): string; getFirstToken(sourceFile?: SourceFile): Node; getLastToken(sourceFile?: SourceFile): Node; - forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; + } + interface Identifier { + readonly text: string; } interface Symbol { + readonly name: string; getFlags(): SymbolFlags; + getEscapedName(): __String; getName(): string; - getDeclarations(): Declaration[]; + getDeclarations(): Declaration[] | undefined; getDocumentationComment(): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } 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; } interface Signature { getDeclaration(): SignatureDeclaration; - getTypeParameters(): TypeParameter[]; + getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; @@ -3352,6 +3663,9 @@ declare namespace ts { interface SourceFileLike { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; } + interface SourceMapSource { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } /** * Represents an immutable snapshot of a script at a specified time.Once acquired, the * snapshot is observably immutable. i.e. the same calls with the same parameters will return @@ -3402,8 +3716,8 @@ declare namespace ts { trace?(s: string): void; error?(s: string): void; useCaseSensitiveFileNames?(): boolean; - readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; - readFile?(path: string, encoding?: string): string; + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile?(path: string, encoding?: string): string | undefined; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; @@ -3461,7 +3775,7 @@ declare 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; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3472,7 +3786,7 @@ declare namespace ts { } interface ClassifiedSpan { textSpan: TextSpan; - classificationType: string; + classificationType: ClassificationTypeNames; } /** * Navigation bar interface designed for visual studio's dual-column layout. @@ -3482,7 +3796,7 @@ declare namespace ts { */ interface NavigationBarItem { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems: NavigationBarItem[]; @@ -3497,8 +3811,7 @@ declare namespace ts { 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; /** @@ -3532,10 +3845,54 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + type RefactorActionInfo = { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + }; + /** + * A set of edits to make in response to a refactor action, plus an optional + * location where renaming should be invoked from + */ + type RefactorEditInfo = { + edits: FileTextChanges[]; + renameFilename?: string; + renameLocation?: number; + }; interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -3553,35 +3910,35 @@ declare namespace ts { isInString?: true; } interface ImplementationLocation extends DocumentSpan { - kind: string; + kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; } interface DocumentHighlights { fileName: string; highlightSpans: HighlightSpan[]; } - namespace HighlightSpanKind { - const none = "none"; - const definition = "definition"; - const reference = "reference"; - const writtenReference = "writtenReference"; + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference", } interface HighlightSpan { fileName?: string; isInString?: true; textSpan: TextSpan; - kind: string; + kind: HighlightSpanKind; } interface NavigateToItem { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; matchKind: string; isCaseSensitive: boolean; fileName: string; textSpan: TextSpan; containerName: string; - containerKind: string; + containerKind: ScriptElementKind; } enum IndentStyle { None = 0, @@ -3641,9 +3998,9 @@ declare namespace ts { interface DefinitionInfo { fileName: string; textSpan: TextSpan; - kind: string; + kind: ScriptElementKind; name: string; - containerKind: string; + containerKind: ScriptElementKind; containerName: string; } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { @@ -3686,7 +4043,7 @@ declare namespace ts { text?: string; } interface QuickInfo { - kind: string; + kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; @@ -3698,7 +4055,7 @@ declare namespace ts { localizedErrorMessage: string; displayName: string; fullDisplayName: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } @@ -3745,7 +4102,7 @@ declare namespace ts { } interface CompletionEntry { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; sortText: string; /** @@ -3757,7 +4114,7 @@ declare namespace ts { } interface CompletionEntryDetails { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; @@ -3842,107 +4199,107 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } - namespace ScriptElementKind { - const unknown = ""; - const warning = "warning"; + enum ScriptElementKind { + unknown = "", + warning = "warning", /** predefined type (void) or keyword (class) */ - const keyword = "keyword"; + keyword = "keyword", /** top level script node */ - const scriptElement = "script"; + scriptElement = "script", /** module foo {} */ - const moduleElement = "module"; + moduleElement = "module", /** class X {} */ - const classElement = "class"; + classElement = "class", /** var x = class X {} */ - const localClassElement = "local class"; + localClassElement = "local class", /** interface Y {} */ - const interfaceElement = "interface"; + interfaceElement = "interface", /** type T = ... */ - const typeElement = "type"; + typeElement = "type", /** enum E */ - const enumElement = "enum"; - const enumMemberElement = "enum member"; + enumElement = "enum", + enumMemberElement = "enum member", /** * Inside module and script only * const v = .. */ - const variableElement = "var"; + variableElement = "var", /** Inside function */ - const localVariableElement = "local var"; + localVariableElement = "local var", /** * Inside module and script only * function f() { } */ - const functionElement = "function"; + functionElement = "function", /** Inside function */ - const localFunctionElement = "local function"; + localFunctionElement = "local function", /** class X { [public|private]* foo() {} } */ - const memberFunctionElement = "method"; + memberFunctionElement = "method", /** class X { [public|private]* [get|set] foo:number; } */ - const memberGetAccessorElement = "getter"; - const memberSetAccessorElement = "setter"; + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", /** * class X { [public|private]* foo:number; } * interface Y { foo:number; } */ - const memberVariableElement = "property"; + memberVariableElement = "property", /** class X { constructor() { } } */ - const constructorImplementationElement = "constructor"; + constructorImplementationElement = "constructor", /** interface Y { ():number; } */ - const callSignatureElement = "call"; + callSignatureElement = "call", /** interface Y { []:number; } */ - const indexSignatureElement = "index"; + indexSignatureElement = "index", /** interface Y { new():Y; } */ - const constructSignatureElement = "construct"; + constructSignatureElement = "construct", /** function foo(*Y*: string) */ - const parameterElement = "parameter"; - const typeParameterElement = "type parameter"; - const primitiveType = "primitive type"; - const label = "label"; - const alias = "alias"; - const constElement = "const"; - const letElement = "let"; - const directory = "directory"; - const externalModuleName = "external module name"; + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", /** * */ - const jsxAttribute = "JSX attribute"; + jsxAttribute = "JSX attribute", } - namespace ScriptElementKindModifier { - const none = ""; - const publicMemberModifier = "public"; - const privateMemberModifier = "private"; - const protectedMemberModifier = "protected"; - const exportedModifier = "export"; - const ambientModifier = "declare"; - const staticModifier = "static"; - const abstractModifier = "abstract"; + enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - static jsxOpenTagName: string; - static jsxCloseTagName: string; - static jsxSelfClosingTagName: string; - static jsxAttribute: string; - static jsxText: string; - static jsxAttributeStringLiteralValue: string; + enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", + punctuation = "punctuation", + 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", } enum ClassificationType { comment = 1, diff --git a/lib/typescript.js b/lib/typescript.js index 9f28644b4e5..eb71a73ba46 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -13,6 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +"use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; @@ -336,40 +337,32 @@ var ts; SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; // The ? type 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["JSDocNullableType"] = 270] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; // Transformation nodes - 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["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -397,9 +390,9 @@ var ts; 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[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -423,6 +416,17 @@ var ts; NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // This flag will be set when the parser encounters a dynamic import expression so that module resolution + // will not have to walk the tree if the flag is not set. However, this flag is just a approximation because + // once it is set, the flag never gets cleared (hence why it's named "PossiblyContainsDynamicImport"). + // During editing, if dynamic import is removed, incremental parsing will *NOT* update this flag. This means that the tree will always be traversed + // during module resolution. However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ + NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -557,18 +561,20 @@ var ts; (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[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -646,13 +652,11 @@ var ts; 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["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -681,14 +685,13 @@ var ts; 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["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "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"; /* @internal */ // The set of things we consider semantically classifiable. Used to speed up the LS during @@ -716,6 +719,25 @@ var ts; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); /* @internal */ var NodeCheckFlags; (function (NodeCheckFlags) { @@ -826,6 +848,18 @@ var ts; IndexKind[IndexKind["String"] = 0] = "String"; IndexKind[IndexKind["Number"] = 1] = "Number"; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; + InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /* @internal */ var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { @@ -860,6 +894,7 @@ var ts; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); var JsxEmit; (function (JsxEmit) { @@ -881,6 +916,7 @@ var ts; ScriptKind[ScriptKind["TS"] = 3] = "TS"; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -1039,12 +1075,11 @@ var ts; })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { - Extension[Extension["Ts"] = 0] = "Ts"; - Extension[Extension["Tsx"] = 1] = "Tsx"; - Extension[Extension["Dts"] = 2] = "Dts"; - Extension[Extension["Js"] = 3] = "Js"; - Extension[Extension["Jsx"] = 4] = "Jsx"; - Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; })(Extension = ts.Extension || (ts.Extension = {})); /* @internal */ var TransformFlags; @@ -1082,6 +1117,10 @@ var ts; TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. @@ -1168,6 +1207,7 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of @@ -1179,7 +1219,7 @@ var ts; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1287,8 +1327,11 @@ var ts; /// var ts; (function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "2.5"; /** The version of the TypeScript compiler release */ - ts.version = "2.4.0"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -1326,14 +1369,32 @@ var ts; return new MapCtr(); } ts.createMap = createMap; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + /* @internal */ + function createSymbolTable(symbols) { + var result = createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; function createMapFromTemplate(template) { var map = new MapCtr(); // Copies keys/values from template. Note that for..in will not throw if // template is undefined, and instead will just exit the loop. - for (var key in template) + for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); } + } return map; } ts.createMapFromTemplate = createMapFromTemplate; @@ -1407,46 +1468,6 @@ var ts; return class_1; }()); } - function createFileMap(keyMapper) { - var files = createMap(); - return { - get: get, - set: set, - contains: contains, - remove: remove, - forEachValue: forEachValueInMap, - getKeys: getKeys, - clear: clear, - }; - function forEachValueInMap(f) { - files.forEach(function (file, key) { - f(key, file); - }); - } - function getKeys() { - return arrayFrom(files.keys()); - } - // path should already be well-formed so it does not need to be normalized - function get(path) { - return files.get(toKey(path)); - } - function set(path, value) { - files.set(toKey(path), value); - } - function contains(path) { - return files.has(toKey(path)); - } - function remove(path) { - files.delete(toKey(path)); - } - function clear() { - files.clear(); - } - function toKey(path) { - return keyMapper ? keyMapper(path) : path; - } - } - ts.createFileMap = createFileMap; function toPath(fileName, basePath, getCanonicalFileName) { var nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) @@ -1657,6 +1678,10 @@ var ts; array.length = outIndex; } ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; function map(array, f) { var result; if (array) { @@ -1668,7 +1693,6 @@ var ts; return result; } ts.map = map; - // Maps from T to T and avoids allocation if all elements map to themselves function sameMap(array, f) { var result; if (array) { @@ -1738,13 +1762,19 @@ 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 flatMapIter(iter, mapfn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapfn(value); + if (res) + result.push.apply(result, res); + } + return result; + } + ts.flatMapIter = flatMapIter; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1767,6 +1797,18 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapDefined(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } + } + return result; + } + ts.mapDefined = mapDefined; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -1916,9 +1958,6 @@ var ts; !equalOwnProperties(oldOptions.paths, newOptions.paths); } ts.changesAffectModuleResolution = changesAffectModuleResolution; - /** - * Compacts an array, removing any falsey elements. - */ function compact(array) { var result; if (array) { @@ -1966,6 +2005,7 @@ var ts; var result = 0; for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { var v = array_7[_i]; + // Note: we need the following type assertion because of GH #17069 result += v[prop]; } return result; @@ -1988,6 +2028,13 @@ var ts; return to; } ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } /** * Appends a range of value to an array, returning the array. * @@ -1995,13 +2042,21 @@ var ts; * is created if `value` was appended. * @param from The values to append to the array. If `from` is `undefined`, nothing is * appended. If an element of `from` is `undefined`, that element is not appended. + * @param start The offset in `from` at which to start copying values. + * @param end The offset in `from` at which to stop copying values (non-inclusive). */ - function addRange(to, from) { + function addRange(to, from, start, end) { if (from === undefined) return to; - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - to = append(to, v); + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + var v = from[i]; + if (v !== undefined) { + to.push(from[i]); + } } return to; } @@ -2027,22 +2082,32 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; /** * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array && array.length > 0 - ? array[0] - : undefined; + return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; /** * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; /** @@ -2054,10 +2119,6 @@ var ts; : undefined; } ts.singleOrUndefined = singleOrUndefined; - /** - * Returns the only element of an array if it contains only one element; otheriwse, returns the - * array. - */ function singleOrMany(array) { return array && array.length === 1 ? array[0] @@ -2181,10 +2242,11 @@ var ts; */ function getOwnKeys(map) { var keys = []; - for (var key in map) + for (var key in map) { if (hasOwnProperty.call(map, key)) { keys.push(key); } + } return keys; } ts.getOwnKeys = getOwnKeys; @@ -2197,19 +2259,6 @@ var ts; var _b; } ts.arrayFrom = arrayFrom; - function convertToArray(iterator, f) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(f(value)); - } - return result; - var _b; - } - ts.convertToArray = convertToArray; - /** - * Calls `callback` for each entry in the map, returning the first truthy result. - * Use `map.forEach` instead for normal iteration. - */ function forEachEntry(map, callback) { var iterator = map.entries(); for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { @@ -2223,7 +2272,6 @@ var ts; var _b; } ts.forEachEntry = forEachEntry; - /** `forEachEntry` for just keys. */ function forEachKey(map, callback) { var iterator = map.keys(); for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { @@ -2236,7 +2284,6 @@ var ts; var _b; } ts.forEachKey = forEachKey; - /** Copy entries from `source` to `target`. */ function copyEntries(source, target) { source.forEach(function (value, key) { target.set(key, value); @@ -2250,10 +2297,11 @@ var ts; } for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var arg = args_1[_a]; - for (var p in arg) + for (var p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; } + } } return t; } @@ -2269,18 +2317,20 @@ var ts; return true; if (!left || !right) return false; - for (var key in left) + for (var key in left) { if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } - for (var key in right) + } + for (var key in right) { if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } + } return true; } ts.equalOwnProperties = equalOwnProperties; @@ -2293,6 +2343,10 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToSet(array, makeKey) { + return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2311,14 +2365,16 @@ var ts; ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) + for (var id in second) { if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - for (var id in first) + } + for (var id in first) { if (hasOwnProperty.call(first, id)) { result[id] = first[id]; } + } return result; } ts.extend = extend; @@ -2355,6 +2411,16 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; /** Does nothing. */ function noop() { } ts.noop = noop; @@ -2696,12 +2762,23 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + /* @internal */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isExternalModuleNameRelative(moduleName) { // TypeScript 1.0 spec (April 2014): 11.2.1 // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ + function moduleHasNonRelativeName(moduleName) { + return !isExternalModuleNameRelative(moduleName); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -2824,7 +2901,7 @@ var ts; if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] - directoryComponents.length--; + directoryComponents.pop(); } // Find the component that differs var joinStartIndex; @@ -2962,7 +3039,8 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsAny(path, extensions) { + /* @internal */ + function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; if (fileExtensionIs(path, extension)) { @@ -2971,7 +3049,7 @@ var ts; } return false; } - ts.fileExtensionIsAny = fileExtensionIsAny; + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. @@ -3097,7 +3175,7 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -3111,17 +3189,16 @@ var ts; var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } return flatten(results); - function visitDirectory(path, absolutePath) { + function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; files = files.slice().sort(comparer); - directories = directories.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; @@ -3139,13 +3216,20 @@ var ts; var current = files_1[_i]; _loop_1(current); } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + directories = directories.slice().sort(comparer); for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { var current = directories_1[_b]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName); + visitDirectory(name, absoluteName, depth); } } } @@ -3201,20 +3285,22 @@ var ts; // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt // to get the ScriptKind from the file name. If it cannot be resolved // from the file name then the default 'TS' script kind is returned. - return (scriptKind || getScriptKindFromFileName(fileName)) || 3 /* TS */; + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; } ts.ensureScriptKind = ensureScriptKind; function getScriptKindFromFileName(fileName) { var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { - case ".js": + case ".js" /* Js */: return 1 /* JS */; - case ".jsx": + case ".jsx" /* Jsx */: return 2 /* JSX */; - case ".ts": + case ".ts" /* Ts */: return 3 /* TS */; - case ".tsx": + case ".tsx" /* Tsx */: return 4 /* TSX */; + case ".json": + return 6 /* JSON */; default: return 0 /* Unknown */; } @@ -3223,10 +3309,10 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; - ts.supportedJavascriptExtensions = [".js", ".jsx"]; + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; @@ -3314,7 +3400,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -3340,11 +3426,14 @@ var ts; ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; this.declarations = undefined; } - function Type(_checker, flags) { + function Type(checker, flags) { this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } } function Signature() { } @@ -3359,6 +3448,11 @@ var ts; this.parent = undefined; this.original = undefined; } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, getTokenConstructor: function () { return Node; }, @@ -3366,7 +3460,8 @@ var ts; getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, - getSignatureConstructor: function () { return Signature; } + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; var AssertionLevel; (function (AssertionLevel) { @@ -3378,25 +3473,43 @@ var ts; var Debug; (function (Debug) { Debug.currentAssertionLevel = 0 /* None */; + Debug.isDebugging = false; function shouldAssert(level) { return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo) { + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { - var verboseDebugString = ""; if (verboseDebugInfo) { - verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); } - debugger; - throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; - function fail(message) { - Debug.assert(/*expression*/ false, message); + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; } Debug.fail = fail; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; })(Debug = ts.Debug || (ts.Debug = {})); /** Remove an item from an array, moving everything to its right one space left. */ function orderedRemoveItem(array, item) { @@ -3524,7 +3637,7 @@ var ts; ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ function extensionIsTypeScript(ext) { - return ext <= ts.Extension.LastTypeScriptExtension; + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } ts.extensionIsTypeScript = extensionIsTypeScript; /** @@ -3540,21 +3653,7 @@ var ts; } ts.extensionFromPath = extensionFromPath; function tryGetExtensionFromPath(path) { - if (fileExtensionIs(path, ".d.ts")) { - return ts.Extension.Dts; - } - if (fileExtensionIs(path, ".ts")) { - return ts.Extension.Ts; - } - if (fileExtensionIs(path, ".tsx")) { - return ts.Extension.Tsx; - } - if (fileExtensionIs(path, ".js")) { - return ts.Extension.Js; - } - if (fileExtensionIs(path, ".jsx")) { - return ts.Extension.Jsx; - } + return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3565,6 +3664,12 @@ var ts; /// var ts; (function (ts) { + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -3640,7 +3745,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName); + fileCallback(fileName, FileWatcherEventKind.Changed); } } } @@ -3654,9 +3759,15 @@ var ts; if (platform === "win32" || platform === "win64") { return false; } - // convert current file name to upper case / lower case and check if file exists - // (guards against cases when name is already all uppercase or lowercase) - return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); @@ -3737,8 +3848,8 @@ var ts; return { files: [], directories: [] }; } } - function readDirectory(path, extensions, excludes, includes) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -3790,10 +3901,19 @@ var ts; }; } function fileChanged(curr, prev) { - if (+curr.mtime <= +prev.mtime) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { return; } - callback(fileName); + callback(fileName, eventKind); } }, watchDirectory: function (directoryName, callback, recursive) { @@ -3820,9 +3940,7 @@ var ts; } }); }, - resolvePath: function (path) { - return _path.resolve(path); - }, + resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { @@ -3876,6 +3994,7 @@ var ts; realpath: function (path) { return _fs.realpathSync(path); }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { try { require("source-map-support").install(); @@ -3915,7 +4034,7 @@ var ts; getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), - readDirectory: function (path, extensions, excludes, includes) { + readDirectory: function (path, extensions, excludes, includes, _depth) { var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, @@ -3960,913 +4079,936 @@ var ts; ? 1 /* Normal */ : 0 /* None */; } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } })(ts || (ts = {})); // /// /* @internal */ var ts; (function (ts) { + function diag(code, category, key, message) { + return { code: code, category: category, key: key, message: message }; + } ts.Diagnostics = { - Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated_string_literal_1002", message: "Unterminated string literal." }, - Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_1003", message: "Identifier expected." }, - _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "_0_expected_1005", message: "'{0}' expected." }, - A_file_cannot_have_a_reference_to_itself: { code: 1006, category: ts.DiagnosticCategory.Error, key: "A_file_cannot_have_a_reference_to_itself_1006", message: "A file cannot have a reference to itself." }, - Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing_comma_not_allowed_1009", message: "Trailing comma not allowed." }, - Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "Asterisk_Slash_expected_1010", message: "'*/' expected." }, - Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_1012", message: "Unexpected token." }, - A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_last_in_a_parameter_list_1014", message: "A rest parameter must be last in a parameter list." }, - Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: ts.DiagnosticCategory.Error, key: "Parameter_cannot_have_question_mark_and_initializer_1015", message: "Parameter cannot have question mark and initializer." }, - A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: ts.DiagnosticCategory.Error, key: "A_required_parameter_cannot_follow_an_optional_parameter_1016", message: "A required parameter cannot follow an optional parameter." }, - An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: ts.DiagnosticCategory.Error, key: "An_index_signature_cannot_have_a_rest_parameter_1017", message: "An index signature cannot have a rest parameter." }, - An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", message: "An index signature parameter cannot have an accessibility modifier." }, - An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_a_question_mark_1019", message: "An index signature parameter cannot have a question mark." }, - An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_initializer_1020", message: "An index signature parameter cannot have an initializer." }, - An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, - An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, - An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, - readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, - Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, - _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, - _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, - _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_class_element_1031", message: "'{0}' modifier cannot appear on a class element." }, - super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: ts.DiagnosticCategory.Error, key: "super_must_be_followed_by_an_argument_list_or_member_access_1034", message: "'super' must be followed by an argument list or member access." }, - Only_ambient_modules_can_use_quoted_names: { code: 1035, category: ts.DiagnosticCategory.Error, key: "Only_ambient_modules_can_use_quoted_names_1035", message: "Only ambient modules can use quoted names." }, - Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: ts.DiagnosticCategory.Error, key: "Statements_are_not_allowed_in_ambient_contexts_1036", message: "Statements are not allowed in ambient contexts." }, - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", message: "A 'declare' modifier cannot be used in an already ambient context." }, - Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: ts.DiagnosticCategory.Error, key: "Initializers_are_not_allowed_in_ambient_contexts_1039", message: "Initializers are not allowed in ambient contexts." }, - _0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_in_an_ambient_context_1040", message: "'{0}' modifier cannot be used in an ambient context." }, - _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, - _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, - _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, - A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, - A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, - A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, - A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_have_an_initializer_1048", message: "A rest parameter cannot have an initializer." }, - A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_must_have_exactly_one_parameter_1049", message: "A 'set' accessor must have exactly one parameter." }, - A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_an_optional_parameter_1051", message: "A 'set' accessor cannot have an optional parameter." }, - A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, - A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, - A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, - An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, - The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", message: "The return type of an async function must either be a valid promise or must not contain a callable 'then' member." }, - A_promise_must_have_a_then_method: { code: 1059, category: ts.DiagnosticCategory.Error, key: "A_promise_must_have_a_then_method_1059", message: "A promise must have a 'then' method." }, - The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: { code: 1060, category: ts.DiagnosticCategory.Error, key: "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", message: "The first parameter of the 'then' method of a promise must be a callback." }, - Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, - Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, - An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, - In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, - Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, - _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, - _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, - A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, - Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." }, - An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_be_declared_in_an_ambient_context_1086", message: "An accessor cannot be declared in an ambient context." }, - _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", message: "'{0}' modifier cannot appear on a constructor declaration." }, - _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_parameter_1090", message: "'{0}' modifier cannot appear on a parameter." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", message: "Only a single variable declaration is allowed in a 'for...in' statement." }, - Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: ts.DiagnosticCategory.Error, key: "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", message: "Type parameters cannot appear on a constructor declaration." }, - Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: ts.DiagnosticCategory.Error, key: "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", message: "Type annotation cannot appear on a constructor declaration." }, - An_accessor_cannot_have_type_parameters: { code: 1094, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_have_type_parameters_1094", message: "An accessor cannot have type parameters." }, - A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_a_return_type_annotation_1095", message: "A 'set' accessor cannot have a return type annotation." }, - An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_exactly_one_parameter_1096", message: "An index signature must have exactly one parameter." }, - _0_list_cannot_be_empty: { code: 1097, category: ts.DiagnosticCategory.Error, key: "_0_list_cannot_be_empty_1097", message: "'{0}' list cannot be empty." }, - Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type_parameter_list_cannot_be_empty_1098", message: "Type parameter list cannot be empty." }, - Type_argument_list_cannot_be_empty: { code: 1099, category: ts.DiagnosticCategory.Error, key: "Type_argument_list_cannot_be_empty_1099", message: "Type argument list cannot be empty." }, - Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_in_strict_mode_1100", message: "Invalid use of '{0}' in strict mode." }, - with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_strict_mode_1101", message: "'with' statements are not allowed in strict mode." }, - delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", message: "'delete' cannot be called on an identifier in strict mode." }, - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: { code: 1103, category: ts.DiagnosticCategory.Error, key: "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", message: "A 'for-await-of' statement is only allowed within an async function or async generator." }, - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", message: "A 'continue' statement can only be used within an enclosing iteration statement." }, - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", message: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, - Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump_target_cannot_cross_function_boundary_1107", message: "Jump target cannot cross function boundary." }, - A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: ts.DiagnosticCategory.Error, key: "A_return_statement_can_only_be_used_within_a_function_body_1108", message: "A 'return' statement can only be used within a function body." }, - Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." }, - Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." }, - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", message: "A 'default' clause cannot appear more than once in a 'switch' statement." }, - Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'." }, - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", message: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", message: "A 'break' statement can only jump to a label of an enclosing statement." }, - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", message: "An object literal cannot have multiple properties with the same name in strict mode." }, - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", message: "An object literal cannot have multiple get/set accessors with the same name." }, - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", message: "An object literal cannot have property and accessor with the same name." }, - An_export_assignment_cannot_have_modifiers: { code: 1120, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_have_modifiers_1120", message: "An export assignment cannot have modifiers." }, - Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_strict_mode_1121", message: "Octal literals are not allowed in strict mode." }, - A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: ts.DiagnosticCategory.Error, key: "A_tuple_type_element_list_cannot_be_empty_1122", message: "A tuple type element list cannot be empty." }, - Variable_declaration_list_cannot_be_empty: { code: 1123, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_list_cannot_be_empty_1123", message: "Variable declaration list cannot be empty." }, - Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit_expected_1124", message: "Digit expected." }, - Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal_digit_expected_1125", message: "Hexadecimal digit expected." }, - Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected_end_of_text_1126", message: "Unexpected end of text." }, - Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid_character_1127", message: "Invalid character." }, - Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration_or_statement_expected_1128", message: "Declaration or statement expected." }, - Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement_expected_1129", message: "Statement expected." }, - case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "case_or_default_expected_1130", message: "'case' or 'default' expected." }, - Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property_or_signature_expected_1131", message: "Property or signature expected." }, - Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum_member_expected_1132", message: "Enum member expected." }, - Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_expected_1134", message: "Variable declaration expected." }, - Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument_expression_expected_1135", message: "Argument expression expected." }, - Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property_assignment_expected_1136", message: "Property assignment expected." }, - Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression_or_comma_expected_1137", message: "Expression or comma expected." }, - Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter_declaration_expected_1138", message: "Parameter declaration expected." }, - Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type_parameter_declaration_expected_1139", message: "Type parameter declaration expected." }, - Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type_argument_expected_1140", message: "Type argument expected." }, - String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, - Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, - or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, - Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, - File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing." }, - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, - const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized." }, - const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "const_declarations_can_only_be_declared_inside_a_block_1156", message: "'const' declarations can only be declared inside a block." }, - let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "let_declarations_can_only_be_declared_inside_a_block_1157", message: "'let' declarations can only be declared inside a block." }, - Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." }, - Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated_regular_expression_literal_1161", message: "Unterminated regular expression literal." }, - An_object_member_cannot_be_declared_optional: { code: 1162, category: ts.DiagnosticCategory.Error, key: "An_object_member_cannot_be_declared_optional_1162", message: "An object member cannot be declared optional." }, - A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: ts.DiagnosticCategory.Error, key: "A_yield_expression_is_only_allowed_in_a_generator_body_1163", message: "A 'yield' expression is only allowed in a generator body." }, - Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "Computed_property_names_are_not_allowed_in_enums_1164", message: "Computed property names are not allowed in enums." }, - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", message: "A computed property name in an ambient context must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", message: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", message: "A computed property name in a method overload must directly refer to a built-in symbol." }, - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", message: "A computed property name in an interface must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", message: "A computed property name in a type literal must directly refer to a built-in symbol." }, - A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: ts.DiagnosticCategory.Error, key: "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", message: "A comma expression is not allowed in a computed property name." }, - extends_clause_already_seen: { code: 1172, category: ts.DiagnosticCategory.Error, key: "extends_clause_already_seen_1172", message: "'extends' clause already seen." }, - extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "extends_clause_must_precede_implements_clause_1173", message: "'extends' clause must precede 'implements' clause." }, - Classes_can_only_extend_a_single_class: { code: 1174, category: ts.DiagnosticCategory.Error, key: "Classes_can_only_extend_a_single_class_1174", message: "Classes can only extend a single class." }, - implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "implements_clause_already_seen_1175", message: "'implements' clause already seen." }, - Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface_declaration_cannot_have_implements_clause_1176", message: "Interface declaration cannot have 'implements' clause." }, - Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary_digit_expected_1177", message: "Binary digit expected." }, - Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal_digit_expected_1178", message: "Octal digit expected." }, - Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_expected_1179", message: "Unexpected token. '{' expected." }, - Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property_destructuring_pattern_expected_1180", message: "Property destructuring pattern expected." }, - Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array_element_destructuring_pattern_expected_1181", message: "Array element destructuring pattern expected." }, - A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: ts.DiagnosticCategory.Error, key: "A_destructuring_declaration_must_have_an_initializer_1182", message: "A destructuring declaration must have an initializer." }, - An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1183, category: ts.DiagnosticCategory.Error, key: "An_implementation_cannot_be_declared_in_ambient_contexts_1183", message: "An implementation cannot be declared in ambient contexts." }, - Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, - Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, - A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, - The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, - The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, - An_import_declaration_cannot_have_modifiers: { code: 1191, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_cannot_have_modifiers_1191", message: "An import declaration cannot have modifiers." }, - Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, - An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, - Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, - Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, - An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, - Unterminated_Unicode_escape_sequence: { code: 1199, category: ts.DiagnosticCategory.Error, key: "Unterminated_Unicode_escape_sequence_1199", message: "Unterminated Unicode escape sequence." }, - 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." }, - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", message: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." }, - Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", message: "Invalid use of '{0}'. Class definitions are automatically in strict mode." }, - A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, - Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, - Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, - Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, - Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, - Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: ts.DiagnosticCategory.Error, key: "Generators_are_not_allowed_in_an_ambient_context_1221", message: "Generators are not allowed in an ambient context." }, - An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, - _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "_0_tag_already_specified_1223", message: "'{0}' tag already specified." }, - Signature_0_must_have_a_type_predicate: { code: 1224, category: ts.DiagnosticCategory.Error, key: "Signature_0_must_have_a_type_predicate_1224", message: "Signature '{0}' must have a type predicate." }, - Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot_find_parameter_0_1225", message: "Cannot find parameter '{0}'." }, - Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: ts.DiagnosticCategory.Error, key: "Type_predicate_0_is_not_assignable_to_1_1226", message: "Type predicate '{0}' is not assignable to '{1}'." }, - Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: ts.DiagnosticCategory.Error, key: "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", message: "Parameter '{0}' is not in the same position as parameter '{1}'." }, - A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", message: "A type predicate is only allowed in return type position for functions and methods." }, - A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_a_rest_parameter_1229", message: "A type predicate cannot reference a rest parameter." }, - A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", message: "A type predicate cannot reference element '{0}' in a binding pattern." }, - An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_can_only_be_used_in_a_module_1231", message: "An export assignment can only be used in a module." }, - An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", message: "An import declaration can only be used in a namespace or module." }, - An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_can_only_be_used_in_a_module_1233", message: "An export declaration can only be used in a module." }, - An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", message: "An ambient module declaration is only allowed at the top level in a file." }, - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", message: "A namespace declaration is only allowed in a namespace or module." }, - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", message: "The return type of a property decorator function must be either 'void' or 'any'." }, - The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", message: "The return type of a parameter decorator function must be either 'void' or 'any'." }, - Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", message: "Unable to resolve signature of class decorator when called as an expression." }, - Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, - Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, - Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, - _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, - Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, - Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, - An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, - A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, - A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, - A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: { code: 1250, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, - _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, - with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, - await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, - The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, - Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, - Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, - Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, - A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, - An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, - A_default_export_can_only_be_used_in_an_ECMAScript_style_module: { code: 1319, category: ts.DiagnosticCategory.Error, key: "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", message: "A default export can only be used in an ECMAScript-style module." }, - Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1320, category: ts.DiagnosticCategory.Error, key: "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", message: "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1321, category: ts.DiagnosticCategory.Error, key: "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", message: "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1322, category: ts.DiagnosticCategory.Error, key: "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", message: "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member." }, - Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, - Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, - Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, - Circular_definition_of_import_alias_0: { code: 2303, category: ts.DiagnosticCategory.Error, key: "Circular_definition_of_import_alias_0_2303", message: "Circular definition of import alias '{0}'." }, - Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_2304", message: "Cannot find name '{0}'." }, - Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, - File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, - Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, - Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, - An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, - Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, - A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, - An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, - Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, - Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, - Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, - Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_have_1_type_parameter_s_2317", message: "Global type '{0}' must have {1} type parameter(s)." }, - Cannot_find_global_type_0: { code: 2318, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_type_0_2318", message: "Cannot find global type '{0}'." }, - Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: ts.DiagnosticCategory.Error, key: "Named_property_0_of_types_1_and_2_are_not_identical_2319", message: "Named property '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, - Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, - Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, - Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, - Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, - Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: ts.DiagnosticCategory.Error, key: "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", message: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: ts.DiagnosticCategory.Error, key: "Types_of_parameters_0_and_1_are_incompatible_2328", message: "Types of parameters '{0}' and '{1}' are incompatible." }, - Index_signature_is_missing_in_type_0: { code: 2329, category: ts.DiagnosticCategory.Error, key: "Index_signature_is_missing_in_type_0_2329", message: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index_signatures_are_incompatible_2330", message: "Index signatures are incompatible." }, - this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", message: "'this' cannot be referenced in a module or namespace body." }, - this_cannot_be_referenced_in_current_location: { code: 2332, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_current_location_2332", message: "'this' cannot be referenced in current location." }, - this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_constructor_arguments_2333", message: "'this' cannot be referenced in constructor arguments." }, - this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_static_property_initializer_2334", message: "'this' cannot be referenced in a static property initializer." }, - super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_a_derived_class_2335", message: "'super' can only be referenced in a derived class." }, - super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_constructor_arguments_2336", message: "'super' cannot be referenced in constructor arguments." }, - Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: ts.DiagnosticCategory.Error, key: "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", message: "Super calls are not permitted outside constructors or in nested functions inside constructors." }, - super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: ts.DiagnosticCategory.Error, key: "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", message: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." }, - Property_0_does_not_exist_on_type_1: { code: 2339, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_2339", message: "Property '{0}' does not exist on type '{1}'." }, - Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, - Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, - An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, - 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}'." }, - 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." }, - Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, - Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, - Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, - Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, - The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, - The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter." }, - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, - Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, - Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, - Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'." }, - A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", message: "A parameter property is only allowed in a constructor implementation." }, - A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_of_an_array_type_2370", message: "A rest parameter must be of an array type." }, - A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", message: "A parameter initializer is only allowed in a function or constructor implementation." }, - Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: ts.DiagnosticCategory.Error, key: "Parameter_0_cannot_be_referenced_in_its_initializer_2372", message: "Parameter '{0}' cannot be referenced in its initializer." }, - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: ts.DiagnosticCategory.Error, key: "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", message: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, - Duplicate_string_index_signature: { code: 2374, category: ts.DiagnosticCategory.Error, key: "Duplicate_string_index_signature_2374", message: "Duplicate string index signature." }, - Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, - Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, - Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, - get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, - A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, - Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, - Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, - Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, - Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, - Function_overload_must_be_static: { code: 2387, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_be_static_2387", message: "Function overload must be static." }, - Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_not_be_static_2388", message: "Function overload must not be static." }, - Function_implementation_name_must_be_0: { code: 2389, category: ts.DiagnosticCategory.Error, key: "Function_implementation_name_must_be_0_2389", message: "Function implementation name must be '{0}'." }, - Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor_implementation_is_missing_2390", message: "Constructor implementation is missing." }, - Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: ts.DiagnosticCategory.Error, key: "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", message: "Function implementation is missing or not immediately following the declaration." }, - Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: ts.DiagnosticCategory.Error, key: "Multiple_constructor_implementations_are_not_allowed_2392", message: "Multiple constructor implementations are not allowed." }, - Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate_function_implementation_2393", message: "Duplicate function implementation." }, - Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, - Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, - Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, - Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, - Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, - Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, - Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", message: "Expression resolves to '_super' that compiler uses to capture base class reference." }, - Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, - The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, - The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, - Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, - Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class." }, - The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, - Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, - Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, - Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, - Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'." }, - Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, - A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, - Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'." }, - All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, - Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'." }, - In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, - A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged." }, - A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged." }, - Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", message: "Ambient modules cannot be nested in other modules or namespaces." }, - Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient_module_declaration_cannot_specify_relative_module_name_2436", message: "Ambient module declaration cannot specify relative module name." }, - Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name." }, - Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'." }, - Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", message: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." }, - Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." }, - Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types_have_separate_declarations_of_a_private_property_0_2442", message: "Types have separate declarations of a private property '{0}'." }, - Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", message: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." }, - Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", message: "Property '{0}' is protected in type '{1}' but public in type '{2}'." }, - Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", message: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, - The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, - Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - Class_0_used_before_its_declaration: { code: 2449, category: ts.DiagnosticCategory.Error, key: "Class_0_used_before_its_declaration_2449", message: "Class '{0}' used before its declaration." }, - Enum_0_used_before_its_declaration: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Enum_0_used_before_its_declaration_2450", message: "Enum '{0}' used before its declaration." }, - Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, - An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, - The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, - Variable_0_is_used_before_being_assigned: { code: 2454, category: ts.DiagnosticCategory.Error, key: "Variable_0_is_used_before_being_assigned_2454", message: "Variable '{0}' is used before being assigned." }, - Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", message: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, - Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type_alias_0_circularly_references_itself_2456", message: "Type alias '{0}' circularly references itself." }, - Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'." }, - An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An_AMD_module_cannot_have_multiple_name_assignments_2458", message: "An AMD module cannot have multiple name assignments." }, - Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, - Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, - Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern." }, - A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, - A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, - this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, - super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_a_computed_property_name_2466", message: "'super' cannot be referenced in a computed property name." }, - A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", message: "A computed property name cannot reference a type parameter from its containing type." }, - Cannot_find_global_value_0: { code: 2468, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_value_0_2468", message: "Cannot find global value '{0}'." }, - The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: ts.DiagnosticCategory.Error, key: "The_0_operator_cannot_be_applied_to_type_symbol_2469", message: "The '{0}' operator cannot be applied to type 'symbol'." }, - Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: ts.DiagnosticCategory.Error, key: "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", message: "'Symbol' reference does not refer to the global Symbol constructor object." }, - A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", message: "A computed property name of the form '{0}' must be of type 'symbol'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", message: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." }, - Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: ts.DiagnosticCategory.Error, key: "Enum_declarations_must_all_be_const_or_non_const_2473", message: "Enum declarations must all be const or non-const." }, - In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: ts.DiagnosticCategory.Error, key: "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", message: "In 'const' enum declarations member initializer must be constant expression." }, - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: ts.DiagnosticCategory.Error, key: "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", message: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." }, - A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: ts.DiagnosticCategory.Error, key: "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", message: "A const enum member can only be accessed using a string literal." }, - const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", message: "'const' enum member initializer was evaluated to a non-finite value." }, - const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", message: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, - Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_const_enum_1_2479", message: "Property '{0}' does not exist on 'const' enum '{1}'." }, - let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", message: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." }, - Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, - The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, - Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'." }, - The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, - An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, - The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", message: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." }, - Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause." }, - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", message: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." }, - Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", message: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." }, - Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_2495", message: "Type '{0}' is not an array type or a string type." }, - The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", message: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." }, - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: ts.DiagnosticCategory.Error, key: "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", message: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." }, - Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: ts.DiagnosticCategory.Error, key: "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", message: "Module '{0}' uses 'export =' and cannot be used with 'export *'." }, - An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", message: "An interface can only extend an identifier/qualified-name with optional type arguments." }, - A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", message: "A class can only implement an identifier/qualified-name with optional type arguments." }, - A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, - _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, - Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: { code: 2504, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", message: "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator." }, - A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, - _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, - Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, - No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: ts.DiagnosticCategory.Error, key: "No_base_constructor_has_the_specified_number_of_type_arguments_2508", message: "No base constructor has the specified number of type arguments." }, - Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, - Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, - Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, - Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, - Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, - Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, - All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, - Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, - A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, - An_async_iterator_must_have_a_next_method: { code: 2519, category: ts.DiagnosticCategory.Error, key: "An_async_iterator_must_have_a_next_method_2519", message: "An async iterator must have a 'next()' method." }, - Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, - Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, - yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, - await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, - A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, - A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, - Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, - Object_is_possibly_null: { code: 2531, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_2531", message: "Object is possibly 'null'." }, - Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, - Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, - A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, - Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, - Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, - Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, - Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, - The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, - Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, - Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, - Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, - A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, - The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: { code: 2547, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", message: "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property." }, - Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { 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." }, - Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'." }, - JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", message: "JSX element type '{0}' does not have any construct or call signatures." }, - JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", message: "JSX element type '{0}' is not a constructor function for JSX elements." }, - Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", message: "Property '{0}' of JSX spread attribute is not assignable to target property." }, - JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property." }, - The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property." }, - JSX_spread_child_must_be_an_array_type: { code: 2609, category: ts.DiagnosticCategory.Error, key: "JSX_spread_child_must_be_an_array_type_2609", message: "JSX spread child must be an array type." }, - Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: { code: 2649, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", message: "Cannot augment module '{0}' with value exports because it resolves to a non-module entity." }, - Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React." }, - A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", message: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." }, - Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", message: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, - Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", message: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." }, - Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, - Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, - JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element." }, - Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'." }, - super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, - super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, - Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", message: "Cannot export '{0}'. Only local declarations can be exported from a module." }, - Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, - Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, - Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, - Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, - Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, - Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, - export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, - Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, - Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, - Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, - Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, - Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, - Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, - Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, - Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, - A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: { code: 2677, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", message: "A type predicate's type must be assignable to its parameter's type." }, - Type_0_is_not_comparable_to_type_1: { code: 2678, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_comparable_to_type_1_2678", message: "Type '{0}' is not comparable to type '{1}'." }, - A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: { code: 2679, category: ts.DiagnosticCategory.Error, key: "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", message: "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'." }, - A_this_parameter_must_be_the_first_parameter: { code: 2680, category: ts.DiagnosticCategory.Error, key: "A_this_parameter_must_be_the_first_parameter_2680", message: "A 'this' parameter must be the first parameter." }, - A_constructor_cannot_have_a_this_parameter: { code: 2681, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_have_a_this_parameter_2681", message: "A constructor cannot have a 'this' parameter." }, - get_and_set_accessor_must_have_the_same_this_type: { code: 2682, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_this_type_2682", message: "'get' and 'set' accessor must have the same 'this' type." }, - this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, - The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, - The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, - All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, - Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, - Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, - Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, - The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, - Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, - Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: { code: 2699, category: ts.DiagnosticCategory.Error, key: "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", message: "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'." }, - Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, - The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, - The_operand_of_a_delete_operator_must_be_a_property_reference: { code: 2703, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", message: "The operand of a delete operator must be a property reference." }, - The_operand_of_a_delete_operator_cannot_be_a_read_only_property: { code: 2704, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", message: "The operand of a delete operator cannot be a read-only property." }, - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: { code: 2705, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", message: "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option." }, - Required_type_parameters_may_not_follow_optional_type_parameters: { code: 2706, category: ts.DiagnosticCategory.Error, key: "Required_type_parameters_may_not_follow_optional_type_parameters_2706", message: "Required type parameters may not follow optional type parameters." }, - Generic_type_0_requires_between_1_and_2_type_arguments: { code: 2707, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_between_1_and_2_type_arguments_2707", message: "Generic type '{0}' requires between {1} and {2} type arguments." }, - Cannot_use_namespace_0_as_a_value: { code: 2708, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_value_2708", message: "Cannot use namespace '{0}' as a value." }, - Cannot_use_namespace_0_as_a_type: { code: 2709, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_type_2709", message: "Cannot use namespace '{0}' as a type." }, - _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: { code: 2710, category: ts.DiagnosticCategory.Error, key: "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", message: "'{0}' are specified twice. The attribute named '{0}' will be overwritten." }, - Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, - Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, - Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", message: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", message: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", message: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", message: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", message: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", message: "Type parameter '{0}' of exported function has or is using private name '{1}'." }, - Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", message: "Implements clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "'extends' clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "'extends' clause of exported interface '{0}' has or is using private name '{1}'." }, - Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", message: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." }, - Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", message: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." }, - Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_private_name_1_4025", message: "Exported variable '{0}' has or is using private name '{1}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", message: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", message: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", message: "Public static property '{0}' of exported class has or is using private name '{1}'." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", message: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", message: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", message: "Public property '{0}' of exported class has or is using private name '{1}'." }, - Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", message: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." }, - Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", message: "Property '{0}' of exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", message: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", message: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", message: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", message: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", message: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", message: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", message: "Return type of public static property getter from exported class has or is using private name '{0}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", message: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", message: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", message: "Return type of public property getter from exported class has or is using private name '{0}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", message: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", message: "Return type of constructor signature from exported interface has or is using private name '{0}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", message: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", message: "Return type of call signature from exported interface has or is using private name '{0}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", message: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", message: "Return type of index signature from exported interface has or is using private name '{0}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", message: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", message: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", message: "Return type of public static method from exported class has or is using private name '{0}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", message: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", message: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", message: "Return type of public method from exported class has or is using private name '{0}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", message: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", message: "Return type of method from exported interface has or is using private name '{0}'." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", message: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", message: "Return type of exported function has or is using name '{0}' from private module '{1}'." }, - Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", message: "Return type of exported function has or is using private name '{0}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", message: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", message: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", message: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", message: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", message: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", message: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", message: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", message: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", message: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", message: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", message: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, - Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, - Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced: { code: 4093, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced_4093", message: "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced." }, - The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, - Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, - File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, - Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}." }, - Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, - Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "Unknown compiler option '{0}'." }, - Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_requires_a_value_of_type_1_5024", message: "Compiler option '{0}' requires a value of type {1}." }, - Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}." }, - Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", message: "Option 'project' cannot be mixed with source files on a command line." }, - Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher." }, - Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", message: "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." }, - Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, - Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, - A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, - Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, - Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, - Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'." }, - The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'." }, - Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, - Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, - Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character." }, - Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character." }, - Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, - Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, - File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, - Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, - Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, - Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, - Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, - Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", message: "Specify the location where debugger should locate TypeScript files instead of source locations." }, - Watch_input_files: { code: 6005, category: ts.DiagnosticCategory.Message, key: "Watch_input_files_6005", message: "Watch input files." }, - Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect_output_structure_to_the_directory_6006", message: "Redirect output structure to the directory." }, - Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: ts.DiagnosticCategory.Message, key: "Do_not_erase_const_enum_declarations_in_generated_code_6007", message: "Do not erase const enum declarations in generated code." }, - Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, - Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, - Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, - Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, - Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'." }, - Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'." }, - Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, - Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, - Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", message: "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'." }, - Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" }, - options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" }, - file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" }, - Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples_Colon_0_6026", message: "Examples: {0}" }, - Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options_Colon_6027", message: "Options:" }, - Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version_0_6029", message: "Version {0}" }, - Insert_command_line_options_and_files_from_a_file: { code: 6030, category: ts.DiagnosticCategory.Message, key: "Insert_command_line_options_and_files_from_a_file_6030", message: "Insert command line options and files from a file." }, - File_change_detected_Starting_incremental_compilation: { code: 6032, category: ts.DiagnosticCategory.Message, key: "File_change_detected_Starting_incremental_compilation_6032", message: "File change detected. Starting incremental compilation..." }, - KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND_6034", message: "KIND" }, - FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE_6035", message: "FILE" }, - VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, - LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, - DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, - STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, - FILE_OR_DIRECTORY: { code: 6040, category: ts.DiagnosticCategory.Message, key: "FILE_OR_DIRECTORY_6040", message: "FILE OR DIRECTORY" }, - Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, - Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, - Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, - Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}." }, - Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, - Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, - Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." }, - Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted_locale_file_0_6051", message: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", message: "Raise error on expressions and declarations with an implied 'any' type." }, - File_0_not_found: { code: 6053, category: ts.DiagnosticCategory.Error, key: "File_0_not_found_6053", message: "File '{0}' not found." }, - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: ts.DiagnosticCategory.Error, key: "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", message: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, - Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: ts.DiagnosticCategory.Message, key: "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", message: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, - Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", message: "Do not emit declarations for code that has an '@internal' annotation." }, - Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: ts.DiagnosticCategory.Message, key: "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", message: "Specify the root directory of input files. Use to control the output directory structure with --outDir." }, - File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", message: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, - Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", message: "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, - NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, - Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, - Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, - Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, - Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, - Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: { code: 6069, category: ts.DiagnosticCategory.Message, key: "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", message: "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)." }, - Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, - Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, - Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context (experimental)." }, - Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, - Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, - Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, - Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, - Specify_library_files_to_be_included_in_the_compilation_Colon: { code: 6079, category: ts.DiagnosticCategory.Message, key: "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", message: "Specify library files to be included in the compilation: " }, - Specify_JSX_code_generation_Colon_preserve_react_native_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", message: "Specify JSX code generation: 'preserve', 'react-native', or 'react'." }, - File_0_has_an_unsupported_extension_so_skipping_it: { code: 6081, category: ts.DiagnosticCategory.Message, key: "File_0_has_an_unsupported_extension_so_skipping_it_6081", message: "File '{0}' has an unsupported extension, so skipping it." }, - Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, - Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, - Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", message: "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit" }, - Enable_tracing_of_the_name_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_name_resolution_process_6085", message: "Enable tracing of the name resolution process." }, - Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, - Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, - Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, - Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, - Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, - paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, - Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, - Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, - Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, - Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", message: "Loading module as file / folder, candidate module location '{0}', target file type '{1}'." }, - File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, - File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, - Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, - Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, - package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, - Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, - Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, - Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, - Expected_type_of_0_field_in_package_json_to_be_string_got_1: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", message: "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'." }, - baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'." }, - rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'." }, - Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'." }, - Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'." }, - Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'." }, - Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed." }, - Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, - Enable_strict_null_checks: { code: 6113, category: ts.DiagnosticCategory.Message, key: "Enable_strict_null_checks_6113", message: "Enable strict null checks." }, - Unknown_option_excludes_Did_you_mean_exclude: { code: 6114, category: ts.DiagnosticCategory.Error, key: "Unknown_option_excludes_Did_you_mean_exclude_6114", message: "Unknown option 'excludes'. Did you mean 'exclude'?" }, - Raise_error_on_this_expressions_with_an_implied_any_type: { code: 6115, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_this_expressions_with_an_implied_any_type_6115", message: "Raise error on 'this' expressions with an implied 'any' type." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_2: { code: 6116, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========" }, - Resolving_using_primary_search_paths: { code: 6117, category: ts.DiagnosticCategory.Message, key: "Resolving_using_primary_search_paths_6117", message: "Resolving using primary search paths..." }, - Resolving_from_node_modules_folder: { code: 6118, category: ts.DiagnosticCategory.Message, key: "Resolving_from_node_modules_folder_6118", message: "Resolving from node_modules folder..." }, - Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: { code: 6119, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", message: "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========" }, - Type_reference_directive_0_was_not_resolved: { code: 6120, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_not_resolved_6120", message: "======== Type reference directive '{0}' was not resolved. ========" }, - Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'." }, - Root_directory_cannot_be_determined_skipping_primary_search_paths: { code: 6122, category: ts.DiagnosticCategory.Message, key: "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", message: "Root directory cannot be determined, skipping primary search paths." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: { code: 6123, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========" }, - Type_declaration_files_to_be_included_in_compilation: { code: 6124, category: ts.DiagnosticCategory.Message, key: "Type_declaration_files_to_be_included_in_compilation_6124", message: "Type declaration files to be included in compilation." }, - Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'." }, - Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: { code: 6126, category: ts.DiagnosticCategory.Message, key: "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", message: "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder." }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: { code: 6127, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", message: "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========" }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, - The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, - Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'." }, - Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, - File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it." }, - _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - 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}'." }, - Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file." }, - Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, - Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, - Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, - Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, - Resolution_for_module_0_was_found_in_cache: { code: 6147, category: ts.DiagnosticCategory.Message, key: "Resolution_for_module_0_was_found_in_cache_6147", message: "Resolution for module '{0}' was found in cache." }, - Directory_0_does_not_exist_skipping_all_lookups_in_it: { code: 6148, category: ts.DiagnosticCategory.Message, key: "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", message: "Directory '{0}' does not exist, skipping all lookups in it." }, - Show_diagnostic_information: { code: 6149, category: ts.DiagnosticCategory.Message, key: "Show_diagnostic_information_6149", message: "Show diagnostic information." }, - Show_verbose_diagnostic_information: { code: 6150, category: ts.DiagnosticCategory.Message, key: "Show_verbose_diagnostic_information_6150", message: "Show verbose diagnostic information." }, - Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: { code: 6151, category: ts.DiagnosticCategory.Message, key: "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", message: "Emit a single file with source maps instead of having a separate file." }, - Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: { code: 6152, category: ts.DiagnosticCategory.Message, key: "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", message: "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set." }, - Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: { code: 6153, category: ts.DiagnosticCategory.Message, key: "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", message: "Transpile each file as a separate module (similar to 'ts.transpileModule')." }, - Print_names_of_generated_files_part_of_the_compilation: { code: 6154, category: ts.DiagnosticCategory.Message, key: "Print_names_of_generated_files_part_of_the_compilation_6154", message: "Print names of generated files part of the compilation." }, - Print_names_of_files_part_of_the_compilation: { code: 6155, category: ts.DiagnosticCategory.Message, key: "Print_names_of_files_part_of_the_compilation_6155", message: "Print names of files part of the compilation." }, - The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: { code: 6156, category: ts.DiagnosticCategory.Message, key: "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", message: "The locale used when displaying messages to the user (e.g. 'en-us')" }, - Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: { code: 6157, category: ts.DiagnosticCategory.Message, key: "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", message: "Do not generate custom helper functions like '__extends' in compiled output." }, - Do_not_include_the_default_library_file_lib_d_ts: { code: 6158, category: ts.DiagnosticCategory.Message, key: "Do_not_include_the_default_library_file_lib_d_ts_6158", message: "Do not include the default library file (lib.d.ts)." }, - Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: { code: 6159, category: ts.DiagnosticCategory.Message, key: "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", message: "Do not add triple-slash references or imported modules to the list of compiled files." }, - Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: { code: 6160, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", message: "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files." }, - List_of_folders_to_include_type_definitions_from: { code: 6161, category: ts.DiagnosticCategory.Message, key: "List_of_folders_to_include_type_definitions_from_6161", message: "List of folders to include type definitions from." }, - Disable_size_limitations_on_JavaScript_projects: { code: 6162, category: ts.DiagnosticCategory.Message, key: "Disable_size_limitations_on_JavaScript_projects_6162", message: "Disable size limitations on JavaScript projects." }, - The_character_set_of_the_input_files: { code: 6163, category: ts.DiagnosticCategory.Message, key: "The_character_set_of_the_input_files_6163", message: "The character set of the input files." }, - Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: { code: 6164, category: ts.DiagnosticCategory.Message, key: "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", message: "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files." }, - Do_not_truncate_error_messages: { code: 6165, category: ts.DiagnosticCategory.Message, key: "Do_not_truncate_error_messages_6165", message: "Do not truncate error messages." }, - Output_directory_for_generated_declaration_files: { code: 6166, category: ts.DiagnosticCategory.Message, key: "Output_directory_for_generated_declaration_files_6166", message: "Output directory for generated declaration files." }, - A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: { code: 6167, category: ts.DiagnosticCategory.Message, key: "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", message: "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'." }, - List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: { code: 6168, category: ts.DiagnosticCategory.Message, key: "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", message: "List of root folders whose combined content represents the structure of the project at runtime." }, - Show_all_compiler_options: { code: 6169, category: ts.DiagnosticCategory.Message, key: "Show_all_compiler_options_6169", message: "Show all compiler options." }, - Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: { code: 6170, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", message: "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file" }, - Command_line_Options: { code: 6171, category: ts.DiagnosticCategory.Message, key: "Command_line_Options_6171", message: "Command-line Options" }, - Basic_Options: { code: 6172, category: ts.DiagnosticCategory.Message, key: "Basic_Options_6172", message: "Basic Options" }, - Strict_Type_Checking_Options: { code: 6173, category: ts.DiagnosticCategory.Message, key: "Strict_Type_Checking_Options_6173", message: "Strict Type-Checking Options" }, - Module_Resolution_Options: { code: 6174, category: ts.DiagnosticCategory.Message, key: "Module_Resolution_Options_6174", message: "Module Resolution Options" }, - Source_Map_Options: { code: 6175, category: ts.DiagnosticCategory.Message, key: "Source_Map_Options_6175", message: "Source Map Options" }, - Additional_Checks: { code: 6176, category: ts.DiagnosticCategory.Message, key: "Additional_Checks_6176", message: "Additional Checks" }, - Experimental_Options: { code: 6177, category: ts.DiagnosticCategory.Message, key: "Experimental_Options_6177", message: "Experimental Options" }, - Advanced_Options: { code: 6178, category: ts.DiagnosticCategory.Message, key: "Advanced_Options_6178", message: "Advanced Options" }, - Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: { code: 6179, category: ts.DiagnosticCategory.Message, key: "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", message: "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'." }, - 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." }, - new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: ts.DiagnosticCategory.Error, key: "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", message: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, - _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, - Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, - Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, - Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, - Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, - Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, - Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", message: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." }, - _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: { code: 7023, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", message: "'{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." }, - 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: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "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." }, - Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, - JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists." }, - Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, - Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, - Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, - Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, - Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, - Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: { code: 7035, category: ts.DiagnosticCategory.Error, key: "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", message: "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`" }, - You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, - You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, - import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, - export_can_only_be_used_in_a_ts_file: { code: 8003, category: ts.DiagnosticCategory.Error, key: "export_can_only_be_used_in_a_ts_file_8003", message: "'export=' can only be used in a .ts file." }, - type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: ts.DiagnosticCategory.Error, key: "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", message: "'type parameter declarations' can only be used in a .ts file." }, - implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: ts.DiagnosticCategory.Error, key: "implements_clauses_can_only_be_used_in_a_ts_file_8005", message: "'implements clauses' can only be used in a .ts file." }, - interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: ts.DiagnosticCategory.Error, key: "interface_declarations_can_only_be_used_in_a_ts_file_8006", message: "'interface declarations' can only be used in a .ts file." }, - module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: ts.DiagnosticCategory.Error, key: "module_declarations_can_only_be_used_in_a_ts_file_8007", message: "'module declarations' can only be used in a .ts file." }, - type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: ts.DiagnosticCategory.Error, key: "type_aliases_can_only_be_used_in_a_ts_file_8008", message: "'type aliases' can only be used in a .ts file." }, - _0_can_only_be_used_in_a_ts_file: { code: 8009, category: ts.DiagnosticCategory.Error, key: "_0_can_only_be_used_in_a_ts_file_8009", message: "'{0}' can only be used in a .ts file." }, - types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, - type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, - parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, - type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, - Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, - JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, - JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, - Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, - JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "JSX attribute expected." }, - Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, - A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'." }, - An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, - super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, - super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, - _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: { code: 17012, category: ts.DiagnosticCategory.Error, key: "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", message: "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" }, - Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: { code: 17013, category: ts.DiagnosticCategory.Error, key: "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", message: "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." }, - Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, - The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, - No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, - Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, - Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, - Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'." }, - Remove_declaration_for_Colon_0: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_declaration_for_Colon_0_90004", message: "Remove declaration for: '{0}'." }, - Implement_interface_0: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_0_90006", message: "Implement interface '{0}'." }, - Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class." }, - Add_this_to_unresolved_variable: { code: 90008, category: ts.DiagnosticCategory.Message, key: "Add_this_to_unresolved_variable_90008", message: "Add 'this.' to unresolved variable." }, - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig." }, - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, - Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}." }, - Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}." }, - Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}." }, - Add_declaration_for_missing_property_0: { code: 90016, category: ts.DiagnosticCategory.Message, key: "Add_declaration_for_missing_property_0_90016", message: "Add declaration for missing property '{0}'." }, - Add_index_signature_for_missing_property_0: { code: 90017, category: ts.DiagnosticCategory.Message, key: "Add_index_signature_for_missing_property_0_90017", message: "Add index signature for missing property '{0}'." }, - Disable_checking_for_this_file: { code: 90018, category: ts.DiagnosticCategory.Message, key: "Disable_checking_for_this_file_90018", message: "Disable checking for this file." }, - 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." }, + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), + A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), + A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), + A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), + A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "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: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "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: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "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: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "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: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), + Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "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: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _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: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{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."), + 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), }; })(ts || (ts = {})); /// @@ -5135,13 +5277,20 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function computePositionOfLineAndCharacter(lineStarts, line, character) { + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { ts.Debug.assert(line >= 0 && line < lineStarts.length); - return lineStarts[line] + character; + var res = lineStarts[line] + character; + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res < debugText.length); + } + return res; } ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; /* @internal */ @@ -5236,6 +5385,7 @@ var ts; case 47 /* slash */: // starts of normal trivia case 60 /* lessThan */: + case 124 /* bar */: case 61 /* equals */: case 62 /* greaterThan */: // Starts of conflict marker trivia @@ -5302,6 +5452,7 @@ var ts; } break; case 60 /* lessThan */: + case 124 /* bar */: case 61 /* equals */: case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { @@ -5358,12 +5509,12 @@ var ts; } } else { - ts.Debug.assert(ch === 61 /* equals */); - // Consume everything from the start of the mid-conflict marker to the start of the next - // end-conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. while (pos < len) { - var ch_1 = text.charCodeAt(pos); - if (ch_1 === 62 /* greaterThan */ && isConflictMarkerTrivia(text, pos)) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { break; } pos++; @@ -6110,13 +6261,13 @@ var ts; pos += 2; var commentClosed = false; while (pos < end) { - var ch_2 = text.charCodeAt(pos); - if (ch_2 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; commentClosed = true; break; } - if (isLineBreak(ch_2)) { + if (isLineBreak(ch_1)) { precedingLineBreak = true; } pos++; @@ -6276,6 +6427,15 @@ var ts; pos++; return token = 17 /* OpenBraceToken */; case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } if (text.charCodeAt(pos + 1) === 124 /* bar */) { return pos += 2, token = 54 /* BarBarToken */; } @@ -6636,6 +6796,8 @@ var ts; /* @internal */ var ts; (function (ts) { + ts.emptyArray = []; + ts.emptyMap = ts.createMap(); ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -6663,51 +6825,51 @@ var ts; return undefined; } ts.findDeclaration = findDeclaration; - // Pool writers to avoid needing to allocate them for every symbol we write. - var stringWriters = []; - function getSingleLineStringWriter() { - if (stringWriters.length === 0) { - var str_1 = ""; - var writeText = function (text) { return str_1 += text; }; - return { - string: function () { return str_1; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - // Completely ignore indentation for string writers. And map newlines to - // a single space. - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { return str_1 = ""; }, - trackSymbol: ts.noop, - reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop - }; + var stringWriter = createSingleLineStringWriter(); + var stringWriterAcquired = false; + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + string: function () { return str; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function usingSingleLineStringWriter(action) { + try { + ts.Debug.assert(!stringWriterAcquired); + stringWriterAcquired = true; + action(stringWriter); + return stringWriter.string(); + } + finally { + stringWriter.clear(); + stringWriterAcquired = false; } - return stringWriters.pop(); } - ts.getSingleLineStringWriter = getSingleLineStringWriter; - function releaseStringWriter(writer) { - writer.clear(); - stringWriters.push(writer); - } - ts.releaseStringWriter = releaseStringWriter; + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; function getFullWidth(node) { return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText)); - } - ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { - return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined; + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); } ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { @@ -6863,17 +7025,13 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 142 /* LastToken */; - } - ts.isToken = isToken; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. if (nodeIsMissing(node)) { return node.pos; } - if (isJSDocNode(node)) { + if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { @@ -6883,20 +7041,12 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 294 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; - function isJSDocNode(node) { - return node.kind >= 267 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */; - } - ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 283 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -6925,13 +7075,21 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + /** + * Gets flags that control emit behavior of a node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -6956,8 +7114,16 @@ var ts; } ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * @deprecated Use `id.escapedText` to get the escaped text of an Identifier. + * @param identifier The identifier to escape + */ function escapeIdentifier(identifier) { - return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; + return identifier; } ts.escapeIdentifier = escapeIdentifier; // Make an identifier from an external module name by extracting the string after the last "/" and replacing @@ -6981,6 +7147,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + /* @internal */ + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; /** Given a symbol for a module, checks that it is a shorthand ambient module. */ function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); @@ -6993,7 +7164,7 @@ var ts; function isBlockScopedContainerTopLevel(node) { return node.kind === 265 /* SourceFile */ || node.kind === 233 /* ModuleDeclaration */ || - isFunctionLike(node); + ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { @@ -7040,7 +7211,7 @@ var ts; case 207 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block - return parentNode && !isFunctionLike(parentNode); + return parentNode && !ts.isFunctionLike(parentNode); } return false; } @@ -7071,13 +7242,13 @@ var ts; function getTextOfPropertyName(name) { switch (name.kind) { case 71 /* Identifier */: - return name.text; + return name.escapedText; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return name.text; + return escapeLeadingUnderscores(name.text); case 144 /* ComputedPropertyName */: if (isStringOrNumericLiteral(name.expression)) { - return name.expression.text; + return escapeLeadingUnderscores(name.expression.text); } } return undefined; @@ -7086,7 +7257,7 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71 /* Identifier */: - return getFullWidth(name) === 0 ? ts.unescapeIdentifier(name.text) : getTextOfNode(name); + return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); case 143 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); case 179 /* PropertyAccessExpression */: @@ -7200,6 +7371,10 @@ var ts; return n.kind === 181 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 181 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + } + ts.isImportCall = isImportCall; function isPrologueDirective(node) { return node.kind === 210 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; @@ -7217,7 +7392,8 @@ var ts; var commentRanges = (node.kind === 146 /* Parameter */ || node.kind === 145 /* TypeParameter */ || node.kind === 186 /* FunctionExpression */ || - node.kind === 187 /* ArrowFunction */) ? + node.kind === 187 /* ArrowFunction */ || + node.kind === 185 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); // True if the comment starts with '/**' but not if it is '/**/' @@ -7323,10 +7499,6 @@ var ts; return false; } ts.isChildOfNodeWithKind = isChildOfNodeWithKind; - function isPrefixUnaryExpression(node) { - return node.kind === 192 /* PrefixUnaryExpression */; - } - ts.isPrefixUnaryExpression = isPrefixUnaryExpression; // Warning: This has the same semantics as the forEach family of functions, // in that traversal terminates in the event that 'visitor' supplies a truthy value. function forEachReturnStatement(body, visitor) { @@ -7377,7 +7549,7 @@ var ts; // skipped in this traversal. return; default: - if (isFunctionLike(node)) { + if (ts.isFunctionLike(node)) { var name = node.name; if (name && name.kind === 144 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require @@ -7430,47 +7602,6 @@ var ts; return false; } ts.isVariableLike = isVariableLike; - function isAccessor(node) { - return node && (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */); - } - ts.isAccessor = isAccessor; - function isClassLike(node) { - return node && (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */); - } - ts.isClassLike = isClassLike; - function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); - } - ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { - switch (kind) { - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - return true; - } - 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 */: @@ -7485,20 +7616,6 @@ var ts; return false; } ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; - function isIterationStatement(node, lookInLabeledStatements) { - switch (node.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - return true; - case 222 /* LabeledStatement */: - return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); - } - return false; - } - ts.isIterationStatement = isIterationStatement; function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { while (true) { if (beforeUnwrapLabelCallback) { @@ -7512,7 +7629,7 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 207 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { @@ -7533,10 +7650,19 @@ var ts; return predicate && predicate.kind === 0 /* This */; } ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return ts.filter(objectLiteral.properties, function (property) { + if (property.kind === 261 /* PropertyAssignment */) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (key2 && key2 === propName); + } + }); + } + ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { while (true) { node = node.parent; - if (!node || isFunctionLike(node)) { + if (!node || ts.isFunctionLike(node)) { return node; } } @@ -7545,7 +7671,7 @@ var ts; function getContainingClass(node) { while (true) { node = node.parent; - if (!node || isClassLike(node)) { + if (!node || ts.isClassLike(node)) { return node; } } @@ -7563,7 +7689,7 @@ var ts; // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container // so that we can error on it. - if (isClassLike(node.parent.parent)) { + if (ts.isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -7575,12 +7701,12 @@ var ts; break; case 147 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. node = node.parent; @@ -7659,12 +7785,12 @@ var ts; return node; case 147 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. node = node.parent; @@ -7700,7 +7826,6 @@ var ts; function getEntityNameFromTypeNode(node) { switch (node.kind) { case 159 /* TypeReference */: - case 277 /* JSDocTypeReference */: return node.typeName; case 201 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) @@ -7713,29 +7838,11 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; - function isCallLikeExpression(node) { - switch (node.kind) { - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 183 /* TaggedTemplateExpression */: - case 147 /* Decorator */: - return true; - default: - return false; - } - } - 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; } - else if (isJsxOpeningLikeElement(node)) { + else if (ts.isJsxOpeningLikeElement(node)) { return node.tagName; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -7798,7 +7905,6 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: case 95 /* NullKeyword */: case 101 /* TrueKeyword */: @@ -7867,7 +7973,6 @@ var ts; case 221 /* SwitchStatement */: case 257 /* CaseClause */: case 223 /* ThrowStatement */: - case 221 /* SwitchStatement */: return parent.expression === node; case 214 /* ForStatement */: var forStatement = parent; @@ -7902,12 +8007,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isInstantiatedModule(node, preserveConstEnums) { - var moduleState = ts.getModuleInstanceState(node); - return moduleState === 1 /* Instantiated */ || - (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); - } - ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */; } @@ -7929,6 +8028,10 @@ var ts; return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJSDoc(node) { + return node && !!(node.flags & 1048576 /* JSDoc */); + } + ts.isInJSDoc = isInJSDoc; /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). @@ -7939,7 +8042,7 @@ var ts; return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 /* Identifier */ || expression.text !== "require") { + if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -7973,11 +8076,11 @@ var ts; } ts.getRightMostAssignedExpression = getRightMostAssignedExpression; function isExportsIdentifier(node) { - return isIdentifier(node) && node.text === "exports"; + return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; function isModuleExportsPropertyAccessExpression(node) { - return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports"; + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property @@ -7993,11 +8096,11 @@ var ts; var lhs = expr.left; if (lhs.expression.kind === 71 /* Identifier */) { var lhsId = lhs.expression; - if (lhsId.text === "exports") { + if (lhsId.escapedText === "exports") { // exports.name = expr return 1 /* ExportsProperty */; } - else if (lhsId.text === "module" && lhs.name.text === "exports") { + else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { // module.exports = expr return 2 /* ModuleExports */; } @@ -8015,10 +8118,10 @@ var ts; if (innerPropertyAccess.expression.kind === 71 /* Identifier */) { // module.exports.name = expr var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { + if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { return 1 /* ExportsProperty */; } - if (innerPropertyAccess.name.text === "prototype") { + if (innerPropertyAccess.name.escapedText === "prototype") { return 3 /* PrototypeProperty */; } } @@ -8077,52 +8180,41 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 279 /* JSDocFunctionType */ && + return node.kind === 273 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 281 /* JSDocConstructorType */; + node.parameters[0].name && + node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getCommentsFromJSDoc(node) { - return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); - } - ts.getCommentsFromJSDoc = getCommentsFromJSDoc; function hasJSDocParameterTags(node) { - var parameterTags = getJSDocTags(node, 286 /* JSDocParameterTag */); - return parameterTags && parameterTags.length > 0; + return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); } ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getJSDocTags(node, kind) { - var docs = getJSDocs(node); - if (docs) { - var result = []; - for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { - var doc = docs_1[_i]; - if (doc.kind === 286 /* JSDocParameterTag */) { - if (doc.kind === kind) { - result.push(doc); - } - } - else { - var tags = doc.tags; - if (tags) { - result.push.apply(result, ts.filter(tags, function (tag) { return tag.kind === kind; })); - } - } - } - return result; - } - } function getFirstJSDocTag(node, kind) { - return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); } - function getJSDocs(node) { - var cache = node.jsDocCache; - if (!cache) { - getJSDocsWorker(node); - node.jsDocCache = cache; + function getAllJSDocs(node) { + if (ts.isJSDocTypedefTag(node)) { + return [node.parent]; } - return cache; - function getJSDocsWorker(node) { + return getJSDocCommentsAndTags(node); + } + ts.getAllJSDocs = getAllJSDocs; + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getJSDocCommentsAndTags(node) { + var result; + getJSDocCommentsAndTagsWorker(node); + return result || ts.emptyArray; + function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. // /** @@ -8139,7 +8231,7 @@ var ts; isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - getJSDocsWorker(variableStatementNode); + getJSDocCommentsAndTagsWorker(variableStatementNode); } // Also recognize when the node is the RHS of an assignment expression var isSourceOfAssignmentExpressionStatement = parent && parent.parent && @@ -8147,52 +8239,61 @@ var ts; parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.kind === 210 /* ExpressionStatement */; if (isSourceOfAssignmentExpressionStatement) { - getJSDocsWorker(parent.parent); + getJSDocCommentsAndTagsWorker(parent.parent); } var isModuleDeclaration = node.kind === 233 /* ModuleDeclaration */ && parent && parent.kind === 233 /* ModuleDeclaration */; var isPropertyAssignmentExpression = parent && parent.kind === 261 /* PropertyAssignment */; if (isModuleDeclaration || isPropertyAssignmentExpression) { - getJSDocsWorker(parent); + getJSDocCommentsAndTagsWorker(parent); } // Pull parameter comments from declaring function as well if (node.kind === 146 /* Parameter */) { - cache = ts.concatenate(cache, getJSDocParameterTags(node)); + result = ts.addRange(result, getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer) { - cache = ts.concatenate(cache, node.initializer.jsDoc); + result = ts.addRange(result, node.initializer.jsDoc); } - cache = ts.concatenate(cache, node.jsDoc); + result = ts.addRange(result, node.jsDoc); } } - ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } - var func = param.parent; - var tags = getJSDocTags(func, 286 /* JSDocParameterTag */); - if (!param.name) { - // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification - var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 286 /* JSDocParameterTag */; }); - if (paramTags && 0 <= i && i < paramTags.length) { - return [paramTags[i]]; - } - } - else if (param.name.kind === 71 /* Identifier */) { - var name_1 = param.name.text; - return ts.filter(tags, function (tag) { return tag.kind === 286 /* JSDocParameterTag */ && tag.parameterName.text === name_1; }); - } - else { - // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines - // But multi-line object types aren't supported yet either - return undefined; + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); } + // a binding pattern doesn't have a name, so it's not possible to match it a jsdoc parameter, which is identified by name + return undefined; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + ts.Debug.assert(node.parent.kind === 275 /* JSDocComment */); + var func = node.parent.parent; + if (!ts.isFunctionLike(func)) { + return undefined; + } + var parameter = ts.find(func.parameters, function (p) { + return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; + }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 288 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); if (!tag && node.kind === 146 /* Parameter */) { var paramTags = getJSDocParameterTags(node); if (paramTags) { @@ -8203,15 +8304,24 @@ var ts; } ts.getJSDocType = getJSDocType; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278 /* JSDocClassTag */); + } + ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 287 /* JSDocReturnTag */); + return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 289 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { @@ -8223,9 +8333,9 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 65536 /* JavaScriptFile */)) { - if (node.type && node.type.kind === 280 /* JSDocVariadicType */ || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 280 /* JSDocVariadicType */; })) { + if (isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { return true; } } @@ -8327,46 +8437,33 @@ var ts; case 71 /* Identifier */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return isDeclaration(name.parent) && name.parent.name === name; + return ts.isDeclaration(name.parent) && name.parent.name === name; default: 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; + /* @internal */ + // See GH#16030 + function isAnyDeclarationName(name) { + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isDeclaration(name.parent)) { + return name.parent.name === name; + } + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + default: + return false; } } - ts.getNameOfDeclaration = getNameOfDeclaration; + ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && - isDeclaration(node.parent.parent); + ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; // Return true if the given identifier is classified as an IdentifierName @@ -8398,7 +8495,8 @@ var ts; // Property name in binding element or import specifier return parent.propertyName === node; case 246 /* ExportSpecifier */: - // Any name in an export specifier + case 253 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute return true; } return false; @@ -8556,10 +8654,6 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isNumericLiteral(node) { - return node.kind === 8 /* NumericLiteral */; - } - ts.isNumericLiteral = isNumericLiteral; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ @@ -8574,7 +8668,7 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - var name = getNameOfDeclaration(declaration); + var name = ts.getNameOfDeclaration(declaration); return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; @@ -8590,26 +8684,55 @@ var ts; * where Symbol is literally the word "Symbol", and name is any identifierName */ function isWellKnownSymbolSyntactically(node) { - return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 146 /* Parameter */) { - return name.text; + if (name.kind === 71 /* Identifier */) { + return name.escapedText; + } + if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { + return escapeLeadingUnderscores(name.text); } if (name.kind === 144 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.text; - return getPropertyNameForKnownSymbolName(rightHandSideName); + var rightHandSideName = nameExpression.name.escapedText; + return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); } else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { - return nameExpression.text; + return escapeLeadingUnderscores(nameExpression.text); } } return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71 /* Identifier */) { + return ts.unescapeLeadingUnderscores(node.escapedText); + } + if (node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { + return node.text; + } + } + return undefined; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71 /* Identifier */) { + return node.escapedText; + } + if (node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { + return escapeLeadingUnderscores(node.text); + } + } + return undefined; + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { return "__@" + symbolName; } @@ -8618,31 +8741,13 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 71 /* Identifier */ && node.text === "Symbol"; + return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { - return node.text === "push" || node.text === "unshift"; + return node.escapedText === "push" || node.escapedText === "unshift"; } ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; - function isModifierKind(token) { - switch (token) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 79 /* DefaultKeyword */: - case 84 /* ExportKeyword */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 131 /* ReadonlyKeyword */: - case 115 /* StaticKeyword */: - return true; - } - return false; - } - ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 146 /* Parameter */; @@ -8673,25 +8778,14 @@ var ts; || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266 /* Bundle */) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile)); - } - return getOriginalSourceFile(sourceFileOrBundle); - } - ts.getOriginalSourceFileOrBundle = getOriginalSourceFileOrBundle; function getOriginalSourceFile(sourceFile) { - return ts.getParseTreeNode(sourceFile, isSourceFile) || sourceFile; + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } + ts.getOriginalSourceFile = getOriginalSourceFile; function getOriginalSourceFiles(sourceFiles) { return ts.sameMap(sourceFiles, getOriginalSourceFile); } ts.getOriginalSourceFiles = getOriginalSourceFiles; - function getOriginalNodeId(node) { - node = ts.getOriginalNode(node); - return node ? ts.getNodeId(node) : 0; - } - ts.getOriginalNodeId = getOriginalNodeId; var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; @@ -8858,7 +8952,7 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: return 0; default: return -1; @@ -8963,6 +9057,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { + // An escaped identifier had a leading underscore prior to being escaped, which would return true + // The escape adds an extra underscore which does not change the result var ch = name.substr(0, 1); return ch.toLowerCase() === ch; } @@ -9105,7 +9201,7 @@ var ts; var path = outputDir ? getSourceFilePathInNewDir(sourceFile, host, outputDir) : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; /** @@ -9139,57 +9235,6 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - /** - * Iterates over the source files that are expected to have an emit output. - * - * @param host An EmitHost. - * @param action The action to execute. - * @param sourceFilesOrTargetSourceFile - * If an array, the full list of source files to emit. - * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. - */ - function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { - var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); - var options = host.getCompilerOptions(); - if (options.outFile || options.out) { - if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); - } - } - else { - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); - } - } - } - ts.forEachEmittedFile = forEachEmittedFile; - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } - // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. - // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. - // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve - function getOutputExtension(sourceFile, options) { - if (options.jsx === 1 /* Preserve */) { - if (isSourceFileJavaScript(sourceFile)) { - if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { - return ".jsx"; - } - } - else if (sourceFile.languageVariant === 1 /* JSX */) { - // TypeScript source file preserving JSX syntax - return ".jsx"; - } - } - return ".js"; - } function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); var commonSourceDirectory = host.getCommonSourceDirectory(); @@ -9220,13 +9265,17 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; - /** Get the type annotaion for the value parameter. */ - function getSetAccessorTypeAnnotationNode(accessor) { + function getSetAccessorValueParameter(accessor) { if (accessor && accessor.parameters.length > 0) { var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); - return accessor.parameters[hasThis ? 1 : 0].type; + return accessor.parameters[hasThis ? 1 : 0]; } } + /** Get the type annotation for the value parameter. */ + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { if (signature.parameters.length) { @@ -9297,6 +9346,55 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocType(node); + } + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocReturnType(node); + } + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (node.typeParameters) { + return node.typeParameters; + } + if (isInJavaScriptFile(node)) { + var templateTag = getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); } @@ -9502,6 +9600,13 @@ var ts; if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; + /* @internal */ + function getModifierFlagsNoCache(node) { var flags = 0 /* None */; if (node.modifiers) { for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { @@ -9512,10 +9617,9 @@ var ts; if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } - node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; return flags; } - ts.getModifierFlags = getModifierFlags; + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { case 115 /* StaticKeyword */: return 32 /* Static */; @@ -9547,17 +9651,17 @@ var ts; function tryGetClassExtendingExpressionWithTypeArguments(node) { if (node.kind === 201 /* ExpressionWithTypeArguments */ && node.parent.token === 85 /* ExtendsKeyword */ && - isClassLike(node.parent.parent)) { + ts.isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { - return isBinaryExpression(node) + return ts.isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 58 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) - && isLeftHandSideExpression(node.left); + && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { @@ -9579,7 +9683,7 @@ var ts; if (node.kind === 71 /* Identifier */) { return true; } - else if (isPropertyAccessExpression(node)) { + else if (ts.isPropertyAccessExpression(node)) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -9596,7 +9700,7 @@ var ts; && node.parent && node.parent.token === 108 /* ImplementsKeyword */ && node.parent.parent - && isClassLike(node.parent.parent); + && ts.isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { @@ -9620,11 +9724,11 @@ var ts; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined; + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isExportDefaultSymbol(symbol) { - return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */); + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { @@ -9784,27 +9888,77 @@ var ts; } return false; } - var syntaxKindCache = []; - function formatSyntaxKind(kind) { - var syntaxKindEnum = ts.SyntaxKind; - if (syntaxKindEnum) { - var cached = syntaxKindCache[kind]; - if (cached !== undefined) { - return cached; - } - for (var name in syntaxKindEnum) { - if (syntaxKindEnum[name] === kind) { - var result = kind + " (" + name + ")"; - syntaxKindCache[kind] = result; - return result; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; } } + if (remainingFlags === 0) { + return result; + } } else { - return kind.toString(); + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); + } + ts.formatObjectFlags = formatObjectFlags; function getRangePos(range) { return range ? range.pos : -1; } @@ -9987,675 +10141,13 @@ var ts; return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; } ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; - // Node tests - // - // All node tests in the following list should *not* reference parent pointers so that - // they may be used with transformations. - // Node Arrays - function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); - } - ts.isNodeArray = isNodeArray; - // Literals - function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13 /* NoSubstitutionTemplateLiteral */; - } - ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; - function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 /* StringLiteral */ || kind === 13 /* NoSubstitutionTemplateLiteral */; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isLiteralExpression(node) { - return isLiteralKind(node.kind); - } - ts.isLiteralExpression = isLiteralExpression; - // Pseudo-literals - function isTemplateLiteralKind(kind) { - return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateHead(node) { - return node.kind === 14 /* TemplateHead */; - } - ts.isTemplateHead = isTemplateHead; - function isTemplateMiddleOrTemplateTail(node) { - var kind = node.kind; - return kind === 15 /* TemplateMiddle */ - || kind === 16 /* TemplateTail */; - } - ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; - // Identifiers - function isIdentifier(node) { - return node.kind === 71 /* Identifier */; - } - ts.isIdentifier = isIdentifier; - function isGeneratedIdentifier(node) { - // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; - } - ts.isGeneratedIdentifier = isGeneratedIdentifier; - // Keywords - function isModifier(node) { - return isModifierKind(node.kind); - } - ts.isModifier = isModifier; - // Names - function isQualifiedName(node) { - return node.kind === 143 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 144 /* ComputedPropertyName */; - } - ts.isComputedPropertyName = isComputedPropertyName; - function isEntityName(node) { - var kind = node.kind; - return kind === 143 /* QualifiedName */ - || kind === 71 /* Identifier */; - } - ts.isEntityName = isEntityName; - function isPropertyName(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 144 /* ComputedPropertyName */; - } - ts.isPropertyName = isPropertyName; - function isModuleName(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */; - } - ts.isModuleName = isModuleName; - function isBindingName(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 174 /* ObjectBindingPattern */ - || kind === 175 /* ArrayBindingPattern */; - } - ts.isBindingName = isBindingName; - // Signature elements - function isTypeParameter(node) { - return node.kind === 145 /* TypeParameter */; - } - ts.isTypeParameter = isTypeParameter; - function isParameter(node) { - return node.kind === 146 /* Parameter */; - } - ts.isParameter = isParameter; - function isDecorator(node) { - return node.kind === 147 /* Decorator */; - } - ts.isDecorator = isDecorator; - // Type members - function isMethodDeclaration(node) { - return node.kind === 151 /* MethodDeclaration */; - } - ts.isMethodDeclaration = isMethodDeclaration; - function isClassElement(node) { - var kind = node.kind; - return kind === 152 /* Constructor */ - || kind === 149 /* PropertyDeclaration */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 157 /* IndexSignature */ - || 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 */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 263 /* SpreadAssignment */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 247 /* MissingDeclaration */; - } - ts.isObjectLiteralElementLike = isObjectLiteralElementLike; - // Type - function isTypeNodeKind(kind) { - return (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) - || kind === 119 /* AnyKeyword */ - || kind === 133 /* NumberKeyword */ - || kind === 134 /* ObjectKeyword */ - || kind === 122 /* BooleanKeyword */ - || kind === 136 /* StringKeyword */ - || kind === 137 /* SymbolKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 105 /* VoidKeyword */ - || kind === 139 /* UndefinedKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 130 /* NeverKeyword */ - || kind === 201 /* ExpressionWithTypeArguments */; - } - /** - * Node test that determines whether a node is a valid type node. - * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* - * of a TypeNode. - */ - function isTypeNode(node) { - return isTypeNodeKind(node.kind); - } - ts.isTypeNode = isTypeNode; - // Binding patterns - function isArrayBindingPattern(node) { - return node.kind === 175 /* ArrayBindingPattern */; - } - ts.isArrayBindingPattern = isArrayBindingPattern; - function isObjectBindingPattern(node) { - return node.kind === 174 /* ObjectBindingPattern */; - } - ts.isObjectBindingPattern = isObjectBindingPattern; - function isBindingPattern(node) { - if (node) { - var kind = node.kind; - return kind === 175 /* ArrayBindingPattern */ - || kind === 174 /* ObjectBindingPattern */; - } - return false; - } - ts.isBindingPattern = isBindingPattern; - function isAssignmentPattern(node) { - var kind = node.kind; - return kind === 177 /* ArrayLiteralExpression */ - || kind === 178 /* ObjectLiteralExpression */; - } - ts.isAssignmentPattern = isAssignmentPattern; - function isBindingElement(node) { - return node.kind === 176 /* BindingElement */; - } - ts.isBindingElement = isBindingElement; - function isArrayBindingElement(node) { - var kind = node.kind; - return kind === 176 /* BindingElement */ - || kind === 200 /* OmittedExpression */; - } - ts.isArrayBindingElement = isArrayBindingElement; - /** - * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration - */ - function isDeclarationBindingElement(bindingElement) { - switch (bindingElement.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 176 /* BindingElement */: - return true; - } - return false; - } - ts.isDeclarationBindingElement = isDeclarationBindingElement; - /** - * Determines whether a node is a BindingOrAssignmentPattern - */ - function isBindingOrAssignmentPattern(node) { - return isObjectBindingOrAssignmentPattern(node) - || isArrayBindingOrAssignmentPattern(node); - } - ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; - /** - * Determines whether a node is an ObjectBindingOrAssignmentPattern - */ - function isObjectBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 174 /* ObjectBindingPattern */: - case 178 /* ObjectLiteralExpression */: - return true; - } - return false; - } - ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; - /** - * Determines whether a node is an ArrayBindingOrAssignmentPattern - */ - function isArrayBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: - return true; - } - return false; - } - ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; - // Expression - function isArrayLiteralExpression(node) { - return node.kind === 177 /* ArrayLiteralExpression */; - } - ts.isArrayLiteralExpression = isArrayLiteralExpression; - function isObjectLiteralExpression(node) { - return node.kind === 178 /* ObjectLiteralExpression */; - } - ts.isObjectLiteralExpression = isObjectLiteralExpression; - function isPropertyAccessExpression(node) { - return node.kind === 179 /* PropertyAccessExpression */; - } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isPropertyAccessOrQualifiedName(node) { - var kind = node.kind; - return kind === 179 /* PropertyAccessExpression */ - || kind === 143 /* QualifiedName */; - } - ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; - function isElementAccessExpression(node) { - return node.kind === 180 /* ElementAccessExpression */; - } - ts.isElementAccessExpression = isElementAccessExpression; - function isBinaryExpression(node) { - return node.kind === 194 /* BinaryExpression */; - } - ts.isBinaryExpression = isBinaryExpression; - function isConditionalExpression(node) { - return node.kind === 195 /* ConditionalExpression */; - } - ts.isConditionalExpression = isConditionalExpression; - function isCallExpression(node) { - return node.kind === 181 /* CallExpression */; - } - ts.isCallExpression = isCallExpression; - function isTemplateLiteral(node) { - var kind = node.kind; - return kind === 196 /* TemplateExpression */ - || kind === 13 /* NoSubstitutionTemplateLiteral */; - } - ts.isTemplateLiteral = isTemplateLiteral; - function isSpreadExpression(node) { - return node.kind === 198 /* SpreadElement */; - } - ts.isSpreadExpression = isSpreadExpression; - function isExpressionWithTypeArguments(node) { - return node.kind === 201 /* ExpressionWithTypeArguments */; - } - ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 /* PropertyAccessExpression */ - || kind === 180 /* ElementAccessExpression */ - || kind === 182 /* NewExpression */ - || kind === 181 /* CallExpression */ - || kind === 249 /* JsxElement */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 183 /* TaggedTemplateExpression */ - || kind === 177 /* ArrayLiteralExpression */ - || kind === 185 /* ParenthesizedExpression */ - || kind === 178 /* ObjectLiteralExpression */ - || kind === 199 /* ClassExpression */ - || kind === 186 /* FunctionExpression */ - || kind === 71 /* Identifier */ - || kind === 12 /* RegularExpressionLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 9 /* StringLiteral */ - || kind === 13 /* NoSubstitutionTemplateLiteral */ - || kind === 196 /* TemplateExpression */ - || kind === 86 /* FalseKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 101 /* TrueKeyword */ - || kind === 97 /* SuperKeyword */ - || kind === 203 /* NonNullExpression */ - || kind === 204 /* MetaProperty */; - } - function isLeftHandSideExpression(node) { - return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 /* PrefixUnaryExpression */ - || kind === 193 /* PostfixUnaryExpression */ - || kind === 188 /* DeleteExpression */ - || kind === 189 /* TypeOfExpression */ - || kind === 190 /* VoidExpression */ - || kind === 191 /* AwaitExpression */ - || kind === 184 /* TypeAssertionExpression */ - || isLeftHandSideExpressionKind(kind); - } - function isUnaryExpression(node) { - return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isUnaryExpression = isUnaryExpression; - function isExpressionKind(kind) { - return kind === 195 /* ConditionalExpression */ - || kind === 197 /* YieldExpression */ - || kind === 187 /* ArrowFunction */ - || kind === 194 /* BinaryExpression */ - || kind === 198 /* SpreadElement */ - || kind === 202 /* AsExpression */ - || kind === 200 /* OmittedExpression */ - || kind === 297 /* CommaListExpression */ - || isUnaryExpressionKind(kind); - } - function isExpression(node) { - return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isExpression = isExpression; - function isAssertionExpression(node) { - var kind = node.kind; - return kind === 184 /* TypeAssertionExpression */ - || kind === 202 /* AsExpression */; - } - ts.isAssertionExpression = isAssertionExpression; - function isPartiallyEmittedExpression(node) { - return node.kind === 296 /* PartiallyEmittedExpression */; - } - ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; - function isNotEmittedStatement(node) { - return node.kind === 295 /* NotEmittedStatement */; - } - ts.isNotEmittedStatement = isNotEmittedStatement; - function isNotEmittedOrPartiallyEmittedNode(node) { - return isNotEmittedStatement(node) - || isPartiallyEmittedExpression(node); - } - ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - function isOmittedExpression(node) { - return node.kind === 200 /* OmittedExpression */; - } - ts.isOmittedExpression = isOmittedExpression; - // Misc - function isTemplateSpan(node) { - return node.kind === 205 /* TemplateSpan */; - } - ts.isTemplateSpan = isTemplateSpan; - // Element - function isBlock(node) { - return node.kind === 207 /* Block */; - } - ts.isBlock = isBlock; - function isConciseBody(node) { - return isBlock(node) - || isExpression(node); - } - ts.isConciseBody = isConciseBody; - function isFunctionBody(node) { - return isBlock(node); - } - ts.isFunctionBody = isFunctionBody; - function isForInitializer(node) { - return isVariableDeclarationList(node) - || isExpression(node); - } - ts.isForInitializer = isForInitializer; - function isVariableDeclaration(node) { - return node.kind === 226 /* VariableDeclaration */; - } - ts.isVariableDeclaration = isVariableDeclaration; - function isVariableDeclarationList(node) { - return node.kind === 227 /* VariableDeclarationList */; - } - ts.isVariableDeclarationList = isVariableDeclarationList; - function isCaseBlock(node) { - return node.kind === 235 /* CaseBlock */; - } - ts.isCaseBlock = isCaseBlock; - function isModuleBody(node) { - var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */ - || kind === 71 /* Identifier */; - } - ts.isModuleBody = isModuleBody; - function isNamespaceBody(node) { - var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */; - } - ts.isNamespaceBody = isNamespaceBody; - function isJSDocNamespaceBody(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 233 /* ModuleDeclaration */; - } - ts.isJSDocNamespaceBody = isJSDocNamespaceBody; - function isImportEqualsDeclaration(node) { - 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 */; - } - ts.isImportClause = isImportClause; - function isNamedImportBindings(node) { - var kind = node.kind; - return kind === 241 /* NamedImports */ - || kind === 240 /* NamespaceImport */; - } - ts.isNamedImportBindings = isNamedImportBindings; - function isImportSpecifier(node) { - return node.kind === 242 /* ImportSpecifier */; - } - ts.isImportSpecifier = isImportSpecifier; - function isNamedExports(node) { - return node.kind === 245 /* NamedExports */; - } - ts.isNamedExports = isNamedExports; - function isExportSpecifier(node) { - 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 */; - } - ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; - function isDeclarationKind(kind) { - return kind === 187 /* ArrowFunction */ - || kind === 176 /* BindingElement */ - || kind === 229 /* ClassDeclaration */ - || kind === 199 /* ClassExpression */ - || kind === 152 /* Constructor */ - || kind === 232 /* EnumDeclaration */ - || kind === 264 /* EnumMember */ - || kind === 246 /* ExportSpecifier */ - || kind === 228 /* FunctionDeclaration */ - || kind === 186 /* FunctionExpression */ - || kind === 153 /* GetAccessor */ - || kind === 239 /* ImportClause */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 242 /* ImportSpecifier */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 253 /* JsxAttribute */ - || kind === 151 /* MethodDeclaration */ - || kind === 150 /* MethodSignature */ - || kind === 233 /* ModuleDeclaration */ - || kind === 236 /* NamespaceExportDeclaration */ - || kind === 240 /* NamespaceImport */ - || kind === 146 /* Parameter */ - || kind === 261 /* PropertyAssignment */ - || kind === 149 /* PropertyDeclaration */ - || kind === 148 /* PropertySignature */ - || kind === 154 /* SetAccessor */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 145 /* TypeParameter */ - || kind === 226 /* VariableDeclaration */ - || kind === 290 /* JSDocTypedefTag */; - } - function isDeclarationStatementKind(kind) { - return kind === 228 /* FunctionDeclaration */ - || kind === 247 /* MissingDeclaration */ - || kind === 229 /* ClassDeclaration */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 232 /* EnumDeclaration */ - || kind === 233 /* ModuleDeclaration */ - || kind === 238 /* ImportDeclaration */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 244 /* ExportDeclaration */ - || kind === 243 /* ExportAssignment */ - || kind === 236 /* NamespaceExportDeclaration */; - } - function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 /* BreakStatement */ - || kind === 217 /* ContinueStatement */ - || kind === 225 /* DebuggerStatement */ - || kind === 212 /* DoStatement */ - || kind === 210 /* ExpressionStatement */ - || kind === 209 /* EmptyStatement */ - || kind === 215 /* ForInStatement */ - || kind === 216 /* ForOfStatement */ - || kind === 214 /* ForStatement */ - || kind === 211 /* IfStatement */ - || kind === 222 /* LabeledStatement */ - || kind === 219 /* ReturnStatement */ - || kind === 221 /* SwitchStatement */ - || kind === 223 /* ThrowStatement */ - || kind === 224 /* TryStatement */ - || kind === 208 /* VariableStatement */ - || kind === 213 /* WhileStatement */ - || kind === 220 /* WithStatement */ - || kind === 295 /* NotEmittedStatement */ - || kind === 299 /* EndOfDeclarationMarker */ - || kind === 298 /* MergeDeclarationMarker */; - } - function isDeclaration(node) { - return isDeclarationKind(node.kind); - } - ts.isDeclaration = isDeclaration; - function isDeclarationStatement(node) { - return isDeclarationStatementKind(node.kind); - } - ts.isDeclarationStatement = isDeclarationStatement; - /** - * Determines whether the node is a statement that is not also a declaration - */ - function isStatementButNotDeclaration(node) { - return isStatementKindButNotDeclarationKind(node.kind); - } - ts.isStatementButNotDeclaration = isStatementButNotDeclaration; - function isStatement(node) { - var kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) - || isDeclarationStatementKind(kind) - || kind === 207 /* Block */; - } - ts.isStatement = isStatement; - // Module references - function isModuleReference(node) { - var kind = node.kind; - return kind === 248 /* ExternalModuleReference */ - || kind === 143 /* QualifiedName */ - || kind === 71 /* Identifier */; - } - ts.isModuleReference = isModuleReference; - // JSX - function isJsxOpeningElement(node) { - return node.kind === 251 /* JsxOpeningElement */; - } - ts.isJsxOpeningElement = isJsxOpeningElement; - function isJsxClosingElement(node) { - return node.kind === 252 /* JsxClosingElement */; - } - ts.isJsxClosingElement = isJsxClosingElement; - function isJsxTagNameExpression(node) { - var kind = node.kind; - return kind === 99 /* ThisKeyword */ - || kind === 71 /* Identifier */ - || kind === 179 /* PropertyAccessExpression */; - } - ts.isJsxTagNameExpression = isJsxTagNameExpression; - function isJsxChild(node) { - var kind = node.kind; - return kind === 249 /* JsxElement */ - || kind === 256 /* JsxExpression */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */; - } - ts.isJsxChild = isJsxChild; - function isJsxAttributes(node) { - var kind = node.kind; - return kind === 254 /* JsxAttributes */; - } - ts.isJsxAttributes = isJsxAttributes; - function isJsxAttributeLike(node) { - var kind = node.kind; - return kind === 253 /* JsxAttribute */ - || kind === 255 /* JsxSpreadAttribute */; - } - ts.isJsxAttributeLike = isJsxAttributeLike; - function isJsxSpreadAttribute(node) { - return node.kind === 255 /* JsxSpreadAttribute */; - } - ts.isJsxSpreadAttribute = isJsxSpreadAttribute; - function isJsxAttribute(node) { - return node.kind === 253 /* JsxAttribute */; - } - ts.isJsxAttribute = isJsxAttribute; - function isStringLiteralOrJsxExpression(node) { - var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 256 /* JsxExpression */; - } - ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; - function isJsxOpeningLikeElement(node) { - var kind = node.kind; - return kind === 251 /* JsxOpeningElement */ - || kind === 250 /* JsxSelfClosingElement */; - } - ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; - // Clauses - function isCaseOrDefaultClause(node) { - var kind = node.kind; - return kind === 257 /* CaseClause */ - || kind === 258 /* DefaultClause */; - } - ts.isCaseOrDefaultClause = isCaseOrDefaultClause; - function isHeritageClause(node) { - return node.kind === 259 /* HeritageClause */; - } - ts.isHeritageClause = isHeritageClause; - function isCatchClause(node) { - return node.kind === 260 /* CatchClause */; - } - ts.isCatchClause = isCatchClause; - // Property assignments - function isPropertyAssignment(node) { - return node.kind === 261 /* PropertyAssignment */; - } - ts.isPropertyAssignment = isPropertyAssignment; - function isShorthandPropertyAssignment(node) { - return node.kind === 262 /* ShorthandPropertyAssignment */; - } - ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; - // Enum - function isEnumMember(node) { - return node.kind === 264 /* EnumMember */; - } - ts.isEnumMember = isEnumMember; - // Top-level nodes - function isSourceFile(node) { - return node.kind === 265 /* SourceFile */; - } - ts.isSourceFile = isSourceFile; function isWatchSet(options) { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; function getDeclarationModifierFlagsFromSymbol(s) { @@ -10671,7 +10163,7 @@ var ts; var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } - if (s.flags & 16777216 /* Prototype */) { + if (s.flags & 4194304 /* Prototype */) { return 4 /* Public */ | 32 /* Static */; } return 0; @@ -10697,6 +10189,15 @@ var ts; return previous[previous.length - 1]; } ts.levenshtein = levenshtein; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11067,10 +10568,34762 @@ var ts; * @param identifier The escaped identifier text. * @returns The unescaped identifier text. */ - function unescapeIdentifier(identifier) { - return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier; + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + /** + * Remove extra underscore from escaped identifier text content. + * @deprecated Use `id.text` for the unescaped text. + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeIdentifier(id) { + return id; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143 /* QualifiedName */) { + return declaration.name.right; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; +})(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. +(function (ts) { + // Literals + function isNumericLiteral(node) { + return node.kind === 8 /* NumericLiteral */; + } + ts.isNumericLiteral = isNumericLiteral; + function isStringLiteral(node) { + return node.kind === 9 /* StringLiteral */; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 10 /* JsxText */; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 12 /* RegularExpressionLiteral */; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 13 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals + function isTemplateHead(node) { + return node.kind === 14 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 15 /* TemplateMiddle */; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 16 /* TemplateTail */; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 71 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + // Names + function isQualifiedName(node) { + return node.kind === 143 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 144 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements + function isTypeParameterDeclaration(node) { + return node.kind === 145 /* TypeParameter */; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 146 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 147 /* Decorator */; + } + ts.isDecorator = isDecorator; + // TypeMember + function isPropertySignature(node) { + return node.kind === 148 /* PropertySignature */; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 149 /* PropertyDeclaration */; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 150 /* MethodSignature */; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 151 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 152 /* Constructor */; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 153 /* GetAccessor */; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 154 /* SetAccessor */; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 155 /* CallSignature */; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 156 /* ConstructSignature */; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 157 /* IndexSignature */; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + // Type + function isTypePredicateNode(node) { + return node.kind === 158 /* TypePredicate */; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 159 /* TypeReference */; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 160 /* FunctionType */; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 161 /* ConstructorType */; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 162 /* TypeQuery */; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 163 /* TypeLiteral */; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 164 /* ArrayType */; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 165 /* TupleType */; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 166 /* UnionType */; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 167 /* IntersectionType */; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 168 /* ParenthesizedType */; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 169 /* ThisType */; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 170 /* TypeOperator */; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 171 /* IndexedAccessType */; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 172 /* MappedType */; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 173 /* LiteralType */; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + // Binding patterns + function isObjectBindingPattern(node) { + return node.kind === 174 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 175 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 176 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + // Expression + function isArrayLiteralExpression(node) { + return node.kind === 177 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 178 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 179 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 180 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 181 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 182 /* NewExpression */; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 183 /* TaggedTemplateExpression */; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 184 /* TypeAssertionExpression */; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 185 /* ParenthesizedExpression */; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 186 /* FunctionExpression */; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 187 /* ArrowFunction */; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 188 /* DeleteExpression */; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 191 /* AwaitExpression */; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 190 /* VoidExpression */; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 191 /* AwaitExpression */; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 192 /* PrefixUnaryExpression */; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 193 /* PostfixUnaryExpression */; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 194 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 195 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 196 /* TemplateExpression */; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 197 /* YieldExpression */; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 198 /* SpreadElement */; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 199 /* ClassExpression */; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 200 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 201 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 202 /* AsExpression */; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 203 /* NonNullExpression */; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 204 /* MetaProperty */; + } + ts.isMetaProperty = isMetaProperty; + // Misc + function isTemplateSpan(node) { + return node.kind === 205 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 206 /* SemicolonClassElement */; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + // Block + function isBlock(node) { + return node.kind === 207 /* Block */; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 208 /* VariableStatement */; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 209 /* EmptyStatement */; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 210 /* ExpressionStatement */; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 211 /* IfStatement */; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 212 /* DoStatement */; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 213 /* WhileStatement */; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 214 /* ForStatement */; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 215 /* ForInStatement */; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 216 /* ForOfStatement */; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 217 /* ContinueStatement */; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 218 /* BreakStatement */; + } + ts.isBreakStatement = isBreakStatement; + function isReturnStatement(node) { + return node.kind === 219 /* ReturnStatement */; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 220 /* WithStatement */; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 221 /* SwitchStatement */; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 222 /* LabeledStatement */; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 223 /* ThrowStatement */; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 224 /* TryStatement */; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 225 /* DebuggerStatement */; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 226 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 227 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 228 /* FunctionDeclaration */; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 229 /* ClassDeclaration */; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 230 /* InterfaceDeclaration */; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 231 /* TypeAliasDeclaration */; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 232 /* EnumDeclaration */; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 233 /* ModuleDeclaration */; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 234 /* ModuleBlock */; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 235 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 236 /* NamespaceExportDeclaration */; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + 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 */; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 240 /* NamespaceImport */; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 241 /* NamedImports */; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 242 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 244 /* ExportDeclaration */; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 245 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 246 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 247 /* MissingDeclaration */; + } + ts.isMissingDeclaration = isMissingDeclaration; + // Module References + function isExternalModuleReference(node) { + return node.kind === 248 /* ExternalModuleReference */; + } + ts.isExternalModuleReference = isExternalModuleReference; + // JSX + function isJsxElement(node) { + return node.kind === 249 /* JsxElement */; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 250 /* JsxSelfClosingElement */; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 251 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 252 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxAttribute(node) { + return node.kind === 253 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 254 /* JsxAttributes */; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 255 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 256 /* JsxExpression */; + } + ts.isJsxExpression = isJsxExpression; + // Clauses + function isCaseClause(node) { + return node.kind === 257 /* CaseClause */; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 258 /* DefaultClause */; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 259 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 260 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 261 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 262 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 263 /* SpreadAssignment */; + } + ts.isSpreadAssignment = isSpreadAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 264 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 265 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 266 /* Bundle */; + } + ts.isBundle = isBundle; + // JSDoc + function isJSDocTypeExpression(node) { + return node.kind === 267 /* JSDocTypeExpression */; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 268 /* JSDocAllType */; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 269 /* JSDocUnknownType */; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 270 /* JSDocNullableType */; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 271 /* JSDocNonNullableType */; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 272 /* JSDocOptionalType */; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 273 /* JSDocFunctionType */; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 274 /* JSDocVariadicType */; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 275 /* JSDocComment */; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 277 /* JSDocAugmentsTag */; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocParameterTag(node) { + return node.kind === 279 /* JSDocParameterTag */; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 280 /* JSDocReturnTag */; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 281 /* JSDocTypeTag */; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 282 /* JSDocTemplateTag */; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 283 /* JSDocTypedefTag */; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 284 /* JSDocPropertyTag */; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 284 /* JSDocPropertyTag */ || node.kind === 279 /* JSDocParameterTag */; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 285 /* JSDocTypeLiteral */; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; +})(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. +(function (ts) { + /* @internal */ + function isSyntaxList(n) { + return n.kind === 286 /* SyntaxList */; + } + ts.isSyntaxList = isSyntaxList; + /* @internal */ + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + /* @internal */ + function isNodeKind(kind) { + return kind >= 143 /* FirstNode */; + } + ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + */ + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 142 /* LastToken */; + } + ts.isToken = isToken; + // Node Arrays + /* @internal */ + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ + function isTemplateLiteralKind(kind) { + return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 15 /* TemplateMiddle */ + || kind === 16 /* TemplateTail */; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isStringTextContainingNode(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + case 13 /* NoSubstitutionTemplateLiteral */: + return true; + default: + return false; + } + } + ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ + function isGeneratedIdentifier(node) { + // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. + return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ + function isModifierKind(token) { + switch (token) { + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 79 /* DefaultKeyword */: + case 84 /* ExportKeyword */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 115 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 143 /* QualifiedName */ + || kind === 71 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 71 /* Identifier */ + || kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 144 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 71 /* Identifier */ + || kind === 174 /* ObjectBindingPattern */ + || kind === 175 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Functions + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 152 /* Constructor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 160 /* FunctionType */: + case 273 /* JSDocFunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionLikeKind = isFunctionLikeKind; + // Classes + function isClassElement(node) { + var kind = node.kind; + return kind === 152 /* Constructor */ + || kind === 149 /* PropertyDeclaration */ + || kind === 151 /* MethodDeclaration */ + || kind === 153 /* GetAccessor */ + || kind === 154 /* SetAccessor */ + || kind === 157 /* IndexSignature */ + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + // Type members + 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 */ + || kind === 262 /* ShorthandPropertyAssignment */ + || kind === 263 /* SpreadAssignment */ + || kind === 151 /* MethodDeclaration */ + || kind === 153 /* GetAccessor */ + || kind === 154 /* SetAccessor */ + || kind === 247 /* MissingDeclaration */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + function isTypeNodeKind(kind) { + return (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) + || kind === 119 /* AnyKeyword */ + || kind === 133 /* NumberKeyword */ + || kind === 134 /* ObjectKeyword */ + || kind === 122 /* BooleanKeyword */ + || kind === 136 /* StringKeyword */ + || kind === 137 /* SymbolKeyword */ + || kind === 99 /* ThisKeyword */ + || kind === 105 /* VoidKeyword */ + || kind === 139 /* UndefinedKeyword */ + || kind === 95 /* NullKeyword */ + || kind === 130 /* NeverKeyword */ + || kind === 201 /* ExpressionWithTypeArguments */; + } + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 175 /* ArrayBindingPattern */ + || kind === 174 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + /* @internal */ + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 177 /* ArrayLiteralExpression */ + || kind === 178 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 176 /* BindingElement */ + || kind === 200 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 226 /* VariableDeclaration */: + case 146 /* Parameter */: + case 176 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 174 /* ObjectBindingPattern */: + case 178 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 175 /* ArrayBindingPattern */: + case 177 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + // Expression + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 179 /* PropertyAccessExpression */ + || kind === 143 /* QualifiedName */; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 251 /* JsxOpeningElement */: + case 250 /* JsxSelfClosingElement */: + case 181 /* CallExpression */: + case 182 /* NewExpression */: + case 183 /* TaggedTemplateExpression */: + case 147 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 196 /* TemplateExpression */ + || kind === 13 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplateLiteral = isTemplateLiteral; + function isLeftHandSideExpressionKind(kind) { + return kind === 179 /* PropertyAccessExpression */ + || kind === 180 /* ElementAccessExpression */ + || kind === 182 /* NewExpression */ + || kind === 181 /* CallExpression */ + || kind === 249 /* JsxElement */ + || kind === 250 /* JsxSelfClosingElement */ + || kind === 183 /* TaggedTemplateExpression */ + || kind === 177 /* ArrayLiteralExpression */ + || kind === 185 /* ParenthesizedExpression */ + || kind === 178 /* ObjectLiteralExpression */ + || kind === 199 /* ClassExpression */ + || kind === 186 /* FunctionExpression */ + || kind === 71 /* Identifier */ + || kind === 12 /* RegularExpressionLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 9 /* StringLiteral */ + || kind === 13 /* NoSubstitutionTemplateLiteral */ + || kind === 196 /* TemplateExpression */ + || kind === 86 /* FalseKeyword */ + || kind === 95 /* NullKeyword */ + || kind === 99 /* ThisKeyword */ + || kind === 101 /* TrueKeyword */ + || kind === 97 /* SuperKeyword */ + || kind === 91 /* ImportKeyword */ + || kind === 203 /* NonNullExpression */ + || kind === 204 /* MetaProperty */; + } + /* @internal */ + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 192 /* PrefixUnaryExpression */ + || kind === 193 /* PostfixUnaryExpression */ + || kind === 188 /* DeleteExpression */ + || kind === 189 /* TypeOfExpression */ + || kind === 190 /* VoidExpression */ + || kind === 191 /* AwaitExpression */ + || kind === 184 /* TypeAssertionExpression */ + || isLeftHandSideExpressionKind(kind); + } + /* @internal */ + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 195 /* ConditionalExpression */ + || kind === 197 /* YieldExpression */ + || kind === 187 /* ArrowFunction */ + || kind === 194 /* BinaryExpression */ + || kind === 198 /* SpreadElement */ + || kind === 202 /* AsExpression */ + || kind === 200 /* OmittedExpression */ + || kind === 289 /* CommaListExpression */ + || isUnaryExpressionKind(kind); + } + /* @internal */ + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 184 /* TypeAssertionExpression */ + || kind === 202 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + /* @internal */ + function isPartiallyEmittedExpression(node) { + return node.kind === 288 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ + function isNotEmittedStatement(node) { + return node.kind === 287 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + // Statement + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + return true; + case 222 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + /* @internal */ + function isForInOrOfStatement(node) { + return node.kind === 215 /* ForInStatement */ || node.kind === 216 /* ForOfStatement */; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + /* @internal */ + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + /* @internal */ + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + /* @internal */ + function isModuleBody(node) { + var kind = node.kind; + return kind === 234 /* ModuleBlock */ + || kind === 233 /* ModuleDeclaration */ + || kind === 71 /* Identifier */; + } + ts.isModuleBody = isModuleBody; + /* @internal */ + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 234 /* ModuleBlock */ + || kind === 233 /* ModuleDeclaration */; + } + ts.isNamespaceBody = isNamespaceBody; + /* @internal */ + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 71 /* Identifier */ + || kind === 233 /* ModuleDeclaration */; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 241 /* NamedImports */ + || kind === 240 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ + function isModuleOrEnumDeclaration(node) { + return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 187 /* ArrowFunction */ + || kind === 176 /* BindingElement */ + || kind === 229 /* ClassDeclaration */ + || kind === 199 /* ClassExpression */ + || kind === 152 /* Constructor */ + || kind === 232 /* EnumDeclaration */ + || kind === 264 /* EnumMember */ + || kind === 246 /* ExportSpecifier */ + || kind === 228 /* FunctionDeclaration */ + || kind === 186 /* FunctionExpression */ + || kind === 153 /* GetAccessor */ + || kind === 239 /* ImportClause */ + || kind === 237 /* ImportEqualsDeclaration */ + || kind === 242 /* ImportSpecifier */ + || kind === 230 /* InterfaceDeclaration */ + || kind === 253 /* JsxAttribute */ + || kind === 151 /* MethodDeclaration */ + || kind === 150 /* MethodSignature */ + || kind === 233 /* ModuleDeclaration */ + || kind === 236 /* NamespaceExportDeclaration */ + || kind === 240 /* NamespaceImport */ + || kind === 146 /* Parameter */ + || kind === 261 /* PropertyAssignment */ + || kind === 149 /* PropertyDeclaration */ + || kind === 148 /* PropertySignature */ + || kind === 154 /* SetAccessor */ + || kind === 262 /* ShorthandPropertyAssignment */ + || kind === 231 /* TypeAliasDeclaration */ + || kind === 145 /* TypeParameter */ + || kind === 226 /* VariableDeclaration */ + || kind === 283 /* JSDocTypedefTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 228 /* FunctionDeclaration */ + || kind === 247 /* MissingDeclaration */ + || kind === 229 /* ClassDeclaration */ + || kind === 230 /* InterfaceDeclaration */ + || kind === 231 /* TypeAliasDeclaration */ + || kind === 232 /* EnumDeclaration */ + || kind === 233 /* ModuleDeclaration */ + || kind === 238 /* ImportDeclaration */ + || kind === 237 /* ImportEqualsDeclaration */ + || kind === 244 /* ExportDeclaration */ + || kind === 243 /* ExportAssignment */ + || kind === 236 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 218 /* BreakStatement */ + || kind === 217 /* ContinueStatement */ + || kind === 225 /* DebuggerStatement */ + || kind === 212 /* DoStatement */ + || kind === 210 /* ExpressionStatement */ + || kind === 209 /* EmptyStatement */ + || kind === 215 /* ForInStatement */ + || kind === 216 /* ForOfStatement */ + || kind === 214 /* ForStatement */ + || kind === 211 /* IfStatement */ + || kind === 222 /* LabeledStatement */ + || kind === 219 /* ReturnStatement */ + || kind === 221 /* SwitchStatement */ + || kind === 223 /* ThrowStatement */ + || kind === 224 /* TryStatement */ + || kind === 208 /* VariableStatement */ + || kind === 213 /* WhileStatement */ + || kind === 220 /* WithStatement */ + || kind === 287 /* NotEmittedStatement */ + || kind === 291 /* EndOfDeclarationMarker */ + || kind === 290 /* MergeDeclarationMarker */; + } + /* @internal */ + function isDeclaration(node) { + if (node.kind === 145 /* TypeParameter */) { + return node.parent.kind !== 282 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + /* @internal */ + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 207 /* Block */; + } + ts.isStatement = isStatement; + // Module references + /* @internal */ + function isModuleReference(node) { + var kind = node.kind; + return kind === 248 /* ExternalModuleReference */ + || kind === 143 /* QualifiedName */ + || kind === 71 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 99 /* ThisKeyword */ + || kind === 71 /* Identifier */ + || kind === 179 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ + function isJsxChild(node) { + var kind = node.kind; + return kind === 249 /* JsxElement */ + || kind === 256 /* JsxExpression */ + || kind === 250 /* JsxSelfClosingElement */ + || kind === 10 /* JsxText */; + } + ts.isJsxChild = isJsxChild; + /* @internal */ + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 253 /* JsxAttribute */ + || kind === 255 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 256 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 251 /* JsxOpeningElement */ + || kind === 250 /* JsxSelfClosingElement */; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 257 /* CaseClause */ + || kind === 258 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ + function isJSDocNode(node) { + return node.kind >= 267 /* FirstJSDocNode */ && node.kind <= 285 /* LastJSDocNode */; + } + ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node) { + return node.kind === 275 /* JSDocComment */ || isJSDocTag(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ + function isJSDocTag(node) { + return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; +})(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 265 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 71 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 142 /* LastToken */) { + return; + } + switch (node.kind) { + case 143 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 145 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 262 /* ShorthandPropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 263 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 146 /* Parameter */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 261 /* PropertyAssignment */: + case 226 /* VariableDeclaration */: + case 176 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 159 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 158 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 162 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 163 /* TypeLiteral */: + return visitNodes(cbNode, cbNodes, node.members); + case 164 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 165 /* TupleType */: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 166 /* UnionType */: + case 167 /* IntersectionType */: + return visitNodes(cbNode, cbNodes, node.types); + case 168 /* ParenthesizedType */: + case 170 /* TypeOperator */: + return visitNode(cbNode, node.type); + case 171 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 172 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 173 /* LiteralType */: + return visitNode(cbNode, node.literal); + case 174 /* ObjectBindingPattern */: + case 175 /* ArrayBindingPattern */: + return visitNodes(cbNode, cbNodes, node.elements); + case 177 /* ArrayLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 178 /* ObjectLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.properties); + case 179 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 180 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 181 /* CallExpression */: + case 182 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 183 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.template); + case 184 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 185 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 188 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 189 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 190 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 192 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 197 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 191 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 193 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 194 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 202 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 203 /* NonNullExpression */: + return visitNode(cbNode, node.expression); + case 204 /* MetaProperty */: + return visitNode(cbNode, node.name); + case 195 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 198 /* SpreadElement */: + return visitNode(cbNode, node.expression); + case 207 /* Block */: + case 234 /* ModuleBlock */: + return visitNodes(cbNode, cbNodes, node.statements); + case 265 /* SourceFile */: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 208 /* VariableStatement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 227 /* VariableDeclarationList */: + return visitNodes(cbNode, cbNodes, node.declarations); + case 210 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 211 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 212 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 213 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 215 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 216 /* ForOfStatement */: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 217 /* ContinueStatement */: + case 218 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 219 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 220 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 221 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 235 /* CaseBlock */: + return visitNodes(cbNode, cbNodes, node.clauses); + case 257 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 258 /* DefaultClause */: + return visitNodes(cbNode, cbNodes, node.statements); + case 222 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 223 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 224 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 260 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 147 /* Decorator */: + return visitNode(cbNode, node.expression); + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 230 /* InterfaceDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 231 /* TypeAliasDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 232 /* EnumDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 264 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 233 /* ModuleDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 237 /* ImportEqualsDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 238 /* ImportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 239 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 236 /* NamespaceExportDeclaration */: + return visitNode(cbNode, node.name); + case 240 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 241 /* NamedImports */: + case 245 /* NamedExports */: + return visitNodes(cbNode, cbNodes, node.elements); + case 244 /* ExportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 243 /* ExportAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 196 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 205 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 144 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 259 /* HeritageClause */: + return visitNodes(cbNode, cbNodes, node.types); + case 201 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 248 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 247 /* MissingDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators); + case 289 /* CommaListExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 249 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 250 /* JsxSelfClosingElement */: + case 251 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.attributes); + case 254 /* JsxAttributes */: + return visitNodes(cbNode, cbNodes, node.properties); + case 253 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 255 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 256 /* JsxExpression */: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 252 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 267 /* JSDocTypeExpression */: + return visitNode(cbNode, node.type); + case 271 /* JSDocNonNullableType */: + return visitNode(cbNode, node.type); + case 270 /* JSDocNullableType */: + return visitNode(cbNode, node.type); + case 272 /* JSDocOptionalType */: + return visitNode(cbNode, node.type); + case 273 /* JSDocFunctionType */: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 274 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 275 /* JSDocComment */: + return visitNodes(cbNode, cbNodes, node.tags); + case 279 /* JSDocParameterTag */: + case 284 /* JSDocPropertyTag */: + if (node.isNameFirst) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression); + } + else { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name); + } + case 280 /* JSDocReturnTag */: + return visitNode(cbNode, node.typeExpression); + case 281 /* JSDocTypeTag */: + return visitNode(cbNode, node.typeExpression); + case 277 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.typeExpression); + case 282 /* JSDocTemplateTag */: + return visitNodes(cbNode, cbNodes, node.typeParameters); + case 283 /* JSDocTypedefTag */: + if (node.typeExpression && + node.typeExpression.kind === 267 /* JSDocTypeExpression */) { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName); + } + else { + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + } + case 285 /* JSDocTypeLiteral */: + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } + return; + case 288 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 524288 /* PossiblyContainsDynamicImport */); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */); + var result = sourceFile; + // Prime the scanner. + nextToken(); + if (token() === 1 /* EndOfFileToken */) { + sourceFile.endOfFileToken = parseTokenNode(); + } + else if (token() === 17 /* OpenBraceToken */ || + lookAhead(function () { return token() === 9 /* StringLiteral */; })) { + result.jsonObject = parseObjectLiteralExpression(); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Unexpected_token); + } + else { + parseExpected(17 /* OpenBraceToken */); + } + sourceFile.parseDiagnostics = parseDiagnostics; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ || scriptKind === 6 /* JSON */ ? 65536 /* JavaScriptFile */ : 0 /* None */; + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + } + function addJSDocComment(node) { + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; + } + if (!node.jsDoc) { + node.jsDoc = []; + } + node.jsDoc.push(jsDoc); + } + } + return node; + } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(265 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 4096 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 16384 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048 /* DisallowInContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(2048 /* DisallowInContext */); + } + function inDecoratorContext() { + return inContext(8192 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(16384 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, arg0) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + parseErrorAtPosition(start, length, message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function scanError(message, length) { + var pos = scanner.getTextPos(); + parseErrorAtPosition(pos, length || 0, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token() === 71 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 116 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 107 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token() === 25 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 25 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(25 /* SemicolonToken */); + } + } + // note: this function creates only node + function createNode(kind, pos) { + nodeCount++; + if (!(pos >= 0)) { + pos = scanner.getStartPos(); + } + return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : + kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind, scanner.getStartPos()); + if (kind === 71 /* Identifier */) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(71 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 71 /* Identifier */) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName() { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(144 /* ComputedPropertyName */); + parseExpected(21 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(22 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + if (token() === 76 /* ConstKeyword */) { + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; + } + if (token() === 84 /* ExportKeyword */) { + nextToken(); + if (token() === 79 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); + } + if (token() === 79 /* DefaultKeyword */) { + return nextTokenCanFollowDefaultKeyword(); + } + if (token() === 115 /* StaticKeyword */) { + nextToken(); + return canFollowModifier(); + } + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 21 /* OpenBracketToken */ + || token() === 17 /* OpenBraceToken */ + || token() === 39 /* AsteriskToken */ + || token() === 24 /* DotDotDotToken */ + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || + token() === 109 /* InterfaceKeyword */ || + (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + case 17 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 17 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 18 /* TypeParameters */: + return isIdentifier(); + case 11 /* ArgumentExpressions */: + case 15 /* ArrayLiteralMembers */: + return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(); + case 19 /* TypeArguments */: + case 20 /* TupleElementTypes */: + return token() === 26 /* CommaToken */ || isStartOfType(); + case 21 /* HeritageClauses */: + return isHeritageClause(); + case 22 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 17 /* OpenBraceToken */); + if (nextToken() === 18 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 108 /* ImplementsKeyword */ || + token() === 85 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 22 /* ImportOrExportSpecifiers */: + return token() === 18 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 18 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 20 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 22 /* CloseBracketToken */; + case 16 /* Parameters */: + case 17 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 19 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 26 /* CommaToken */; + case 21 /* HeritageClauses */: + return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token())) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 36 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 23 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { + var element = parseListElement(kind, parseElement); + result.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 96256 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 16 /* Parameters */: + return isReusableParameter(node); + case 17 /* RestProperties */: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 21 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 18 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 20 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 19 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 152 /* Constructor */: + case 157 /* IndexSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 149 /* PropertyDeclaration */: + case 206 /* SemicolonClassElement */: + return true; + case 151 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 257 /* CaseClause */: + case 258 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 228 /* FunctionDeclaration */: + case 208 /* VariableStatement */: + case 207 /* Block */: + case 211 /* IfStatement */: + case 210 /* ExpressionStatement */: + case 223 /* ThrowStatement */: + case 219 /* ReturnStatement */: + case 221 /* SwitchStatement */: + case 218 /* BreakStatement */: + case 217 /* ContinueStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + case 214 /* ForStatement */: + case 213 /* WhileStatement */: + case 220 /* WithStatement */: + case 209 /* EmptyStatement */: + case 224 /* TryStatement */: + case 222 /* LabeledStatement */: + case 212 /* DoStatement */: + case 225 /* DebuggerStatement */: + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + case 244 /* ExportDeclaration */: + case 243 /* ExportAssignment */: + case 233 /* ModuleDeclaration */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 232 /* EnumDeclaration */: + case 231 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 264 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 156 /* ConstructSignature */: + case 150 /* MethodSignature */: + case 157 /* IndexSignature */: + case 148 /* PropertySignature */: + case 155 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 226 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + return createNodeArray(); + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(23 /* DotToken */)) { + if (token() === 27 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(143 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(196 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + var templateSpans = createNodeArray(); + do { + templateSpans.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 15 /* TemplateMiddle */); + templateSpans.end = getNodeEnd(); + template.templateSpans = templateSpans; + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(205 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 18 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(16 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + var text = scanner.getTokenValue(); + node.text = text; + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + } + nextToken(); + finishNode(node); + return node; + } + // TYPES + function parseTypeReference() { + var node = createNode(159 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ !!(contextFlags & 1048576 /* JSDoc */), ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + } + return finishNode(node); + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(158 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(169 /* ThisType */); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType() { + var result = createNode(268 /* JSDocAllType */); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 26 /* CommaToken */ || + token() === 18 /* CloseBraceToken */ || + token() === 20 /* CloseParenToken */ || + token() === 29 /* GreaterThanToken */ || + token() === 58 /* EqualsToken */ || + token() === 49 /* BarToken */) { + var result = createNode(269 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(270 /* JSDocNullableType */, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNode(273 /* JSDocFunctionType */); + nextToken(); + fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); + } + var node = createNode(159 /* TypeReference */); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(146 /* Parameter */); + if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { + parameter.name = parseIdentifierName(); + parseExpected(56 /* ColonToken */); + } + parameter.type = parseType(); + return finishNode(parameter); + } + function parseJSDocNodeWithType(kind) { + var result = createNode(kind); + nextToken(); + result.type = parseType(); + return finishNode(result); + } + function parseTypeQuery() { + var node = createNode(162 /* TypeQuery */); + parseExpected(103 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(145 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(85 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the > as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(58 /* EqualsToken */)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 27 /* LessThanToken */) { + return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(56 /* ColonToken */)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter() { + return token() === 24 /* DotDotDotToken */ || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 57 /* AtToken */ || isStartOfType(); + } + function parseParameter() { + var node = createNode(146 /* Parameter */); + if (token() === 99 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseBindingElementInitializer(/*inParameter*/ true); + return addJSDocComment(finishNode(node)); + } + function parseBindingElementInitializer(inParameter) { + return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); + } + function parseParameterInitializer() { + return parseInitializer(/*inParameter*/ true); + } + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32 /* JSDoc */)) { + signature.typeParameters = parseTypeParameters(); + } + signature.parameters = parseParameterList(flags); + var returnTokenRequired = returnToken === 36 /* EqualsGreaterThanToken */; + if (returnTokenRequired) { + parseExpected(returnToken); + signature.type = parseTypeOrTypePredicate(); + } + else if (parseOptional(returnToken)) { + signature.type = parseTypeOrTypePredicate(); + } + else if (flags & 4 /* Type */) { + var start = scanner.getTokenPos(); + var length_1 = scanner.getTextPos() - start; + var backwardToken = parseOptional(returnToken === 56 /* ColonToken */ ? 36 /* EqualsGreaterThanToken */ : 56 /* ColonToken */); + if (backwardToken) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + signature.type = parseTypeOrTypePredicate(); + parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); + } + } + } + function parseParameterList(flags) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (parseExpected(19 /* OpenParenToken */)) { + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { + // Caller insisted that we had to end with a ) We didn't. So just return + // undefined here. + return undefined; + } + return result; + } + // We didn't even have an open paren. If the caller requires a complete parameter list, + // we definitely can't provide that. However, if they're ok with an incomplete one, + // then just return an empty set of parameters. + return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(26 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNode(kind); + if (kind === 156 /* ConstructSignature */) { + parseExpected(94 /* NewKeyword */); + } + fillSignature(56 /* ColonToken */, 4 /* Type */, node); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(node)); + } + function isIndexSignature() { + if (token() !== 21 /* OpenBracketToken */) { + return false; + } + return lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 55 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { + var node = createNode(157 /* IndexSignature */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(fullStart, modifiers) { + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + var method = createNode(150 /* MethodSignature */, fullStart); + method.modifiers = modifiers; + method.name = name; + method.questionToken = questionToken; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(56 /* ColonToken */, 4 /* Type */, method); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(method)); + } + else { + var property = createNode(148 /* PropertySignature */, fullStart); + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + if (token() === 58 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + property.initializer = parseNonParameterInitializer(); + } + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(property)); + } + } + function isTypeMemberStart() { + // Return true if we have the start of a signature member + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return true; + } + var idToken; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + // Index signatures and computed property names are type members + if (token() === 21 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token() === 19 /* OpenParenToken */ || + token() === 27 /* LessThanToken */ || + token() === 55 /* QuestionToken */ || + token() === 56 /* ColonToken */ || + token() === 26 /* CommaToken */ || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseSignatureMember(155 /* CallSignature */); + } + if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(156 /* ConstructSignature */); + } + var fullStart = getNodePos(); + var modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; + } + function parseTypeLiteral() { + var node = createNode(163 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(17 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(18 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 131 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(145 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(92 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(172 /* MappedType */); + parseExpected(17 /* OpenBraceToken */); + node.readonlyToken = parseOptionalToken(131 /* ReadonlyKeyword */); + parseExpected(21 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(22 /* CloseBracketToken */); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseTupleType() { + var node = createNode(165 /* TupleType */); + node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(168 /* ParenthesizedType */); + parseExpected(19 /* OpenParenToken */); + node.type = parseType(); + parseExpected(20 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType(kind) { + var node = createNode(kind); + if (kind === 161 /* ConstructorType */) { + parseExpected(94 /* NewKeyword */); + } + fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 23 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(173 /* LiteralType */); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8 /* NumericLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 139 /* UndefinedKeyword */: + case 130 /* NeverKeyword */: + case 134 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 39 /* AsteriskToken */: + return parseJSDocAllType(); + case 55 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 89 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 24 /* DotDotDotToken */: + return parseJSDocNodeWithType(274 /* JSDocVariadicType */); + case 51 /* ExclamationToken */: + return parseJSDocNodeWithType(271 /* JSDocNonNullableType */); + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 38 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + case 105 /* VoidKeyword */: + case 95 /* NullKeyword */: + return parseTokenNode(); + case 99 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 103 /* TypeOfKeyword */: + return parseTypeQuery(); + case 17 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 21 /* OpenBracketToken */: + return parseTupleType(); + case 19 /* OpenParenToken */: + return parseParenthesizedType(); + default: + return parseTypeReference(); + } + } + function isStartOfType() { + switch (token()) { + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 99 /* ThisKeyword */: + case 103 /* TypeOfKeyword */: + case 130 /* NeverKeyword */: + case 17 /* OpenBraceToken */: + case 21 /* OpenBracketToken */: + case 27 /* LessThanToken */: + case 49 /* BarToken */: + case 48 /* AmpersandToken */: + case 94 /* NewKeyword */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 134 /* ObjectKeyword */: + return true; + case 38 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral); + case 19 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + } + function parseJSDocPostfixTypeOrHigher() { + var type = parseNonArrayType(); + var kind = getKind(token()); + if (!kind) + return type; + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + function getKind(tokenKind) { + switch (tokenKind) { + case 58 /* EqualsToken */: + // only parse postfix = inside jsdoc, because it's ambiguous elsewhere + return contextFlags & 1048576 /* JSDoc */ ? 272 /* JSDocOptionalType */ : undefined; + case 51 /* ExclamationToken */: + return 271 /* JSDocNonNullableType */; + case 55 /* QuestionToken */: + return 270 /* JSDocNullableType */; + } + } + } + function parseArrayTypeOrHigher() { + var type = parseJSDocPostfixTypeOrHigher(); + while (!scanner.hasPrecedingLineBreak() && parseOptional(21 /* OpenBracketToken */)) { + if (isStartOfType()) { + var node = createNode(171 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(164 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + } + return type; + } + function parseTypeOperator(operator) { + var node = createNode(170 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 127 /* KeyOfKeyword */: + return parseTypeOperator(127 /* KeyOfKeyword */); + } + return parseArrayTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = createNodeArray([type], type.pos); + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + types.end = getNodeEnd(); + var node = createNode(kind, type.pos); + node.types = types; + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(167 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(166 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + } + function isStartOfFunctionType() { + if (token() === 27 /* LessThanToken */) { + return true; + } + return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier() || token() === 99 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || + token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = + return true; + } + if (token() === 20 /* CloseParenToken */) { + nextToken(); + if (token() === 36 /* EqualsGreaterThanToken */) { + // ( xxx ) => + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(158 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker() { + if (isStartOfFunctionType()) { + return parseFunctionOrConstructorType(160 /* FunctionType */); + } + if (token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(161 /* ConstructorType */); + } + return parseUnionTypeOrHigher(); + } + function parseTypeAnnotation() { + return parseOptional(56 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 19 /* OpenParenToken */: + case 21 /* OpenBracketToken */: + case 17 /* OpenBraceToken */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 94 /* NewKeyword */: + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + case 71 /* Identifier */: + return true; + case 91 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThan); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 80 /* DeleteKeyword */: + case 103 /* TypeOfKeyword */: + case 105 /* VoidKeyword */: + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 27 /* LessThanToken */: + case 121 /* AwaitKeyword */: + case 116 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 17 /* OpenBraceToken */ && + token() !== 89 /* FunctionKeyword */ && + token() !== 75 /* ClassKeyword */ && + token() !== 57 /* AtToken */ && + isStartOfExpression(); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return expr; + } + function parseInitializer(inParameter) { + if (token() !== 58 /* EqualsToken */) { + // It's not uncommon during typing for the user to miss writing the '=' token. Check if + // there is no newline after the last token and if we're on an expression. If so, parse + // this as an equals-value clause with a missing equals. + // NOTE: There are two places where we allow equals-value clauses. The first is in a + // variable declarator. The second is with a parameter. For variable declarators + // it's more likely that a { would be a allowed (as an object literal). While this + // is also allowed for parameters, the risk is that we consume the { as an object + // literal when it really will be for the block following the parameter. + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17 /* OpenBraceToken */) || !isStartOfExpression()) { + // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - + // do not try to parse initializer + return undefined; + } + } + // Initializer[In, Yield] : + // = AssignmentExpression[?In, ?Yield] + parseExpected(58 /* EqualsToken */); + return parseAssignmentExpressionOrHigher(); + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like > > = becoming >>= + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 116 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(197 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(187 /* ArrowFunction */, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(187 /* ArrowFunction */, identifier.pos); + } + var parameter = createNode(146 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos); + node.parameters.end = parameter.end; + node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return addJSDocComment(finishNode(arrowFunction)); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 36 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 120 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token(); + var second = nextToken(); + if (first === 19 /* OpenParenToken */) { + if (second === 20 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 36 /* EqualsGreaterThanToken */: + case 56 /* ColonToken */: + case 17 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 24 /* DotDotDotToken */) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. + // Note: we could be a little more lenient and allow + // "(public" or "(private". These would not ever actually be allowed, + // but we could provide a good error message instead of bailing out. + if (!isIdentifier()) { + return 0 /* False */; + } + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + if (nextToken() === 56 /* ColonToken */) { + return 1 /* True */; + } + // This *could* be a parenthesized arrow function. + // Return Unknown to let the caller know. + return 2 /* Unknown */; + } + else { + ts.Debug.assert(first === 27 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 85 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 58 /* EqualsToken */: + case 29 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 26 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 120 /* AsyncKeyword */) { + var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); + if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 120 /* AsyncKeyword */) { + nextToken(); + // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNode(187 /* ArrowFunction */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); + // If we couldn't get parameters, we definitely could not parse out an arrow function. + if (!node.parameters) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 17 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 25 /* SemicolonToken */ && + token() !== 89 /* FunctionKeyword */ && + token() !== 75 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(195 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + node.whenFalse = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 92 /* InKeyword */ || t === 142 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = getBinaryOperatorPrecedence(); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 92 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 118 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 92 /* InKeyword */) { + return false; + } + return getBinaryOperatorPrecedence() > 0; + } + function getBinaryOperatorPrecedence() { + switch (token()) { + case 54 /* BarBarToken */: + return 1; + case 53 /* AmpersandAmpersandToken */: + return 2; + case 49 /* BarToken */: + return 3; + case 50 /* CaretToken */: + return 4; + case 48 /* AmpersandToken */: + return 5; + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return 6; + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: + return 7; + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + return 8; + case 37 /* PlusToken */: + case 38 /* MinusToken */: + return 9; + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + return 10; + case 40 /* AsteriskAsteriskToken */: + return 11; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(194 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(202 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(192 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(188 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(189 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(190 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 121 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(191 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ + function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 40 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + updateExpression; + } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 40 /* AsteriskAsteriskToken */) { + var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + if (simpleUnaryExpression.kind === 184 /* TypeAssertionExpression */) { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token()) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 80 /* DeleteKeyword */: + return parseDeleteExpression(); + case 103 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 105 /* VoidKeyword */: + return parseVoidExpression(); + case 27 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + case 121 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly + switch (token()) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 80 /* DeleteKeyword */: + case 103 /* TypeOfKeyword */: + case 105 /* VoidKeyword */: + case 121 /* AwaitKeyword */: + return false; + case 27 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseUpdateExpression() { + if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { + var node = createNode(192 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(193 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. + var expression; + if (token() === 91 /* ImportKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else { + expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation) Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(179 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + parseExpectedToken(23 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 71 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 99 /* ThisKeyword */) { + return true; + } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + function parseJsxElementOrSelfClosingElement(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + var result; + if (opening.kind === 251 /* JsxOpeningElement */) { + var node = createNode(249 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement.tagName); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 250 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + result = opening; + } + // If the user writes the invalid code '
' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 27 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(194 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(10 /* JsxText */, scanner.getStartPos()); + node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild() { + switch (token()) { + case 10 /* JsxText */: + case 11 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 17 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 27 /* LessThanToken */: + return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); + } + ts.Debug.fail("Unknown JSX child kind " + token()); + } + function parseJsxChildren(openingTagName) { + var result = createNodeArray(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + currentToken = scanner.reScanJsxToken(); + if (token() === 28 /* LessThanSlashToken */) { + // Closing tag + break; + } + else if (token() === 1 /* EndOfFileToken */) { + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + break; + } + else if (token() === 7 /* ConflictMarkerTrivia */) { + break; + } + var child = parseJsxChild(); + if (child) { + result.push(child); + } + } + result.end = scanner.getTokenPos(); + parsingContext = saveParsingContext; + return result; + } + function parseJsxAttributes() { + var jsxAttributes = createNode(254 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(27 /* LessThanToken */); + var tagName = parseJsxElementName(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 29 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(251 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(41 /* SlashToken */); + if (inExpressionContext) { + parseExpected(29 /* GreaterThanToken */); + } + else { + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + node = createNode(250 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 99 /* ThisKeyword */ ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(23 /* DotToken */)) { + var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(256 /* JsxExpression */); + parseExpected(17 /* OpenBraceToken */); + if (token() !== 18 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(18 /* CloseBraceToken */); + } + else { + parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 17 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(253 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (token() === 58 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { + case 9 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(255 /* JsxSpreadAttribute */); + parseExpected(17 /* OpenBraceToken */); + parseExpected(24 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(252 /* JsxClosingElement */); + parseExpected(28 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(29 /* GreaterThanToken */); + } + else { + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(184 /* TypeAssertionExpression */); + parseExpected(27 /* LessThanToken */); + node.type = parseType(); + parseExpected(29 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(23 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(203 /* NonNullExpression */, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { + var indexedAccess = createNode(180 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + // It's not uncommon for a user to write: "new Type[]". + // Check for that common pattern and report a better error message. + if (token() !== 22 /* CloseBracketToken */) { + indexedAccess.argumentExpression = allowInAnd(parseExpression); + if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { + var literal = indexedAccess.argumentExpression; + literal.text = internIdentifier(literal.text); + } + } + parseExpected(22 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { + var tagExpression = createNode(183 /* TaggedTemplateExpression */, expression.pos); + tagExpression.tag = expression; + tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + expression = finishNode(tagExpression); + continue; + } + return expression; + } + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 27 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + var callExpr = createNode(181 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 19 /* OpenParenToken */) { + var callExpr = createNode(181 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(19 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(20 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(27 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + if (!parseExpected(29 /* GreaterThanToken */)) { + // If it doesn't have the closing > then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 19 /* OpenParenToken */: // foo( + // this case are the only case where this token can legally follow a type argument + // list. So we definitely want to treat this as a type arg list. + case 23 /* DotToken */: // foo. + case 20 /* CloseParenToken */: // foo) + case 22 /* CloseBracketToken */: // foo] + case 56 /* ColonToken */: // foo: + case 25 /* SemicolonToken */: // foo; + case 55 /* QuestionToken */: // foo? + case 32 /* EqualsEqualsToken */: // foo == + case 34 /* EqualsEqualsEqualsToken */: // foo === + case 33 /* ExclamationEqualsToken */: // foo != + case 35 /* ExclamationEqualsEqualsToken */: // foo !== + case 53 /* AmpersandAmpersandToken */: // foo && + case 54 /* BarBarToken */: // foo || + case 50 /* CaretToken */: // foo ^ + case 48 /* AmpersandToken */: // foo & + case 49 /* BarToken */: // foo | + case 18 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */:// foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 26 /* CommaToken */: // foo, + case 17 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + return parseTokenNode(); + case 19 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 21 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 17 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 120 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 75 /* ClassKeyword */: + return parseClassExpression(); + case 89 /* FunctionKeyword */: + return parseFunctionExpression(); + case 94 /* NewKeyword */: + return parseNewExpression(); + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 14 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNode(185 /* ParenthesizedExpression */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + return addJSDocComment(finishNode(node)); + } + function parseSpreadElement() { + var node = createNode(198 /* SpreadElement */); + parseExpected(24 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 26 /* CommaToken */ ? createNode(200 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(177 /* ArrayLiteralExpression */); + parseExpected(21 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(22 /* CloseBracketToken */); + return finishNode(node); + } + function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(153 /* GetAccessor */, fullStart, decorators, modifiers); + } + else if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(154 /* SetAccessor */, fullStart, decorators, modifiers); + } + return undefined; + } + function parseObjectLiteralElement() { + var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + if (dotDotDotToken) { + var spreadElement = createNode(263 /* SpreadAssignment */, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + // Disallowing of optional property assignments happens in the grammar checker. + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); + if (isShorthandPropertyAssignment) { + var shorthandDeclaration = createNode(262 /* ShorthandPropertyAssignment */, fullStart); + shorthandDeclaration.name = propertyName; + shorthandDeclaration.questionToken = questionToken; + var equalsToken = parseOptionalToken(58 /* EqualsToken */); + if (equalsToken) { + shorthandDeclaration.equalsToken = equalsToken; + shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return addJSDocComment(finishNode(shorthandDeclaration)); + } + else { + var propertyAssignment = createNode(261 /* PropertyAssignment */, fullStart); + propertyAssignment.modifiers = modifiers; + propertyAssignment.name = propertyName; + propertyAssignment.questionToken = questionToken; + parseExpected(56 /* ColonToken */); + propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + return addJSDocComment(finishNode(propertyAssignment)); + } + } + function parseObjectLiteralExpression() { + var node = createNode(178 /* ObjectLiteralExpression */); + parseExpected(17 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var node = createNode(186 /* FunctionExpression */); + node.modifiers = parseModifiers(); + parseExpected(89 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return addJSDocComment(finishNode(node)); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpression() { + var fullStart = scanner.getStartPos(); + parseExpected(94 /* NewKeyword */); + if (parseOptional(23 /* DotToken */)) { + var node_1 = createNode(204 /* MetaProperty */, fullStart); + node_1.keywordToken = 94 /* NewKeyword */; + node_1.name = parseIdentifierName(); + return finishNode(node_1); + } + var node = createNode(182 /* NewExpression */, fullStart); + node.expression = parseMemberExpressionOrHigher(); + node.typeArguments = tryParse(parseTypeArgumentsInExpression); + if (node.typeArguments || token() === 19 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(207 /* Block */); + if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(209 /* EmptyStatement */); + parseExpected(25 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(211 /* IfStatement */); + parseExpected(90 /* IfKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(212 /* DoStatement */); + parseExpected(81 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(106 /* WhileKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(25 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(213 /* WhileStatement */); + parseExpected(106 /* WhileKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(88 /* ForKeyword */); + var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); + parseExpected(19 /* OpenParenToken */); + var initializer = undefined; + if (token() !== 25 /* SemicolonToken */) { + if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(142 /* OfKeyword */) : parseOptional(142 /* OfKeyword */)) { + var forOfStatement = createNode(216 /* ForOfStatement */, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(20 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(92 /* InKeyword */)) { + var forInStatement = createNode(215 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(214 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(25 /* SemicolonToken */); + if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(25 /* SemicolonToken */); + if (token() !== 20 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(20 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 218 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(219 /* ReturnStatement */); + parseExpected(96 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(220 /* WithStatement */); + parseExpected(107 /* WithKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(257 /* CaseClause */); + parseExpected(73 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(56 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(258 /* DefaultClause */); + parseExpected(79 /* DefaultKeyword */); + parseExpected(56 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(221 /* SwitchStatement */); + parseExpected(98 /* SwitchKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + var caseBlock = createNode(235 /* CaseBlock */, scanner.getStartPos()); + parseExpected(17 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(18 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(223 /* ThrowStatement */); + parseExpected(100 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(224 /* TryStatement */); + parseExpected(102 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 87 /* FinallyKeyword */) { + parseExpected(87 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(260 /* CatchClause */); + parseExpected(74 /* CatchKeyword */); + if (parseExpected(19 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + } + parseExpected(20 /* CloseParenToken */); + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(225 /* DebuggerStatement */); + parseExpected(78 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var fullStart = scanner.getStartPos(); + var expression = allowInAnd(parseExpression); + if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { + var labeledStatement = createNode(222 /* LabeledStatement */, fullStart); + labeledStatement.label = expression; + labeledStatement.statement = parseStatement(); + return addJSDocComment(finishNode(labeledStatement)); + } + else { + var expressionStatement = createNode(210 /* ExpressionStatement */, fullStart); + expressionStatement.expression = expression; + parseSemicolon(); + return addJSDocComment(finishNode(expressionStatement)); + } + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 83 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 109 /* InterfaceKeyword */: + case 138 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 124 /* DeclareKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 131 /* ReadonlyKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 141 /* GlobalKeyword */: + nextToken(); + return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; + case 91 /* ImportKeyword */: + nextToken(); + return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 84 /* ExportKeyword */: + nextToken(); + if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || + token() === 118 /* AsKeyword */) { + return true; + } + continue; + case 115 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 57 /* AtToken */: + case 25 /* SemicolonToken */: + case 17 /* OpenBraceToken */: + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 83 /* EnumKeyword */: + case 90 /* IfKeyword */: + case 81 /* DoKeyword */: + case 106 /* WhileKeyword */: + case 88 /* ForKeyword */: + case 77 /* ContinueKeyword */: + case 72 /* BreakKeyword */: + case 96 /* ReturnKeyword */: + case 107 /* WithKeyword */: + case 98 /* SwitchKeyword */: + case 100 /* ThrowKeyword */: + case 102 /* TryKeyword */: + case 78 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: + return true; + case 91 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + case 76 /* ConstKeyword */: + case 84 /* ExportKeyword */: + return isStartOfDeclaration(); + case 120 /* AsyncKeyword */: + case 124 /* DeclareKeyword */: + case 109 /* InterfaceKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + case 138 /* TypeKeyword */: + case 141 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 25 /* SemicolonToken */: + return parseEmptyStatement(); + case 17 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 104 /* VarKeyword */: + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 110 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + } + break; + case 89 /* FunctionKeyword */: + return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 75 /* ClassKeyword */: + return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 90 /* IfKeyword */: + return parseIfStatement(); + case 81 /* DoKeyword */: + return parseDoStatement(); + case 106 /* WhileKeyword */: + return parseWhileStatement(); + case 88 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 77 /* ContinueKeyword */: + return parseBreakOrContinueStatement(217 /* ContinueStatement */); + case 72 /* BreakKeyword */: + return parseBreakOrContinueStatement(218 /* BreakStatement */); + case 96 /* ReturnKeyword */: + return parseReturnStatement(); + case 107 /* WithKeyword */: + return parseWithStatement(); + case 98 /* SwitchKeyword */: + return parseSwitchStatement(); + case 100 /* ThrowKeyword */: + return parseThrowStatement(); + case 102 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: + return parseTryStatement(); + case 78 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 57 /* AtToken */: + return parseDeclaration(); + case 120 /* AsyncKeyword */: + case 109 /* InterfaceKeyword */: + case 138 /* TypeKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 83 /* EnumKeyword */: + case 84 /* ExportKeyword */: + case 91 /* ImportKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + case 141 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function parseDeclaration() { + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + switch (token()) { + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + return parseVariableStatement(fullStart, decorators, modifiers); + case 89 /* FunctionKeyword */: + return parseFunctionDeclaration(fullStart, decorators, modifiers); + case 75 /* ClassKeyword */: + return parseClassDeclaration(fullStart, decorators, modifiers); + case 109 /* InterfaceKeyword */: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 138 /* TypeKeyword */: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 83 /* EnumKeyword */: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 141 /* GlobalKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 91 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 84 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 79 /* DefaultKeyword */: + case 58 /* EqualsToken */: + return parseExportAssignment(fullStart, decorators, modifiers); + case 118 /* AsKeyword */: + return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + default: + return parseExportDeclaration(fullStart, decorators, modifiers); + } + default: + if (decorators || modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var node = createMissingNode(247 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + node.modifiers = modifiers; + return finishNode(node); + } + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token() === 26 /* CommaToken */) { + return createNode(200 /* OmittedExpression */); + } + var node = createNode(176 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(176 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(56 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(174 /* ObjectBindingPattern */); + parseExpected(17 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(175 /* ArrayBindingPattern */); + parseExpected(21 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(22 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 21 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 17 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclaration() { + var node = createNode(226 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(/*inParameter*/ false); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(227 /* VariableDeclarationList */); + switch (token()) { + case 104 /* VarKeyword */: + break; + case 110 /* LetKeyword */: + node.flags |= 1 /* Let */; + break; + case 76 /* ConstKeyword */: + node.flags |= 2 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 142 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; + } + function parseVariableStatement(fullStart, decorators, modifiers) { + var node = createNode(208 /* VariableStatement */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseFunctionDeclaration(fullStart, decorators, modifiers) { + var node = createNode(228 /* FunctionDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(89 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseConstructorDeclaration(pos, decorators, modifiers) { + var node = createNode(152 /* Constructor */, pos); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(123 /* ConstructorKeyword */); + fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { + var method = createNode(151 /* MethodDeclaration */, fullStart); + method.decorators = decorators; + method.modifiers = modifiers; + method.asteriskToken = asteriskToken; + method.name = name; + method.questionToken = questionToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(method, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, method); + method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return addJSDocComment(finishNode(method)); + } + function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { + var property = createNode(149 /* PropertyDeclaration */, fullStart); + property.decorators = decorators; + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + property.initializer = ts.hasModifier(property, 32 /* Static */) + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); + parseSemicolon(); + return addJSDocComment(finishNode(property)); + } + function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + } + else { + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + } + } + function parseNonParameterInitializer() { + return parseInitializer(/*inParameter*/ false); + } + function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.name = parsePropertyName(); + fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return addJSDocComment(finishNode(node)); + } + function isClassMemberModifier(idToken) { + switch (idToken) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + return true; + default: + return false; + } + } + function isClassMemberStart() { + var idToken; + if (token() === 57 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifierKind(token())) { + idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 39 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token() === 21 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 135 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token()) { + case 19 /* OpenParenToken */: // Method declaration + case 27 /* LessThanToken */: // Generic Method declaration + case 56 /* ColonToken */: // Type Annotation for declaration + case 58 /* EqualsToken */: // Initializer for declaration + case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on. + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var decorators; + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(57 /* AtToken */)) { + break; + } + var decorator = createNode(147 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } + } + if (decorators) { + decorators.end = getNodeEnd(); + } + return decorators; + } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { + var modifiers; + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + if (!modifiers) { + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); + } + } + if (modifiers) { + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 120 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseClassElement() { + if (token() === 25 /* SemicolonToken */) { + var result = createNode(206 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + if (token() === 123 /* ConstructorKeyword */) { + return parseConstructorDeclaration(fullStart, decorators, modifiers); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 39 /* AsteriskToken */ || + token() === 21 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + } + if (decorators || modifiers) { + // treat this as a property declaration with a missing name. + var name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression( + /*fullStart*/ scanner.getStartPos(), + /*decorators*/ undefined, + /*modifiers*/ undefined, 199 /* ClassExpression */); + } + function parseClassDeclaration(fullStart, decorators, modifiers) { + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(75 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(17 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(21 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { + var node = createNode(259 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + return undefined; + } + function parseExpressionWithTypeArguments() { + var node = createNode(201 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + if (token() === 27 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + } + return finishNode(node); + } + function isHeritageClause() { + return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(fullStart, decorators, modifiers) { + var node = createNode(230 /* InterfaceDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(109 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return addJSDocComment(finishNode(node)); + } + function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { + var node = createNode(231 /* TypeAliasDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(138 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(58 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNode(264 /* EnumMember */, scanner.getStartPos()); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseNonParameterInitializer); + return addJSDocComment(finishNode(node)); + } + function parseEnumDeclaration(fullStart, decorators, modifiers) { + var node = createNode(232 /* EnumDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(83 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(17 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseModuleBlock() { + var node = createNode(234 /* ModuleBlock */, scanner.getStartPos()); + if (parseExpected(17 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { + var node = createNode(233 /* ModuleDeclaration */, fullStart); + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; + node.decorators = decorators; + node.modifiers = modifiers; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(23 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) + : parseModuleBlock(); + return addJSDocComment(finishNode(node)); + } + function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { + var node = createNode(233 /* ModuleDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (token() === 141 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 512 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 17 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(fullStart, decorators, modifiers) { + var flags = 0; + if (token() === 141 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(129 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; + } + else { + parseExpected(128 /* ModuleKeyword */); + if (token() === 9 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + } + return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + } + function isExternalModuleReference() { + return token() === 132 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 19 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 41 /* SlashToken */; + } + function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { + var exportDeclaration = createNode(236 /* NamespaceExportDeclaration */, fullStart); + exportDeclaration.decorators = decorators; + exportDeclaration.modifiers = modifiers; + parseExpected(118 /* AsKeyword */); + parseExpected(129 /* NamespaceKeyword */); + exportDeclaration.name = parseIdentifier(); + parseSemicolon(); + return finishNode(exportDeclaration); + } + function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + parseExpected(91 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 26 /* CommaToken */ && token() !== 140 /* FromKeyword */) { + return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + } + } + // Import statement + var importDeclaration = createNode(238 /* ImportDeclaration */, fullStart); + importDeclaration.decorators = decorators; + importDeclaration.modifiers = modifiers; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || + token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */) { + importDeclaration.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(140 /* FromKeyword */); + } + importDeclaration.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(importDeclaration); + } + function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { + var importEqualsDeclaration = createNode(237 /* ImportEqualsDeclaration */, fullStart); + importEqualsDeclaration.decorators = decorators; + importEqualsDeclaration.modifiers = modifiers; + importEqualsDeclaration.name = identifier; + parseExpected(58 /* EqualsToken */); + importEqualsDeclaration.moduleReference = parseModuleReference(); + parseSemicolon(); + return addJSDocComment(finishNode(importEqualsDeclaration)); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(239 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(26 /* CommaToken */)) { + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(241 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(248 /* ExternalModuleReference */); + parseExpected(132 /* RequireKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(20 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 9 /* StringLiteral */) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(240 /* NamespaceImport */); + parseExpected(39 /* AsteriskToken */); + parseExpected(118 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 241 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(246 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(242 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 118 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(118 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 242 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + // Report error identifier expected + parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(fullStart, decorators, modifiers) { + var node = createNode(244 /* ExportDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(39 /* AsteriskToken */)) { + parseExpected(140 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(245 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 140 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(140 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(fullStart, decorators, modifiers) { + var node = createNode(243 /* ExportAssignment */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(58 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(79 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function processReferenceComments(sourceFile) { + var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var referencedFiles = []; + var typeReferenceDirectives = []; + var amdDependencies = []; + var amdModuleName; + var checkJsDirective = undefined; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (kind !== 2 /* SingleLineCommentTrivia */) { + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); + if (referencePathMatchResult) { + var fileReference = referencePathMatchResult.fileReference; + sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + if (fileReference) { + if (referencePathMatchResult.isTypeReferenceDirective) { + typeReferenceDirectives.push(fileReference); + } + else { + referencedFiles.push(fileReference); + } + } + if (diagnosticMessage) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + } + } + else { + var amdModuleNameRegEx = /^\/\/\/\s*= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + var tags; + var comments = []; + var result; + // Check for /** (JSDoc opening part) + if (!isJsDocStart(content, start)) { + return result; + } + // + 3 for leading /**, - 5 in total for /** */ + scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var advanceToken = true; + var state = 1 /* SawAsterisk */; + var margin = undefined; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5 /* WhitespaceTrivia */) { + nextJSDocToken(); + } + if (token() === 4 /* NewLineTrivia */) { + state = 0 /* BeginningOfLine */; + indent = 0; + nextJSDocToken(); + } + while (token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 57 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingNewlines(comments); + parseTag(indent); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 39 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 71 /* Identifier */: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + pushComment(scanner.getTokenText()); + state = 2 /* SavingComments */; + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break; + default: + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { + nextJSDocToken(); + } + else { + advanceToken = true; + } + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */; + } + function createJSDocComment() { + var result = createNode(275 /* JSDocComment */, start); + result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function skipWhitespace() { + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 57 /* AtToken */); + var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return; + } + var tag; + if (tagName) { + switch (tagName.escapedText) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + tag = parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */); + break; + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; + } + } + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + // a badly malformed tag should not be added to the list of tags + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + } + function parseTagComments(indent) { + var comments = []; + var state = 0 /* BeginningOfLine */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 57 /* AtToken */: + // Done + break; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 39 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += scanner.getTokenText().length; + break; + } + // record the * as a comment + // falls through + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + if (token() === 57 /* AtToken */) { + // Done + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { + var result = createNode(276 /* JSDocTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); + } + else { + tags.push(tag); + } + tags.end = tag.end; + } + function tryParseTypeExpression() { + return tryParse(function () { + skipWhitespace(); + if (token() !== 17 /* OpenBraceToken */) { + return undefined; + } + return parseJSDocTypeExpression(); + }); + } + function parseBracketNameInPropertyAndParamTag() { + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(21 /* OpenBracketToken */); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(58 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(22 /* CloseBracketToken */); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 134 /* ObjectKeyword */: + return true; + case 164 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(atToken, tagName, target) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespace(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 /* Parameter */ ? + createNode(279 /* JSDocParameterTag */, atToken.pos) : + createNode(284 /* JSDocPropertyTag */, atToken.pos); + var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { + if (!children) { + children = []; + } + children.push(child); + } + if (children) { + jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 164 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 280 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(280 /* JSDocReturnTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 281 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(281 /* JSDocTypeTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(277 /* JSDocAugmentsTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } + function parseClassTag(atToken, tagName) { + var tag = createNode(278 /* JSDocClassTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var typedefTag = createNode(283 /* JSDocTypedefTag */, atToken.pos); + typedefTag.atToken = atToken; + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (true) { + if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { + // if node is identifier - use it as name + // otherwise use name of the rightmost part that we were able to parse + typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; + break; + } + rightNode = rightNode.body; + } + } + skipWhitespace(); + typedefTag.typeExpression = typeExpression; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var alreadyHasTypeTag = false; + var start_3 = scanner.getStartPos(); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_3); + } + if (child.kind === 281 /* JSDocTypeTag */) { + if (alreadyHasTypeTag) { + break; + } + else { + jsdocTypeLiteral.jsDocTypeTag = child; + alreadyHasTypeTag = true; + } + } + else { + if (!jsdocTypeLiteral.jsDocPropertyTags) { + jsdocTypeLiteral.jsDocPropertyTags = []; + } + jsdocTypeLiteral.jsDocPropertyTags.push(child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + } + } + return finishNode(typedefTag); + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(233 /* ModuleDeclaration */, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildParameterOrPropertyTag(target, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + nextJSDocToken(); + switch (token()) { + case 57 /* AtToken */: + if (canParseTag) { + var child = tryParseChildTag(target); + if (child && child.kind === 279 /* JSDocParameterTag */ && + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 39 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 71 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target) { + ts.Debug.assert(token() === 57 /* AtToken */); + var atToken = createNode(57 /* AtToken */, scanner.getStartPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return false; + } + switch (tagName.escapedText) { + case "type": + return target === 0 /* Property */ && parseTypeTag(atToken, tagName); + case "prop": + case "property": + return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + case "arg": + case "argument": + case "param": + return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + } + return false; + } + function parseTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 282 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + // Type parameter list looks like '@template T,U,V' + var typeParameters = createNodeArray(); + while (true) { + var name = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(145 /* TypeParameter */, name.pos); + typeParameter.name = name; + finishNode(typeParameter); + typeParameters.push(typeParameter); + if (token() === 26 /* CommaToken */) { + nextJSDocToken(); + skipWhitespace(); + } + else { + break; + } + } + var result = createNode(282 /* JSDocTemplateTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + finishNode(result); + typeParameters.end = result.end; + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(21 /* OpenBracketToken */)) { + parseExpected(22 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(23 /* DotToken */)) { + var name = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(21 /* OpenBracketToken */)) { + parseExpected(22 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(createIfMissing) { + if (createIfMissing === void 0) { createIfMissing = false; } + if (!ts.tokenIsIdentifierOrKeyword(token())) { + if (createIfMissing) { + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); + return undefined; + } + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(71 /* Identifier */, pos); + result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + forEachChild(jsDocComment, visitNode, visitArray); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 71 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); +})(ts || (ts = {})); +/// +/// +/* @internal */ +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) { + // A module is uninstantiated if it contains only + // 1. interface declarations, type alias declarations + if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 231 /* TypeAliasDeclaration */) { + return 0 /* NonInstantiated */; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2 /* ConstEnumOnly */; + } + else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + else if (node.kind === 234 /* ModuleBlock */) { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return false; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return false; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + } + }); + return state_1; + } + else if (node.kind === 233 /* ModuleDeclaration */) { + var body = node.body; + return body ? getModuleInstanceState(body) : 1 /* Instantiated */; + } + else if (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + else { + return 1 /* Instantiated */; + } + } + ts.getModuleInstanceState = getModuleInstanceState; + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + 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"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233 /* ModuleDeclaration */)) { + // 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) { + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + 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 ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + } + return ts.getEscapedTextOfIdentifierOrLiteral(name); + } + switch (node.kind) { + case 152 /* Constructor */: + return "__constructor" /* Constructor */; + case 160 /* FunctionType */: + case 155 /* CallSignature */: + return "__call" /* Call */; + case 161 /* ConstructorType */: + case 156 /* ConstructSignature */: + return "__new" /* New */; + case 157 /* IndexSignature */: + return "__index" /* Index */; + case 244 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 243 /* ExportAssignment */: + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + case 194 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 228 /* FunctionDeclaration */: + case 229 /* ClassDeclaration */: + return (ts.hasModifier(node, 512 /* Default */) ? "default" /* Default */ : undefined); + case 273 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 146 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 273 /* JSDocFunctionType */); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "arg" + index; + case 283 /* JSDocTypedefTag */: + var parentNode = node.parent && node.parent.parent; + var nameFromParentNode = void 0; + if (parentNode && parentNode.kind === 208 /* VariableStatement */) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (ts.isIdentifier(nameIdentifier)) { + nameFromParentNode = nameIdentifier.escapedText; + } + } + } + return nameFromParentNode; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 788448 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else { + if (node.name) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 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 === 243 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 246 /* ExportSpecifier */ || (node.kind === 237 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // 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 === 283 /* JSDocTypedefTag */) + ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + var isJSDocTypedefInJSDocNamespace = node.kind === 283 /* JSDocTypedefTag */ && + node.name && + node.name.kind === 71 /* Identifier */ && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { + var exportKind = symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we proactively initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (isIIFE) { + currentReturnTarget = createBranchLabel(); + } + else { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + currentReturnTarget = undefined; + } + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 265 /* SourceFile */) { + node.flags |= emitFlags; + } + if (isIIFE) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + } + else { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + // 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 (node.jsDoc) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + if (checkUnreachable(node)) { + bindEachChild(node); + return; + } + switch (node.kind) { + case 213 /* WhileStatement */: + bindWhileStatement(node); + break; + case 212 /* DoStatement */: + bindDoStatement(node); + break; + case 214 /* ForStatement */: + bindForStatement(node); + break; + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 211 /* IfStatement */: + bindIfStatement(node); + break; + case 219 /* ReturnStatement */: + case 223 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 218 /* BreakStatement */: + case 217 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 224 /* TryStatement */: + bindTryStatement(node); + break; + case 221 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 235 /* CaseBlock */: + bindCaseBlock(node); + break; + case 257 /* CaseClause */: + bindCaseClause(node); + break; + case 222 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 192 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 193 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 194 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 188 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 195 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 226 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 181 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 275 /* JSDocComment */: + bindJSDocComment(node); + break; + case 283 /* JSDocTypedefTag */: + bindJSDocTypedefTag(node); + break; + default: + bindEachChild(node); + break; + } + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 179 /* PropertyAccessExpression */: + return isNarrowableReference(expr); + case 181 /* CallExpression */: + return hasNarrowableArgument(expr); + case 185 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 194 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 192 /* PrefixUnaryExpression */: + return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 71 /* Identifier */ || + expr.kind === 99 /* ThisKeyword */ || + expr.kind === 97 /* SuperKeyword */ || + expr.kind === 179 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 179 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 189 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 93 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 26 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 185 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 194 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 26 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: flags, + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128 /* SwitchClause */, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent + }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 16 /* Assignment */, + antecedent: antecedent, + node: node + }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256 /* ArrayMutation */, + antecedent: antecedent, + node: node + }; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 211 /* IfStatement */: + case 213 /* WhileStatement */: + case 212 /* DoStatement */: + return parent.expression === node; + case 214 /* ForStatement */: + case 195 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 185 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 192 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 194 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 54 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 185 /* ParenthesizedExpression */ || + node.parent.kind === 192 /* PrefixUnaryExpression */ && + node.parent.operator === 51 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 222 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 216 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 227 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 219 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 218 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + } + if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 177 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 198 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 178 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 261 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 262 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 263 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 51 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 58 /* EqualsToken */ && node.left.kind === 180 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 179 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocComment(node) { + ts.forEachChild(node, function (n) { + if (n.kind !== 283 /* JSDocTypedefTag */) { + bind(n); + } + }); + } + function bindJSDocTypedefTag(node) { + ts.forEachChild(node, function (n) { + // if the node has a fullName "A.B.C", that means symbol "C" was already bound + // when we visit "fullName"; so when we visit the name "C" as the next child of + // the jsDocTypedefTag, we should skip binding it. + if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { + return; + } + bind(n); + }); + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 185 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 186 /* FunctionExpression */ || expr.kind === 187 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 179 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 199 /* ClassExpression */: + case 229 /* ClassDeclaration */: + case 232 /* EnumDeclaration */: + case 178 /* ObjectLiteralExpression */: + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 254 /* JsxAttributes */: + return 1 /* IsContainer */; + case 230 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 233 /* ModuleDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 172 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 265 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 151 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 152 /* Constructor */: + case 228 /* FunctionDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 155 /* CallSignature */: + case 273 /* JSDocFunctionType */: + case 160 /* FunctionType */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 161 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 234 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 149 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 260 /* CatchClause */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + case 235 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 207 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + // Just call this directly so that the return type of this function stays "void". + return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 233 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 265 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 199 /* ClassExpression */: + case 229 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 232 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 178 /* ObjectLiteralExpression */: + case 230 /* InterfaceDeclaration */: + case 254 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 273 /* JSDocFunctionType */: + case 231 /* TypeAliasDeclaration */: + case 172 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 265 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 265 /* SourceFile */ || body.kind === 234 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 244 /* ExportDeclaration */ || stat.kind === 243 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isExternalModuleAugmentation(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 9 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + if (pattern) { + (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); + } + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { + // if module was already merged with some function, class or non-const enum + // treat is a non-const-enum-only + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; + if (node.symbol.constEnumOnlyModule === undefined) { + // non-merged case - use the current state + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + // merged case: module is const enum only if all its pieces are non-instantiated or const enum + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, 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.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */ || prop.kind === 151 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 233 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 265 /* SourceFile */: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !ts.isInAmbientContext(node)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 71 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 265 /* SourceFile */ && + blockScopeContainer.kind !== 233 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // 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 (ts.isInJavaScriptFile(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 + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 142 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } + inStrictMode = saveInStrictMode; + } + function bindJSDocTypedefTagIfAny(node) { + if (!node.jsDoc) { + return; + } + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (!jsDoc.tags) { + continue; + } + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.kind === 283 /* JSDocTypedefTag */) { + var savedParent = parent; + parent = jsDoc; + bind(tag); + parent = savedParent; + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 71 /* Identifier */: + // 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) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 283 /* JSDocTypedefTag */) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + break; + } + // falls through + case 99 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 262 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 179 /* PropertyAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + break; + case 194 /* BinaryExpression */: + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindStaticPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 260 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 188 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 193 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 192 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 220 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 169 /* ThisType */: + seenThisKeyword = true; + return; + case 158 /* TypePredicate */: + return checkTypePredicate(node); + case 145 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + case 146 /* Parameter */: + return bindParameter(node); + case 226 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 176 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + return bindPropertyWorker(node); + case 261 /* PropertyAssignment */: + case 262 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 264 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 228 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 152 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 153 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 154 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 160 /* FunctionType */: + case 273 /* JSDocFunctionType */: + case 161 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 172 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 178 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return bindFunctionExpression(node); + case 181 /* CallExpression */: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 199 /* ClassExpression */: + case 229 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 230 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + case 231 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + case 232 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 233 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 254 /* JsxAttributes */: + return bindJsxAttributes(node); + case 253 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 237 /* ImportEqualsDeclaration */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 236 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 239 /* ImportClause */: + return bindImportClause(node); + case 244 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 243 /* ExportAssignment */: + return bindExportAssignment(node); + case 265 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 207 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 234 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 279 /* JSDocParameterTag */: + if (node.parent.kind !== 285 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 284 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 283 /* JSDocTypedefTag */: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71 /* Identifier */) { + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 71 /* Identifier */) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 169 /* ThisType */) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. + var flags = node.kind === 243 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 2097152 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + if (node.parent.kind !== 265 /* SourceFile */) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + } + function isExportsOrModuleExportsOrAlias(node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + isNameOfExportsOrModuleExportsAliasDeclaration(node); + } + function isNameOfExportsOrModuleExportsAliasDeclaration(node) { + if (ts.isIdentifier(node)) { + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); + } + return false; + } + function isExportsOrModuleExportsOrAliasOrAssignment(node) { + return isExportsOrModuleExportsOrAlias(node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + // Mark it as a module in case there are no other exports in the file + setCommonJsModuleIndicator(node); + return; + } + // 'module.exports = expr' assignment + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (container.kind) { + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + // Declare a 'member' if the container is an ES5 class or ES6 constructor + container.symbol.members = container.symbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + break; + case 152 /* Constructor */: + case 149 /* PropertyDeclaration */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = container.parent; + var symbolTable = ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + } + } + function bindPrototypePropertyAssignment(node) { + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ true); + } + function bindStaticPropertyAssignment(node) { + // We saw a node of the form 'x.y = z'. Declare a 'member' y on x if x was a function. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var leftSideOfAssignment = node.left; + var target = leftSideOfAssignment.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } + } + function lookupSymbolForName(name) { + return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); + } + function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { + var targetSymbol = lookupSymbolForName(functionName); + if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { + targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + } + if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */))) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : + (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); + // Declare the method/property + declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4 /* Property */, 0 /* PropertyExcludes */); + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 229 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); + } + } + } + function bindParameter(node) { + 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); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 209 /* EmptyStatement */) || + // report error on class declarations + node.kind === 229 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 233 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 232 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 208 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + } + return true; + } + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 181 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 182 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 233 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 185 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 194 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 210 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 146 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 187 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 186 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 228 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 226 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 227 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 208 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 222 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 229 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 199 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 259 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 260 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 201 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 152 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 149 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 151 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 237 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 179 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */ + || isSuperOrSuperProperty(expression, expressionKind)) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + if (expression.kind === 91 /* ImportKeyword */) { + transformFlags |= 67108864 /* ContainsDynamicImport */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 97 /* SuperKeyword */: + return true; + case 179 /* PropertyAccessExpression */: + case 180 /* ElementAccessExpression */: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 97 /* SuperKeyword */; + } + return false; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 177 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ + || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & 4096 /* ContainsDecorators */ + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (modifierFlags & 92 /* ParameterPropertyModifier */) { + transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 202 /* AsExpression */ + || expressionKind === 184 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2 /* Ambient */) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~539358529 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~539358529 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 85 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 108 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537920833 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer) { + transformFlags |= 8192 /* ContainsPropertyInitializer */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601281857 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601281857 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionKind === 97 /* SuperKeyword */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (modifierFlags & 2 /* Ambient */) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~574674241 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 536872257 /* NodeExcludes */; + switch (kind) { + case 120 /* AsyncKeyword */: + case 191 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 117 /* AbstractKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 232 /* EnumDeclaration */: + case 264 /* EnumMember */: + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + case 203 /* NonNullExpression */: + case 131 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 249 /* JsxElement */: + case 250 /* JsxSelfClosingElement */: + case 251 /* JsxOpeningElement */: + case 10 /* JsxText */: + case 252 /* JsxClosingElement */: + case 253 /* JsxAttribute */: + case 254 /* JsxAttributes */: + case 255 /* JsxSpreadAttribute */: + case 256 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + case 196 /* TemplateExpression */: + case 183 /* TaggedTemplateExpression */: + case 262 /* ShorthandPropertyAssignment */: + case 115 /* StaticKeyword */: + case 204 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 9 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 216 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 197 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + break; + case 119 /* AnyKeyword */: + case 133 /* NumberKeyword */: + case 130 /* NeverKeyword */: + case 134 /* ObjectKeyword */: + case 136 /* StringKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 145 /* TypeParameter */: + case 148 /* PropertySignature */: + case 150 /* MethodSignature */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 158 /* TypePredicate */: + case 159 /* TypeReference */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 162 /* TypeQuery */: + case 163 /* TypeLiteral */: + case 164 /* ArrayType */: + case 165 /* TupleType */: + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 168 /* ParenthesizedType */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 169 /* ThisType */: + case 170 /* TypeOperator */: + case 171 /* IndexedAccessType */: + case 172 /* MappedType */: + case 173 /* LiteralType */: + case 236 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 144 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 2097152 /* ContainsComputedPropertyName */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 198 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + break; + case 263 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + break; + case 97 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 99 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 16384 /* ContainsLexicalThis */; + break; + case 174 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + if (subtreeFlags & 524288 /* ContainsRest */) { + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + } + excludeFlags = 537396545 /* BindingPatternExcludes */; + break; + case 175 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + excludeFlags = 537396545 /* BindingPatternExcludes */; + break; + case 176 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 524288 /* ContainsRest */; + } + break; + case 147 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + break; + case 178 /* ObjectLiteralExpression */: + excludeFlags = 540087617 /* ObjectLiteralExcludes */; + if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 177 /* ArrayLiteralExpression */: + case 182 /* NewExpression */: + excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 265 /* SourceFile */: + if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 219 /* ReturnStatement */: + case 217 /* ContinueStatement */: + case 218 /* BreakStatement */: + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 181 /* CallExpression */: + case 182 /* NewExpression */: + case 177 /* ArrayLiteralExpression */: + return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + case 233 /* ModuleDeclaration */: + return 574674241 /* ModuleExcludes */; + case 146 /* Parameter */: + return 536872257 /* ParameterExcludes */; + case 187 /* ArrowFunction */: + return 601249089 /* ArrowFunctionExcludes */; + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + return 601281857 /* FunctionExcludes */; + case 227 /* VariableDeclarationList */: + return 546309441 /* VariableDeclarationListExcludes */; + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + return 539358529 /* ClassExcludes */; + case 152 /* Constructor */: + return 601015617 /* ConstructorExcludes */; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return 601015617 /* MethodOrAccessorExcludes */; + case 119 /* AnyKeyword */: + case 133 /* NumberKeyword */: + case 130 /* NeverKeyword */: + case 136 /* StringKeyword */: + case 134 /* ObjectKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 145 /* TypeParameter */: + case 148 /* PropertySignature */: + case 150 /* MethodSignature */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 178 /* ObjectLiteralExpression */: + return 540087617 /* ObjectLiteralExcludes */; + case 260 /* CatchClause */: + return 537920833 /* CatchClauseExcludes */; + case 174 /* ObjectBindingPattern */: + case 175 /* ArrayBindingPattern */: + return 537396545 /* BindingPatternExcludes */; + default: + return 536872257 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + } +})(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; + } + /** Reads from "main" or "types"/"typings" depending on `extensions`. */ + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); + function tryReadFromField(fieldName) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. + } + var typeRoots; + forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + resolvedFile = resolvedTypeScriptOnly(result && result.value); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + var directoryToModuleNameMap = ts.createMap(); + var moduleNameToDirectoryMap = ts.createMap(); + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + var perFolderCache = directoryToModuleNameMap.get(path); + if (!perFolderCache) { + perFolderCache = ts.createMap(); + directoryToModuleNameMap.set(path, perFolderCache); + } + return perFolderCache; + } + function getOrCreateCacheForModuleName(nonRelativeModuleName) { + if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { + return undefined; + } + var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); + if (!perModuleNameCache) { + perModuleNameCache = createPerModuleNameCache(); + moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + } + return perModuleNameCache; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + // find common prefix between directory and resolved file name + // this common prefix should be the shorted path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + var commonPrefix = getCommonPrefix(path, resolvedFileName); + var current = path; + while (true) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + if (current === commonPrefix) { + break; + } + } + } + function getCommonPrefix(directory, resolution) { + if (resolution === undefined) { + return undefined; + } + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs + var i = 0; + while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + // find last directory separator before position i + var sep = directory.lastIndexOf(ts.directorySeparator, i); + if (sep < 0) { + return undefined; + } + return directory.substr(0, sep); + } + } + } + ts.createModuleResolutionCache = createModuleResolutionCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + break; + 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); + // put result in per-module name cache + var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); + if (perModuleNameCache) { + perModuleNameCache.set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (path_1 !== undefined) { + return { path: path_1, extension: extension }; + } + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + 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 }; + var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + } + } + } + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + if (resolvedFromFile) { + return resolvedFromFile; + } + } + if (!onlyRecordFailures) { + var candidateExists = directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts" /* Dts */); + case Extensions.TypeScript: + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); + case Extensions.JavaScript: + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + } + function tryExtension(extension) { + var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } + } + else { + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); + } + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions, path) { + var extension = ts.tryGetExtensionFromPath(path); + return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + } + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TypeScript: + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; + case Extensions.DtsOnly: + return extension === ".d.ts" /* Dts */; + } + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + } + }); + } + /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== Extensions.JavaScript) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + } + } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + var mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackage(moduleName, state) { + if (ts.startsWith(moduleName, "@")) { + var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== moduleName) { + var mangled = replaceSlash.slice(1); // Take off the "@" + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + } + return moduleName; + } + /* @internal */ + function getPackageNameFromAtTypesDirectory(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + var result = cache && cache.get(containingDirectory); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + } + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // Climb up parent directories looking for a module. + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var symbolInstantiationDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); + var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; + var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; + var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; + var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount; + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { + parameter = ts.getParseTreeNode(parameter, ts.isParameter); + ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (node) { + node = ts.getParseTreeNode(node, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : unknownType; + }, + getParameterType: getTypeAtPosition, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (node) { + node = ts.getParseTreeNode(node, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : unknownType; + }, + getPropertySymbolOfDestructuringAssignment: function (location) { + location = ts.getParseTreeNode(location, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, + symbolToString: function (symbol, enclosingDeclaration, meaning) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (node) { + node = ts.getParseTreeNode(node, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { + node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + apparentArgumentCount = theArgumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; + apparentArgumentCount = undefined; + return res; + }, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (node, propertyName) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); + return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + }, + getSignatureFromDeclaration: function (declaration) { + declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: function (symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + }, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getAmbientModules: getAmbientModules, + getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { + node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; + }, + getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + isOptionalParameter: function (node) { + node = ts.getParseTreeNode(node, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + }, + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + resolveNameAtLocation: function (location, name, meaning) { + location = ts.getParseTreeNode(location); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, ts.escapeLeadingUnderscores(name)); + }, + }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(4096 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(2 /* String */, "string"); + var numberType = createIntrinsicType(4 /* Number */, "number"); + var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); + var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(1024 /* Void */, "void"); + var neverType = createIntrinsicType(8192 /* Never */, "never"); + var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + var globals = ts.createSymbolTable(); + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredJsxElementClassType; + var deferredJsxElementType; + var deferredJsxStatelessElementType; + var deferredNodes; + var deferredUnusedIdentifierNodes; + var flowLoopStart = 0; + var flowLoopCount = 0; + var visitedFlowCount = 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 = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var visitedFlowNodes = []; + var visitedFlowTypes = []; + var potentialThisCollisions = []; + 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"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. + 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 /* TypeofEQString */, + "number": 2 /* TypeofEQNumber */, + "boolean": 4 /* TypeofEQBoolean */, + "symbol": 8 /* TypeofEQSymbol */, + "undefined": 16384 /* EQUndefined */, + "object": 16 /* TypeofEQObject */, + "function": 32 /* TypeofEQFunction */ + }); + var typeofNEFacts = ts.createMapFromTemplate({ + "string": 128 /* TypeofNEString */, + "number": 256 /* TypeofNENumber */, + "boolean": 512 /* TypeofNEBoolean */, + "symbol": 1024 /* TypeofNESymbol */, + "undefined": 131072 /* NEUndefined */, + "object": 2048 /* TypeofNEObject */, + "function": 4096 /* TypeofNEFunction */ + }); + var typeofTypesByName = ts.createMapFromTemplate({ + "string": stringType, + "number": numberType, + "boolean": booleanType, + "symbol": esSymbolType, + "undefined": undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var _jsxElementPropertiesName; + var _hasComputedJsxElementPropertiesName = false; + var _jsxElementChildrenPropertyName; + var _hasComputedJsxElementChildrenPropertyName = false; + /** Things we lazy load from the JSX namespace */ + var jsxTypes = ts.createUnderscoreEscapedMap(); + var JsxNames = { + JSX: "JSX", + IntrinsicElements: "IntrinsicElements", + ElementClass: "ElementClass", + ElementAttributesPropertyNameContainer: "ElementAttributesProperty", + ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" + }; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. + 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.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + initializeTypeChecker(); + return checker; + function getJsxNamespace() { + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function error(location, message, arg0, arg1, arg2) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + diagnostics.add(diagnostic); + } + function createSymbol(flags, name) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 107455 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 107454 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 900095 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 106927 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 899519 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 792968 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 899327 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 899967 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 106639 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 99263 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 41919 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 74687 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 530920 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 793064 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations.slice(0); + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 233 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 233 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024 /* NamespaceModule */) { + 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + ts.forEach(target.declarations, function (node) { + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + } + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + } + else { + if (!(targetSymbol.flags & 33554432 /* Transient */)) { + targetSymbol = cloneSymbol(targetSymbol); + target.set(id, targetSymbol); + } + mergeSymbol(targetSymbol, sourceSymbol); + } + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + // if module symbol has already been merged - it is safe to use it. + // otherwise clone it + mainModule = mainModule.flags & 33554432 /* Transient */ ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + // Error on redeclarations + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function getObjectFlags(type) { + return type.flags & 32768 /* Object */ ? type.objectFlags : 0; + } + function isGlobalSourceFile(node) { + return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + // return undefined if we can't find a symbol. + } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + ts.isInAmbientContext(declaration)) { + // nodes are in different files and order cannot be determined + return true; + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + if (declaration.kind === 176 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 176 /* BindingElement */); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226 /* VariableDeclaration */), usage); + } + else if (declaration.kind === 226 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + return true; + } + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + if (usage.parent.kind === 246 /* ExportSpecifier */) { + // export specifiers do not use the variable, they only make it available for use + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 208 /* VariableStatement */: + case 214 /* ForStatement */: + case 216 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + // ForIn/ForOf case - use site should not be used in expression part + return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 149 /* PropertyDeclaration */ && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.getModifierFlags(current.parent) & 32 /* Static */) { + if (declaration.kind === 151 /* MethodDeclaration */) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !(ts.getModifierFlags(declaration) & 32 /* Static */); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + }); + } + } + // 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, 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; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + 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 = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 275 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + ? lastLocation === location.type || + lastLocation.kind === 146 /* Parameter */ || + lastLocation.kind === 145 /* TypeParameter */ + : false; + } + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 146 /* Parameter */ || + (lastLocation === location.type && + result.valueDeclaration.kind === 146 /* Parameter */); + } + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 265 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + // falls through + case 233 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 265 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports.get("default")) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 246 /* ExportSpecifier */)) { + break; + } + } + if (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */)) { + break loop; + } + break; + case 232 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container + result = undefined; + break; + } + if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 199 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 144 /* ComputedPropertyName */: + 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 = 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; + } + } + break; + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 186 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 147 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 146 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (result && nameNotFoundMessage && noUnusedIdentifiers) { + result.isReferenced = true; + } + if (!result) { + result = lookup(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 236 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + } + } + } + return result; + } + function diagnosticName(nameArg) { + return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 145 /* TypeParameter */ && decl.parent === container) { + return true; + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if ((errorLocation.kind === 71 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); + if (isError) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + } + return isError; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 71 /* Identifier */: + case 179 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 201 /* ExpressionWithTypeArguments */: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920 /* Namespace */) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + 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, ts.unescapeLeadingUnderscores(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, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232 /* EnumDeclaration */) ? d : undefined; }); + 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(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 32 /* Class */) { + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + if (ts.isAliasSymbolDeclaration(node)) { + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; + } + return ts.findAncestor(node, ts.isImportDeclaration); + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + var exportValue = moduleSymbol.exports.get("export="); + exportDefaultSymbol = exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") + : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + } + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536 /* Module */) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, 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); + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + switch (node.kind) { + case 237 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 239 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 240 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 242 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 246 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 243 /* ExportAssignment */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 236 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + } + } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + */ + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */; } + return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; + } + function resolveSymbol(symbol, dontResolveAlias) { + var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); + return shouldResolve ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + if (node.kind === 243 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 246 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 143 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 237 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol) { + return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + } + /** + * Resolves a qualified name and any involved aliases. + */ + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var symbol; + if (name.kind === 71 /* Identifier */) { + var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + if (!symbol) { + return undefined; + } + } + else if (name.kind === 143 /* QualifiedName */ || name.kind === 179 /* PropertyAccessExpression */) { + var left = void 0; + if (name.kind === 143 /* QualifiedName */) { + left = name.left; + } + else if (name.kind === 179 /* PropertyAccessExpression */ && + (name.expression.kind === 185 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { + left = name.expression; + } + else { + // If the expression in property-access expression is not entity-name or parenthsizedExpression (e.g. it is a call expression), it won't be able to successfully resolve the name. + // This is the case when we are trying to do any language service operation in heritage clauses. By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression + // will attempt to checkPropertyAccessExpression to resolve symbol. + // i.e class C extends foo()./*do language service operation here*/B {} + return undefined; + } + var right = name.kind === 143 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else if (name.kind === 185 /* ParenthesizedExpression */) { + // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name. + // This is the case when we are trying to do any language service operation in heritage clauses. + // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol. + // i.e class C extends foo()./*do language service operation here*/B {} + return ts.isEntityNameExpression(name.expression) ? + resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : + undefined; + } + else { + ts.Debug.fail("Unknown entity name kind."); + } + 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) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReferenceExpression.kind !== 9 /* StringLiteral */ && moduleReferenceExpression.kind !== 13 /* NoSubstitutionTemplateLiteral */) { + return; + } + var moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === 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(moduleReference, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + var isRelative = ts.isExternalModuleNameRelative(moduleReference); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (noImplicitAny && moduleNotFoundError) { + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { + // report errors only if it was requested + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, + // and an external module with no 'export =' declaration resolves to the module itself. + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // 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, moduleReferenceExpression, dontResolveAlias) { + 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)); + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=") !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (!symbol) { + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); + } + } + return symbol; + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { + source && source.forEach(function (sourceSymbol, id) { + if (id === "default") + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + return; + } + visitedSymbols.push(symbol); + var symbols = ts.cloneMap(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent); + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 + ? getMergedSymbol(symbol.exportSymbol) + : symbol; + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 152 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(32768 /* Object */); + type.objectFlags = objectFlags; + type.symbol = symbol; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(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 + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + if (symbolIsValue(symbol)) { + result.push(symbol); + } + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + // 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 = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 265 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 233 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { + return true; + } + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + return !!accessibleParent; + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + } + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { + if (!useOnlyExternalAliasing || + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + } + }); + } + } + if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + if (!symbolFromSymbolTable) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 149 /* PropertyDeclaration */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { + var initialSymbol = symbol; + var meaningToLook = meaning; + while (symbol) { + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (!hasAccessibleDeclarations) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + return hasAccessibleDeclarations; + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + meaningToLook = getQualifiedLeftMeaning(meaning); + symbol = getParentOfSymbol(symbol); + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 /* Accessible */ }; + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && + isDeclarationVisible(anyImportSyntax.parent)) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; + } + } + return true; + } + // Declaration is not visible + return false; + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 162 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + // Typeof value + meaning = 107455 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 143 /* QualifiedName */ || entityName.kind === 179 /* PropertyAccessExpression */ || + entityName.parent.kind === 237 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 793064 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function writeKeyword(writer, kind) { + writer.writeKeyword(ts.tokenToString(kind)); + } + function writePunctuation(writer, kind) { + writer.writePunctuation(ts.tokenToString(kind)); + } + function writeSpace(writer) { + writer.writeSpace(" "); + } + function symbolToString(symbol, enclosingDeclaration, meaning) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); + }); + } + function signatureToString(signature, enclosingDeclaration, flags, kind) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); + }); + } + function typeToString(type, enclosingDeclaration, flags) { + 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); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); + var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; + if (maxLength && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 8 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 256 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 4096 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 64 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + 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) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + } + }; + function createNodeBuilderContext(enclosingDeclaration, flags) { + return { + enclosingDeclaration: enclosingDeclaration, + flags: flags, + encounteredError: false, + symbolStack: undefined + }; + } + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + if (!type) { + context.encounteredError = true; + return undefined; + } + if (type.flags & 1 /* Any */) { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + if (type.flags & 2 /* String */) { + return ts.createKeywordTypeNode(136 /* StringKeyword */); + } + if (type.flags & 4 /* Number */) { + return ts.createKeywordTypeNode(133 /* NumberKeyword */); + } + if (type.flags & 8 /* Boolean */) { + return ts.createKeywordTypeNode(122 /* BooleanKeyword */); + } + 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.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & (64 /* NumberLiteral */)) { + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 128 /* BooleanLiteral */) { + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 1024 /* Void */) { + return ts.createKeywordTypeNode(105 /* VoidKeyword */); + } + if (type.flags & 2048 /* Undefined */) { + return ts.createKeywordTypeNode(139 /* UndefinedKeyword */); + } + if (type.flags & 4096 /* Null */) { + return ts.createKeywordTypeNode(95 /* NullKeyword */); + } + if (type.flags & 8192 /* Never */) { + return ts.createKeywordTypeNode(130 /* NeverKeyword */); + } + if (type.flags & 512 /* ESSymbol */) { + return ts.createKeywordTypeNode(137 /* SymbolKeyword */); + } + if (type.flags & 16777216 /* NonPrimitive */) { + return ts.createKeywordTypeNode(134 /* ObjectKeyword */); + } + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + context.encounteredError = true; + } + } + return ts.createThis(); + } + var objectFlags = getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + return typeReferenceToTypeNode(type); + } + 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 (!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); + } + 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)) { + context.encounteredError = true; + } + return undefined; + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + // The type is an object literal type. + return createAnonymousTypeNode(type); + } + if (type.flags & 262144 /* Index */) { + var indexedType = type.type; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 524288 /* IndexedAccess */) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; + var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; + 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; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || + shouldWriteTypeOfFunctionSymbol()) { + 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, context, 793064 /* Type */, /*expectsIdentifier*/ false); + return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); + } + else { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + } + 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 + if (!context.symbolStack) { + context.symbolStack = []; + } + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } + } + else { + // Anonymous types without a symbol are never circular. + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + } + } + } + function createTypeNodeFromObjectType(type) { + if (type.objectFlags & 32 /* Mapped */) { + if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { + return createMappedTypeNodeFromType(type); + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + } + 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.escapedName) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var qualifiedName = void 0; + if (outerTypeParameters) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // 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 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 { + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); + } + } + } + } + var entityName = undefined; + var nameIdentifier = symbolToTypeReferenceName(type.symbol); + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); + entityName = qualifiedName; + } + else { + entityName = nameIdentifier; + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.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 */, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); + } + if (resolvedType.stringIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + var propertyType = getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* 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 */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + typeElements.push(methodDeclaration); + } + } + else { + 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 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 indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : 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 /* 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, context); + } + 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, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); + var constraint = getConstraintFromTypeParameter(type); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function symbolToParameterDeclaration(parameterSymbol, context) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { + // special-case synthetic rest parameters in JS files + return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameterSymbol.isRestParameter ? ts.createToken(24 /* DotDotDotToken */) : undefined, "args", + /*questionToken*/ undefined, typeToTypeNodeHelper(anyArrayType, context), + /*initializer*/ undefined); + } + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var parameterType = getTypeOfSymbol(parameterSymbol); + 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, 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 || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(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 typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { + var parentSymbol = chain[index - 1]; + var typeParameters = void 0; + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); + } + else { + var targetSymbol = getTargetSymbol(parentSymbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + } + } + typeParameterNodes = mapToTypeNodes(typeParameters, context); + } + 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. */ + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var parentSymbol; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + parentSymbol = parent; + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + return [symbol]; + } + } + } + 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 ts.unescapeLeadingUnderscores(symbol.escapedName); + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + }); + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144 /* Nullable */)) { + if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { + 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); + } + } + if (flags & 4096 /* Null */) + result.push(nullType); + if (flags & 2048 /* Undefined */) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168 /* ParenthesizedType */; }); + if (node.kind === 231 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 234 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function literalTypeToString(type) { + 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]; + 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); + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; + } + } + return ts.unescapeLeadingUnderscores(symbol.escapedName); + } + function getSymbolDisplayBuilder() { + /** + * Writes only the name of the symbol out to the writer. Uses the original source text + * for the name of the symbol if it is available to match how the user wrote the name. + */ + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); + } + /** + * Writes a property access or element access with the name of the symbol out to the writer. + * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, + * ensuring that any names written with literals use element accesses. + */ + function appendPropertyOrElementAccessForSymbol(symbol, writer) { + var symbolName = getNameOfSymbol(symbol); + var firstChar = symbolName.charCodeAt(0); + var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); + if (needsElementAccess) { + writePunctuation(writer, 21 /* OpenBracketToken */); + if (ts.isSingleOrDoubleQuote(firstChar)) { + writer.writeStringLiteral(symbolName); + } + else { + writer.writeSymbol(symbolName, symbol); + } + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else { + writePunctuation(writer, 23 /* DotToken */); + writer.writeSymbol(symbolName, symbol); + } + } + /** + * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope + * Meaning needs to be specified if the enclosing declaration is given + */ + function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { + var parentSymbol; + function appendParentTypeArgumentsAndSymbolName(symbol) { + if (parentSymbol) { + // Write type arguments of instantiated class/interface here + if (flags & 1 /* WriteTypeParametersOrArguments */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); + } + else { + buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); + } + } + appendPropertyOrElementAccessForSymbol(symbol, writer); + } + else { + appendSymbolNameOnly(symbol, writer); + } + parentSymbol = symbol; + } + // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // this to determine if an import it has previously seen (and not written out) needs + // to be written to the file once the walk of the tree is complete. + // + // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree + // up front (for example, during checking) could determine if we need to emit the imports + // and we could then access that data during declaration emit. + writer.trackSymbol(symbol, enclosingDeclaration, meaning); + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + } + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + } + } + else if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + // Get qualified name if the symbol is not a type parameter + // and there is an enclosing declaration or we specifically + // asked for it + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; + if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { + walkSymbol(symbol, meaning, /*endOfChain*/ true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { + var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); + var inObjectTypeLiteral = false; + return writeType(type, globalFlags); + function writeType(type, flags) { + var nextFlags = flags & ~1024 /* InTypeAlias */; + // Write undefined/null type as any + if (type.flags & 16793231 /* Intrinsic */) { + // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving + writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (inObjectTypeLiteral) { + writer.reportInaccessibleThisError(); + } + writer.writeKeyword("this"); + } + else if (getObjectFlags(type) & 4 /* Reference */) { + writeTypeReference(type, nextFlags); + } + 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 & (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); + } + else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); + } + else if (type.flags & 196608 /* UnionOrIntersection */) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96 /* StringOrNumberLiteral */) { + writer.writeStringLiteral(literalTypeToString(type)); + } + else if (type.flags & 262144 /* Index */) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 128 /* InElementType */); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + } + else if (type.flags & 524288 /* IndexedAccess */) { + writeType(type.objectType, 128 /* InElementType */); + writePunctuation(writer, 21 /* OpenBracketToken */); + writeType(type.indexType, 0 /* None */); + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else { + // Should never get here + // { ... } + writePunctuation(writer, 17 /* OpenBraceToken */); + writeSpace(writer); + writePunctuation(writer, 24 /* DotDotDotToken */); + writeSpace(writer); + writePunctuation(writer, 18 /* CloseBraceToken */); + } + } + function writeTypeList(types, delimiter) { + for (var i = 0; i < types.length; i++) { + if (i > 0) { + if (delimiter !== 26 /* CommaToken */) { + writeSpace(writer); + } + writePunctuation(writer, delimiter); + writeSpace(writer); + } + writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); + } + } + function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + } + if (pos < end) { + writePunctuation(writer, 27 /* LessThanToken */); + writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); + pos++; + while (pos < end) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + writeType(typeArguments[pos], 0 /* None */); + pos++; + } + writePunctuation(writer, 29 /* GreaterThanToken */); + } + } + function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { + writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); + writePunctuation(writer, 21 /* OpenBracketToken */); + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else if (type.target.objectFlags & 8 /* Tuple */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 199 /* 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 + // type parameters. + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_3 = outerTypeParameters.length; + while (i < length_3) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // 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)) { + writeSymbolTypeReference(parent, typeArguments, start, i, flags); + writePunctuation(writer, 23 /* DotToken */); + } + } + } + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); + } + } + function writeUnionOrIntersectionType(type, flags) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + if (type.flags & 65536 /* Union */) { + writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); + } + else { + writeTypeList(type.types, 48 /* AmpersandToken */); + } + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + } + function writeAnonymousType(type, flags) { + var symbol = type.symbol; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & 32 /* Class */ && + !getBaseTypeVariableOfClass(symbol) && + !(symbol.valueDeclaration.kind === 199 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { + writeTypeOfSymbol(type, flags); + } + else if (shouldWriteTypeOfFunctionSymbol()) { + writeTypeOfSymbol(type, flags); + } + else if (ts.contains(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 + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + } + else { + // Recursive usage, use any + writeKeyword(writer, 119 /* AnyKeyword */); + } + } + 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 = []; + } + var isConstructorObject = type.flags & 32768 /* Object */ && + getObjectFlags(type) & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & 32 /* Class */; + if (isConstructorObject) { + writeLiteralType(type, flags); + } + else { + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } + } + } + else { + // Anonymous types with no symbol are never circular + writeLiteralType(type, flags); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return !!(flags & 4 /* UseTypeOfFunction */) || + (ts.contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively + } + } + } + function writeTypeOfSymbol(type, typeFormatFlags) { + if (typeFormatFlags & 32768 /* InArrayType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + writeKeyword(writer, 103 /* TypeOfKeyword */); + writeSpace(writer); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); + if (typeFormatFlags & 32768 /* InArrayType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 131 /* ReadonlyKeyword */); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 16777216 /* Optional */) { + writePunctuation(writer, 55 /* QuestionToken */); + } + } + function shouldAddParenthesisAroundFunctionType(callSignature, flags) { + if (flags & 128 /* InElementType */) { + return true; + } + else if (flags & 512 /* InFirstTypeArgument */) { + // Add parenthesis around function type for the first type argument to avoid ambiguity + var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? + callSignature.target.typeParameters : callSignature.typeParameters; + return typeParameters && typeParameters.length !== 0; + } + return false; + } + function writeLiteralType(type, flags) { + if (type.objectFlags & 32 /* Mapped */) { + if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { + writeMappedType(type); + return; + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + writePunctuation(writer, 17 /* OpenBraceToken */); + writePunctuation(writer, 18 /* CloseBraceToken */); + return; + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); + if (parenthesizeSignature) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); + if (parenthesizeSignature) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + return; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + writeKeyword(writer, 94 /* NewKeyword */); + writeSpace(writer); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + return; + } + } + var saveInObjectTypeLiteral = inObjectTypeLiteral; + inObjectTypeLiteral = true; + writePunctuation(writer, 17 /* OpenBraceToken */); + writer.writeLine(); + writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 18 /* CloseBraceToken */); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); + buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { + if (p.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { + writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + } + } + var t = getTypeOfSymbol(p); + if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { + var signatures = getSignaturesOfType(t, 0 /* Call */); + for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { + var signature = signatures_2[_f]; + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + } + else { + writePropertyWithModifiers(p); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + } + } + function writeMappedType(type) { + writePunctuation(writer, 17 /* OpenBraceToken */); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 131 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 21 /* OpenBracketToken */); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 92 /* InKeyword */); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 22 /* CloseBracketToken */); + if (type.declaration.questionToken) { + writePunctuation(writer, 55 /* QuestionToken */); + } + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 18 /* CloseBraceToken */); + } + } + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); + } + } + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { + appendSymbolNameOnly(tp.symbol, writer); + var constraint = getConstraintOfTypeParameter(tp); + if (constraint) { + writeSpace(writer); + writeKeyword(writer, 85 /* ExtendsKeyword */); + writeSpace(writer); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); + } + var defaultType = getDefaultFromTypeParameter(tp); + if (defaultType) { + writeSpace(writer); + writePunctuation(writer, 58 /* EqualsToken */); + writeSpace(writer); + buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { + writePunctuation(writer, 24 /* DotDotDotToken */); + } + if (parameterNode && ts.isBindingPattern(parameterNode.name)) { + buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + appendSymbolNameOnly(p, writer); + } + if (parameterNode && isOptionalParameter(parameterNode)) { + writePunctuation(writer, 55 /* QuestionToken */); + } + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + var type = getTypeOfSymbol(p); + if (parameterNode && isRequiredInitializedParameter(parameterNode)) { + type = getNullableType(type, 2048 /* Undefined */); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { + // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. + if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { + writePunctuation(writer, 17 /* OpenBraceToken */); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 18 /* CloseBraceToken */); + } + else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + var elements = bindingPattern.elements; + buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (elements && elements.hasTrailingComma) { + writePunctuation(writer, 26 /* CommaToken */); + } + writePunctuation(writer, 22 /* CloseBracketToken */); + } + } + function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isOmittedExpression(bindingElement)) { + return; + } + ts.Debug.assert(bindingElement.kind === 176 /* BindingElement */); + if (bindingElement.propertyName) { + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + } + if (ts.isBindingPattern(bindingElement.name)) { + buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + if (bindingElement.dotDotDotToken) { + writePunctuation(writer, 24 /* DotDotDotToken */); + } + appendSymbolNameOnly(bindingElement.symbol, writer); + } + } + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27 /* LessThanToken */); + buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 29 /* GreaterThanToken */); + } + } + function buildDisplayForCommaSeparatedList(list, writer, action) { + for (var i = 0; i < list.length; i++) { + if (i > 0) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + } + action(list[i]); + } + } + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27 /* LessThanToken */); + var flags = 512 /* InFirstTypeArgument */; + for (var i = 0; i < typeParameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + flags = 0 /* None */; + } + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); + } + writePunctuation(writer, 29 /* GreaterThanToken */); + } + } + function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { + writePunctuation(writer, 19 /* OpenParenToken */); + if (thisParameter) { + buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); + } + for (var i = 0; i < parameters.length; i++) { + if (i > 0 || thisParameter) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + } + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); + } + writePunctuation(writer, 20 /* CloseParenToken */); + } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 99 /* ThisKeyword */); + } + writeSpace(writer); + writeKeyword(writer, 126 /* IsKeyword */); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + var returnType = getReturnTypeOfSignature(signature); + if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { + return; + } + if (flags & 16 /* WriteArrowStyleSignature */) { + writeSpace(writer); + writePunctuation(writer, 36 /* EqualsGreaterThanToken */); + } + else { + writePunctuation(writer, 56 /* ColonToken */); + } + writeSpace(writer); + if (signature.typePredicate) { + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); + } + else { + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1 /* Construct */) { + writeKeyword(writer, 94 /* NewKeyword */); + writeSpace(writer); + } + if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { + // Instantiated signature, write type arguments instead + // This is achieved by passing in the mapper separately + buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); + } + else { + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); + } + buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); + } + function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 131 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 21 /* OpenBracketToken */); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + switch (kind) { + case 1 /* Number */: + writeKeyword(writer, 133 /* NumberKeyword */); + break; + case 0 /* String */: + writeKeyword(writer, 136 /* StringKeyword */); + break; + } + writePunctuation(writer, 22 /* CloseBracketToken */); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + } + return _displayBuilder || (_displayBuilder = { + buildSymbolDisplay: buildSymbolDisplay, + buildTypeDisplay: buildTypeDisplay, + buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, + buildParameterDisplay: buildParameterDisplay, + buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, + buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, + buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, + buildSignatureDisplay: buildSignatureDisplay, + buildIndexSignatureDisplay: buildIndexSignatureDisplay, + buildReturnTypeDisplay: buildReturnTypeDisplay + }); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 176 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 226 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // falls through + case 233 /* ModuleDeclaration */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 228 /* FunctionDeclaration */: + case 232 /* EnumDeclaration */: + case 237 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 237 /* ImportEqualsDeclaration */ && parent.kind !== 265 /* SourceFile */ && ts.isInAmbientContext(parent))) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 152 /* Constructor */: + case 156 /* ConstructSignature */: + case 155 /* CallSignature */: + case 157 /* IndexSignature */: + case 146 /* Parameter */: + case 234 /* ModuleBlock */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 163 /* TypeLiteral */: + case 159 /* TypeReference */: + case 164 /* ArrayType */: + case 165 /* TupleType */: + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 168 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 239 /* ImportClause */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 145 /* TypeParameter */: + // Source file and namespace export are always visible + case 265 /* SourceFile */: + case 236 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 243 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node) { + var exportSymbol; + if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { + exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + } + else if (node.parent.kind === 246 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result = []; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + getNodeLinks(declaration).isVisible = true; + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (!ts.contains(result, resultNode)) { + result.push(resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_4 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_4; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + if (propertyName === 0 /* Type */) { + return getSymbolLinks(target).type; + } + if (propertyName === 2 /* DeclaredType */) { + return getSymbolLinks(target).declaredType; + } + if (propertyName === 1 /* ResolvedBaseConstructorType */) { + return target.resolvedBaseConstructorType; + } + if (propertyName === 3 /* ResolvedReturnType */) { + return target.resolvedReturnType; + } + ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 226 /* VariableDeclaration */: + case 227 /* VariableDeclarationList */: + case 242 /* ImportSpecifier */: + case 241 /* NamedImports */: + case 240 /* NamespaceImport */: + case 239 /* ImportClause */: + return false; + default: + return true; + } + }); + return node && node.parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + } + function isComputedNonLiteralName(name) { + return name.kind === 144 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (source.flags & 8192 /* Never */) { + return emptyObjectType; + } + if (source.flags & 65536 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createSymbolTable(); + var names = ts.createUnderscoreEscapedMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name), true); + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = names.has(prop.escapedName); + 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.escapedName, prop); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + /** Return the inferred type for a binding element */ + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === unknownType) { + return unknownType; + } + // If no type was specified or inferred for parent, or if the specified or inferred type is any, + // infer from the initializer of the binding element if one is present. Otherwise, go with the + // undefined or any type of the parent. + if (!parentType || isTypeAny(parentType)) { + if (declaration.initializer) { + return checkDeclarationInitializer(declaration); + } + return parentType; + } + var type; + if (pattern.kind === 174 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, + // or otherwise the type of the string index signature. + var text = ts.getTextOfPropertyName(name); + var declaredType = getTypeOfPropertyOfType(parentType, text); + type = declaredType && getFlowTypeOfReference(declaration, declaredType) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || + getIndexTypeOfType(parentType, 0 /* String */); + if (!type) { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); + return unknownType; + } + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + if (declaration.dotDotDotToken) { + // Rest element has an array type with the same element type as the parent type + type = createArrayType(elementType); + } + else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var propName = "" + ts.indexOf(pattern.elements, declaration); + type = isTupleLikeType(parentType) + ? getTypeOfPropertyOfType(parentType, propName) + : elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + } + return unknownType; + } + } + } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { + type = getTypeWithFacts(type, 131072 /* NEUndefined */); + } + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, optional) { + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (declaration.parent.parent.kind === 215 /* ForInStatement */) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; + } + if (declaration.parent.parent.kind === 216 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + // Use type from type annotation if one is present + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + var declaredType = getTypeFromTypeNode(typeNode); + return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); + } + if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + declaration.kind === 226 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 146 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 154 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153 /* GetAccessor */); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + // Use contextual parameter type if one is available + var type = void 0; + if (declaration.symbol.escapedName === "this") { + type = getContextualThisParameterType(func); + } + else { + type = getContextuallyTypedParameterType(declaration); + } + if (type) { + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + } + if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for + return trueType; + } + // If it is a short-hand property assignment, use the type of the identifier + if (declaration.kind === 262 /* ShorthandPropertyAssignment */) { + return checkIdentifier(declaration.name); + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + } + // No type specified and nothing can be inferred + return undefined; + } + function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + 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 : + declaration.kind === 179 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 194 /* BinaryExpression */) : + undefined; + if (!expression) { + return unknownType; + } + if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { + if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 152 /* Constructor */) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + // 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)); + } + } + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } + } + 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 + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return checkDeclarationInitializer(element); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAnyError(element, anyType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var hasComputedProperties = false; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + hasComputedProperties = true; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + if (includePatternInType) { + result.pattern = pattern; + } + if (hasComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + // If the pattern has at least one element, and no rest element, then it should imply a tuple type. + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + return pattern.kind === 174 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // During a normal type check we'll never get to here with a property assignment (the check of the containing + // object literal uses a different path). We exclude widening only so that language services and type verification + // tools see the actual type. + if (declaration.kind === 261 /* PropertyAssignment */) { + return type; + } + return getWidenedType(type); + } + // Rest parameters default to type any[], other parameters default to type any + type = declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors && noImplicitAny) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAnyError(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 146 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return links.type = getTypeOfPrototypeProperty(symbol); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return links.type = anyType; + } + // Handle export default expressions + if (declaration.kind === 243 /* ExportAssignment */) { + return links.type = checkExpression(declaration.expression); + } + if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = void 0; + // Handle certain special assignment kinds, which happen to union across multiple declarations: + // * module.exports = expr + // * exports.p = expr + // * this.p = expr + // * className.prototype.method = expr + if (declaration.kind === 194 /* BinaryExpression */ || + declaration.kind === 179 /* PropertyAccessExpression */ && declaration.parent.kind === 194 /* BinaryExpression */) { + type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } + else { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function getAnnotatedAccessorType(accessor) { + if (accessor) { + if (accessor.kind === 153 /* GetAccessor */) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + } + } + return undefined; + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var getter = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 154 /* SetAccessor */); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return links.type = jsDocType; + } + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = void 0; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + else { + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); + error(getter_1, 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, symbolToString(symbol)); + } + } + links.type = type; + } + return links.type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 540672 /* TypeVariable */ ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + links.type = anyType; + } + else { + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; + } + } + } + return links.type; + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getDeclaredTypeOfEnumMember(symbol); + } + return links.type; + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 107455 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : unknownType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbolInstantiationDepth === 100) { + error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); + links.type = unknownType; + } + else { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + symbolInstantiationDepth++; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + symbolInstantiationDepth--; + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + } + return links.type; + } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return unknownType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (getObjectFlags(type) & 4 /* Reference */) !== 0 + && type.target === target; + } + function getTargetType(type) { + return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + var target = getTargetType(type); + return target === checkBase || ts.forEach(getBaseTypes(target), check); + } + else if (type.flags & 131072 /* Intersection */) { + return ts.forEach(type.types, check); + } + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + if (!typeParameters) { + typeParameters = [tp]; + } + else if (!ts.contains(typeParameters, tp)) { + typeParameters.push(tp); + } + } + return typeParameters; + } + // Appends the outer type parameters of a node to a set of type parameters and returns the resulting set. The function + // allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set in-place and + // returns the same array. + function appendOuterTypeParameters(typeParameters, node) { + while (true) { + node = node.parent; + if (!node) { + return typeParameters; + } + if (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || + node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */ || + node.kind === 151 /* MethodDeclaration */ || node.kind === 187 /* ArrowFunction */) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); + } + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); + return appendOuterTypeParameters(/*typeParameters*/ undefined, declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 229 /* ClassDeclaration */ || + node.kind === 199 /* ClassExpression */ || node.kind === 231 /* TypeAliasDeclaration */) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 540672 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type); + return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return false; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavaScript = ts.isInJavaScriptFile(location); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = unknownType; + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + return type.resolvedBaseConstructorType = unknownType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { + 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 */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // 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, typeArgs); + } + else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } + if (baseType === unknownType) { + return; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + return; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + return; + } + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. + function isValidBaseType(type) { + return type.flags & (32768 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 131072 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== unknownType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + } + } + } + } + } + } + // Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is + // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, + // and if none of the base interfaces have a "this" type. + function isIndependentInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return unknownType; + } + var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; }); + var type = getTypeFromTypeNode(declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type); + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + switch (expr.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return true; + case 192 /* PrefixUnaryExpression */: + return expr.operator === 38 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + default: + return false; + } + } + 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 (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; + } + 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) { + 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); + } + } + } + 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; + } + } + 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)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(16384 /* TypeParameter */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return unknownType; + } + // A type reference is considered independent if each type argument is considered independent. + function isIndependentTypeReference(node) { + if (node.typeArguments) { + for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { + var typeNode = _a[_i]; + if (!isIndependentType(typeNode)) { + return false; + } + } + } + return true; + } + // A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string + // literal type, an array with an element type that is considered independent, or a type reference that is + // considered independent. + function isIndependentType(node) { + switch (node.kind) { + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 134 /* ObjectKeyword */: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 130 /* NeverKeyword */: + case 173 /* LiteralType */: + return true; + case 164 /* ArrayType */: + return isIndependentType(node.elementType); + case 159 /* TypeReference */: + return isIndependentTypeReference(node); + } + return false; + } + // A variable-like declaration is considered independent (free of this references) if it has a type annotation + // that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any). + function isIndependentVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isIndependentType(typeNode) : !node.initializer; + } + // A function-like declaration is considered independent (free of this references) if it has a return type + // annotation that is considered independent and if each parameter is considered independent. + function isIndependentFunctionLikeDeclaration(node) { + if (node.kind !== 152 /* Constructor */) { + var typeNode = ts.getEffectiveReturnTypeNode(node); + if (!typeNode || !isIndependentType(typeNode)) { + return false; + } + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (!isIndependentVariableLikeDeclaration(parameter)) { + return false; + } + } + return true; + } + // Returns true if the class or interface member given by the symbol is free of "this" references. The + // function may return false for symbols that are actually free of "this" references because it is not + // feasible to perform a complete analysis in all cases. In particular, property members with types + // inferred from their initializers and function members with inferred return types are conservatively + // assumed not to be free of "this" references. + function isIndependentMember(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + return isIndependentVariableLikeDeclaration(declaration); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + return isIndependentFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + } + return type; + } + function getTypeWithThisArgument(type, thisArgument) { + if (getObjectFlags(type) & 4 /* Reference */) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + } + } + else if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + } + return type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === source.symbol.members) { + members = ts.createSymbolTable(source.declaredProperties); + } + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + if (!ts.contains(result, match)) { + (result || (result = [])).push(match); + } + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(types, kind) { + var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + s = cloneSignature(signature); + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + // Clear resolved return type we possibly got from cloneSignature + s.resolvedReturnType = undefined; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + 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; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(type.types, 0 /* Call */); + var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_3 = function (i) { + var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); + }; + for (var i = 0; i < types.length; i++) { + _loop_3(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + /** + * Converts an AnonymousType to a ResolvedType. + */ + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + // Combinations of function, class, enum and module + var members = emptySymbols; + var constructSignatures = ts.emptyArray; + var stringIndexInfo = undefined; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } + } + } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 170 /* TypeOperator */) { + // We have a { [P in keyof T]: X } + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var propertySymbol = _a[_i]; + addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); + } + if (getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + } + else { + // First, if the constraint type is a type parameter, obtain the base constraint. Then, + // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Finally, iterate over the constituents of the resulting iteration type. + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t, propertySymbol) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var iterationMapper = createTypeMapper([typeParameter], [t]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + // 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 = ts.escapeLeadingUnderscores(t.value); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; + prop.type = propType; + if (propertySymbol) { + prop.syntheticOrigin = propertySymbol; + prop.declarations = propertySymbol.declarations; + } + members.set(propName, prop); + } + else if (t.flags & 2 /* String */) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 170 /* TypeOperator */) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function isPartialMappedType(type) { + return getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; + } + function isGenericMappedType(type) { + return getObjectFlags(type) & 32 /* Mapped */ && + maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 /* TypeVariable */ | 262144 /* Index */); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 65536 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 131072 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + /** Return properties of an object type or an empty array for other types */ + function getPropertiesOfObjectType(type) { + if (type.flags & 32768 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ + function getPropertyOfObjectType(type, name) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 65536 /* Union */) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 196608 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createSymbolTable(); + 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 escapedName = _c[_b].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); + } + } + } + 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) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var baseObjectType = getBaseConstraintOfType(type.objectType); + var baseIndexType = getBaseConstraintOfType(type.indexType); + return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (540672 /* TypeVariable */ | 196608 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + if (constraint !== noConstraintType && constraint !== circularConstraintType) { + return constraint; + } + } + else if (type.flags & 262144 /* Index */) { + return stringType; + } + return undefined; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ + function getResolvedBaseConstraint(type) { + var typeStack; + var circular; + if (!type.resolvedBaseConstraint) { + typeStack = []; + var constraint = getBaseConstraint(type); + type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + } + return type.resolvedBaseConstraint; + function getBaseConstraint(t) { + if (ts.contains(typeStack, t)) { + circular = true; + return undefined; + } + typeStack.push(t); + var result = computeBaseConstraint(t); + typeStack.pop(); + return result; + } + function computeBaseConstraint(t) { + if (t.flags & 16384 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType ? constraint : + constraint ? getBaseConstraint(constraint) : undefined; + } + if (t.flags & 196608 /* UnionOrIntersection */) { + var types = t.types; + var baseTypes = []; + 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); + } + } + return t.flags & 65536 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 131072 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 262144 /* Index */) { + return stringType; + } + if (t.flags & 524288 /* IndexedAccess */) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type, `undefined` + * is returned. + * + * This function *does not* perform a circularity check. + */ + function getDefaultFromTypeParameter(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + } + } + return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 262178 /* StringLike */ ? globalStringType : + t.flags & 84 /* NumberLike */ ? globalNumberType : + t.flags & 136 /* BooleanLike */ ? globalBooleanType : + t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var types = containingType.types; + var isUnion = containingType.flags & 65536 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; + var checkFlags = 0; + 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + if (!props) { + props = [prop]; + } + else if (!ts.contains(props, prop)) { + props.push(prop); + } + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + if (!isMethodLike(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } + else if (isUnion) { + checkFlags |= 16 /* Partial */; + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + return props[0]; + } + var propTypes = []; + var declarations = []; + var commonType = undefined; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; + if (prop.declarations) { + ts.addRange(declarations, prop.declarations); + } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } + propTypes.push(type); + } + var result = createSymbol(4 /* Property */ | commonFlags, name); + result.checkFlags = syntheticFlag | checkFlags; + result.containingType = containingType; + result.declarations = declarations; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + 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 + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @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, name) { + type = getApparentType(type); + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 196608 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 229376 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 229376 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, /*subtypeReduction*/ true); + } + } + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(declaration) { + var result; + ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + var tp = getDeclaredTypeOfTypeParameter(node.symbol); + if (!ts.contains(result, tp)) { + if (!result) { + result = []; + } + result.push(tp); + } + }); + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + if (ts.isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 272 /* JSDocOptionalType */) { + return true; + } + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 272 /* JSDocOptionalType */; + } + } + } + } + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signatureDeclaration = node.parent; + var signature = getSignatureFromDeclaration(signatureDeclaration); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= signature.minArgumentCount; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } + return false; + } + function createTypePredicateFromTypePredicateNode(node) { + var parameterName = node.parameterName; + if (parameterName.kind === 71 /* Identifier */) { + return { + kind: 1 /* Identifier */, + parameterName: parameterName ? parameterName.escapedText : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0 /* This */, + type: getTypeFromTypeNode(node.type) + }; + } + } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!getDefaultFromTypeParameter(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + /** + * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined + * when a default type is supplied, a new array will be created and returned. + * + * @param typeArguments The supplied type arguments. + * @param typeParameters The requested type parameters. + * @param minTypeArgumentCount The minimum number of required type arguments. + */ + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + var numTypeParameters = ts.length(typeParameters); + if (numTypeParameters) { + var numTypeArguments = ts.length(typeArguments); + var isJavaScript = ts.isInJavaScriptFile(location); + if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (!typeArguments) { + typeArguments = []; + } + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + for (var i = numTypeArguments; i < numTypeParameters; i++) { + typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, typeArguments); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + } + } + } + return typeArguments; + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = undefined; + var hasThisParameter = void 0; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455 /* Value */, undefined, undefined); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this") { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (param.type && param.type.kind === 173 /* LiteralType */) { + hasLiteralTypes = true; + } + // Record a new minimum argument count if this is not an optional parameter + var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !param.type || + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 153 /* GetAccessor */ || declaration.kind === 154 /* SetAccessor */) && + !ts.hasDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; + var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 152 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 158 /* TypePredicate */ ? + createTypePredicateFromTypePredicateNode(declaration.type) : + undefined; + // JS functions get a free rest parameter if they reference `arguments` + var hasRestLikeParameter = ts.hasRestParameter(declaration); + if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { + hasRestLikeParameter = true; + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + syntheticArgsSymbol.type = anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + parameters.push(syntheticArgsSymbol); + } + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { + if (isJSConstructSignature) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { + return classType; + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + // 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 === 153 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 154 /* SetAccessor */); + return getAnnotatedAccessorType(setter); + } + if (ts.nodeIsMissing(declaration.body)) { + return anyType; + } + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 71 /* Identifier */: + return node.escapedText === "arguments" && ts.isPartOfExpression(node); + case 149 /* PropertyDeclaration */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return node.name.kind === 144 /* ComputedPropertyName */ + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var node = symbol.declarations[i]; + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 273 /* JSDocFunctionType */: + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + break; + } + } + result.push(getSignatureFromDeclaration(node)); + } + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return unknownType; + } + var type = void 0; + if (signature.target) { + type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); + } + else if (signature.unionSignatures) { + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + } + else { + type = getReturnTypeFromBody(signature.declaration); + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var declaration = signature.declaration; + 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); + } + } + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { + return type.typeArguments[0]; + } + } + return anyType; + } + function getSignatureInstantiation(signature, typeArguments) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); + } + function getErasedSignature(signature) { + if (!signature.typeParameters) + return signature; + if (!signature.erasedSignatureCache) { + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + return signature.erasedSignatureCache; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 152 /* Constructor */ || signature.declaration.kind === 156 /* ConstructSignature */; + var type = createObjectType(16 /* Anonymous */); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index" /* Index */); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 133 /* NumberKeyword */ : 136 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = decl; + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 145 /* TypeParameter */).constraint; + } + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145 /* TypeParameter */).parent); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_5 = types.length; + var i = 0; + while (i < length_5) { + var startId = types[i].id; + var count = 1; + while (i + count < length_5 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // 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_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 14680064 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); + return unknownType; + } + // 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(typeArgs, typeParameters, minTypeArgumentCount, node)); + return createTypeReference(type, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + } + 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, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return unknownType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + /** + * Get type from reference to named type that cannot be generic (enum or type parameter) + */ + function getTypeFromNonGenericTypeReference(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 159 /* TypeReference */: + return node.typeName; + case 201 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { + return unknownType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + if (symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node)) { + // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + // the symbol is a constructor function, return the inferred class type; otherwise, + // the type of this reference is just the type of the value we resolved to. + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; + } + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + return valueType; + } + return getTypeFromNonGenericTypeReference(node, symbol); + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 /* Function */ && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function isJSDocTypeReference(node) { + return node.flags & 1048576 /* JSDoc */ && node.kind === 159 /* TypeReference */; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + if (node.typeName.escapedText === "Object") { + if (node.typeArguments && node.typeArguments.length === 2) { + var indexed = getTypeFromTypeNode(node.typeArguments[0]); + var target = getTypeFromTypeNode(node.typeArguments[1]); + var index = createIndexInfo(target, /*isReadonly*/ false); + if (indexed === stringType || indexed === numberType) { + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + } + } + return anyType; + } + switch (node.typeName.escapedText) { + case "String": + return stringType; + case "Number": + return numberType; + case "Boolean": + return booleanType; + case "Void": + return voidType; + case "Undefined": + return undefinedType; + case "Null": + return nullType; + case "Function": + case "function": + return globalFunctionType; + case "Array": + case "array": + return !node.typeArguments || !node.typeArguments.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getUnionType([type, nullType]) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 793064 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 107455 /* Value */; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // type reference in checkTypeReferenceOrExpressionWithTypeArguments. + 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) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getWidenedType(checkExpression(node.exprName)); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + switch (declaration.kind) { + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 232 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 32768 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName(undefined, name, meaning, diagnostic, name); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + /** + * Returns a type that is inside a namespace at the global scope, e.g. + * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type + */ + function getExportedTypeFromNamespace(namespace, name) { + var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); + return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384 /* TypeParameter */); + typeParameters.push(typeParameter); + var property = createSymbol(4 /* Property */, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + return type; + } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + } + return links.resolvedType; + } + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 65536 /* Union */) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144 /* Nullable */) { + if (flags & 2048 /* Undefined */) + typeSet.containsUndefined = true; + if (flags & 4096 /* Null */) + typeSet.containsNull = true; + if (!(flags & 2097152 /* ContainsWideningType */)) + typeSet.containsNonWideningType = true; + } + else if (!(flags & 8192 /* Never */)) { + if (flags & 2 /* String */) + typeSet.containsString = true; + if (flags & 4 /* Number */) + typeSet.containsNumber = true; + if (flags & 96 /* StringOrNumberLiteral */) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToUnion(typeSet, types) { + 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_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function isSubtypeOfAny(candidate, types) { + 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; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 /* StringLiteral */ && types.containsString || + t.flags & 64 /* NumberLiteral */ && types.containsNumber || + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + addTypesToUnion(typeSet, types); + if (typeSet.containsAny) { + return anyType; + } + if (subtypeReduction) { + removeSubtypes(typeSet); + } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } + if (typeSet.length === 0) { + return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : + typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : + neverType; + } + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); + type = createType(65536 /* Union */ | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, type) { + if (type.flags & 131072 /* Intersection */) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (type.flags & 8192 /* Never */) { + typeSet.containsNever = true; + } + else if (getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { + typeSet.containsEmptyObject = true; + } + else if ((strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { + if (type.flags & 32768 /* Object */) { + typeSet.containsObjectType = true; + } + if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; + addTypeToIntersection(typeSet, type); + } + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return emptyObjectType; + } + var typeSet = []; + addTypesToIntersection(typeSet, types); + if (typeSet.containsNever) { + return neverType; + } + if (typeSet.containsAny) { + return anyType; + } + if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { + typeSet.push(emptyObjectType); + } + if (typeSet.length === 1) { + return typeSet[0]; + } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), + /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); + type = createType(131072 /* Intersection */ | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144 /* Index */); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + neverType : + getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + ts.escapeLeadingUnderscores("" + indexType.value) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + 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.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)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + return unknownType; + } + return anyType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + // If the index type is generic, if the object type is generic and doesn't originate in an expression, + // or if the object type is a mapped type with a generic constraint, we are performing a higher-order + // index access where we cannot meaningfully access the properties of the object type. Note that for a + // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to + // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved + // eagerly using the constraint type of 'this' at the given location. + if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || + maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1 /* Any */) { + return objectType; + } + // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes + // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the + // type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise we defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + // In the following we resolve T[K] to the type of the property in T selected by K. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (node.symbol.members.size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 231 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 8192 /* Never */) { + return right; + } + if (right.flags & 8192 /* Never */) { + return left; + } + if (left.flags & 65536 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right); }); + } + if (right.flags & 65536 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t); }); + } + if (right.flags & 16777216 /* NonPrimitive */) { + return emptyObjectType; + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + 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 (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) + || skippedPrivateMembers.has(leftProp.escapedName) + || isClassMethod(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + } + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getNonReadonlySymbol(prop) { + if (!isReadonlySymbol(prop)) { + return prop; + } + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); + var result = createSymbol(flags, prop.escapedName); + result.type = getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.syntheticOrigin = prop; + return result; + } + function isClassMethod(prop) { + return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + 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.value, type.symbol); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; + } + 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) { + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { + if (!(ts.getModifierFlags(container) & 32 /* Static */) && + (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return unknownType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 119 /* AnyKeyword */: + case 268 /* JSDocAllType */: + case 269 /* JSDocUnknownType */: + return anyType; + case 136 /* StringKeyword */: + return stringType; + case 133 /* NumberKeyword */: + return numberType; + case 122 /* BooleanKeyword */: + return booleanType; + case 137 /* SymbolKeyword */: + return esSymbolType; + case 105 /* VoidKeyword */: + return voidType; + case 139 /* UndefinedKeyword */: + return undefinedType; + case 95 /* NullKeyword */: + return nullType; + case 130 /* NeverKeyword */: + return neverType; + case 134 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 169 /* ThisType */: + case 99 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 173 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 159 /* TypeReference */: + return getTypeFromTypeReference(node); + case 158 /* TypePredicate */: + return booleanType; + case 201 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 162 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 164 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 165 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 166 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 167 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 270 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 168 /* ParenthesizedType */: + case 271 /* JSDocNonNullableType */: + case 272 /* JSDocOptionalType */: + case 267 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 273 /* JSDocFunctionType */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 170 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 171 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 172 /* MappedType */: + return getTypeFromMappedTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 71 /* Identifier */: + case 143 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + case 274 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + default: + return unknownType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + var result = []; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; + result.push(instantiator(v, mapper)); + } + return result; + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + mapper.mappedTypes = sources; + return mapper; + } + function createTypeEraser(sources) { + return createTypeMapper(sources, /*targets*/ undefined); + } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ + function createBackreferenceMapper(typeParameters, index) { + var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + mapper.mappedTypes = typeParameters; + return mapper; + } + function isInferenceContext(mapper) { + return !!mapper.signature; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.inferences) : + mapper; + } + function identityMapper(type) { + return type; + } + function combineTypeMappers(mapper1, mapper2) { + var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; + mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); + return mapper; + } + function createReplacementMapper(source, target, baseMapper) { + var mapper = function (t) { return t === source ? target : baseMapper(t); }; + mapper.mappedTypes = baseMapper.mappedTypes; + return mapper; + } + function cloneTypeParameter(typeParameter) { + var result = createType(16384 /* TypeParameter */); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + var freshTypePredicate; + if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + if (signature.typePredicate) { + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); + } + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + 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 + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName); + result.checkFlags = 1 /* Instantiated */; + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + return result; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); + result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some + // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated + // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for + // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a + // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144 /* Index */) { + var typeVariable_1 = constraintType.type; + if (typeVariable_1.flags & 16384 /* TypeParameter */) { + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + } + return t; + }); + } + } + } + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } + var mappedTypes = mapper.mappedTypes; + // Starting with the parent of the symbol's declaration, check if the mapper maps any of + // the type parameters introduced by enclosing declarations. We just pick the first + // declaration since multiple declarations will all have the same parent anyway. + return !!ts.findAncestor(symbol.declarations[0], function (node) { + if (node.kind === 233 /* ModuleDeclaration */ || node.kind === 265 /* SourceFile */) { + return "quit"; + } + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var d = typeParameters_1[_i]; + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { + return true; + } + } + } + if (ts.isClassLike(node) || node.kind === 230 /* InterfaceDeclaration */) { + var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + if (thisType && ts.contains(mappedTypes, thisType)) { + return true; + } + } + break; + case 172 /* MappedType */: + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { + return true; + } + break; + case 273 /* JSDocFunctionType */: + var func = node; + for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { + var p = _b[_a]; + if (ts.contains(mappedTypes, getTypeOfNode(p))) { + return true; + } + } + break; + } + }); + } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 265 /* SourceFile */ || parentKind === 234 /* ModuleBlock */; + } + return false; + } + function instantiateType(type, mapper) { + if (type && mapper !== identityMapper) { + // If we are instantiating a type that has a top-level type alias, obtain the instantiation through + // the type alias instead in order to share instantiations for the same type arguments. This can + // dramatically reduce the number of structurally identical types we generate. Note that we can only + // perform this optimization for top-level type aliases. Consider: + // + // function f1(x: T) { + // type Foo = { x: X, t: T }; + // let obj: Foo = { x: x }; + // return obj; + // } + // function f2(x: U) { return f1(x); } + // let z = f2(42); + // + // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo + // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's + // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been + // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; + } + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. We skip instantiation + // if none of the type parameters that are in scope in the type's declaration are mapped by + // the given mapper, however we can only do that analysis if the type isn't itself an + // instantiation. + return type.symbol && + type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && + (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; + } + if (type.objectFlags & 32 /* Mapped */) { + return instantiateCached(type, mapper, instantiateMappedType); + } + if (type.objectFlags & 4 /* Reference */) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + } + } + if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + return type; + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 178 /* ObjectLiteralExpression */: + return ts.forEach(node.properties, isContextSensitive); + case 177 /* ArrayLiteralExpression */: + return ts.forEach(node.elements, isContextSensitive); + case 195 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 194 /* BinaryExpression */: + return node.operatorToken.kind === 54 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 261 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 185 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 254 /* JsxAttributes */: + return ts.forEach(node.properties, isContextSensitive); + case 253 /* JsxAttribute */: + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. + return node.initializer && isContextSensitive(node.initializer); + case 256 /* JsxExpression */: + // It is possible to that node.expression is undefined (e.g
) + return node.expression && isContextSensitive(node.expression); + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + // For arrow functions we now know we're not context sensitive. + if (node.kind === 187 /* ArrowFunction */) { + return false; + } + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. Otherwise we + // know that all parameters (including 'this') have type annotations and nothing is + // subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length) { + var result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + // A type S is considered to be an instance of a type T if S and T are the same type or if S is a + // subtype of T but not structurally identical to T. This specifically means that two distinct but + // structurally identical types (such as two classes) are not considered instances of each other. + function isTypeInstanceOf(source, target) { + return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0 /* False */; + } + if (source.typeParameters) { + source = instantiateSignatureInContextOf(source, target); + } + var result = -1 /* True */; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + var related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); + var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we known we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); + var related = callbacks ? + compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !checkAsCallback && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 32768 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 16777216 /* NonPrimitive */ ? true : + type.flags & 65536 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + false; + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined) { + return relation; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + enumRelation.set(id, false); + return false; + } + 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.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + } + enumRelation.set(id, false); + return false; + } + } + } + enumRelation.set(id, true); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) + return false; + if (t & 1 /* Any */ || s & 8192 /* Never */) + return true; + if (s & 262178 /* StringLike */ && t & 2 /* String */) + return true; + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 84 /* NumberLike */ && t & 4 /* Number */) + return true; + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) + return true; + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + 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 (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (s & 1 /* 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 & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); + } + return false; + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + var errorInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0; + var overflow = false; + var isIntersectionConstituent = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ + function isRelatedTo(source, target, reportErrors, headMessage) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + target = target.regularType; + } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && + !(source.flags & 196608 /* UnionOrIntersection */) && + !(target.flags & 65536 /* Union */) && + !isIntersectionConstituent && + source !== globalObjectType && + getPropertiesOfType(source).length > 0 && + isWeakType(target) && + !hasCommonProperties(source, target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var result = 0 /* False */; + var saveErrorInfo = errorInfo; + var saveIsIntersectionConstituent = isIntersectionConstituent; + isIntersectionConstituent = false; + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 65536 /* Union */) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + } + else { + if (target.flags & 65536 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */)); + } + else if (target.flags & 131072 /* Intersection */) { + isIntersectionConstituent = true; + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 131072 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + } + } + } + isIntersectionConstituent = saveIsIntersectionConstituent; + if (!result && reportErrors) { + if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + } + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || + source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + function hasExcessProperties(source, target, reportErrors) { + if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + if ((relation === assignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + var _loop_4 = function (prop) { + if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + ts.Debug.assert(!!errorNode); + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + errorNode = prop.valueDeclaration; + } + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); + if (related) { + return related; + } + } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } + return 0 /* False */; + } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(source, target, reportErrors) { + var sources = source.typeArguments || ts.emptyArray; + var targets = target.typeArguments || ts.emptyArray; + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1 /* True */; + for (var i = 0; i < length; i++) { + var related = isRelatedTo(sources[i], targets[i], reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function recursiveTypeRelatedTo(source, target, reportErrors) { + if (overflow) { + return 0 /* False */; + } + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation.set(id, 3 /* FailedAndReported */); + } + else { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions + if (id === maybeKeys[i]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2; + var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1 /* Succeeded */); + } + maybeCount = maybeStart; + } + } + else { + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); + maybeCount = maybeStart; + } + return result; + } + function structuredTypeRelatedTo(source, target, reportErrors) { + var result; + var saveErrorInfo = errorInfo; + if (target.flags & 16384 /* TypeParameter */) { + // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. + if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 262144 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { + return result; + } + } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // constraint of T. + var constraint = getConstraintOfType(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + else if (target.flags & 524288 /* IndexedAccess */) { + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. + var constraint = getConstraintOfType(target); + if (constraint) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + if (source.flags & 16384 /* TypeParameter */) { + // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. + if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + var constraint = getConstraintOfTypeParameter(source); + // A type parameter with no constraint is not related to the non-primitive object type. + if (constraint || !(target.flags & 16777216 /* NonPrimitive */)) { + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // The constraint may need to be further instantiated with its 'this' type. + constraint = getTypeWithThisArgument(constraint, source); + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else if (source.flags & 524288 /* IndexedAccess */) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. + var constraint = getConstraintOfType(source); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (target.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { + // if we have indexed access types with identical index types, see if relationship holds for + // the two object types. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + } + else { + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // We have type references to same target type, see if relationship holds for all type arguments + if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + return result; + } + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + var sourceIsPrimitive = !!(source.flags & 8190 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + result = -1 /* True */; + } + else if (isGenericMappedType(target)) { + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; + } + else { + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + return 0 /* False */; + } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. + function mappedTypeRelatedTo(source, target, reportErrors) { + var sourceReadonly = !!source.declaration.readonlyToken; + var sourceOptional = !!source.declaration.questionToken; + var targetReadonly = !!target.declaration.readonlyToken; + var targetOptional = !!target.declaration.questionToken; + var modifiersRelated = relation === identityRelation ? + sourceReadonly === targetReadonly && sourceOptional === targetOptional : + relation === comparableRelation || !sourceOptional || targetOptional; + if (modifiersRelated) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0 /* False */; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var result = -1 /* True */; + var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp !== targetProp) { + if (!sourceProp) { + if (!(targetProp.flags & 16777216 /* Optional */) || requireOptionalProperties) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); + } + return 0 /* False */; + } + } + else if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + 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)); + } + return 0 /* False */; + } + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (reportErrors) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 16 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 16 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 131072 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have 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. We erase type parameters + // as they are known to always be the same. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. + var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + 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, /*erase*/ true, 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 result; + } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, + /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + // 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 (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.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // 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 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 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 + function isAbstractConstructorType(type) { + if (getObjectFlags(type) & 16 /* Anonymous */) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { + return true; + } + } + } + return false; + } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. + function isDeeplyNestedType(type, stack, depth) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 32768 /* Object */) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 32768 /* Object */ && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; + } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + var targetLen = target.parameters.length; + for (var i = 0; i < targetLen; i++) { + var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); + var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var related = compareTypes(s, t); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function isRestParameterIndex(signature, parameterIndex) { + return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144 /* Nullable */) : + getUnionType(types, /*subtypeReduction*/ true); + } + function isArrayType(type) { + return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + } + function isArrayLikeType(type) { + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isTupleLikeType(type) { + return !!getPropertyOfType(type, "0"); + } + function isUnitType(type) { + 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 & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + 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 & 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; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + result |= getFalsyFlags(t); + } + return result; + } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // 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.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 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; + } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ + 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; + } + /** + * Return true if type was inferred from an object literal or written as an object type literal + * with no call or construct signatures. + */ + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && + getSignaturesOfType(type, 0 /* Call */).length === 0 && + getSignaturesOfType(type, 1 /* Construct */).length === 0; + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ + function getRegularTypeOfObjectLiteral(type) { + if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */; + type.regularType = regularNew; + return regularNew; + } + function getWidenedProperty(prop) { + var original = getTypeOfSymbol(prop); + var widened = getWidenedType(original); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getWidenedTypeOfObjectLiteral(type) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop) : prop); + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + } + function getWidenedConstituentType(type) { + return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); + } + function getWidenedType(type) { + if (type.flags & 6291456 /* RequiresWidening */) { + if (type.flags & 6144 /* Nullable */) { + return anyType; + } + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { + return getWidenedTypeOfObjectLiteral(type); + } + if (type.flags & 65536 /* Union */) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 65536 /* Union */) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 2097152 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + return errorReported; + } + function reportImplicitAnyError(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + var diagnostic; + switch (declaration.kind) { + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + break; + case 146 /* Parameter */: + diagnostic = declaration.dotDotDotToken ? + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + break; + case 176 /* BindingElement */: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + if (!declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + break; + default: + diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + } + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAnyError(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var count; + if (source.hasRestParameter && target.hasRestParameter) { + count = Math.max(sourceMax, targetMax); + } + else if (source.hasRestParameter) { + count = targetMax; + } + else if (target.hasRestParameter) { + count = sourceMax; + } + else { + count = Math.min(sourceMax, targetMax); + } + for (var i = 0; i < count; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + } + function createInferenceContext(signature, flags, baseInferences) { + var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + var context = mapper; + context.mappedTypes = signature.typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 /* TypeVariable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + // an object type with the same set of properties as the source type, where the type of each + // property is computed by inferring from the source property type to X for the type + // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0 /* String */); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var inference = createInferenceInfo(typeParameter); + var inferences = [inference]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 16777216 /* Optional */; + var members = ts.createSymbolTable(); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + members.set(prop.escapedName, inferredProp); + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + inference.candidates = undefined; + inferTypes(inferences, sourceType, templateType); + return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); + } + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + 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. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 540672 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType which is used as a wildcard + // when constructing types from type parameters that had no inference candidates. + if (source.flags & 8388608 /* ContainsAnyFunctionType */ || source === silentNeverType) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (!inference.candidates || priority < inference.priority) { + inference.candidates = [source]; + inference.priority = priority; + } + else if (priority === inference.priority) { + inference.candidates.push(source); + } + if (!(priority & 4 /* ReturnType */) && target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + } + else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + for (var i = 0; i < count; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 196608 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1 /* NakedTypeVariable */; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 196608 /* UnionOrIntersection */) { + // Source is a union or intersection type, infer from each constituent type + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + source = getApparentType(source); + if (source.flags & 32768 /* Object */) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (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); + } + } + } + } + function getInferenceInfoForType(type) { + if (type.flags & 540672 /* TypeVariable */) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* MappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return; + } + if (constraintType.flags & 16384 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + function inferFromProperties(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + for (var i = 0; i < len; i++) { + inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + } + } + function inferFromSignature(source, target) { + forEachMatchingParameterType(source, target, inferFromTypes); + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + if (inference.candidates) { + // We widen inferred literal types if + // all inferences were made to top-level ocurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var signature = context.signature; + var widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; + // Infer widened union or supertype, or the unknown type for no common supertype. We infer union types + // for inferences coming from return types in order to avoid common supertype failures. + var unionOrSuperType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, /*subtypeReduction*/ true) : getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; + } + else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + } + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + // EXPRESSION TYPE CHECKING + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 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; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 162 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 143 /* QualifiedName */ ? false : "quit"; }); + } + // 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. 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 ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 99 /* ThisKeyword */) { + return "0"; + } + if (node.kind === 179 /* PropertyAccessExpression */) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + } + if (node.kind === 176 /* BindingElement */) { + var container = node.parent.parent; + var key = container.kind === 176 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getLeftmostIdentifierOrThis(node) { + switch (node.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + return node; + case 179 /* PropertyAccessExpression */: + return getLeftmostIdentifierOrThis(node.expression); + } + return undefined; + } + function getBindingElementNameText(element) { + if (element.parent.kind === 174 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 71 /* Identifier */: + return ts.unescapeLeadingUnderscores(name.escapedText); + case 144 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + element.parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 71 /* Identifier */: + return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 226 /* VariableDeclaration */ || target.kind === 176 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 99 /* ThisKeyword */: + return target.kind === 99 /* ThisKeyword */; + case 97 /* SuperKeyword */: + return target.kind === 97 /* SuperKeyword */; + case 179 /* PropertyAccessExpression */: + return target.kind === 179 /* PropertyAccessExpression */ && + source.name.escapedText === target.name.escapedText && + isMatchingReference(source.expression, target.expression); + case 176 /* BindingElement */: + if (target.kind !== 179 /* PropertyAccessExpression */) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 176 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 226 /* VariableDeclaration */) { + var maybeId = source.parent.parent.initializer; + return maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function containsMatchingReference(source, target) { + while (source.kind === 179 /* PropertyAccessExpression */) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 179 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 71 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 179 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 65536 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 179 /* PropertyAccessExpression */ && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 65536 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 8192 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192 /* Never */)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 2 /* String */) { + return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; + } + if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; + return strictNullChecks ? + 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 */) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : + isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + } + if (flags & 8 /* Boolean */) { + return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; + } + if (flags & 136 /* BooleanLike */) { + return strictNullChecks ? + type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + } + if (flags & 32768 /* Object */) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : + strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + } + if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { + return 2457472 /* UndefinedFacts */; + } + if (flags & 4096 /* Null */) { + return 2340752 /* NullFacts */; + } + if (flags & 512 /* ESSymbol */) { + return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; + } + if (flags & 16777216 /* NonPrimitive */) { + return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + } + if (flags & 540672 /* TypeVariable */) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 196608 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); + } + return 8388607 /* All */; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getTypeOfPropertyOfType(type, text) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || + unknownType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || + unknownType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 177 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 261 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 194 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 216 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 215 /* ForInStatement */: + return stringType; + case 216 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; + case 194 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 188 /* DeleteExpression */: + return undefinedType; + case 177 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 198 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 261 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 262 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return unknownType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 174 /* ObjectBindingPattern */ ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 215 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 216 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; + } + return unknownType; + } + function getInitialType(node) { + return node.kind === 226 /* VariableDeclaration */ ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node) { + return node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node); + } + function isEmptyArrayAssignment(node) { + return node.kind === 226 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 176 /* BindingElement */ && node.parent.kind === 194 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 185 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 194 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 58 /* EqualsToken */: + return getReferenceCandidate(node.left); + case 26 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 185 /* ParenthesizedExpression */ || + parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 257 /* CaseClause */) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + // If all case clauses specify expressions that have unit types, we return an array + // of those unit types. Otherwise we return an empty array. + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + var type = getTypeOfSwitchClause(clause); + if (type === undefined) { + return links.switchTypes = ts.emptyArray; + } + links.switchTypes.push(type); + } + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 65536 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 65536 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; + } + // Apply a mapping function to a type and return the resulting type. If the source type + // is a union type, the mapping function is applied to each constituent type and a union + // of the resulting types is returned. + function mapType(type, mapper) { + if (!(type.flags & 65536 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 65536 /* Union */ ? + getUnionType(elementType.types, /*subtypeReduction*/ true) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; + if (!(t.flags & 8192 /* Never */)) { + if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 179 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 181 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 180 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 194 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 58 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 97 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { + return declaredType; + } + var visitedFlowStart = visitedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + visitedFlowCount = visitedFlowStart; + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 203 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + while (true) { + if (flow.flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. + for (var i = visitedFlowStart; i < visitedFlowCount; i++) { + if (visitedFlowNodes[i] === flow) { + return visitedFlowTypes[i]; + } + } + } + var type = void 0; + if (flow.flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } + else if (flow.flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } + else if (flow.flags & 12 /* Label */) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flow.flags & 4 /* BranchLabel */ ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flow.flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. + var container = flow.container; + if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + flow = container.flowNode; + continue; + } + // At the top of the flow we have the initial type. + type = initialType; + } + else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); + } + if (flow.flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. + visitedFlowNodes[visitedFlowCount] = flow; + visitedFlowTypes[visitedFlowCount] = type; + visitedFlowCount++; + } + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; + } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. + if (containsMatchingReference(reference, node)) { + return declaredType; + } + // Assignment doesn't affect reference + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 181 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 181 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 8192 /* Never */) { + return flowType; + } + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. + if (type === declaredType && declaredType === initialType) { + return type; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); + } + } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. + if (type === declaredType) { + break; + } + } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + return expr.kind === 179 /* PropertyAccessExpression */ && + computedType.flags & 65536 /* Union */ && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(computedType, expr.name.escapedText); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.escapedText; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 189 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 189 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 93 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 26 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 6144 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : + value.kind === 95 /* NullKeyword */ ? + assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : + assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 16810497 /* NotUnionOrUnit */) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the + // narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target)) { + return declaredType; + } + return type; + } + if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue && !(type.flags & 65536 /* Union */)) { + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + var targetType = typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 540672 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(type, facts); + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the + // narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left)) { + return declaredType; + } + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = getTypeOfExpression(expr.right); + if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + // Target type is type of construct signature + var constructSignatures = void 0; + if (getObjectFlags(rightType) & 2 /* Interface */) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; + } + else if (getObjectFlags(rightType) & 16 /* Anonymous */) { + constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + } + if (constructSignatures && constructSignatures.length) { + targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + } + } + if (targetType) { + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + } + return type; + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 65536 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 8192 /* Never */)) { + return assignableType; + } + } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 180 /* ElementAccessExpression */ || invokedExpression.kind === 179 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 179 /* PropertyAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 181 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 185 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 194 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 192 /* PrefixUnaryExpression */: + if (expr.operator === 51 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 71 /* Identifier */) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 234 /* ModuleBlock */ || + node.kind === 265 /* SourceFile */ || + node.kind === 149 /* PropertyDeclaration */; + }); + } + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304 /* AssignmentsMarked */)) { + links.flags |= 4194304 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + } + function markParameterAssignments(node) { + if (node.kind === 71 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 146 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 2048 /* Undefined */ && + !(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) { + return unknownType; + } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 187 /* ArrowFunction */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; + return getTypeOfSymbol(symbol); + } + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 229 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 199 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container !== undefined) { + if (container.parent === declaration) { + if (container.kind === 149 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); + } + } + } + checkCollisionWithCapturedSuperVariable(node, node); + checkCollisionWithCapturedThisVariable(node, node); + checkCollisionWithCapturedNewTargetVariable(node, node); + checkNestedBlockScopedBinding(node, symbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 146 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 186 /* FunctionExpression */ || + flowContainer.kind === 187 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = isParameter || isAlias || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 246 /* ExportSpecifier */) || + node.parent.kind === 203 /* NonNullExpression */ || + ts.isInAmbientContext(declaration); + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : + type === autoType || type === autoArrayType ? undefinedType : + 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 + // control flow based type does include undefined. + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + 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); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 260 /* CatchClause */) { + return; + } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 214 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 227 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + } + } + function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes + var current = node; + while (current.parent.kind === 185 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 192 /* PrefixUnaryExpression */ || current.parent.kind === 193 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 149 /* PropertyDeclaration */ || container.kind === 152 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var needToCaptureLexicalThis = false; + if (container.kind === 152 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 187 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code + needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); + } + switch (container.kind) { + case 233 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 232 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 152 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + if (ts.getModifierFlags(container) & 32 /* Static */) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 144 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node, container); + } + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (container.kind === 186 /* FunctionExpression */ && + container.parent.kind === 194 /* BinaryExpression */ && + ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.prototype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + return getInferredClassType(classSymbol); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return thisType; + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + } + if (noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return anyType; + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 273 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this") { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146 /* Parameter */; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 181 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); + var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting + if (!isCallExpression) { + while (container && container.kind === 187 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144 /* ComputedPropertyName */; }); + if (current && current.kind === 144 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return unknownType; + } + if (!isCallExpression && container.kind === 152 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = name => super[name]; + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super("asyncMethod").call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // return __awaiter(this, arguments, Promise, function *() { + // [_super("a").value, _super("b").value] = yield ar; + // }); + // } + // ... + // + // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. + // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment + // while a property access can. + if (container.kind === 151 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 152 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return unknownType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 152 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (ts.getModifierFlags(container) & 32 /* Static */) { + return container.kind === 151 /* MethodDeclaration */ || + container.kind === 150 /* MethodSignature */ || + container.kind === 153 /* GetAccessor */ || + container.kind === 154 /* SetAccessor */; + } + else { + return container.kind === 151 /* MethodDeclaration */ || + container.kind === 150 /* MethodSignature */ || + container.kind === 153 /* GetAccessor */ || + container.kind === 154 /* SetAccessor */ || + container.kind === 149 /* PropertyDeclaration */ || + container.kind === 148 /* PropertySignature */ || + container.kind === 152 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 151 /* MethodDeclaration */ || + func.kind === 153 /* GetAccessor */ || + func.kind === 154 /* SetAccessor */) && func.parent.kind === 178 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 186 /* FunctionExpression */ && func.parent.kind === 261 /* PropertyAssignment */ ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 131072 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 187 /* ArrowFunction */) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 261 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + if (func.parent.kind === 194 /* BinaryExpression */ && func.parent.operatorToken.kind === 58 /* EqualsToken */) { + var target = func.parent.left; + if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { + return checkExpressionCached(target.expression); + } + } + } + return undefined; + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); + } + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + // If last parameter is contextually rest parameter get its type + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + } + } + } + return undefined; + } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 146 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 176 /* BindingElement */) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + return functionFlags & 2 /* Async */ + ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function + : contextualReturnType; // Regular function + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (node.parent.kind === 146 /* Parameter */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + if (functionDecl.kind === 152 /* Constructor */ || + ts.getEffectiveReturnTypeNode(functionDecl) || + isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); + if (argIndex >= 0) { + // If we're already in the process of resolving the given signature, don't resolve again as + // that could cause infinite recursion. Instead, return anySignature. + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + return getTypeAtPosition(signature, argIndex); + } + return undefined; + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 183 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var operator = binaryExpression.operatorToken.kind; + if (ts.isAssignmentOperator(operator)) { + // Don't do this for special property assignments to avoid circularity + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { + return undefined; + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + if (node === binaryExpression.right) { + return getTypeOfExpression(binaryExpression.left); + } + } + else if (operator === 54 /* BarBarToken */) { + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand. + var type = getContextualType(binaryExpression); + if (!type && node === binaryExpression.right) { + type = getTypeOfExpression(binaryExpression.left); + } + return type; + } + else if (operator === 53 /* AmpersandAmpersandToken */ || operator === 26 /* CommaToken */) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } + return undefined; + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + return prop ? getTypeOfSymbol(prop) : undefined; + }); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + } + // Return true if the given contextual type is a tuple-like type + function contextualTypeIsTupleLikeType(type) { + return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!ts.hasDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(node) { + var arrayLiteral = node.parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + if (type) { + var index = ts.indexOf(arrayLiteral.elements, node); + return getTypeOfPropertyOfContextualType(type, "" + index) + || getIndexTypeOfContextualType(type, 1 /* Number */) + || getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + } + return undefined; + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForJsxExpression(node) { + // JSX expression can appear in two position : JSX Element's children or JSX attribute + var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? + node.parent.parent : + node.parent.openingElement.attributes; // node.parent is JsxElement + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + var attributesType = getContextualType(jsxAttributes); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + if (ts.isJsxAttribute(node.parent)) { + // JSX expression is in JSX attribute + return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + } + else if (node.parent.kind === 249 /* JsxElement */) { + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + } + else { + // JSX expression is in JSX spread attribute + return attributesType; + } + } + function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + var attributesType = getContextualType(attribute.parent); + if (ts.isJsxAttribute(attribute)) { + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + } + else { + return attributesType; + } + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); + return type && getApparentType(type); + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 226 /* VariableDeclaration */: + case 146 /* Parameter */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 176 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 187 /* ArrowFunction */: + case 219 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 197 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 181 /* CallExpression */: + case 182 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 194 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 261 /* PropertyAssignment */: + case 262 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 263 /* SpreadAssignment */: + return getApparentTypeOfContextualType(parent.parent); + case 177 /* ArrayLiteralExpression */: + return getContextualTypeForElementExpression(node); + case 195 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 205 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 185 /* ParenthesizedExpression */: + return getContextualType(parent); + case 256 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent); + case 253 /* JsxAttribute */: + case 255 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); + case 251 /* JsxOpeningElement */: + case 250 /* JsxSelfClosingElement */: + return getAttributesTypeFromJsxOpeningLikeElement(parent); + } + return undefined; + } + function getContextualMapper(node) { + node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return node ? node.contextualMapper : identityMapper; + } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 65536 /* Union */)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + // Clear resolved return type we possibly got from cloneSignature + result.resolvedReturnType = undefined; + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 176 /* BindingElement */ && !!node.initializer) || + (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + } + function checkArrayLiteral(node, checkMode) { + var elements = node.elements; + var hasSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; + if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, checkMode); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var type = checkExpressionForMutableLocation(e, checkMode); + elementTypes.push(type); + } + hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; + } + if (!hasSpreadElement) { + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + if (inDestructuringPattern && elementTypes.length) { + var type = cloneTypeReference(createTupleType(elementTypes)); + type.pattern = node; + return type; + } + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementTypes.length; i < patternElements.length; i++) { + var patternElement = patternElements[i]; + if (hasDefaultValue(patternElement)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else { + if (patternElement.kind !== 200 /* OmittedExpression */) { + error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(unknownType); + } + } + } + if (elementTypes.length) { + return createTupleType(elementTypes); + } + } + } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, /*subtypeReduction*/ true) : + strictNullChecks ? neverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 144 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 71 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + 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), 84 /* NumberLike */); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || isTypeOfKind(type, kind); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + 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, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable = ts.createSymbolTable(); + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 174 /* ObjectBindingPattern */ || contextualType.pattern.kind === 178 /* ObjectLiteralExpression */); + var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + var isInJSFile = ts.isInJavaScriptFile(node); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 261 /* PropertyAssignment */ || + memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var jsdocType = void 0; + if (isInJSFile) { + jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); + } + var type = void 0; + if (memberDecl.kind === 261 /* PropertyAssignment */) { + type = checkPropertyAssignment(memberDecl, checkMode); + } + else if (memberDecl.kind === 151 /* MethodDeclaration */) { + type = checkObjectLiteralMethod(memberDecl, checkMode); + } + else { + ts.Debug.assert(memberDecl.kind === 262 /* ShorthandPropertyAssignment */); + type = checkExpressionForMutableLocation(memberDecl.name, checkMode); + } + if (jsdocType) { + checkTypeAssignableTo(type, jsdocType, memberDecl); + type = jsdocType; + } + typeFlags |= type.flags; + var prop = createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 261 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 262 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216 /* Optional */; + } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } + } + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 263 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type); + offset = i + 1; + continue; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName)) { + if (!(prop.flags & 16777216 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + } + if (spread.flags & 32768 /* Object */) { + // only set the symbol and flags if this is a (fresh) object type + spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; + spread.symbol = node.symbol; + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; + result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + result.objectFlags |= 128 /* ObjectLiteral */; + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144 /* Nullable */)) { + propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */ | 16777216 /* NonPrimitive */) || + type.flags & 32768 /* Object */ && !isGenericMappedType(type) || + type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + } + function checkJsxSelfClosingElement(node) { + checkJsxOpeningLikeElement(node); + return getJsxGlobalElementType() || anyType; + } + function checkJsxElement(node) { + // Check attributes + checkJsxOpeningLikeElement(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + return getJsxGlobalElementType() || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return name.indexOf("-") < 0; + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + // TODO (yuisu): comment + switch (tagName.kind) { + case 179 /* PropertyAccessExpression */: + case 99 /* ThisKeyword */: + return false; + case 71 /* Identifier */: + return ts.isIntrinsicJsxName(tagName.escapedText); + default: + ts.Debug.fail(); + } + } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + 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; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = attributeDecl.initializer ? + checkExpression(attributeDecl.initializer, checkMode) : + trueType; // is sugar for + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + attributesArray.push(attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpression(attributeDecl.expression); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createSymbolTable(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; + if (!filter || filter(attr)) { + attributesTable.set(attr.escapedName, 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 _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 */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + 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, ts.unescapeLeadingUnderscores(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 + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); + attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + } + } + 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 + * @param attributesTable a symbol table of attributes property + */ + function createJsxAttributesType(symbol, attributesTable) { + var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; + result.objectFlags |= 128 /* ObjectLiteral */; + return result; + } + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); + } + function getJsxType(name) { + var jsxType = jsxTypes.get(name); + if (jsxType === undefined) { + jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); + } + return jsxType; + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + // Property case + if (!ts.isIdentifier(node.tagName)) + throw ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + /** + * Given a JSX element that is a class element, finds the Element Instance Type. If the + * element is not a class element, or the class element type cannot be determined, returns 'undefined'. + * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). + */ + function getJsxElementInstanceType(node, valueType) { + ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); + if (isTypeAny(valueType)) { + // Short-circuit if the class tag is using an element type 'any' + return anyType; + } + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(valueType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(valueType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return unknownType; + } + } + 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. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { + // JSX + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName() { + if (!_hasComputedJsxElementPropertiesName) { + _hasComputedJsxElementPropertiesName = true; + _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); + } + return _jsxElementPropertiesName; + } + function getJsxElementChildrenPropertyname() { + if (!_hasComputedJsxElementChildrenPropertyName) { + _hasComputedJsxElementChildrenPropertyName = true; + _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); + } + 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. + * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) + * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. + * @param openingLikeElement a JSX opening-like element to find attributes type + * @param elementType a type of the opening-like element. This elementType can't be an union type + * @param elemInstanceType an element instance type (the result of newing or invoking this tag) + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global + */ + function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { + ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); + 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); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + } + } + } + return undefined; + } + /** + * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. + * Return all attributes type of resolved call signature including candidate signatures. + * This function assumes that the caller handled other possible element type of the JSX element. + * This function is a behavior used by language service when looking up completion in JSX element. + * @param openingLikeElement a JSX opening-like element to find attributes type + * @param elementType a type of the opening-like element. This elementType can't be an union type + * @param elemInstanceType an element instance type (the result of newing or invoking this tag) + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global + */ + function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { + ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. + var candidatesOutArray = []; + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + var result = void 0; + var allMatchingAttributesType = void 0; + for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { + 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++) { + var attribute = _b[_a]; + if (ts.isJsxAttribute(attribute) && + isUnhyphenatedJsxName(attribute.name.escapedText) && + !getPropertyOfType(paramType, attribute.name.escapedText)) { + shouldBeCandidate = false; + break; + } + } + if (shouldBeCandidate) { + result = intersectTypes(result, paramType); + } + allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); + } + } + // If we can't find any matching, just return everything. + if (!result) { + result = allMatchingAttributesType; + } + // Intersect in JSX.IntrinsicAttributes if it exists + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + result = intersectTypes(intrinsicAttributes, result); + } + return result; + } + } + return undefined; + } + /** + * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. + * For instance: + * declare function Foo(attr: { p1: string}): JSX.Element; + * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" + * + * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. + * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component + * + * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement + * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature + * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) + * @return attributes type if able to resolve the type of node + * anyType if there is no type ElementAttributesProperty or there is an error + * emptyObjectType if there is no "prop" in the element instance type + */ + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { + if (!elementType) { + elementType = checkExpression(openingLikeElement.tagName); + } + if (elementType.flags & 65536 /* Union */) { + var types = elementType.types; + return getUnionType(types.map(function (type) { + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); + }), /*subtypeReduction*/ true); + } + // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type + if (elementType.flags & 2 /* String */) { + return anyType; + } + else if (elementType.flags & 32 /* StringLiteral */) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + // Get the element instance type (the result of newing or invoking this tag) + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. + // Otherwise get only attributes type from the signature picked by choose-overload logic. + var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? + tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : + defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); + if (statelessAttributesType) { + return statelessAttributesType; + } + // Issue an error if this return type isn't assignable to JSX.ElementClass + if (elementClassType) { + checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + if (isTypeAny(elemInstanceType)) { + return elemInstanceType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + // There is no type ElementAttributesProperty, return 'any' + return anyType; + } + else if (propsName === "") { + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + return elemInstanceType; + } + else { + var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + if (!attributesType) { + // There is no property named 'props' on this instance type + return emptyObjectType; + } + else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + else { + return links.resolvedJsxElementAttributesType = unknownType; + } + } + return links.resolvedJsxElementAttributesType; + } + /** + * Get attributes type of the given custom opening-like JSX element. + * This function is intended to be called from a caller that handles intrinsic JSX element already. + * @param node a custom JSX opening-like element + * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component + */ + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var elemClassType = getJsxGlobalElementClassType(); + return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + } + return links.resolvedJsxElementAttributesType; + } + /** + * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. + * This function is called by language service (see: completions-tryGetGlobalSymbols). + * @param node a JSX opening-like element to get attributes type for + */ + function getAllAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + // Because in language service, the given JSX opening-like element may be incomplete and therefore, + // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); + } + } + /** + * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. + * @param node a JSXOpeningLikeElement node + * @return an attributes type of the given node + */ + function getAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); + } + } + /** + * Given a JSX attribute, returns the symbol for the corresponds property + * of the element attributes type. Will return unknownSymbol for attributes + * that have no matching element attributes type property. + */ + function getJsxAttributePropertySymbol(attrib) { + var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); + var prop = getPropertyOfType(attributesType, attrib.name.escapedText); + return prop || unknownSymbol; + } + function getJsxGlobalElementClassType() { + if (!deferredJsxElementClassType) { + deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); + } + return deferredJsxElementClassType; + } + function getJsxGlobalElementType() { + if (!deferredJsxElementType) { + deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); + } + return deferredJsxElementType; + } + function getJsxGlobalStatelessElementType() { + if (!deferredJsxStatelessElementType) { + var jsxElementType = getJsxGlobalElementType(); + if (jsxElementType) { + deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); + } + } + return deferredJsxStatelessElementType; + } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ + function getJsxIntrinsicTagNames() { + var intrinsics = getJsxType(JsxNames.IntrinsicElements); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxGlobalElementType() === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElement(node) { + checkGrammarJsxElement(node); + checkJsxPreconditions(node); + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(); + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = true; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + 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 + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. 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) || + getPropertyOfObjectType(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" + * Check assignablity between given attributes property, "source attributes", and the "target attributes" + * @param openingLikeElement an opening-like JSX element to check its JSXAttributes + */ + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + // The function involves following steps: + // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. + // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) + // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. + // 3. Check if the two are assignable to each other + // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); + // sourceAttributesType is a type of an attributes properties. + // i.e
+ // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { + return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); + }); + // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. + // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. + if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + } + else { + // 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.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } + } + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + } + return type; + } + else { + return unknownType; + } + } + // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized + // '.prototype' property as well as synthesized tuple index properties. + function getDeclarationKindFromSymbol(s) { + return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + function isMethodLike(symbol) { + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param left The left hand side of the property access (e.g.: the super in `super.foo`). + * @param type The type of left. + * @param prop The symbol for the right hand side of the property access. + */ + function checkPropertyAccessibility(node, left, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? + node.name : + node.right; + 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; + } + if (left.kind === 97 /* SuperKeyword */) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + var hasNonMethodDeclaration = forEachProperty(prop, function (p) { + var propKind = getDeclarationKindFromSymbol(p); + return propKind !== 151 /* MethodDeclaration */ && propKind !== 150 /* MethodSignature */; + }); + if (hasNonMethodDeclaration) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (left.kind === 97 /* SuperKeyword */) { + return true; + } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + // No further restrictions for static properties + if (flags & 32 /* Static */) { + return true; + } + // An instance property must be accessed through an instance of the enclosing class + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + // get the original type -- represented as the type constraint of the 'this' type + type = getConstraintOfTypeParameter(type); + } + if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); + } + function checkNonNullType(type, errorNode) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144 /* Nullable */; + if (kind) { + error(errorNode, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + var t = getNonNullableType(type); + return t.flags & (6144 /* Nullable */ | 8192 /* Never */) ? unknownType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { + // handle cases when type is Type parameter with invalid or any constraint + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.escapedText); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); + if (stringIndexType) { + return stringIndexType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && + node.parent && node.parent.kind !== 159 /* TypeReference */ && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); + return unknownType; + } + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && + !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { + return propType; + } + 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.escapedText)) { + 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(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455 /* Value */); + return suggestion && suggestion.escapedName; + } + 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(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.escapedName; + } + } + /** + * 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; + var justCheckExactMatches = false; + 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]; + var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); + if (candidate.flags & meaning && + candidateName && + Math.abs(candidateName.length - name.length) < maximumLengthDifference) { + candidateName = candidateName.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + 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) { + justCheckExactMatches = true; + bestCandidate = 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 + : node.left; + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { + if (type !== unknownType && !isTypeAny(type)) { + var prop = getPropertyOfType(type, propertyName); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); + } + // In js files properties of unions are allowed in completion + if (ts.isInJavaScriptFile(left) && (type.flags & 65536 /* Union */)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; + } + return true; + } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 227 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 71 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 71 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 215 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 182 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return unknownType; + } + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === unknownType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 512 /* ESSymbol */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + 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); + } + else if (node.kind !== 147 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + 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) { + if (lastParent && parent === lastParent) { + index++; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function getSpreadArgumentIndex(args) { + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (arg && arg.kind === 198 /* SpreadElement */) { + return i; + } + } + return -1; + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; // Apparent number of arguments we will have in this call + var typeArguments; // Type arguments (undefined if none) + var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var isDecorator; + var spreadArgIndex = -1; + if (ts.isJsxOpeningLikeElement(node)) { + // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". + return true; + } + if (node.kind === 183 /* TaggedTemplateExpression */) { + var tagExpression = node; + // Even if the call is incomplete, we'll have a missing expression as our last argument, + // so we can say the count is just the arg list length + argCount = args.length; + typeArguments = undefined; + if (tagExpression.template.kind === 196 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var templateExpression = tagExpression.template; + var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); + ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = tagExpression.template; + ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 147 /* Decorator */) { + isDecorator = true; + typeArguments = undefined; + argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + } + else { + var callExpression = node; + if (!callExpression.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(callExpression.kind === 182 /* NewExpression */); + return signature.minArgumentCount === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. + callIsIncomplete = callExpression.arguments.end === callExpression.end; + typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); + } + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + var hasRightNumberOfTypeArgs = !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + if (!hasRightNumberOfTypeArgs) { + return false; + } + // 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) || spreadArgIndex >= signature.minArgumentCount; + } + // Too many arguments implies incorrect arity. + if (!signature.hasRestParameter && argCount > signature.parameters.length) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + var hasEnoughArguments = argCount >= signature.minArgumentCount; + return callIsIncomplete || hasEnoughArguments; + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { + var context = createInferenceContext(signature, 1 /* InferUnionTypes */); + forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); + } + return getSignatureInstantiation(signature, getInferredTypes(context)); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (ts.isExpression(node)) { + var contextualType = getContextualType(node); + if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + // We perform two passes over the arguments. In the first pass we infer from all arguments, but use + // wildcards for all context sensitive function expressions. + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + argType = checkExpressionWithContextualType(arg, paramType, mapper); + } + inferTypes(context.inferences, argType, paramType); + } + } + // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this + // time treating function expressions normally (which may cause previously inferred type arguments to be fixed + // as we construct types for contextually typed parameters) + // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. + // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. + if (excludeArgument) { + for (var i = 0; i < argCount; i++) { + // No need to check for omitted args and template expressions, their exclusion value is always undefined + if (excludeArgument[i] === false) { + var arg = args[i]; + var paramType = getTypeAtPosition(signature, i); + inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); + } + } + } + return getInferredTypes(context); + } + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + var typeParameters = signature.typeParameters; + var typeArgumentsAreAssignable = true; + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + if (typeArgumentsAreAssignable /* so far */) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); + } + } + } + return typeArgumentsAreAssignable; + } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { + // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: + // 1. callIsIncomplete + // 2. attributes property has same number of properties as the parameter object type. + // We can figure that out by resolving attributes property and check number of properties in the resolved type + // If the call has correct arity, we will then check if the argument type and parameter type is assignable + var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete + if (callIsIncomplete) { + return true; + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. + var paramType = getTypeAtPosition(signature, 0); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); + var argProperties = getPropertiesOfType(attributesType); + for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { + var arg = argProperties_1[_i]; + if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { + return false; + } + } + return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 182 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. + // If the expression is a new expression, then the check is skipped. + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) + var paramType = getTypeAtPosition(signature, i); + // If the effective argument type is undefined, there is no synthetic type for the argument. + // In that case, we should check the argument. + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + // Use argument expression as error location when reporting errors + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } + } + } + return true; + } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ + function getThisArgumentOfCall(node) { + if (node.kind === 181 /* CallExpression */) { + var callee = node.expression; + if (callee.kind === 179 /* PropertyAccessExpression */) { + return callee.expression; + } + else if (callee.kind === 180 /* ElementAccessExpression */) { + return callee.expression; + } + } + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + * + * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. + * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution + * expressions, where the first element of the list is `undefined`. + * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types + * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. + */ + function getEffectiveCallArguments(node) { + if (node.kind === 183 /* TaggedTemplateExpression */) { + var template = node.template; + var args_4 = [undefined]; + if (template.kind === 196 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + else if (node.kind === 147 /* Decorator */) { + // For a decorator, we return undefined as we will determine + // the number and types of arguments for a decorator using + // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. + return undefined; + } + else if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + } + else { + return node.arguments || ts.emptyArray; + } + } + /** + * Returns the effective argument count for a node that works like a function invocation. + * If 'node' is a Decorator, the number of arguments is derived from the decoration + * target and the signature: + * If 'node.target' is a class declaration or class expression, the effective argument + * count is 1. + * If 'node.target' is a parameter declaration, the effective argument count is 3. + * If 'node.target' is a property declaration, the effective argument count is 2. + * If 'node.target' is a method or accessor declaration, the effective argument count + * is 3, although it can be 2 if the signature only accepts two arguments, allowing + * us to match a property decorator. + * Otherwise, the argument count is the length of the 'args' array. + */ + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 147 /* Decorator */) { + switch (node.parent.kind) { + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) + return 1; + case 149 /* PropertyDeclaration */: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) + return 2; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts) + // If we are emitting decorators for ES3, we will only pass two arguments. + if (languageVersion === 0 /* ES3 */) { + return 2; + } + // If the method decorator signature only accepts a target and a key, we will only + // type check those arguments. + return signature.parameters.length >= 3 ? 3 : 2; + case 146 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) + return 3; + } + } + else { + return args.length; + } + } + /** + * Returns the effective type of the first argument to a decorator. + * If 'node' is a class declaration or class expression, the effective argument type + * is the type of the static side of the class. + * If 'node' is a parameter declaration, the effective argument type is either the type + * of the static or instance side of the class for the parameter's parent method, + * depending on whether the method is declared static. + * For a constructor, the type is always the type of the static side of the class. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. + */ + function getEffectiveDecoratorFirstArgumentType(node) { + // The first argument to a decorator is its `target`. + if (node.kind === 229 /* ClassDeclaration */) { + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + if (node.kind === 146 /* Parameter */) { + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + node = node.parent; + if (node.kind === 152 /* Constructor */) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + } + if (node.kind === 149 /* PropertyDeclaration */ || + node.kind === 151 /* MethodDeclaration */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getParentTypeOfClassElement(node); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective type for the second argument to a decorator. + * If 'node' is a parameter, its effective argument type is one of the following: + * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * will emit `undefined`. + * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * the effective argument type will be a string literal type for the member name. + * If 'node.parent' is a computed property name, the effective argument type will + * either be a symbol type or the string type. + * If 'node' is a member with an identifier, numeric, or string literal name, the + * effective argument type will be a string literal type for the member name. + * If 'node' is a computed property name, the effective argument type will either + * be a symbol type or the string type. + * A class decorator does not have a second argument type. + */ + function getEffectiveDecoratorSecondArgumentType(node) { + // The second argument to a decorator is its `propertyKey` + if (node.kind === 229 /* ClassDeclaration */) { + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + } + if (node.kind === 146 /* Parameter */) { + node = node.parent; + if (node.kind === 152 /* Constructor */) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + } + if (node.kind === 149 /* PropertyDeclaration */ || + node.kind === 151 /* MethodDeclaration */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + var element = node; + switch (element.name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(element.name.text); + case 144 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(element.name); + if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective argument type for the third argument to a decorator. + * If 'node' is a parameter, the effective argument type is the number type. + * If 'node' is a method or accessor, the effective argument type is a + * `TypedPropertyDescriptor` instantiated with the type of the member. + * Class and property decorators do not have a third effective argument. + */ + function getEffectiveDecoratorThirdArgumentType(node) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a parameter decorator + if (node.kind === 229 /* ClassDeclaration */) { + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 146 /* Parameter */) { + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + } + if (node.kind === 149 /* PropertyDeclaration */) { + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 151 /* MethodDeclaration */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective argument type for the provided argument to a decorator. + */ + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + /** + * Gets the effective argument type for an argument in a call expression. + */ + function getEffectiveArgumentType(node, argIndex) { + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types + // unless we're reporting errors + if (node.kind === 147 /* Decorator */) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + return getGlobalTemplateStringsArrayType(); + } + // This is not a synthetic argument, so we return 'undefined' + // to signal that the caller needs to check the argument. + return undefined; + } + /** + * Gets the effective argument expression for an argument in a call expression. + */ + function getEffectiveArgument(node, args, argIndex) { + // For a decorator or the first argument of a tagged template expression we return undefined. + if (node.kind === 147 /* Decorator */ || + (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */)) { + return undefined; + } + return args[argIndex]; + } + /** + * Gets the error node to use when reporting errors for an effective argument. + */ + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 147 /* Decorator */) { + // For a decorator, we use the expression of the decorator for error reporting. + return node.expression; + } + else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 147 /* Decorator */; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var typeArguments; + if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (node.expression.kind !== 97 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The following applies to any value of 'excludeArgument[i]': + // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. + // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. + // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for each of those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary + // because it represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var excludeArgument; + var excludeCount = 0; + if (!isDecorator) { + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + excludeCount++; + } + } + } + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // + var candidateForArgumentError; + var candidateForTypeArgumentError; + var result; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (candidateForArgumentError) { + if (isJsxOpeningOrSelfClosingElement) { + // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". + return candidateForArgumentError; + } + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForTypeArgumentError) { + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); + } + 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 than anySignature. + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + if (!produceDiagnostics) { + ts.Debug.assert(candidates.length > 0); // Else would have exited above. + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { + var typeArguments_2 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_2.length > typeParameters.length) { + typeArguments_2.pop(); + } + while (typeArguments_2.length < typeParameters.length) { + typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + candidates[bestIndex] = instantiated; + return instantiated; + } + return candidate; + } + return resolveErrorCall(node); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var originalCandidate = candidates[candidateIndex]; + if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + continue; + } + var candidate = void 0; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : + undefined; + while (true) { + candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } + } + else { + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + break; + } + if (excludeCount === 0) { + candidates[candidateIndex] = candidate; + return candidate; + } + excludeCount--; + if (excludeCount > 0) { + excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + } + else { + excludeArgument = undefined; + } + } + } + return undefined; + } + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + return i; + } + if (candidate.parameters.length > maxParams) { + maxParams = candidate.parameters.length; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray) { + if (node.expression.kind === 97 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (superType !== unknownType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. + if (funcType !== unknownType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (constructSignatures.length) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + } + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have + // no common signatures. + if (funcType.flags & 65536 /* Union */) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } + function resolveNewExpression(node, candidatesOutArray) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // 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(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray); + if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + return signature; + } + error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + return resolveErrorCall(node); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getModifierFlags(declaration); + // Public constructor is accessible. + if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + while (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 /* Protected */ && + baseType.symbol === declaration.parent.symbol) { + return true; + } + baseTypes = getBaseTypes(baseType); + } + } + if (modifiers & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function resolveTaggedTemplateExpression(node, candidatesOutArray) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 146 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 149 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = void 0; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } + /** + * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. + * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName + * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) + * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. + * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function + * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + */ + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); + return callSignature; + } + /** + * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. + * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible + * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. + * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures + */ + function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { + // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) + if (elementType.flags & 65536 /* Union */) { + var types = elementType.types; + var result = void 0; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; + result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); + } + return result; + } + var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); + if (callSignatures && callSignatures.length > 0) { + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + } + return undefined; + } + function resolveSignature(node, candidatesOutArray) { + switch (node.kind) { + case 181 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray); + case 182 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray); + case 183 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray); + case 147 /* Decorator */: + return resolveDecorator(node, candidatesOutArray); + case 251 /* JsxOpeningElement */: + case 250 /* JsxSelfClosingElement */: + // This code-path is called by language service + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + } + ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ + function getResolvedSignature(node, candidatesOutArray) { + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ + function isJavaScriptConstructor(node) { + if (ts.isInJavaScriptFile(node)) { + // If the node has a @class tag, treat it like a constructor. + if (ts.getJSDocClassTag(node)) + return true; + // If the symbol of the node has members, treat it like a constructor. + var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : + ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + undefined; + return symbol && symbol.members !== undefined; + } + return false; + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && getObjectFlags(type) & 16 /* Anonymous */ + && getSymbolLinks(type.symbol).inferredClassType === type; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 97 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 182 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 152 /* Constructor */ && + declaration.kind !== 156 /* ConstructSignature */ && + declaration.kind !== 161 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = node.expression.kind === 71 /* Identifier */ ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { + funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); + } + if (funcSymbol && funcSymbol.flags & 16 /* Function */ && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { + return getInferredClassType(funcSymbol); + } + else if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + return getReturnTypeOfSignature(signature); + } + function checkImportCallExpression(node) { + // Check grammar of dynamic import + checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + // Even though multiple arugments is grammatically incorrect, type-check extra arguments for completion + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 2048 /* Undefined */ || specifierType.flags & 4096 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + // Make sure require is not a local function + if (!ts.isIdentifier(node.expression)) + throw ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!resolvedRequire) { + // project does not contain symbol named 'require' - assume commonjs require + return true; + } + // project includes symbol named 'require' - make sure that it it ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 228 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 226 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return ts.isInAmbientContext(decl); + } + return false; + } + function checkTaggedTemplateExpression(node) { + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== unknownType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return unknownType; + } + else if (container.kind === 152 /* Constructor */) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && declaration.initializer) { + return getNullableType(type, 2048 /* Undefined */); + } + } + return type; + } + function getTypeAtPosition(signature, pos) { + return signature.hasRestParameter ? + pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : + pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + } + function getTypeOfFirstParameterOfSignature(signature) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + var parameter = ts.lastOrUndefined(signature.parameters); + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + assignBindingElementTypes(element); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + 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 && + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); + } + assignBindingElementTypes(parameter.valueDeclaration); + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return unknownType; + } + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!func.body) { + return unknownType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 207 /* Block */) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2 /* Async */) { + // 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 should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = void 0; + if (functionFlags & 1 /* Generator */) { + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (!types) { + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function + } + if (types.length === 0) { + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function + } + } + // Return a union of the return expression types. + type = getUnionType(types, /*subtypeReduction*/ true); + if (functionFlags & 1 /* Generator */) { + type = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(type) // AsyncGenerator function + : createIterableIteratorType(type); // Generator function + } + } + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } + var widenedType = getWidenedType(type); + // 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 /* AsyncGenerator */) === 2 /* Async */ + ? createPromiseReturnType(func, widenedType) // Async function + : widenedType; // Generator function, AsyncGenerator function, or normal function + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var functionFlags = ts.getFunctionFlags(func); + ts.forEachYieldExpression(func.body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (yieldExpression.asteriskToken) { + // A yield* expression effectively yields everything that its operand yields + type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); + } + if (functionFlags & 2 /* Async */) { + type = checkAwaitedType(type, expr, yieldExpression.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 221 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2 /* Async */) { + // 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 should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 8192 /* Never */) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */)) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (!ts.contains(aggregatedTypes, undefinedType)) { + aggregatedTypes.push(undefinedType); + } + } + return aggregatedTypes; + } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 8192 /* Never */) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + checkNodeDeferred(node); + return anyFunctionType; + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(node.symbol); + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + checkNodeDeferred(node); + } + } + if (produceDiagnostics && node.kind !== 151 /* MethodDeclaration */) { + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + } + return type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnOrPromisedType = returnTypeNode && + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? + checkAsyncFunctionReturnType(node) : + getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + if ((functionFlags & 1 /* Generator */) === 0) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!returnTypeNode) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 207 /* Block */) { + checkSourceElement(node.body); + } + else { + // 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 we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + 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); + } + else { + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + } + } + } + registerForUnusedIdentifiersCheck(node); + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + 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 */); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) && + expr.expression.kind === 99 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 152 /* Constructor */)) { + return true; + } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 71 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 240 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 71 /* Identifier */ && node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 179 /* PropertyAccessExpression */ && expr.kind !== 180 /* ElementAccessExpression */) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 16384 /* AwaitContext */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + switch (node.operator) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + return numberType; + case 51 /* ExclamationToken */: + var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); + return facts === 1048576 /* Truthy */ ? falseType : + facts === 2097152 /* Falsy */ ? trueType : + booleanType; + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + return unknownType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 196608 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + // Return true if type is of the given kind. A union type is of a given kind if all constituent types + // are of the given kind. An intersection type is of a given kind if at least one constituent type is + // of the given kind. + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 65536 /* Union */) { + var types = type.types; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; + if (!isTypeOfKind(t, kind)) { + return false; + } + } + return true; + } + if (type.flags & 131072 /* Intersection */) { + var types = type.types; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isConstEnumObjectType(type) { + return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (isTypeOfKind(leftType, 8190 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || + getSignaturesOfType(rightType, 0 /* Call */).length || + getSignaturesOfType(rightType, 1 /* Construct */).length || + isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + // TypeScript 1.0 spec (April 2014): 4.15.5 + // 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, 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 */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType) { + var properties = node.properties; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + } + return sourceType; + } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 261 /* PropertyAssignment */ || property.kind === 262 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var text = ts.getTextOfPropertyName(name); + var type = isTypeAny(objectLiteralType) + ? objectLiteralType + : getTypeOfPropertyOfType(objectLiteralType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || + getIndexTypeOfType(objectLiteralType, 0 /* String */); + if (type) { + if (property.kind === 262 /* ShorthandPropertyAssignment */) { + return checkDestructuringAssignment(property, type); + } + else { + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.initializer, type); + } + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 263 /* SpreadAssignment */) { + if (languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; + var elements = node.elements; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 200 /* OmittedExpression */) { + if (element.kind !== 198 /* SpreadElement */) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) + ? getTypeOfPropertyOfType(sourceType, propName) + : elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + else { + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 194 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + var target; + if (exprOrAssignment.kind === 262 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 194 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 178 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType); + } + if (target.kind === 177 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 263 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); + } + return sourceType; + } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 183 /* TaggedTemplateExpression */: + case 196 /* TemplateExpression */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 139 /* UndefinedKeyword */: + case 186 /* FunctionExpression */: + case 199 /* ClassExpression */: + case 187 /* ArrowFunction */: + case 177 /* ArrayLiteralExpression */: + case 178 /* ObjectLiteralExpression */: + case 189 /* TypeOfExpression */: + case 203 /* NonNullExpression */: + case 250 /* JsxSelfClosingElement */: + case 249 /* JsxElement */: + return true; + case 195 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 194 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 192 /* PrefixUnaryExpression */: + case 193 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 51 /* ExclamationToken */: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 190 /* VoidExpression */: // Explicit opt-out + case 184 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 202 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], /*subtypeReduction*/ true); + } + function checkBinaryExpression(node, checkMode) { + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 58 /* EqualsToken */ && (left.kind === 178 /* ObjectLiteralExpression */ || left.kind === 177 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + } + var leftType = checkExpression(left, checkMode); + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 39 /* AsteriskToken */: + case 40 /* AsteriskAsteriskToken */: + case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + case 42 /* PercentToken */: + case 64 /* PercentEqualsToken */: + case 38 /* MinusToken */: + case 60 /* MinusEqualsToken */: + case 45 /* LessThanLessThanToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 49 /* BarToken */: + case 69 /* BarEqualsToken */: + case 50 /* CaretToken */: + case 70 /* CaretEqualsToken */: + case 48 /* AmpersandToken */: + case 68 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 136 /* BooleanLike */) && + (rightType.flags & 136 /* BooleanLike */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + if (leftOk && rightOk) { + checkAssignmentOperator(numberType); + } + } + return numberType; + case 37 /* PlusToken */: + case 59 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeOfKind(leftType, 1 /* Any */ | 262178 /* StringLike */) && !isTypeOfKind(rightType, 1 /* Any */ | 262178 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + 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; + } + else { + if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 59 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + reportOperatorError(); + } + } + return booleanType; + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 93 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 92 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 53 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 54 /* BarBarToken */: + return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; + case 58 /* EqualsToken */: + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + case 26 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + } + function isEvalNode(node) { + return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 49 /* BarToken */: + case 69 /* BarEqualsToken */: + return 54 /* BarBarToken */; + case 50 /* CaretToken */: + case 70 /* CaretEqualsToken */: + return 35 /* ExclamationEqualsEqualsToken */; + case 48 /* AmpersandToken */: + case 68 /* AmpersandEqualsToken */: + return 53 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non - compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); + } + } + } + function reportOperatorError() { + error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + if (node.expression) { + var func = ts.getContainingFunction(node); + // If the user's code is syntactically correct, the func should always have a star. After all, + // we are in a yield context. + var functionFlags = func && ts.getFunctionFlags(func); + if (node.asteriskToken) { + // 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 */); + } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + if (functionFlags & 1 /* Generator */) { + var expressionType = checkExpressionCached(node.expression); + var expressionElementType = void 0; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); + } + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + var returnType = ts.getEffectiveReturnTypeNode(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2 /* Async */) !== 0) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(functionFlags & 2 /* Async */ + ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionElementType, signatureElementType, node.expression, + /*headMessage*/ undefined); + } + else { + checkTypeAssignableTo(functionFlags & 2 /* Async */ + ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionType, signatureElementType, node.expression, + /*headMessage*/ undefined); + } + } + } + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getBestChoiceType(type1, type2); + } + function checkLiteralExpression(node) { + if (node.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8 /* NumericLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 101 /* TrueKeyword */: + return trueType; + case 86 /* FalseKeyword */: + return falseType; + } + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + checkExpression(templateSpan.expression); + }); + return stringType; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var saveContextualType = node.contextualType; + var saveContextualMapper = node.contextualMapper; + node.contextualType = contextualType; + node.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; + var result = checkExpression(node, checkMode); + node.contextualType = saveContextualType; + node.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 184 /* TypeAssertionExpression */ || node.kind === 202 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); + return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 540672 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + // If the type parameter is constrained to the base primitive type we're checking for, + // consider this a literal context. For example, given a type parameter 'T extends string', + // this causes us to infer string literal types for T. + if (constraint.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { + return true; + } + contextualType = constraint; + } + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode) { + var type = checkExpression(node, checkMode); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } + function checkPropertyAssignment(node, checkMode) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2 /* Inferential */) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ + function getTypeOfExpression(node, cache) { + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (node.kind === 181 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return cache ? checkExpressionCached(node) : checkExpression(node); + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ + function getContextFreeTypeOfExpression(node) { + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = getTypeOfExpression(node); + node.contextualType = saveContextualType; + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, checkMode) { + var type; + if (node.kind === 143 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281 /* JSDocTypeTag */; }); }); + if (typecasts && typecasts.length) { + // We should have already issued an error if there were multiple type jsdocs + var cast_1 = typecasts[0]; + return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); + } + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode) { + switch (node.kind) { + case 71 /* Identifier */: + return checkIdentifier(node); + case 99 /* ThisKeyword */: + return checkThisExpression(node); + case 97 /* SuperKeyword */: + return checkSuperExpression(node); + case 95 /* NullKeyword */: + return nullWideningType; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + return checkLiteralExpression(node); + case 196 /* TemplateExpression */: + return checkTemplateExpression(node); + case 13 /* NoSubstitutionTemplateLiteral */: + return stringType; + case 12 /* RegularExpressionLiteral */: + return globalRegExpType; + case 177 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode); + case 178 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 179 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 180 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 181 /* CallExpression */: + if (node.expression.kind === 91 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + /* falls through */ + case 182 /* NewExpression */: + return checkCallExpression(node); + case 183 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 185 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 199 /* ClassExpression */: + return checkClassExpression(node); + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 189 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + return checkAssertion(node); + case 203 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 204 /* MetaProperty */: + return checkMetaProperty(node); + case 188 /* DeleteExpression */: + return checkDeleteExpression(node); + case 190 /* VoidExpression */: + return checkVoidExpression(node); + case 191 /* AwaitExpression */: + return checkAwaitExpression(node); + case 192 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 193 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 194 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 195 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 198 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 200 /* OmittedExpression */: + return undefinedWideningType; + case 197 /* YieldExpression */: + return checkYieldExpression(node); + case 256 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 249 /* JsxElement */: + return checkJsxElement(node); + case 250 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node); + case 254 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 251 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return unknownType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { + func = ts.getContainingFunction(node); + if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (ts.indexOf(func.parameters, node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 152 /* Constructor */ || func.kind === 156 /* ConstructSignature */ || func.kind === 161 /* ConstructorType */) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + } + return -1; + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 187 /* ArrowFunction */: + case 155 /* CallSignature */: + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + case 160 /* FunctionType */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 175 /* ArrayBindingPattern */ || name.kind === 174 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 157 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + else if (node.kind === 160 /* FunctionType */ || node.kind === 228 /* FunctionDeclaration */ || node.kind === 161 /* ConstructorType */ || + node.kind === 155 /* CallSignature */ || node.kind === 152 /* Constructor */ || + node.kind === 156 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + 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 */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // 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 */); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 156 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 155 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node); + } + } + if (noUnusedIdentifiers && !node.body) { + checkUnusedTypeParameters(node); + } + } + } + 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.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 152 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); + } + } + } + else { + var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + var names = isStatic ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 153 /* GetAccessor */: + addName(names, member.name, memberName, 1 /* Getter */); + break; + case 154 /* SetAccessor */: + addName(names, member.name, memberName, 2 /* Setter */); + break; + case 149 /* PropertyDeclaration */: + addName(names, member.name, memberName, 3 /* Property */); + break; + case 151 /* MethodDeclaration */: + addName(names, member.name, memberName, 4 /* Method */); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbol(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148 /* PropertySignature */) { + var memberName = void 0; + switch (member.name.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + memberName = member.name.text; + break; + case 71 /* Identifier */: + memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 230 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 136 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 133 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionOrMethodDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructorDeclaration + checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function containsSuperCallAsComputedPropertyName(n) { + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); + } + function containsSuperCall(n) { + if (ts.isSuperCall(n)) { + return true; + } + else if (ts.isFunctionLike(n)) { + return false; + } + else if (ts.isClassLike(n)) { + return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); + } + return ts.forEachChild(n, containsSuperCall); + } + function markThisReferencesAsErrors(n) { + if (n.kind === 99 /* ThisKeyword */) { + error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + } + else if (n.kind !== 186 /* FunctionExpression */ && n.kind !== 228 /* FunctionDeclaration */) { + ts.forEachChild(n, markThisReferencesAsErrors); + } + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 149 /* PropertyDeclaration */ && + !(ts.getModifierFlags(n) & 32 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 153 /* GetAccessor */) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (otherAccessor) { + if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 153 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + mapper = createTypeMapper(typeParameters, typeArguments); + } + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 159 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== unknownType) { + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var symbol = getNodeLinks(node).resolvedSymbol; + var typeParameters = symbol.flags & 524288 /* TypeAlias */ ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); + } + } + 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)); + } + } + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + // Grammar checking + var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { + grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + } + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 524288 /* IndexedAccess */)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + return type; + } + // 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, 84 /* NumberLike */)) { + var constraint = getBaseConstraintOfType(objectType); + if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { + return type; + } + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); + } + function isPrivateWithinAmbient(node) { + return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 230 /* InterfaceDeclaration */ && + n.parent.kind !== 229 /* ClassDeclaration */ && + n.parent.kind !== 199 /* ClassExpression */ && + ts.isInAmbientContext(n)) { + if (!(flags & 2 /* Ambient */)) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2 /* Ambient */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128 /* Abstract */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && + (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.getModifierFlags(node) & 128 /* Abstract */) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var current = declarations_5[_i]; + var node = current; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 228 /* FunctionDeclaration */ || node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */ || node.kind === 152 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + 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; + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anything not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function getDeclarationSpaces(d) { + switch (d.kind) { + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + return 2 /* ExportType */; + case 233 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 229 /* ClassDeclaration */: + case 232 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 237 /* ImportEqualsDeclaration */: + var result_3 = 0 /* None */; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 226 /* VariableDeclaration */: + case 176 /* BindingElement */: + case 228 /* FunctionDeclaration */: + case 242 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; + default: + ts.Debug.fail(ts.SyntaxKind[d.kind]); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 65536 /* Union */) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (errorNode) { + ts.Debug.assert(!!diagnosticMessage); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a + * construct signature that takes in an `initializer` function that in turn supplies + * a `resolve` function as one of its arguments and results in an object with a + * callable `then` signature. + * + * @param node The signature to check + */ + function checkAsyncFunctionReturnType(node) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } + } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + } + // Get and return the awaited type of the return type. + return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 229 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 146 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 149 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (rootSymbol + && rootSymbol.flags & 2097152 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + 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.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 146 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 229 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 149 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 146 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDoc(node) { + if (!ts.isInJavaScriptFile(node)) { + return; + } + ts.forEach(node.jsDoc, checkSourceElement); + } + function checkJSDocComment(node) { + if (node.tags) { + for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + checkSourceElement(tag); + } + } + } + function checkFunctionOrMethodDeclaration(node) { + checkJSDoc(node); + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 144 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + checkSourceElement(node.body); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if ((functionFlags & 1 /* Generator */) === 0) { + var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ + ? checkAsyncFunctionReturnType(node) // Async function + : getTypeFromTypeNode(returnTypeNode)); // normal function + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !returnTypeNode) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(node.body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + registerForUnusedIdentifiersCheck(node); + } + function registerForUnusedIdentifiersCheck(node) { + if (deferredUnusedIdentifierNodes) { + deferredUnusedIdentifierNodes.push(node); + } + } + function checkUnusedIdentifiers() { + if (deferredUnusedIdentifierNodes) { + for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { + var node = deferredUnusedIdentifierNodes_1[_i]; + switch (node.kind) { + case 265 /* SourceFile */: + case 233 /* ModuleDeclaration */: + checkUnusedModuleMembers(node); + break; + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + checkUnusedClassMembers(node); + checkUnusedTypeParameters(node); + break; + case 230 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node); + break; + case 207 /* Block */: + case 235 /* CaseBlock */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node); + break; + case 152 /* Constructor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + if (node.body) { + checkUnusedLocalsAndParameters(node); + } + checkUnusedTypeParameters(node); + break; + case 150 /* MethodSignature */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + checkUnusedTypeParameters(node); + break; + case 231 /* TypeAliasDeclaration */: + checkUnusedTypeParameters(node); + break; + } + } + } + } + function checkUnusedLocalsAndParameters(node) { + if (node.parent.kind !== 230 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + 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(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + } + } + }); + } + } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration.parent.parent)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 71 /* Identifier */ && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.members) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { + error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + } + } + else if (member.kind === 152 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + } + } + } + } + } + } + } + function checkUnusedTypeParameters(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.typeParameters) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var typeParameter = _a[_i]; + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + } + } + } + } + } + function checkUnusedModuleMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + } + }); + } + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 207 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + ts.forEach(node.statements, checkSourceElement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 149 /* PropertyDeclaration */ || + node.kind === 148 /* PropertySignature */ || + node.kind === 151 /* MethodDeclaration */ || + node.kind === 150 /* MethodSignature */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (ts.isInAmbientContext(node)) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 146 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + function checkCollisionWithCapturedThisVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_this")) { + potentialThisCollisions.push(node); + } + } + function checkCollisionWithCapturedNewTargetVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + potentialNewTargetCollisions.push(node); + } + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 71 /* Identifier */; + if (isDeclaration_1) { + 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); + } + return true; + } + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 71 /* Identifier */; + if (isDeclaration_2) { + 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); + } + return true; + } + }); + } + function checkCollisionWithCapturedSuperVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_super")) { + return; + } + // bubble up and find containing type + var enclosingClass = ts.getContainingClass(node); + // if containing type was not found or it is ambient - exit (no codegen) + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + return; + } + if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { + var isDeclaration_3 = node.kind !== 71 /* Identifier */; + if (isDeclaration_3) { + error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); + } + } + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 226 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!ts.isIdentifier(node.name)) + throw ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 208 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 207 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 234 /* ModuleBlock */ || + container.kind === 233 /* ModuleDeclaration */ || + container.kind === 265 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 146 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) + return; + } + if (n.kind === 179 /* PropertyAccessExpression */) { + // skip property names in property access expression + return visit(n.expression); + } + else if (n.kind === 71 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 107455 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 146 /* Parameter */ || + symbol.valueDeclaration.kind === 176 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + // - parameter is wrapped in function-like entity + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 149 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + // fall through to report error + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + checkSourceElement(node.type); + // JSDoc `function(string, string): string` syntax results in parameters with no name + if (!node.name) { + return; + } + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 176 /* BindingElement */) { + if (node.parent.kind === 174 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + markPropertyAsReferenced(property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 175 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 146 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { + error(node.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(node.name), typeToString(type), typeToString(declarationType)); + } + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + 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)); + } + } + if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 146 /* Parameter */ && right.kind === 226 /* VariableDeclaration */) || + (left.kind === 226 /* VariableDeclaration */ && right.kind === 146 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (ts.getFunctionFlags(node) & 2 /* Async */) { + if (node.modifiers.length > 1) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 209 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.statement); + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 227 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 227 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.kind === 216 /* ForOfStatement */) { + if (node.awaitModifier) { + 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 (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + } + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 227 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || unknownType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + var rightType = checkNonNullExpression(node.expression); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 227 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; + } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + var uplevelIteration = languageVersion >= 2 /* ES2015 */; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. + if (allowStringInput) { + if (arrayType.flags & 65536 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + } + } + else if (arrayType.flags & 262178 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 8192 /* Never */) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); + if (hasStringConstituent && arrayElementType) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 262178 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + } + return arrayElementType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return typeAsIterable.iteratedTypeOfIterable; + } + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); + if (!ts.some(signatures)) { + if (errorNode) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + // only report on the first error + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + return asyncMethodType + ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + // Both async and non-async iterators must have a `next` method. + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + if (isTypeAny(nextResult)) { + return undefined; + } + // For an async iterator, we must get the awaited type of the return type. + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isGetAccessorWithAnnotatedSetAccessor(node) { + return node.kind === 153 /* GetAccessor */ + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */)) !== undefined; + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + 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 */); + } + function checkReturnStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + var functionBlock = ts.getContainingFunction(node); + if (!functionBlock) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + } + } + var func = ts.getContainingFunction(node); + if (func) { + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return expressions of generators when return type tracking is added + // for generators. + return; + } + if (func.kind === 154 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 152 /* Constructor */) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2 /* Async */) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableTo(exprType, returnType, node); + } + } + } + else if (func.kind !== 152 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384 /* AwaitContext */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 258 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 257 /* CaseClause */) { + var caseClause = clause; + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + var caseType = checkExpression(caseClause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 222 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + var sourceFile = ts.getSourceFileOfNode(node); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); + return true; + } + }); + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + var classDeclaration = type.symbol.valueDeclaration; + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + var propDeclaration = prop.valueDeclaration; + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.escapedText) { + case "any": + case "number": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, typeParameters) { + var maxTypeArgumentCount = ts.length(typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + // If this declaration has too few or too many type parameters, we report an error + var numTypeParameters = ts.length(declaration.typeParameters); + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = declaration.typeParameters[i]; + var target = typeParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. + var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); + var targetConstraint = getConstraintFromTypeParameter(target); + if ((sourceConstraint || targetConstraint) && + (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { + return false; + } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkTypeParameters(node.typeParameters); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + // Only check for reserved static identifiers on non-ambient context. + if (!ts.isInAmbientContext(node)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseConstructorType.flags & 540672 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 540672 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== unknownType) { + if (isValidBaseType(t)) { + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + } + else { + error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + 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 ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + } + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 229 /* ClassDeclaration */ || d.kind === 230 /* InterfaceDeclaration */; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + 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, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { + if (derivedClassDecl.kind === 199 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + 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 (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; + } + var errorMessage = void 0; + if (isMethodLike(base)) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 4 /* Property */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkInterfaceDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + 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); + } + } + 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; + } + } + 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; + case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 45 /* LessThanLessThanToken */: return left << right; + case 50 /* CaretToken */: return left ^ right; + case 39 /* AsteriskToken */: return left * right; + case 41 /* SlashToken */: return left / right; + case 37 /* PlusToken */: return left + right; + case 38 /* MinusToken */: return left - right; + case 42 /* PercentToken */: return left % right; + } + } + 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.escapedText); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 179 /* PropertyAccessExpression */) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + 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; + } + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isConst(node); + if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 232 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 229 /* ClassDeclaration */ || + (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !ts.isInAmbientContext(declaration)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 229 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); + if (checkBody && node.body) { + // body of ambient external module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 208 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 243 /* ExportAssignment */: + case 244 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 176 /* BindingElement */: + case 226 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 229 /* ClassDeclaration */: + case 232 /* EnumDeclaration */: + case 228 /* FunctionDeclaration */: + case 230 /* InterfaceDeclaration */: + case 233 /* ModuleDeclaration */: + case 231 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); + if (!reportError) { + // symbol should not originate in augmentation + reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 71 /* Identifier */: + return node; + case 143 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 71 /* Identifier */); + return node; + case 179 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 71 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 244 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | + (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 246 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + 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 (compilerOptions.isolatedModules + && node.kind === 246 /* ExportSpecifier */ + && !(target.flags & 107455 /* Value */) + && !ts.isInAmbientContext(node)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.getModifierFlags(node) & 1 /* Export */) { + markExportAsReferenced(node); + } + if (ts.isInternalModuleImportEqualsDeclaration(node)) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 107455 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 793064 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.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); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 /* ModuleBlock */ && + !node.moduleSpecifier && ts.isInAmbientContext(node); + if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 265 /* SourceFile */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 233 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + // Grammar checking + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 71 /* Identifier */) { + markExportAsReferenced(node); + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (modulekind === ts.ModuleKind.System) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports = getExportsOfModule(moduleSymbol); + exports && exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + links.exportsChecked = true; + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || + !!declaration.body; + } + } + function checkSourceElement(node) { + if (!node) { + return; + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. + switch (kind) { + case 233 /* ModuleDeclaration */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 228 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 145 /* TypeParameter */: + return checkTypeParameter(node); + case 146 /* Parameter */: + return checkParameter(node); + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + return checkSignatureDeclaration(node); + case 157 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + return checkMethodDeclaration(node); + case 152 /* Constructor */: + return checkConstructorDeclaration(node); + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 159 /* TypeReference */: + return checkTypeReferenceNode(node); + case 158 /* TypePredicate */: + return checkTypePredicate(node); + case 162 /* TypeQuery */: + return checkTypeQuery(node); + case 163 /* TypeLiteral */: + return checkTypeLiteral(node); + case 164 /* ArrayType */: + return checkArrayType(node); + case 165 /* TupleType */: + return checkTupleType(node); + case 166 /* UnionType */: + case 167 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 168 /* ParenthesizedType */: + case 170 /* TypeOperator */: + return checkSourceElement(node.type); + case 275 /* JSDocComment */: + return checkJSDocComment(node); + case 279 /* JSDocParameterTag */: + return checkSourceElement(node.typeExpression); + case 273 /* JSDocFunctionType */: + checkSignatureDeclaration(node); + // falls through + case 274 /* JSDocVariadicType */: + case 271 /* JSDocNonNullableType */: + case 270 /* JSDocNullableType */: + case 268 /* JSDocAllType */: + case 269 /* JSDocUnknownType */: + if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + return; + case 267 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 171 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 172 /* MappedType */: + return checkMappedType(node); + case 228 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 207 /* Block */: + case 234 /* ModuleBlock */: + return checkBlock(node); + case 208 /* VariableStatement */: + return checkVariableStatement(node); + case 210 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 211 /* IfStatement */: + return checkIfStatement(node); + case 212 /* DoStatement */: + return checkDoStatement(node); + case 213 /* WhileStatement */: + return checkWhileStatement(node); + case 214 /* ForStatement */: + return checkForStatement(node); + case 215 /* ForInStatement */: + return checkForInStatement(node); + case 216 /* ForOfStatement */: + return checkForOfStatement(node); + case 217 /* ContinueStatement */: + case 218 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 219 /* ReturnStatement */: + return checkReturnStatement(node); + case 220 /* WithStatement */: + return checkWithStatement(node); + case 221 /* SwitchStatement */: + return checkSwitchStatement(node); + case 222 /* LabeledStatement */: + return checkLabeledStatement(node); + case 223 /* ThrowStatement */: + return checkThrowStatement(node); + case 224 /* TryStatement */: + return checkTryStatement(node); + case 226 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 176 /* BindingElement */: + return checkBindingElement(node); + case 229 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 230 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 231 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 232 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 233 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 238 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 237 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 244 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 243 /* ExportAssignment */: + return checkExportAssignment(node); + case 209 /* EmptyStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 225 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 247 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 199 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + } + } + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + // If skipLibCheck is enabled, skip type checking if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip type checking if file contains a + // '/// ' directive. + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + deferredNodes = []; + deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + ts.forEach(node.statements, checkSourceElement); + checkDeferredNodes(); + if (ts.isExternalModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile) { + checkUnusedIdentifiers(); + } + deferredNodes = undefined; + deferredUnusedIdentifierNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function isInsideWithStatementBody(node) { + if (node) { + while (node.parent) { + if (node.parent.kind === 220 /* WithStatement */ && node.parent.statement === node) { + return true; + } + node = node.parent; + } + } + return false; + } + function getSymbolsInScope(location, meaning) { + if (isInsideWithStatementBody(location)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + var symbols = ts.createSymbolTable(); + var memberFlags = 0 /* None */; + populateSymbols(); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 233 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 232 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 199 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!(memberFlags & 32 /* Static */)) { + copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); + } + break; + case 186 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + memberFlags = ts.getModifierFlags(location); + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 71 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 145 /* TypeParameter */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 232 /* EnumDeclaration */: + return true; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 143 /* QualifiedName */) { + node = node.parent; + } + return node.parent && node.parent.kind === 159 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 179 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent && node.parent.kind === 201 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 143 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 237 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 243 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + return getSymbolOfNode(entityName.parent.parent); + } + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJavaScriptFile(entityName) && + entityName.parent.kind === 179 /* PropertyAccessExpression */ && + entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 243 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, + /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + if (entityName.kind !== 179 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 237 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + } + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 201 /* ExpressionWithTypeArguments */) { + meaning = 793064 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 107455 /* Value */; + } + } + else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + var entityNameSymbol = resolveEntityName(entityName, meaning); + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 279 /* JSDocParameterTag */) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 145 /* TypeParameter */ && entityName.parent.parent.kind === 282 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isPartOfExpression(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 71 /* Identifier */) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + return getIntrinsicTagSymbol(entityName.parent); + } + return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.kind === 179 /* PropertyAccessExpression */ || entityName.kind === 143 /* QualifiedName */) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 179 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 159 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.parent.kind === 253 /* JsxAttribute */) { + return getJsxAttributePropertySymbol(entityName.parent); + } + if (entityName.parent.kind === 158 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 265 /* SourceFile */) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode + return getSymbolOfNode(node.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(node.parent.parent); + } + if (node.kind === 71 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (node.parent.kind === 176 /* BindingElement */ && + node.parent.parent.kind === 174 /* ObjectBindingPattern */ && + node === node.parent.propertyName) { + var typeOfPattern = getTypeOfNode(node.parent.parent); + var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 71 /* Identifier */: + case 179 /* PropertyAccessExpression */: + case 143 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 99 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + // falls through + case 97 /* SuperKeyword */: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); + return type.symbol; + case 169 /* ThisType */: + return getTypeFromTypeNode(node).symbol; + case 123 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 152 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 9 /* StringLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { + return resolveExternalModuleName(node, node); + } + // falls through + case 8 /* NumericLiteral */: + // index access + if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); + if (objectType === unknownType) + return undefined; + var apparentType = getApparentType(objectType); + if (apparentType === unknownType) + return undefined; + return getPropertyOfType(apparentType, node.text); + } + break; + } + return undefined; + } + function getShorthandAssignmentValueSymbol(location) { + // The function returns a value symbol of an identifier in the short-hand property assignment. + // This is necessary as an identifier in short-hand property assignment can contains two meaning: + // property name and property value. + if (location && location.kind === 262 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); + } + return undefined; + } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + function getTypeOfNode(node) { + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return unknownType; + } + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + var containingClass = ts.getContainingClass(node); + var classType = getTypeOfNode(containingClass); + typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + } + return typeFromTypeNode; + } + if (ts.isPartOfExpression(node)) { + return getRegularTypeOfExpression(node); + } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + var classNode = ts.getContainingClass(node); + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var baseType = getBaseTypes(classType)[0]; + return baseType && getTypeWithThisArgument(baseType, classType.thisType); + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getTypeOfSymbol(symbol); + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + } + return unknownType; + } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 178 /* ObjectLiteralExpression */ || expr.kind === 177 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 216 /* ForOfStatement */) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 194 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 261 /* PropertyAssignment */) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + } + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 177 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] + function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.getModifierFlags(node) & 32 /* Static */ + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function getRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; + var name_2 = symbol.escapedName; + ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { + var symbol = getPropertyOfType(t, name_2); + if (symbol) { + symbols_4.push(symbol); + } + }); + return symbols_4; + } + else if (symbol.flags & 33554432 /* Transient */) { + var transient = symbol; + if (transient.leftSpread) { + return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); + } + if (transient.syntheticOrigin) { + return getRootSymbols(transient.syntheticOrigin); + } + var target = void 0; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + if (target) { + return [target]; + } + } + return [symbol]; + } + // Emitter support + function isArgumentsLocalBinding(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455 /* Value */) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455 /* Value */); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 265 /* SourceFile */) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(node) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 207 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 237 /* ImportEqualsDeclaration */: + case 239 /* ImportClause */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 244 /* ExportDeclaration */: + var exportClause = node.exportClause; + return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + case 243 /* ExportAssignment */: + return node.expression + && node.expression.kind === 71 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(node) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 265 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return target.flags & 107455 /* Value */ && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + } + if (checkChildren) { + return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 264 /* EnumMember */: + case 179 /* PropertyAccessExpression */: + case 180 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 264 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { + return getEnumMemberValue(symbol.valueDeclaration); + } + } + return undefined; + } + function isFunctionType(type) { + return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeName, location) { + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === unknownType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 1 /* Any */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeOfKind(type, 136 /* BooleanLike */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeOfKind(type, 84 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeOfKind(type, 262178 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeOfKind(type, 512 /* ESSymbol */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : unknownType; + if (flags & 8192 /* AddUndefined */) { + type = getNullableType(type, 2048 /* Undefined */); + } + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + var signature = getSignatureFromDeclaration(signatureDeclaration); + getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + } + function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + var type = getWidenedType(getRegularTypeOfExpression(expr)); + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + } + function getReferencedValueDeclaration(reference) { + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); + } + function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : undefined; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + writeTypeOfDeclaration: writeTypeOfDeclaration, + writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, + writeTypeOfExpression: writeTypeOfExpression, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + }; + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + // property access can only be used as values + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = (node.kind === 179 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) + ? 107455 /* Value */ | 1048576 /* ExportValue */ + : 793064 /* Type */ | 1920 /* Namespace */; + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + // check what declarations in the symbol can contribute to the target meaning + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) + if (!symbol.declarations) { + return false; + } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 265 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + return false; + } + // check that at least one declaration of top level symbol originates from type declaration file + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 265 /* SourceFile */); + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + // Initialize global symbol table + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + if (augmentations) { + // merge module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); + getSymbolLinks(unknownSymbol).type = unknownType; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 32768 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + default: ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + // GRAMMAR CHECKING + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node)) { + if (node.kind === 151 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var flags = 0 /* None */; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 131 /* ReadonlyKeyword */) { + if (node.kind === 148 /* PropertySignature */ || node.kind === 150 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 157 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 76 /* ConstKeyword */: + if (node.kind !== 232 /* EnumDeclaration */ && node.parent.kind === 229 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); + } + break; + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 113 /* ProtectedKeyword */) { + lastProtected = modifier; + } + else if (modifier.kind === 112 /* PrivateKeyword */) { + lastPrivate = modifier; + } + if (flags & 28 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 112 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 115 /* StaticKeyword */: + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32 /* Static */; + lastStatic = modifier; + break; + case 131 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */ && node.kind !== 157 /* IndexSignature */ && node.kind !== 146 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; + case 84 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 229 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 79 /* DefaultKeyword */: + var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512 /* Default */; + break; + case 124 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 229 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 117 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 229 /* ClassDeclaration */) { + if (node.kind !== 151 /* MethodDeclaration */ && + node.kind !== 149 /* PropertyDeclaration */ && + node.kind !== 153 /* GetAccessor */ && + node.kind !== 154 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128 /* Abstract */; + break; + case 120 /* AsyncKeyword */: + if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 152 /* Constructor */) { + if (flags & 32 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return; + } + else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 152 /* Constructor */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 157 /* IndexSignature */: + case 233 /* ModuleDeclaration */: + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + case 244 /* ExportDeclaration */: + case 243 /* ExportAssignment */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 146 /* Parameter */: + return false; + default: + if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 228 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); + case 229 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); + case 230 /* InterfaceDeclaration */: + case 208 /* VariableStatement */: + case 231 /* TypeAliasDeclaration */: + return true; + case 232 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 151 /* MethodDeclaration */: + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list) { + if (list && list.hasTrailingComma) { + var start = list.end - ",".length; + var end = list.end; + var sourceFile = ts.getSourceFileOfNode(list[0]); + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (checkGrammarForDisallowedTrailingComma(typeParameters)) { + return true; + } + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (node.kind === 187 /* ArrowFunction */) { + var arrowFunction = node; + var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + if (startLine !== endLine) { + return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + } + return false; + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.getModifierFlags(parameter) !== 0) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(node, args) { + if (args) { + var sourceFile = ts.getSourceFileOfNode(node); + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 200 /* OmittedExpression */) { + return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + } + function checkGrammarArguments(node, args) { + return checkGrammarForOmittedArgument(node, args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + var sourceFile = ts.getSourceFileOfNode(node); + return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 144 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 194 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 228 /* FunctionDeclaration */ || + node.kind === 186 /* FunctionExpression */ || + node.kind === 151 /* MethodDeclaration */); + if (ts.isInAmbientContext(node)) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + if (questionToken) { + return grammarErrorOnNode(questionToken, message); + } + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var seen = ts.createUnderscoreEscapedMap(); + var Property = 1; + var GetAccessor = 2; + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263 /* SpreadAssignment */) { + continue; + } + var name = prop.name; + if (name.kind === 144 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 262 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // Modifiers are never allowed on properties except for 'async' on a method declaration + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 151 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + if (prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */) { + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + currentKind = Property; + } + else if (prop.kind === 151 /* MethodDeclaration */) { + currentKind = Property; + } + else if (prop.kind === 153 /* GetAccessor */) { + currentKind = GetAccessor; + } + else if (prop.kind === 154 /* SetAccessor */) { + currentKind = SetAccessor; + } + else { + ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === Property && existingKind === Property) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { + if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 255 /* JsxSpreadAttribute */) { + continue; + } + var jsxAttr = attr; + var name = jsxAttr.name; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + var initializer = jsxAttr.initializer; + if (initializer && initializer.kind === 256 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 216 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (ts.isInAmbientContext(accessor)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { + return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 153 /* GetAccessor */ ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 154 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarForNonSymbolComputedProperty(node, message) { + if (ts.isDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || + checkGrammarFunctionLikeDeclaration(node) || + checkGrammarForGenerator(node)) { + return true; + } + if (node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (ts.isClassLike(node.parent)) { + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (ts.isInAmbientContext(node)) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + } + else if (!node.body) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + } + } + else if (node.parent.kind === 230 /* InterfaceDeclaration */) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + } + else if (node.parent.kind === 163 /* TypeLiteral */) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 222 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 217 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 221 /* SwitchStatement */: + if (node.kind === 218 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 218 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 218 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.lastOrUndefined(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + if (node.name.kind === 175 /* ArrayBindingPattern */ || node.name.kind === 174 /* ObjectBindingPattern */) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (node.initializer) { + // Error on equals token which immediately precedes the initializer + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 215 /* ForInStatement */ && node.parent.parent.kind !== 216 /* ForOfStatement */) { + if (ts.isInAmbientContext(node)) { + if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + // Error on equals token which immediate precedes the initializer + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { + // Error on equals token which immediate precedes the initializer + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 71 /* Identifier */) { + if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 71 /* Identifier */) { + if (name.originalKeywordKind === 110 /* LetKeyword */) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 211 /* IfStatement */: + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + case 220 /* WithStatement */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + return false; + case 222 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + if (node.keywordToken === 94 /* NewKeyword */) { + if (node.name.escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + } + function checkGrammarConstructorTypeParameters(node) { + if (node.typeParameters) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + if (node.type) { + return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + else if (node.parent.kind === 230 /* InterfaceDeclaration */) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 163 /* TypeLiteral */) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (ts.isInAmbientContext(node) && node.initializer) { + return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 230 /* InterfaceDeclaration */ || + node.kind === 231 /* TypeAliasDeclaration */ || + node.kind === 238 /* ImportDeclaration */ || + node.kind === 237 /* ImportEqualsDeclaration */ || + node.kind === 244 /* ExportDeclaration */ || + node.kind === 243 /* ExportAssignment */ || + node.kind === 236 /* NamespaceExportDeclaration */ || + ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 208 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + } + function checkGrammarSourceFile(node) { + return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (ts.isInAmbientContext(node)) { + // An accessors is already reported about the ambient context + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 207 /* Block */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + var links_1 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_1.hasReportedStatementInAmbientContext) { + return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); + } + } + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.numericLiteralFlags & 4 /* Octal */) { + var diagnosticMessage = void 0; + if (languageVersion >= 1 /* ES5 */) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 173 /* LiteralType */)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 264 /* EnumMember */)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + } + function getAmbientModules() { + var result = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { + result.push(global); + } + }); + return result; + } + function checkGrammarImportCallExpression(node) { + if (modulekind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + } + } + 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 */: + return true; + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 239 /* ImportClause */: // For default import + case 237 /* ImportEqualsDeclaration */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */:// For rename import `x as y` + return true; + case 71 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 242 /* ImportSpecifier */; + default: + return false; + } + } })(ts || (ts = {})); /// /// @@ -11159,13 +45412,13 @@ var ts; return node; } function createLiteralFromNode(sourceNode) { - var node = createStringLiteral(sourceNode.text); + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; return node; } function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); - node.text = ts.escapeIdentifier(text); + node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; @@ -11177,7 +45430,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(node.text, typeArguments), node) + ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -11360,13 +45613,14 @@ var ts; return node; } ts.createProperty = createProperty; - function updateProperty(node, decorators, modifiers, name, type, initializer) { + function updateProperty(node, decorators, modifiers, name, questionToken, type, initializer) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name + || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer), node) + ? updateNode(createProperty(decorators, modifiers, name, questionToken, type, initializer), node) : node; } ts.updateProperty = updateProperty; @@ -11406,6 +45660,7 @@ var ts; || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name + || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type @@ -11603,7 +45858,7 @@ var ts; ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { var node = createSynthesizedNode(164 /* ArrayType */); - node.elementType = ts.parenthesizeElementTypeMember(elementType); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } ts.createArrayTypeNode = createArrayTypeNode; @@ -11808,7 +46063,7 @@ var ts; // instead of using the default from createPropertyAccess return node.expression !== expression || node.name !== name - ? updateNode(setEmitFlags(createPropertyAccess(expression, name), getEmitFlags(node)), node) + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) : node; } ts.updatePropertyAccess = updatePropertyAccess; @@ -13096,7 +47351,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295 /* NotEmittedStatement */); + var node = createSynthesizedNode(287 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -13108,7 +47363,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(291 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -13120,7 +47375,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(290 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -13135,7 +47390,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(288 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -13151,7 +47406,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297 /* CommaListExpression */) { + if (node.kind === 289 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -13161,7 +47416,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297 /* CommaListExpression */); + var node = createSynthesizedNode(289 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -13185,7 +47440,18 @@ var ts; return node; } ts.updateBundle = updateBundle; - // Compound nodes + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; function createComma(left, right) { return createBinary(left, 26 /* CommaToken */, right); } @@ -13306,14 +47572,6 @@ var ts; return range; } ts.setTextRange = setTextRange; - /** - * Gets flags that control emit behavior of a node. - */ - function getEmitFlags(node) { - var emitNode = node.emitNode; - return emitNode && emitNode.flags; - } - ts.getEmitFlags = getEmitFlags; /** * Sets flags that control emit behavior of a node. */ @@ -13338,6 +47596,14 @@ var ts; return node; } ts.setSourceMapRange = setSourceMapRange; + var SourceMapSource; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; /** * Gets the TextRange to use for source maps for a token of a node. */ @@ -13519,6 +47785,7 @@ var ts; var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; if (!destEmitNode) destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. if (leadingComments) destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); if (trailingComments) @@ -13633,12 +47900,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(jsxFactory.right.text); - right.text = jsxFactory.right.text; + var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(jsxFactory.text, parent); + return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -13875,7 +48142,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_1 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -13885,7 +48152,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_1.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -13896,15 +48163,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_1.push(setter); + properties_8.push(setter); } - properties_1.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_1.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_1, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -14063,8 +48330,20 @@ var ts; return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); } ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + ts.Debug.assert(!!node.body); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (node.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; } /** * Add any necessary prologue-directives into target statement-array. @@ -14147,8 +48426,8 @@ var ts; */ function ensureUseStrict(statements) { var foundUseStrict = false; - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; if (ts.isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { foundUseStrict = true; @@ -14177,7 +48456,7 @@ var ts; * BinaryExpression. */ function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var skipped = skipPartiallyEmittedExpressions(operand); + var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. if (skipped.kind === 185 /* ParenthesizedExpression */) { return operand; @@ -14215,7 +48494,7 @@ var ts; // the intended order of operations: `(a ** b) ** c` var binaryOperatorPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(194 /* BinaryExpression */, binaryOperator); - var emittedOperand = skipPartiallyEmittedExpressions(operand); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1 /* LessThan */: @@ -14307,7 +48586,7 @@ var ts; * emitted without parentheses. */ function getLiteralKindOfBinaryPlusOperand(node) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } @@ -14327,7 +48606,7 @@ var ts; } function parenthesizeForConditionalHead(condition) { var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { return ts.createParen(condition); @@ -14351,7 +48630,7 @@ var ts; * @param expression The Expression node. */ function parenthesizeForNew(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { case 181 /* CallExpression */: return ts.createParen(expression); @@ -14376,7 +48655,7 @@ var ts; // NewExpression: // new C.x -> not the same as (new C).x // - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 182 /* NewExpression */ || emittedExpression.arguments)) { return expression; @@ -14414,7 +48693,7 @@ var ts; } ts.parenthesizeListElements = parenthesizeListElements; function parenthesizeExpressionForList(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); var commaPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence @@ -14423,14 +48702,14 @@ var ts; } ts.parenthesizeExpressionForList = parenthesizeExpressionForList; function parenthesizeExpressionForExpressionStatement(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; - var kind = skipPartiallyEmittedExpressions(callee).kind; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; if (kind === 186 /* FunctionExpression */ || kind === 187 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); - return recreatePartiallyEmittedExpressions(expression, mutableCall); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } else { @@ -14453,37 +48732,32 @@ var ts; return member; } ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 162 /* TypeQuery */: + case 170 /* TypeOperator */: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; function parenthesizeElementTypeMembers(members) { return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); } ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; function parenthesizeTypeParameters(typeParameters) { if (ts.some(typeParameters)) { - var nodeArray = ts.createNodeArray(); + var params = []; for (var i = 0; i < typeParameters.length; ++i) { var entry = typeParameters[i]; - nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? ts.createParenthesizedType(entry) : entry); } - return nodeArray; + return ts.createNodeArray(params); } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - /** - * Clones a series of not-emitted expressions with a new inner expression. - * - * @param originalOuterExpression The original outer expression. - * @param newInnerExpression The new inner expression. - */ - function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { - if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { - var clone_1 = ts.getMutableClone(originalOuterExpression); - clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); - return clone_1; - } - return newInnerExpression; - } function getLeftmostExpression(node) { while (true) { switch (node.kind) { @@ -14501,7 +48775,7 @@ var ts; case 179 /* PropertyAccessExpression */: node = node.expression; continue; - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -14522,6 +48796,21 @@ var ts; OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + switch (node.kind) { + case 185 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + case 203 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 288 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } var previousNode; @@ -14534,7 +48823,7 @@ var ts; node = skipAssertions(node); } if (kinds & 4 /* PartiallyEmittedExpressions */) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); } } while (previousNode !== node); return node; @@ -14548,19 +48837,29 @@ var ts; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node)) { + while (ts.isAssertionExpression(node) || node.kind === 203 /* NonNullExpression */) { node = node.expression; } return node; } ts.skipAssertions = skipAssertions; - function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296 /* PartiallyEmittedExpression */) { - node = node.expression; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 185 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 184 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 202 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 203 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } - return node; } - ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + if (outerExpression && isOuterExpression(outerExpression, kinds)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { node.startsOnNewLine = true; return node; @@ -14572,23 +48871,33 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { - if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } - var helpers = ts.getEmitHelpers(node); - if (helpers) { - for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { - var helper = helpers_2[_i]; - if (!helper.scoped) { - var parseNode = ts.getOriginalNode(node, ts.isSourceFile); - var emitNode = ts.getOrCreateEmitNode(parseNode); - return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = hasExportStarsToExportValues + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } } } } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } } } ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; @@ -14691,7 +49000,7 @@ var ts; // `1` in `[[a] = 1] = ...` return bindingElement.right; } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { // Recovery consistent with existing emit. return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); } @@ -14753,7 +49062,7 @@ var ts; // `a[0]` in `[a[0] = 1] = ...` return getTargetOfBindingOrAssignmentElement(bindingElement.left); } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { // `a` in `[...a] = ...` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -14908,33246 +49217,6 @@ var ts; return node; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; - function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { - var externalImports = []; - var exportSpecifiers = ts.createMultiMap(); - var exportedBindings = []; - var uniqueExports = ts.createMap(); - var exportedNames; - var hasExportDefault = false; - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); - var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - if (externalHelpersImportDeclaration) { - externalImports.push(externalHelpersImportDeclaration); - } - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 238 /* ImportDeclaration */: - // import "mod" - // import x from "mod" - // import * as x from "mod" - // import { x, y } from "mod" - externalImports.push(node); - break; - case 237 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { - // import x = require("mod") - externalImports.push(node); - } - break; - case 244 /* ExportDeclaration */: - if (node.moduleSpecifier) { - if (!node.exportClause) { - // export * from "mod" - externalImports.push(node); - hasExportStarsToExportValues = true; - } - else { - // export { x, y } from "mod" - externalImports.push(node); - } - } - else { - // export { x, y } - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - if (!uniqueExports.get(specifier.name.text)) { - var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(name.text, specifier); - var decl = resolver.getReferencedImportDeclaration(name) - || resolver.getReferencedValueDeclaration(name); - if (decl) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); - } - uniqueExports.set(specifier.name.text, true); - exportedNames = ts.append(exportedNames, specifier.name); - } - } - } - break; - case 243 /* ExportAssignment */: - if (node.isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; - case 208 /* VariableStatement */: - if (ts.hasModifier(node, 1 /* Export */)) { - for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { - var decl = _e[_d]; - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); - } - } - break; - case 228 /* FunctionDeclaration */: - if (ts.hasModifier(node, 1 /* Export */)) { - if (ts.hasModifier(node, 512 /* Default */)) { - // export default function() { } - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - // export function x() { } - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - case 229 /* ClassDeclaration */: - if (ts.hasModifier(node, 1 /* Export */)) { - if (ts.hasModifier(node, 512 /* Default */)) { - // export default class { } - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - // export class x { } - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - } - } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; - } - ts.collectExternalModuleInfo = collectExternalModuleInfo; - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { - if (ts.isBindingPattern(decl.name)) { - for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); - } - } - } - else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(decl.name.text)) { - uniqueExports.set(decl.name.text, true); - exportedNames = ts.append(exportedNames, decl.name); - } - } - return exportedNames; - } - /** Use a sparse array as a multi-map. */ - function multiMapSparseArrayAdd(map, key, value) { - var values = map[key]; - if (values) { - values.push(value); - } - else { - map[key] = values = [value]; - } - return values; - } -})(ts || (ts = {})); -/// -/// -/// -var ts; -(function (ts) { - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - function createNode(kind, pos, end) { - if (kind === 265 /* SourceFile */) { - return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); - } - else if (kind === 71 /* Identifier */) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 143 /* FirstNode */) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } - else { - return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); - } - } - ts.createNode = createNode; - function visitNode(cbNode, node) { - if (node) { - return cbNode(node); - } - } - function visitNodeArray(cbNodes, nodes) { - if (nodes) { - return cbNodes(nodes); - } - } - function visitEachNode(cbNode, nodes) { - if (nodes) { - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; - var result = cbNode(node); - if (result) { - return result; - } - } - } - } - // Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes - // stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, - // embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns - // a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. - function forEachChild(node, cbNode, cbNodeArray) { - 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. - var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; - var cbNodes = cbNodeArray || cbNode; - switch (node.kind) { - case 143 /* QualifiedName */: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); - case 145 /* TypeParameter */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.constraint) || - visitNode(cbNode, node.default) || - visitNode(cbNode, node.expression); - case 262 /* ShorthandPropertyAssignment */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.equalsToken) || - visitNode(cbNode, node.objectAssignmentInitializer); - case 263 /* SpreadAssignment */: - return visitNode(cbNode, node.expression); - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.equalsGreaterThanToken) || - visitNode(cbNode, node.body); - case 159 /* TypeReference */: - return visitNode(cbNode, node.typeName) || - visitNodes(cbNodes, node.typeArguments); - case 158 /* TypePredicate */: - return visitNode(cbNode, node.parameterName) || - visitNode(cbNode, node.type); - case 162 /* TypeQuery */: - return visitNode(cbNode, node.exprName); - case 163 /* TypeLiteral */: - return visitNodes(cbNodes, node.members); - case 164 /* ArrayType */: - return visitNode(cbNode, node.elementType); - case 165 /* TupleType */: - return visitNodes(cbNodes, node.elementTypes); - case 166 /* UnionType */: - case 167 /* IntersectionType */: - return visitNodes(cbNodes, node.types); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: - return visitNode(cbNode, node.type); - case 171 /* IndexedAccessType */: - return visitNode(cbNode, node.objectType) || - visitNode(cbNode, node.indexType); - case 172 /* MappedType */: - return visitNode(cbNode, node.readonlyToken) || - visitNode(cbNode, node.typeParameter) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); - case 173 /* LiteralType */: - return visitNode(cbNode, node.literal); - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: - return visitNodes(cbNodes, node.elements); - case 177 /* ArrayLiteralExpression */: - return visitNodes(cbNodes, node.elements); - case 178 /* ObjectLiteralExpression */: - return visitNodes(cbNodes, node.properties); - case 179 /* PropertyAccessExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.name); - case 180 /* ElementAccessExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.argumentExpression); - case 181 /* CallExpression */: - case 182 /* NewExpression */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments) || - visitNodes(cbNodes, node.arguments); - case 183 /* TaggedTemplateExpression */: - return visitNode(cbNode, node.tag) || - visitNode(cbNode, node.template); - case 184 /* TypeAssertionExpression */: - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.expression); - case 185 /* ParenthesizedExpression */: - return visitNode(cbNode, node.expression); - case 188 /* DeleteExpression */: - return visitNode(cbNode, node.expression); - case 189 /* TypeOfExpression */: - return visitNode(cbNode, node.expression); - case 190 /* VoidExpression */: - return visitNode(cbNode, node.expression); - case 192 /* PrefixUnaryExpression */: - return visitNode(cbNode, node.operand); - case 197 /* YieldExpression */: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 191 /* AwaitExpression */: - return visitNode(cbNode, node.expression); - case 193 /* PostfixUnaryExpression */: - return visitNode(cbNode, node.operand); - case 194 /* BinaryExpression */: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.operatorToken) || - visitNode(cbNode, node.right); - case 202 /* AsExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.type); - case 203 /* NonNullExpression */: - return visitNode(cbNode, node.expression); - case 204 /* MetaProperty */: - return visitNode(cbNode, node.name); - case 195 /* ConditionalExpression */: - return visitNode(cbNode, node.condition) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.whenTrue) || - visitNode(cbNode, node.colonToken) || - visitNode(cbNode, node.whenFalse); - case 198 /* SpreadElement */: - return visitNode(cbNode, node.expression); - case 207 /* Block */: - case 234 /* ModuleBlock */: - return visitNodes(cbNodes, node.statements); - case 265 /* SourceFile */: - return visitNodes(cbNodes, node.statements) || - visitNode(cbNode, node.endOfFileToken); - case 208 /* VariableStatement */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.declarationList); - case 227 /* VariableDeclarationList */: - return visitNodes(cbNodes, node.declarations); - case 210 /* ExpressionStatement */: - return visitNode(cbNode, node.expression); - case 211 /* IfStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.thenStatement) || - visitNode(cbNode, node.elseStatement); - case 212 /* DoStatement */: - return visitNode(cbNode, node.statement) || - visitNode(cbNode, node.expression); - case 213 /* WhileStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 214 /* ForStatement */: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.condition) || - visitNode(cbNode, node.incrementor) || - visitNode(cbNode, node.statement); - case 215 /* ForInStatement */: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 216 /* ForOfStatement */: - return visitNode(cbNode, node.awaitModifier) || - visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: - return visitNode(cbNode, node.label); - case 219 /* ReturnStatement */: - return visitNode(cbNode, node.expression); - case 220 /* WithStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 221 /* SwitchStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 235 /* CaseBlock */: - return visitNodes(cbNodes, node.clauses); - case 257 /* CaseClause */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 258 /* DefaultClause */: - return visitNodes(cbNodes, node.statements); - case 222 /* LabeledStatement */: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); - case 223 /* ThrowStatement */: - return visitNode(cbNode, node.expression); - case 224 /* TryStatement */: - return visitNode(cbNode, node.tryBlock) || - visitNode(cbNode, node.catchClause) || - visitNode(cbNode, node.finallyBlock); - case 260 /* CatchClause */: - return visitNode(cbNode, node.variableDeclaration) || - visitNode(cbNode, node.block); - case 147 /* Decorator */: - return visitNode(cbNode, node.expression); - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 230 /* InterfaceDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 231 /* TypeAliasDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); - case 232 /* EnumDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 264 /* EnumMember */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 233 /* ModuleDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); - case 237 /* ImportEqualsDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); - case 238 /* ImportDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.importClause) || - visitNode(cbNode, node.moduleSpecifier); - case 239 /* ImportClause */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.namedBindings); - case 236 /* NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); - case 240 /* NamespaceImport */: - return visitNode(cbNode, node.name); - case 241 /* NamedImports */: - case 245 /* NamedExports */: - return visitNodes(cbNodes, node.elements); - case 244 /* ExportDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.exportClause) || - visitNode(cbNode, node.moduleSpecifier); - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: - return visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name); - case 243 /* ExportAssignment */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.expression); - case 196 /* TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 205 /* TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144 /* ComputedPropertyName */: - return visitNode(cbNode, node.expression); - case 259 /* HeritageClause */: - return visitNodes(cbNodes, node.types); - case 201 /* ExpressionWithTypeArguments */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments); - case 248 /* ExternalModuleReference */: - 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) || - visitNode(cbNode, node.closingElement); - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.attributes); - case 254 /* JsxAttributes */: - return visitNodes(cbNodes, node.properties); - case 253 /* JsxAttribute */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 255 /* JsxSpreadAttribute */: - return visitNode(cbNode, node.expression); - case 256 /* JsxExpression */: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.expression); - case 252 /* JsxClosingElement */: - return visitNode(cbNode, node.tagName); - case 267 /* JSDocTypeExpression */: - return visitNode(cbNode, node.type); - case 271 /* JSDocUnionType */: - return visitNodes(cbNodes, node.types); - case 272 /* JSDocTupleType */: - return visitNodes(cbNodes, node.types); - case 270 /* JSDocArrayType */: - return visitNode(cbNode, node.elementType); - case 274 /* JSDocNonNullableType */: - return visitNode(cbNode, node.type); - case 273 /* JSDocNullableType */: - return visitNode(cbNode, node.type); - case 275 /* JSDocRecordType */: - return visitNode(cbNode, node.literal); - case 277 /* JSDocTypeReference */: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 278 /* JSDocOptionalType */: - return visitNode(cbNode, node.type); - case 279 /* JSDocFunctionType */: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 280 /* JSDocVariadicType */: - return visitNode(cbNode, node.type); - case 281 /* JSDocConstructorType */: - return visitNode(cbNode, node.type); - case 282 /* JSDocThisType */: - return visitNode(cbNode, node.type); - case 276 /* JSDocRecordMember */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.type); - case 283 /* JSDocComment */: - return visitNodes(cbNodes, node.tags); - case 286 /* JSDocParameterTag */: - return visitNode(cbNode, node.preParameterName) || - visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.postParameterName); - case 287 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 288 /* JSDocTypeTag */: - return visitNode(cbNode, node.typeExpression); - case 285 /* JSDocAugmentsTag */: - return visitNode(cbNode, node.typeExpression); - case 289 /* JSDocTemplateTag */: - return visitNodes(cbNodes, node.typeParameters); - case 290 /* JSDocTypedefTag */: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.jsDocTypeLiteral); - case 292 /* JSDocTypeLiteral */: - return visitNodes(cbNodes, node.jsDocPropertyTags); - case 291 /* JSDocPropertyTag */: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - case 296 /* PartiallyEmittedExpression */: - return visitNode(cbNode, node.expression); - case 293 /* JSDocLiteralType */: - return visitNode(cbNode, node.literal); - } - } - ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { - if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); - return result; - } - ts.createSourceFile = createSourceFile; - function parseIsolatedEntityName(text, languageVersion) { - return Parser.parseIsolatedEntityName(text, languageVersion); - } - ts.parseIsolatedEntityName = parseIsolatedEntityName; - // See also `isExternalOrCommonJsModule` in utilities.ts - function isExternalModule(file) { - return file.externalModuleIndicator !== undefined; - } - ts.isExternalModule = isExternalModule; - // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter - // indicates what changed between the 'text' that this SourceFile has and the 'newText'. - // The SourceFile will be created with the compiler attempting to reuse as many nodes from - // this file as possible. - // - // Note: this function mutates nodes from this SourceFile. That means any existing nodes - // from this SourceFile that are being held onto may change as a result (including - // becoming detached from any SourceFile). It is recommended that this SourceFile not - // be used once 'update' is called on it. - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - } - ts.updateSourceFile = updateSourceFile; - /* @internal */ - function parseIsolatedJSDocComment(content, start, length) { - var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDoc) { - // because the jsDocComment was parsed out of the source file, it might - // not be covered by the fixupParentReferences. - Parser.fixupParentReferences(result.jsDoc); - } - return result; - } - ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - /* @internal */ - // Exposed only for testing. - function parseJSDocTypeExpressionForTests(content, start, length) { - return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); - } - ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - // Implement the parser as a singleton module. We do this for perf reasons because creating - // parser instances can actually be expensive enough to impact us on projects with many source - // files. - var Parser; - (function (Parser) { - // Share a single scanner across all calls to parse a source file. This helps speed things - // up by avoiding the cost of creating/compiling scanners over and over again. - var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; - // capture constructors in 'initializeState' to avoid null checks - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - var sourceFile; - var parseDiagnostics; - var syntaxCursor; - var currentToken; - var sourceText; - var nodeCount; - var identifiers; - var identifierCount; - var parsingContext; - // Flags that dictate what parsing context we're in. For example: - // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is - // that some tokens that would be considered identifiers may be considered keywords. - // - // When adding more parser context flags, consider which is the more common case that the - // flag will be in. This should be the 'false' state for that flag. The reason for this is - // that we don't store data in our nodes unless the value is in the *non-default* state. So, - // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for - // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost - // all nodes would need extra state on them to store this info. - // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 - // grammar specification. - // - // An important thing about these context concepts. By default they are effectively inherited - // while parsing through every grammar production. i.e. if you don't change them, then when - // you parse a sub-production, it will have the same context values as the parent production. - // This is great most of the time. After all, consider all the 'expression' grammar productions - // and how nearly all of them pass along the 'in' and 'yield' context values: - // - // EqualityExpression[In, Yield] : - // RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] - // - // Where you have to be careful is then understanding what the points are in the grammar - // where the values are *not* passed along. For example: - // - // SingleNameBinding[Yield,GeneratorParameter] - // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt - // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt - // - // Here this is saying that if the GeneratorParameter context flag is set, that we should - // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier - // and we should explicitly unset the 'yield' context flag before calling into the Initializer. - // production. Conversely, if the GeneratorParameter context flag is not set, then we - // should leave the 'yield' context flag alone. - // - // Getting this all correct is tricky and requires careful reading of the grammar to - // understand when these values should be changed versus when they should be inherited. - // - // Note: it should not be necessary to save/restore these flags during speculative/lookahead - // parsing. These context flags are naturally stored and restored through normal recursive - // descent parsing and unwinding. - var contextFlags; - // Whether or not we've had a parse error since creating the last AST node. If we have - // encountered an error, it will be stored on the next AST node we create. Parse errors - // can be broken down into three categories: - // - // 1) An error that occurred during scanning. For example, an unterminated literal, or a - // character that was completely not understood. - // - // 2) A token was expected, but was not present. This type of error is commonly produced - // by the 'parseExpected' function. - // - // 3) A token was present that no parsing function was able to consume. This type of error - // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser - // decides to skip the token. - // - // In all of these cases, we want to mark the next node as having had an error before it. - // With this mark, we can know in incremental settings if this node can be reused, or if - // we have to reparse it. If we don't keep this information around, we may just reuse the - // node. in that event we would then not produce the same errors as we did before, causing - // significant confusion problems. - // - // Note: it is necessary that this value be saved/restored during speculative/lookahead - // parsing. During lookahead parsing, we will often create a node. That node will have - // this value attached, and then this value will be set back to 'false'. If we decide to - // rewind, we must get back to the same value we had prior to the lookahead. - // - // Note: any errors at the end of the file that do not precede a regular node, should get - // attached to the EOF token. - var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { - scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); - clearState(); - return result; - } - Parser.parseSourceFile = parseSourceFile; - function parseIsolatedEntityName(content, languageVersion) { - initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); - // Prime the scanner. - nextToken(); - var entityName = parseEntityName(/*allowReservedWords*/ true); - var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; - clearState(); - return isInvalid ? entityName : undefined; - } - Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function getLanguageVariant(scriptKind) { - // .tsx and .jsx files are treated as jsx language variant. - return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ ? 1 /* JSX */ : 0 /* Standard */; - } - function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { - NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); - SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); - sourceText = _sourceText; - syntaxCursor = _syntaxCursor; - parseDiagnostics = []; - parsingContext = 0; - identifiers = ts.createMap(); - identifierCount = 0; - nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 65536 /* JavaScriptFile */ : 0 /* None */; - parseErrorBeforeNextFinishedNode = false; - // Initialize and prime the scanner before parsing the source elements. - scanner.setText(sourceText); - scanner.setOnError(scanError); - scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(getLanguageVariant(scriptKind)); - } - function clearState() { - // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. - scanner.setText(""); - scanner.setOnError(undefined); - // Clear any data. We don't want to accidentally hold onto it for too long. - parseDiagnostics = undefined; - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); - sourceFile.flags = contextFlags; - // Prime the scanner. - nextToken(); - processReferenceComments(sourceFile); - sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); - ts.Debug.assert(token() === 1 /* EndOfFileToken */); - sourceFile.endOfFileToken = parseTokenNode(); - setExternalModuleIndicator(sourceFile); - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.identifiers = identifiers; - sourceFile.parseDiagnostics = parseDiagnostics; - if (setParentNodes) { - fixupParentReferences(sourceFile); - } - return sourceFile; - } - function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; - } - node.jsDoc.push(jsDoc); - } - } - return node; - } - function fixupParentReferences(rootNode) { - // normally parent references are set during binding. However, for clients that only need - // a syntax tree, and no semantic features, then the binding process is an unnecessary - // overhead. This functions allows us to set all the parents, without all the expense of - // binding. - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - // walk down setting parents that differ from the parent we think it should be. This - // allows us to quickly bail out of setting parents for subtrees during incremental - // parsing - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDoc) { - for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - jsDoc.parent = n; - parent = jsDoc; - forEachChild(jsDoc, visitNode); - } - } - parent = saveParent; - } - } - } - Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - // code from createNode is inlined here so createNode won't have to deal with special case of creating source files - // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(265 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); - nodeCount++; - sourceFile.text = sourceText; - sourceFile.bindDiagnostics = []; - sourceFile.languageVersion = languageVersion; - sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); - sourceFile.scriptKind = scriptKind; - return sourceFile; - } - function setContextFlag(val, flag) { - if (val) { - contextFlags |= flag; - } - else { - contextFlags &= ~flag; - } - } - function setDisallowInContext(val) { - setContextFlag(val, 2048 /* DisallowInContext */); - } - function setYieldContext(val) { - setContextFlag(val, 4096 /* YieldContext */); - } - function setDecoratorContext(val) { - setContextFlag(val, 8192 /* DecoratorContext */); - } - function setAwaitContext(val) { - setContextFlag(val, 16384 /* AwaitContext */); - } - function doOutsideOfContext(context, func) { - // contextFlagsToClear will contain only the context flags that are - // currently set that we need to temporarily clear - // We don't just blindly reset to the previous flags to ensure - // that we do not mutate cached flags for the incremental - // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and - // HasAggregatedChildData). - var contextFlagsToClear = context & contextFlags; - if (contextFlagsToClear) { - // clear the requested context flags - setContextFlag(/*val*/ false, contextFlagsToClear); - var result = func(); - // restore the context flags we just cleared - setContextFlag(/*val*/ true, contextFlagsToClear); - return result; - } - // no need to do anything special as we are not in any of the requested contexts - return func(); - } - function doInsideOfContext(context, func) { - // contextFlagsToSet will contain only the context flags that - // are not currently set that we need to temporarily enable. - // We don't just blindly reset to the previous flags to ensure - // that we do not mutate cached flags for the incremental - // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and - // HasAggregatedChildData). - var contextFlagsToSet = context & ~contextFlags; - if (contextFlagsToSet) { - // set the requested context flags - setContextFlag(/*val*/ true, contextFlagsToSet); - var result = func(); - // reset the context flags we just set - setContextFlag(/*val*/ false, contextFlagsToSet); - return result; - } - // no need to do anything special as we are already in all of the requested contexts - return func(); - } - function allowInAnd(func) { - return doOutsideOfContext(2048 /* DisallowInContext */, func); - } - function disallowInAnd(func) { - return doInsideOfContext(2048 /* DisallowInContext */, func); - } - function doInYieldContext(func) { - return doInsideOfContext(4096 /* YieldContext */, func); - } - function doInDecoratorContext(func) { - return doInsideOfContext(8192 /* DecoratorContext */, func); - } - function doInAwaitContext(func) { - return doInsideOfContext(16384 /* AwaitContext */, func); - } - function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(16384 /* AwaitContext */, func); - } - function doInYieldAndAwaitContext(func) { - return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); - } - function inContext(flags) { - return (contextFlags & flags) !== 0; - } - function inYieldContext() { - return inContext(4096 /* YieldContext */); - } - function inDisallowInContext() { - return inContext(2048 /* DisallowInContext */); - } - function inDecoratorContext() { - return inContext(8192 /* DecoratorContext */); - } - function inAwaitContext() { - return inContext(16384 /* AwaitContext */); - } - function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); - } - function parseErrorAtPosition(start, length, message, arg0) { - // Don't report another error if it would just be at the same position as the last error. - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (!lastError || start !== lastError.start) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); - } - // Mark that we've encountered an error. We'll set an appropriate bit on the next - // node we finish so that it can't be reused incrementally. - parseErrorBeforeNextFinishedNode = true; - } - function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); - } - function getNodePos() { - return scanner.getStartPos(); - } - function getNodeEnd() { - return scanner.getStartPos(); - } - // Use this function to access the current token instead of reading the currentToken - // variable. Since function results aren't narrowed in control flow analysis, this ensures - // that the type checker doesn't make wrong assumptions about the type of the current - // token (e.g. a call to nextToken() changes the current token but the checker doesn't - // reason about this side effect). Mainstream VMs inline simple functions like this, so - // there is no performance penalty. - function token() { - return currentToken; - } - function nextToken() { - return currentToken = scanner.scan(); - } - function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); - } - function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); - } - function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); - } - function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); - } - function scanJsxText() { - return currentToken = scanner.scanJsxToken(); - } - function scanJsxAttributeValue() { - return currentToken = scanner.scanJsxAttributeValue(); - } - function speculationHelper(callback, isLookAhead) { - // Keep track of the state we'll need to rollback to if lookahead fails (or if the - // caller asked us to always reset our state). - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - // Note: it is not actually necessary to save/restore the context flags here. That's - // because the saving/restoring of these flags happens naturally through the recursive - // descent nature of our parser. However, we still store this here just so we can - // assert that invariant holds. - var saveContextFlags = contextFlags; - // If we're only looking ahead, then tell the scanner to only lookahead as well. - // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the - // same. - var result = isLookAhead - ? scanner.lookAhead(callback) - : scanner.tryScan(callback); - ts.Debug.assert(saveContextFlags === contextFlags); - // If our callback returned something 'falsy' or we're just looking ahead, - // then unconditionally restore us to where we were. - if (!result || isLookAhead) { - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - } - return result; - } - /** Invokes the provided callback then unconditionally restores the parser to the state it - * was in immediately prior to invoking the callback. The result of invoking the callback - * is returned from this function. - */ - function lookAhead(callback) { - return speculationHelper(callback, /*isLookAhead*/ true); - } - /** Invokes the provided callback. If the callback returns something falsy, then it restores - * the parser to the state it was in immediately prior to invoking the callback. If the - * callback returns something truthy, then the parser state is not rolled back. The result - * of invoking the callback is returned from this function. - */ - function tryParse(callback) { - return speculationHelper(callback, /*isLookAhead*/ false); - } - // Ignore strict mode flag because we will report an error in type checker instead. - function isIdentifier() { - if (token() === 71 /* Identifier */) { - return true; - } - // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is - // considered a keyword and is not an identifier. - if (token() === 116 /* YieldKeyword */ && inYieldContext()) { - return false; - } - // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is - // considered a keyword and is not an identifier. - if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { - return false; - } - return token() > 107 /* LastReservedWord */; - } - function parseExpected(kind, diagnosticMessage, shouldAdvance) { - if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { - if (shouldAdvance) { - nextToken(); - } - return true; - } - // Report specific message if provided with one. Otherwise, report generic fallback message. - if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage); - } - else { - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); - } - return false; - } - function parseOptional(t) { - if (token() === t) { - nextToken(); - return true; - } - return false; - } - function parseOptionalToken(t) { - if (token() === t) { - return parseTokenNode(); - } - return undefined; - } - function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { - return parseOptionalToken(t) || - createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); - } - function parseTokenNode() { - var node = createNode(token()); - nextToken(); - return finishNode(node); - } - function canParseSemicolon() { - // If there's a real semicolon, then we can always parse it out. - if (token() === 25 /* SemicolonToken */) { - return true; - } - // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); - } - function parseSemicolon() { - if (canParseSemicolon()) { - if (token() === 25 /* SemicolonToken */) { - // consume the semicolon if it was explicitly provided. - nextToken(); - } - return true; - } - else { - return parseExpected(25 /* SemicolonToken */); - } - } - // note: this function creates only node - function createNode(kind, pos) { - nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); - } - return kind >= 143 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); - } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } - array.pos = pos; - array.end = pos; - return array; - } - function finishNode(node, end) { - node.end = end === undefined ? scanner.getStartPos() : end; - if (contextFlags) { - node.flags |= contextFlags; - } - // Keep track on the node if we encountered an error while parsing it. If we did, then - // we cannot reuse the node incrementally. Once we've marked this node, clear out the - // flag so that we don't mark any subsequent nodes. - if (parseErrorBeforeNextFinishedNode) { - parseErrorBeforeNextFinishedNode = false; - node.flags |= 32768 /* ThisNodeHasError */; - } - return node; - } - function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { - if (reportAtCurrentPosition) { - parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); - } - else { - parseErrorAtCurrentToken(diagnosticMessage, arg0); - } - var result = createNode(kind, scanner.getStartPos()); - result.text = ""; - return finishNode(result); - } - function internIdentifier(text) { - text = ts.escapeIdentifier(text); - var identifier = identifiers.get(text); - if (identifier === undefined) { - identifiers.set(text, identifier = text); - } - return identifier; - } - // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues - // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for - // each identifier in order to reduce memory consumption. - function createIdentifier(isIdentifier, diagnosticMessage) { - identifierCount++; - if (isIdentifier) { - var node = createNode(71 /* Identifier */); - // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 71 /* Identifier */) { - node.originalKeywordKind = token(); - } - node.text = internIdentifier(scanner.getTokenValue()); - nextToken(); - return finishNode(node); - } - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); - } - function parseIdentifier(diagnosticMessage) { - return createIdentifier(isIdentifier(), diagnosticMessage); - } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */; - } - function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { - return parseLiteralNode(/*internName*/ true); - } - if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { - return parseComputedPropertyName(); - } - return parseIdentifierName(); - } - function parsePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); - } - function parseSimplePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); - } - function isSimplePropertyName() { - return token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token()); - } - function parseComputedPropertyName() { - // PropertyName [Yield]: - // LiteralPropertyName - // ComputedPropertyName[?Yield] - var node = createNode(144 /* ComputedPropertyName */); - parseExpected(21 /* OpenBracketToken */); - // We parse any expression (including a comma expression). But the grammar - // says that only an assignment expression is allowed, so the grammar checker - // will error if it sees a comma expression. - node.expression = allowInAnd(parseExpression); - parseExpected(22 /* CloseBracketToken */); - return finishNode(node); - } - function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); - } - function nextTokenIsOnSameLineAndCanFollowModifier() { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); - } - function nextTokenCanFollowModifier() { - if (token() === 76 /* ConstKeyword */) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; - } - if (token() === 84 /* ExportKeyword */) { - nextToken(); - if (token() === 79 /* DefaultKeyword */) { - return lookAhead(nextTokenIsClassOrFunctionOrAsync); - } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - } - if (token() === 79 /* DefaultKeyword */) { - return nextTokenIsClassOrFunctionOrAsync(); - } - if (token() === 115 /* StaticKeyword */) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); - } - function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); - } - function canFollowModifier() { - return token() === 21 /* OpenBracketToken */ - || token() === 17 /* OpenBraceToken */ - || token() === 39 /* AsteriskToken */ - || token() === 24 /* DotDotDotToken */ - || isLiteralPropertyName(); - } - function nextTokenIsClassOrFunctionOrAsync() { - nextToken(); - return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || - (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); - } - // True if positioned at the start of a list element - function isListElement(parsingContext, inErrorRecovery) { - var node = currentNode(parsingContext); - if (node) { - return true; - } - switch (parsingContext) { - case 0 /* SourceElements */: - case 1 /* BlockStatements */: - case 3 /* SwitchClauseStatements */: - // If we're in error recovery, then we don't want to treat ';' as an empty statement. - // The problem is that ';' can show up in far too many contexts, and if we see one - // and assume it's a statement, then we may bail out inappropriately from whatever - // we're parsing. For example, if we have a semicolon in the middle of a class, then - // we really don't want to assume the class is over and we're on a statement in the - // outer module. We just want to consume and move on. - return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); - case 2 /* SwitchClauses */: - return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; - case 4 /* TypeMembers */: - return lookAhead(isTypeMemberStart); - case 5 /* ClassMembers */: - // We allow semicolons as class elements (as specified by ES6) as long as we're - // not in error recovery. If we're in error recovery, we don't want an errant - // semicolon to be treated as a class member (since they're almost always used - // for statements. - return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); - case 6 /* EnumMembers */: - // Include open bracket computed properties. This technically also lets in indexers, - // which would be a candidate for improved error reporting. - return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); - case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 17 /* RestProperties */: - return isLiteralPropertyName(); - case 9 /* ObjectBindingElements */: - return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 7 /* HeritageClauseElement */: - // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` - // That way we won't consume the body of a class in its heritage clause. - if (token() === 17 /* OpenBraceToken */) { - return lookAhead(isValidHeritageClauseObjectLiteral); - } - if (!inErrorRecovery) { - return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - else { - // If we're in error recovery we tighten up what we're willing to match. - // That way we don't treat something like "this" as a valid heritage clause - // element during recovery. - return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - case 8 /* VariableDeclarations */: - return isIdentifierOrPattern(); - case 10 /* ArrayBindingElements */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 18 /* TypeParameters */: - return isIdentifier(); - case 11 /* ArgumentExpressions */: - case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); - case 16 /* Parameters */: - return isStartOfParameter(); - case 19 /* TypeArguments */: - case 20 /* TupleElementTypes */: - return token() === 26 /* CommaToken */ || isStartOfType(); - case 21 /* HeritageClauses */: - return isHeritageClause(); - case 22 /* ImportOrExportSpecifiers */: - return ts.tokenIsIdentifierOrKeyword(token()); - case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; - case 14 /* JsxChildren */: - return true; - case 23 /* JSDocFunctionParameters */: - case 24 /* JSDocTypeArguments */: - case 26 /* JSDocTupleTypes */: - return JSDocParser.isJSDocType(); - case 25 /* JSDocRecordMembers */: - return isSimplePropertyName(); - } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); - } - function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17 /* OpenBraceToken */); - if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not - // the class body) if we have: - // - // extends {} { - // extends {}, - // extends {} extends - // extends {} implements - var next = nextToken(); - return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; - } - return true; - } - function nextTokenIsIdentifier() { - nextToken(); - return isIdentifier(); - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); - } - function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 /* ImplementsKeyword */ || - token() === 85 /* ExtendsKeyword */) { - return lookAhead(nextTokenIsStartOfExpression); - } - return false; - } - function nextTokenIsStartOfExpression() { - nextToken(); - return isStartOfExpression(); - } - // True if positioned at a list terminator - function isListTerminator(kind) { - if (token() === 1 /* EndOfFileToken */) { - // Being at the end of the file ends all lists. - return true; - } - switch (kind) { - case 1 /* BlockStatements */: - case 2 /* SwitchClauses */: - case 4 /* TypeMembers */: - case 5 /* ClassMembers */: - case 6 /* EnumMembers */: - case 12 /* ObjectLiteralMembers */: - case 9 /* ObjectBindingElements */: - case 22 /* ImportOrExportSpecifiers */: - return token() === 18 /* CloseBraceToken */; - case 3 /* SwitchClauseStatements */: - return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; - case 7 /* HeritageClauseElement */: - return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; - case 8 /* VariableDeclarations */: - return isVariableDeclaratorListTerminator(); - case 18 /* TypeParameters */: - // Tokens other than '>' are here for better error recovery - return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; - case 11 /* ArgumentExpressions */: - // Tokens other than ')' are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; - case 15 /* ArrayLiteralMembers */: - case 20 /* TupleElementTypes */: - case 10 /* ArrayBindingElements */: - return token() === 22 /* CloseBracketToken */; - case 16 /* Parameters */: - case 17 /* RestProperties */: - // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 19 /* TypeArguments */: - // All other tokens should cause the type-argument to terminate except comma token - return token() !== 26 /* CommaToken */; - case 21 /* HeritageClauses */: - return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; - case 13 /* JsxAttributes */: - return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; - case 14 /* JsxChildren */: - return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); - case 23 /* JSDocFunctionParameters */: - return token() === 20 /* CloseParenToken */ || token() === 56 /* ColonToken */ || token() === 18 /* CloseBraceToken */; - case 24 /* JSDocTypeArguments */: - return token() === 29 /* GreaterThanToken */ || token() === 18 /* CloseBraceToken */; - case 26 /* JSDocTupleTypes */: - return token() === 22 /* CloseBracketToken */ || token() === 18 /* CloseBraceToken */; - case 25 /* JSDocRecordMembers */: - return token() === 18 /* CloseBraceToken */; - } - } - function isVariableDeclaratorListTerminator() { - // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. - if (canParseSemicolon()) { - return true; - } - // in the case where we're parsing the variable declarator of a 'for-in' statement, we - // are done if we see an 'in' keyword in front of us. Same with for-of - if (isInOrOfKeyword(token())) { - return true; - } - // ERROR RECOVERY TWEAK: - // For better error recovery, if we see an '=>' then we just stop immediately. We've got an - // arrow function here and it's going to be very unlikely that we'll resynchronize and get - // another variable declaration. - if (token() === 36 /* EqualsGreaterThanToken */) { - return true; - } - // Keep trying to parse out variable declarators. - return false; - } - // True if positioned at element or terminator of the current list or any enclosing list - function isInSomeParsingContext() { - for (var kind = 0; kind < 27 /* Count */; kind++) { - if (parsingContext & (1 << kind)) { - if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { - return true; - } - } - } - return false; - } - // Parses a list of elements - function parseList(kind, parseElement) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - while (!isListTerminator(kind)) { - if (isListElement(kind, /*inErrorRecovery*/ false)) { - var element = parseListElement(kind, parseElement); - result.push(element); - continue; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function parseListElement(parsingContext, parseElement) { - var node = currentNode(parsingContext); - if (node) { - return consumeNode(node); - } - return parseElement(); - } - function currentNode(parsingContext) { - // If there is an outstanding parse error that we've encountered, but not attached to - // some node, then we cannot get a node from the old source tree. This is because we - // want to mark the next node we encounter as being unusable. - // - // Note: This may be too conservative. Perhaps we could reuse the node and set the bit - // on it (or its leftmost child) as having the error. For now though, being conservative - // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. - return undefined; - } - var node = syntaxCursor.currentNode(scanner.getStartPos()); - // Can't reuse a missing node. - if (ts.nodeIsMissing(node)) { - return undefined; - } - // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } - // Can't reuse a node that contains a parse error. This is necessary so that we - // produce the same set of errors again. - if (ts.containsParseError(node)) { - return undefined; - } - // We can only reuse a node if it was parsed under the same strict mode that we're - // currently in. i.e. if we originally parsed a node in non-strict mode, but then - // the user added 'using strict' at the top of the file, then we can't use that node - // again as the presence of strict mode may cause us to parse the tokens in the file - // differently. - // - // Note: we *can* reuse tokens when the strict mode changes. That's because tokens - // are unaffected by strict mode. It's just the parser will decide what to do with it - // differently depending on what mode it is in. - // - // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 96256 /* ContextFlags */; - if (nodeContextFlags !== contextFlags) { - return undefined; - } - // Ok, we have a node that looks like it could be reused. Now verify that it is valid - // in the current list parsing context that we're currently at. - if (!canReuseNode(node, parsingContext)) { - return undefined; - } - return node; - } - function consumeNode(node) { - // Move the scanner so it is after the node we just consumed. - scanner.setTextPos(node.end); - nextToken(); - return node; - } - function canReuseNode(node, parsingContext) { - switch (parsingContext) { - case 5 /* ClassMembers */: - return isReusableClassMember(node); - case 2 /* SwitchClauses */: - return isReusableSwitchClause(node); - case 0 /* SourceElements */: - case 1 /* BlockStatements */: - case 3 /* SwitchClauseStatements */: - return isReusableStatement(node); - case 6 /* EnumMembers */: - return isReusableEnumMember(node); - case 4 /* TypeMembers */: - return isReusableTypeMember(node); - case 8 /* VariableDeclarations */: - return isReusableVariableDeclaration(node); - case 16 /* Parameters */: - return isReusableParameter(node); - case 17 /* RestProperties */: - return false; - // Any other lists we do not care about reusing nodes in. But feel free to add if - // you can do so safely. Danger areas involve nodes that may involve speculative - // parsing. If speculative parsing is involved with the node, then the range the - // parser reached while looking ahead might be in the edited range (see the example - // in canReuseVariableDeclaratorNode for a good case of this). - case 21 /* HeritageClauses */: - // This would probably be safe to reuse. There is no speculative parsing with - // heritage clauses. - case 18 /* TypeParameters */: - // This would probably be safe to reuse. There is no speculative parsing with - // type parameters. Note that that's because type *parameters* only occur in - // unambiguous *type* contexts. While type *arguments* occur in very ambiguous - // *expression* contexts. - case 20 /* TupleElementTypes */: - // This would probably be safe to reuse. There is no speculative parsing with - // tuple types. - // Technically, type argument list types are probably safe to reuse. While - // speculative parsing is involved with them (since type argument lists are only - // produced from speculative parsing a < as a type argument list), we only have - // the types because speculative parsing succeeded. Thus, the lookahead never - // went past the end of the list and rewound. - case 19 /* TypeArguments */: - // Note: these are almost certainly not safe to ever reuse. Expressions commonly - // need a large amount of lookahead, and we should not reuse them as they may - // have actually intersected the edit. - case 11 /* ArgumentExpressions */: - // This is not safe to reuse for the same reason as the 'AssignmentExpression' - // cases. i.e. a property assignment may end with an expression, and thus might - // have lookahead far beyond it's old node. - case 12 /* ObjectLiteralMembers */: - // This is probably not safe to reuse. There can be speculative parsing with - // type names in a heritage clause. There can be generic names in the type - // name list, and there can be left hand side expressions (which can have type - // arguments.) - case 7 /* HeritageClauseElement */: - // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes - // on any given element. Same for children. - case 13 /* JsxAttributes */: - case 14 /* JsxChildren */: - } - return false; - } - function isReusableClassMember(node) { - if (node) { - switch (node.kind) { - case 152 /* Constructor */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 149 /* PropertyDeclaration */: - case 206 /* SemicolonClassElement */: - return true; - case 151 /* MethodDeclaration */: - // Method declarations are not necessarily reusable. An object-literal - // may have a method calls "constructor(...)" and we must reparse that - // into an actual .ConstructorDeclaration. - var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; - return !nameIsConstructor; - } - } - return false; - } - function isReusableSwitchClause(node) { - if (node) { - switch (node.kind) { - case 257 /* CaseClause */: - case 258 /* DefaultClause */: - return true; - } - } - return false; - } - function isReusableStatement(node) { - if (node) { - switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 208 /* VariableStatement */: - case 207 /* Block */: - case 211 /* IfStatement */: - case 210 /* ExpressionStatement */: - case 223 /* ThrowStatement */: - case 219 /* ReturnStatement */: - case 221 /* SwitchStatement */: - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 214 /* ForStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 209 /* EmptyStatement */: - case 224 /* TryStatement */: - case 222 /* LabeledStatement */: - case 212 /* DoStatement */: - case 225 /* DebuggerStatement */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 231 /* TypeAliasDeclaration */: - return true; - } - } - return false; - } - function isReusableEnumMember(node) { - return node.kind === 264 /* EnumMember */; - } - function isReusableTypeMember(node) { - if (node) { - switch (node.kind) { - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 148 /* PropertySignature */: - case 155 /* CallSignature */: - return true; - } - } - return false; - } - function isReusableVariableDeclaration(node) { - if (node.kind !== 226 /* VariableDeclaration */) { - return false; - } - // Very subtle incremental parsing bug. Consider the following code: - // - // let v = new List < A, B - // - // This is actually legal code. It's a list of variable declarators "v = new List() - // - // then we have a problem. "v = new List= 0) { - // Always preserve a trailing comma by marking it on the NodeArray - result.hasTrailingComma = true; - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function createMissingList() { - return createNodeArray(); - } - function parseBracketedList(kind, parseElement, open, close) { - if (parseExpected(open)) { - var result = parseDelimitedList(kind, parseElement); - parseExpected(close); - return result; - } - return createMissingList(); - } - // The allowReservedWords parameter controls whether reserved words are permitted after the first dot - function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(23 /* DotToken */)) { - var node = createNode(143 /* QualifiedName */, entity.pos); // !!! - node.left = entity; - node.right = parseRightSideOfDot(allowReservedWords); - entity = finishNode(node); - } - return entity; - } - function parseRightSideOfDot(allowIdentifierNames) { - // Technically a keyword is valid here as all identifiers and keywords are identifier names. - // However, often we'll encounter this in error situations when the identifier or keyword - // is actually starting another valid construct. - // - // So, we check for the following specific case: - // - // name. - // identifierOrKeyword identifierNameOrKeyword - // - // Note: the newlines are important here. For example, if that above code - // were rewritten into: - // - // name.identifierOrKeyword - // identifierNameOrKeyword - // - // Then we would consider it valid. That's because ASI would take effect and - // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". - // In the first case though, ASI will not take effect because there is not a - // line terminator after the identifier or keyword. - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { - var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - if (matchesPattern) { - // Report that we need an identifier. However, report it right after the dot, - // and not on the next token. This is because the next token might actually - // be an identifier and the error would be quite confusing. - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); - } - } - return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); - } - function parseTemplateExpression() { - var template = createNode(196 /* TemplateExpression */); - template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); - do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15 /* TemplateMiddle */); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; - return finishNode(template); - } - function parseTemplateSpan() { - var span = createNode(205 /* TemplateSpan */); - span.expression = allowInAnd(parseExpression); - var literal; - if (token() === 18 /* CloseBraceToken */) { - reScanTemplateToken(); - literal = parseTemplateMiddleOrTemplateTail(); - } - else { - literal = parseExpectedToken(16 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); - } - span.literal = literal; - return finishNode(span); - } - function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); - } - function parseTemplateHead() { - var fragment = parseLiteralLikeNode(token(), /*internName*/ false); - ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); - return fragment; - } - function parseTemplateMiddleOrTemplateTail() { - var fragment = parseLiteralLikeNode(token(), /*internName*/ false); - ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); - return fragment; - } - function parseLiteralLikeNode(kind, internName) { - var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = internName ? internIdentifier(text) : text; - if (scanner.hasExtendedUnicodeEscape()) { - node.hasExtendedUnicodeEscape = true; - } - if (scanner.isUnterminated()) { - node.isUnterminated = true; - } - // Octal literals are not allowed in strict mode or ES5 - // Note that theoretically the following condition would hold true literals like 009, - // which is not octal.But because of how the scanner separates the tokens, we would - // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. - // We also do not need to check for negatives because any prefix operator would be part of a - // parent unary expression. - if (node.kind === 8 /* NumericLiteral */) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); - } - nextToken(); - finishNode(node); - return node; - } - // TYPES - function parseTypeReference() { - var node = createNode(159 /* TypeReference */); - node.typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } - return finishNode(node); - } - function parseThisTypePredicate(lhs) { - nextToken(); - var node = createNode(158 /* TypePredicate */, lhs.pos); - node.parameterName = lhs; - node.type = parseType(); - return finishNode(node); - } - function parseThisTypeNode() { - var node = createNode(169 /* ThisType */); - nextToken(); - return finishNode(node); - } - function parseTypeQuery() { - var node = createNode(162 /* TypeQuery */); - parseExpected(103 /* TypeOfKeyword */); - node.exprName = parseEntityName(/*allowReservedWords*/ true); - return finishNode(node); - } - function parseTypeParameter() { - var node = createNode(145 /* TypeParameter */); - node.name = parseIdentifier(); - if (parseOptional(85 /* ExtendsKeyword */)) { - // It's not uncommon for people to write improper constraints to a generic. If the - // user writes a constraint that is an expression and not an actual type, then parse - // it out as an expression (so we can recover well), but report that a type is needed - // instead. - if (isStartOfType() || !isStartOfExpression()) { - node.constraint = parseType(); - } - else { - // It was not a type, and it looked like an expression. Parse out an expression - // here so we recover well. Note: it is important that we call parseUnaryExpression - // and not parseExpression here. If the user has: - // - // - // - // We do *not* want to consume the > as we're consuming the expression for "". - node.expression = parseUnaryExpressionOrHigher(); - } - } - if (parseOptional(58 /* EqualsToken */)) { - node.default = parseType(); - } - return finishNode(node); - } - function parseTypeParameters() { - if (token() === 27 /* LessThanToken */) { - return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } - } - function parseParameterType() { - if (parseOptional(56 /* ColonToken */)) { - return parseType(); - } - return undefined; - } - function isStartOfParameter() { - return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 /* AtToken */ || token() === 99 /* ThisKeyword */; - } - function parseParameter() { - var node = createNode(146 /* Parameter */); - if (token() === 99 /* ThisKeyword */) { - node.name = createIdentifier(/*isIdentifier*/ true); - node.type = parseParameterType(); - return finishNode(node); - } - node.decorators = parseDecorators(); - node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { - // in cases like - // 'use strict' - // function foo(static) - // isParameter('static') === true, because of isModifier('static') - // however 'static' is not a legal identifier in a strict mode. - // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) - // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) - // to avoid this we'll advance cursor to the next token. - nextToken(); - } - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ true); - // Do not check for initializers in an ambient context for parameters. This is not - // a grammar error because the grammar allows arbitrary call signatures in - // an ambient context. - // It is actually not necessary for this to be an error at all. The reason is that - // function/constructor implementations are syntactically disallowed in ambient - // contexts. In addition, parameter initializers are semantically disallowed in - // overload signatures. So parameter initializers are transitively disallowed in - // ambient contexts. - return addJSDocComment(finishNode(node)); - } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(/*inParameter*/ true); - } - function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 36 /* EqualsGreaterThanToken */; - signature.typeParameters = parseTypeParameters(); - signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); - if (returnTokenRequired) { - parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); - } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); - } - } - function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - // FormalParameters [Yield,Await]: (modified) - // [empty] - // FormalParameterList[?Yield,Await] - // - // FormalParameter[Yield,Await]: (modified) - // BindingElement[?Yield,Await] - // - // BindingElement [Yield,Await]: (modified) - // SingleNameBinding[?Yield,?Await] - // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - // - // SingleNameBinding [Yield,Await]: - // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(19 /* OpenParenToken */)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(yieldContext); - setAwaitContext(awaitContext); - var result = parseDelimitedList(16 /* Parameters */, parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20 /* CloseParenToken */) && requireCompleteParameterList) { - // Caller insisted that we had to end with a ) We didn't. So just return - // undefined here. - return undefined; - } - return result; - } - // We didn't even have an open paren. If the caller requires a complete parameter list, - // we definitely can't provide that. However, if they're ok with an incomplete one, - // then just return an empty set of parameters. - return requireCompleteParameterList ? undefined : createMissingList(); - } - function parseTypeMemberSemicolon() { - // We allow type members to be separated by commas or (possibly ASI) semicolons. - // First check if it was a comma. If so, we're done with the member. - if (parseOptional(26 /* CommaToken */)) { - return; - } - // Didn't have a comma. We must have a (possible ASI) semicolon. - parseSemicolon(); - } - function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156 /* ConstructSignature */) { - parseExpected(94 /* NewKeyword */); - } - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); - } - function isIndexSignature() { - if (token() !== 21 /* OpenBracketToken */) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); - } - function isUnambiguouslyIndexSignature() { - // The only allowed sequence is: - // - // [id: - // - // However, for error recovery, we also check the following cases: - // - // [... - // [id, - // [id?, - // [id?: - // [id?] - // [public id - // [private id - // [protected id - // [] - // - nextToken(); - if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { - return true; - } - if (ts.isModifierKind(token())) { - nextToken(); - if (isIdentifier()) { - return true; - } - } - else if (!isIdentifier()) { - return false; - } - else { - // Skip the identifier - nextToken(); - } - // A colon signifies a well formed indexer - // A comma should be a badly formed indexer because comma expressions are not allowed - // in computed properties. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { - return true; - } - // Question mark could be an indexer with an optional property, - // or it could be a conditional expression in a computed property. - if (token() !== 55 /* QuestionToken */) { - return false; - } - // If any of the following tokens are after the question mark, it cannot - // be a conditional expression, so treat it as an indexer. - nextToken(); - return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; - } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157 /* IndexSignature */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); - node.type = parseTypeAnnotation(); - parseTypeMemberSemicolon(); - return finishNode(node); - } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - var method = createNode(150 /* MethodSignature */, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - // Method signatures don't exist in expression contexts. So they have neither - // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); - } - else { - var property = createNode(148 /* PropertySignature */, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - if (token() === 58 /* EqualsToken */) { - // Although type literal properties cannot not have initializers, we attempt - // to parse an initializer so we can report in the checker that an interface - // property or type literal property cannot have an initializer. - property.initializer = parseNonParameterInitializer(); - } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); - } - } - function isTypeMemberStart() { - // Return true if we have the start of a signature member - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return true; - } - var idToken; - // Eat up all modifiers, but hold on to the last one in case it is actually an identifier - while (ts.isModifierKind(token())) { - idToken = true; - nextToken(); - } - // Index signatures and computed property names are type members - if (token() === 21 /* OpenBracketToken */) { - return true; - } - // Try to get the first property-like token following all modifiers - if (isLiteralPropertyName()) { - idToken = true; - nextToken(); - } - // If we were able to get any potential identifier, check that it is - // the start of a member declaration - if (idToken) { - return token() === 19 /* OpenParenToken */ || - token() === 27 /* LessThanToken */ || - token() === 55 /* QuestionToken */ || - token() === 56 /* ColonToken */ || - token() === 26 /* CommaToken */ || - canParseSemicolon(); - } - return false; - } - function parseTypeMember() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(155 /* CallSignature */); - } - if (token() === 94 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(156 /* ConstructSignature */); - } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); - } - return parsePropertyOrMethodSignature(fullStart, modifiers); - } - function isStartOfConstructSignature() { - nextToken(); - return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; - } - function parseTypeLiteral() { - var node = createNode(163 /* TypeLiteral */); - node.members = parseObjectTypeMembers(); - return finishNode(node); - } - function parseObjectTypeMembers() { - var members; - if (parseExpected(17 /* OpenBraceToken */)) { - members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(18 /* CloseBraceToken */); - } - else { - members = createMissingList(); - } - return members; - } - function isStartOfMappedType() { - nextToken(); - if (token() === 131 /* ReadonlyKeyword */) { - nextToken(); - } - return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; - } - function parseMappedTypeParameter() { - var node = createNode(145 /* TypeParameter */); - node.name = parseIdentifier(); - parseExpected(92 /* InKeyword */); - node.constraint = parseType(); - return finishNode(node); - } - function parseMappedType() { - var node = createNode(172 /* MappedType */); - parseExpected(17 /* OpenBraceToken */); - node.readonlyToken = parseOptionalToken(131 /* ReadonlyKeyword */); - parseExpected(21 /* OpenBracketToken */); - node.typeParameter = parseMappedTypeParameter(); - parseExpected(22 /* CloseBracketToken */); - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - node.type = parseTypeAnnotation(); - parseSemicolon(); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseTupleType() { - var node = createNode(165 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); - return finishNode(node); - } - function parseParenthesizedType() { - var node = createNode(168 /* ParenthesizedType */); - parseExpected(19 /* OpenParenToken */); - node.type = parseType(); - parseExpected(20 /* CloseParenToken */); - return finishNode(node); - } - function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161 /* ConstructorType */) { - parseExpected(94 /* NewKeyword */); - } - fillSignature(36 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - return finishNode(node); - } - function parseKeywordAndNoDot() { - var node = parseTokenNode(); - return token() === 23 /* DotToken */ ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(173 /* LiteralType */); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; - } - function parseNonArrayType() { - switch (token()) { - case 119 /* AnyKeyword */: - case 136 /* StringKeyword */: - case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 139 /* UndefinedKeyword */: - case 130 /* NeverKeyword */: - case 134 /* ObjectKeyword */: - // If these are followed by a dot, then parse these out as a dotted type reference instead. - var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - return parseLiteralTypeNode(); - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 105 /* VoidKeyword */: - case 95 /* NullKeyword */: - return parseTokenNode(); - case 99 /* ThisKeyword */: { - var thisKeyword = parseThisTypeNode(); - if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - return parseThisTypePredicate(thisKeyword); - } - else { - return thisKeyword; - } - } - case 103 /* TypeOfKeyword */: - return parseTypeQuery(); - case 17 /* OpenBraceToken */: - return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21 /* OpenBracketToken */: - return parseTupleType(); - case 19 /* OpenParenToken */: - return parseParenthesizedType(); - default: - return parseTypeReference(); - } - } - function isStartOfType() { - switch (token()) { - case 119 /* AnyKeyword */: - case 136 /* StringKeyword */: - case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 139 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 103 /* TypeOfKeyword */: - case 130 /* NeverKeyword */: - case 17 /* OpenBraceToken */: - case 21 /* OpenBracketToken */: - case 27 /* LessThanToken */: - case 49 /* BarToken */: - case 48 /* AmpersandToken */: - case 94 /* NewKeyword */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 134 /* ObjectKeyword */: - return true; - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral); - case 19 /* OpenParenToken */: - // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, - // or something that starts a type. We don't want to consider things like '(1)' a type. - return lookAhead(isStartOfParenthesizedOrFunctionType); - default: - return isIdentifier(); - } - } - function isStartOfParenthesizedOrFunctionType() { - nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); - } - function parseArrayTypeOrHigher() { - var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21 /* OpenBracketToken */)) { - if (isStartOfType()) { - var node = createNode(171 /* IndexedAccessType */, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); - } - else { - var node = createNode(164 /* ArrayType */, type.pos); - node.elementType = type; - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); - } - } - return type; - } - function parseTypeOperator(operator) { - var node = createNode(170 /* TypeOperator */); - parseExpected(operator); - node.operator = operator; - node.type = parseTypeOperatorOrHigher(); - return finishNode(node); - } - function parseTypeOperatorOrHigher() { - switch (token()) { - case 127 /* KeyOfKeyword */: - return parseTypeOperator(127 /* KeyOfKeyword */); - } - return parseArrayTypeOrHigher(); - } - function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { - parseOptional(operator); - var type = parseConstituentType(); - if (token() === operator) { - var types = createNodeArray([type], type.pos); - while (parseOptional(operator)) { - types.push(parseConstituentType()); - } - types.end = getNodeEnd(); - var node = createNode(kind, type.pos); - node.types = types; - type = finishNode(node); - } - return type; - } - function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); - } - function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); - } - function isStartOfFunctionType() { - if (token() === 27 /* LessThanToken */) { - return true; - } - return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); - } - function skipParameterStart() { - if (ts.isModifierKind(token())) { - // Skip modifiers - parseModifiers(); - } - if (isIdentifier() || token() === 99 /* ThisKeyword */) { - nextToken(); - return true; - } - if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { - // Return true if we can parse an array or object binding pattern with no errors - var previousErrorCount = parseDiagnostics.length; - parseIdentifierOrPattern(); - return previousErrorCount === parseDiagnostics.length; - } - return false; - } - function isUnambiguouslyStartOfFunctionType() { - nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { - // ( ) - // ( ... - return true; - } - if (skipParameterStart()) { - // We successfully skipped modifiers (if any) and an identifier or binding pattern, - // now see if we have something that indicates a parameter declaration - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || - token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { - // ( xxx : - // ( xxx , - // ( xxx ? - // ( xxx = - return true; - } - if (token() === 20 /* CloseParenToken */) { - nextToken(); - if (token() === 36 /* EqualsGreaterThanToken */) { - // ( xxx ) => - return true; - } - } - } - return false; - } - function parseTypeOrTypePredicate() { - var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); - var type = parseType(); - if (typePredicateVariable) { - var node = createNode(158 /* TypePredicate */, typePredicateVariable.pos); - node.parameterName = typePredicateVariable; - node.type = type; - return finishNode(node); - } - else { - return type; - } - } - function parseTypePredicatePrefix() { - var id = parseIdentifier(); - if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - return id; - } - } - function parseType() { - // The rules about 'yield' only apply to actual code/expression contexts. They don't - // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); - } - function parseTypeWorker() { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160 /* FunctionType */); - } - if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(161 /* ConstructorType */); - } - return parseUnionTypeOrHigher(); - } - function parseTypeAnnotation() { - return parseOptional(56 /* ColonToken */) ? parseType() : undefined; - } - // EXPRESSIONS - function isStartOfLeftHandSideExpression() { - switch (token()) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 19 /* OpenParenToken */: - case 21 /* OpenBracketToken */: - case 17 /* OpenBraceToken */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 94 /* NewKeyword */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 71 /* Identifier */: - return true; - default: - return isIdentifier(); - } - } - function isStartOfExpression() { - if (isStartOfLeftHandSideExpression()) { - return true; - } - switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 27 /* LessThanToken */: - case 121 /* AwaitKeyword */: - case 116 /* YieldKeyword */: - // Yield/await always starts an expression. Either it is an identifier (in which case - // it is definitely an expression). Or it's a keyword (either because we're in - // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. - return true; - default: - // Error tolerance. If we see the start of some binary operator, we consider - // that the start of an expression. That way we'll parse out a missing identifier, - // give a good message about an identifier being missing, and then consume the - // rest of the binary expression. - if (isBinaryOperator()) { - return true; - } - return isIdentifier(); - } - } - function isStartOfExpressionStatement() { - // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 17 /* OpenBraceToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - token() !== 57 /* AtToken */ && - isStartOfExpression(); - } - function parseExpression() { - // Expression[in]: - // AssignmentExpression[in] - // Expression[in] , AssignmentExpression[in] - // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ false); - } - var expr = parseAssignmentExpressionOrHigher(); - var operatorToken; - while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); - } - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ true); - } - return expr; - } - function parseInitializer(inParameter) { - if (token() !== 58 /* EqualsToken */) { - // It's not uncommon during typing for the user to miss writing the '=' token. Check if - // there is no newline after the last token and if we're on an expression. If so, parse - // this as an equals-value clause with a missing equals. - // NOTE: There are two places where we allow equals-value clauses. The first is in a - // variable declarator. The second is with a parameter. For variable declarators - // it's more likely that a { would be a allowed (as an object literal). While this - // is also allowed for parameters, the risk is that we consume the { as an object - // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17 /* OpenBraceToken */) || !isStartOfExpression()) { - // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - - // do not try to parse initializer - return undefined; - } - } - // Initializer[In, Yield] : - // = AssignmentExpression[?In, ?Yield] - parseExpected(58 /* EqualsToken */); - return parseAssignmentExpressionOrHigher(); - } - function parseAssignmentExpressionOrHigher() { - // AssignmentExpression[in,yield]: - // 1) ConditionalExpression[?in,?yield] - // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] - // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] - // 4) ArrowFunctionExpression[?in,?yield] - // 5) AsyncArrowFunctionExpression[in,yield,await] - // 6) [+Yield] YieldExpression[?In] - // - // Note: for ease of implementation we treat productions '2' and '3' as the same thing. - // (i.e. they're both BinaryExpressions with an assignment operator in it). - // First, do the simple check if we have a YieldExpression (production '6'). - if (isYieldExpression()) { - return parseYieldExpression(); - } - // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized - // parameter list or is an async arrow function. - // AsyncArrowFunctionExpression: - // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] - // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". - // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". - // - // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done - // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); - if (arrowExpression) { - return arrowExpression; - } - // Now try to see if we're in production '1', '2' or '3'. A conditional expression can - // start with a LogicalOrExpression, while the assignment productions can only start with - // LeftHandSideExpressions. - // - // So, first, we try to just parse out a BinaryExpression. If we get something that is a - // LeftHandSide or higher, then we can try to parse out the assignment expression part. - // Otherwise, we try to parse out the conditional expression bit. We want to allow any - // binary expression here, so we pass in the 'lowest' precedence here so that it matches - // and consumes anything. - var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized - // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single - // identifier and the current token is an arrow. - if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(expr); - } - // Now see if we might be in cases '2' or '3'. - // If the expression was a LHS expression, and we have an assignment operator, then - // we're in '2' or '3'. Consume the assignment and return. - // - // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= - if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); - } - // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr); - } - function isYieldExpression() { - if (token() === 116 /* YieldKeyword */) { - // If we have a 'yield' keyword, and this is a context where yield expressions are - // allowed, then definitely parse out a yield expression. - if (inYieldContext()) { - return true; - } - // We're in a context where 'yield expr' is not allowed. However, if we can - // definitely tell that the user was trying to parse a 'yield expr' and not - // just a normal expr that start with a 'yield' identifier, then parse out - // a 'yield expr'. We can then report an error later that they are only - // allowed in generator expressions. - // - // for example, if we see 'yield(foo)', then we'll have to treat that as an - // invocation expression of something called 'yield'. However, if we have - // 'yield foo' then that is not legal as a normal expression, so we can - // definitely recognize this as a yield expression. - // - // for now we just check if the next token is an identifier. More heuristics - // can be added here later as necessary. We just need to make sure that we - // don't accidentally consume something legal. - return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); - } - return false; - } - function nextTokenIsIdentifierOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && isIdentifier(); - } - function parseYieldExpression() { - var node = createNode(197 /* YieldExpression */); - // YieldExpression[In] : - // yield - // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] - // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] - nextToken(); - if (!scanner.hasPrecedingLineBreak() && - (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - else { - // if the next token is not on the same line as yield. or we don't have an '*' or - // the start of an expression, then this is just a simple "yield" expression. - return finishNode(node); - } - } - function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node; - if (asyncModifier) { - node = createNode(187 /* ArrowFunction */, asyncModifier.pos); - node.modifiers = asyncModifier; - } - else { - node = createNode(187 /* ArrowFunction */, identifier.pos); - } - var parameter = createNode(146 /* Parameter */, identifier.pos); - parameter.name = identifier; - finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); - node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); - return addJSDocComment(finishNode(node)); - } - function tryParseParenthesizedArrowFunctionExpression() { - var triState = isParenthesizedArrowFunctionExpression(); - if (triState === 0 /* False */) { - // It's definitely not a parenthesized arrow function expression. - return undefined; - } - // If we definitely have an arrow function, then we can just parse one, not requiring a - // following => or { token. Otherwise, we *might* have an arrow function. Try to parse - // it out, but don't allow any ambiguity, and return 'undefined' if this could be an - // expression instead. - var arrowFunction = triState === 1 /* True */ - ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) - : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); - if (!arrowFunction) { - // Didn't appear to actually be a parenthesized arrow function. Just bail out. - return undefined; - } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); - // If we have an arrow, then try to parse the body. Even if not, try to parse if we - // have an opening brace, just in case we're in an error state. - var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) - ? parseArrowFunctionExpressionBody(isAsync) - : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); - } - // True -> We definitely expect a parenthesized arrow function here. - // False -> There *cannot* be a parenthesized arrow function here. - // Unknown -> There *might* be a parenthesized arrow function here. - // Speculatively look ahead to be sure, and rollback if not. - function isParenthesizedArrowFunctionExpression() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { - return lookAhead(isParenthesizedArrowFunctionExpressionWorker); - } - if (token() === 36 /* EqualsGreaterThanToken */) { - // ERROR RECOVERY TWEAK: - // If we see a standalone => try to parse it as an arrow function expression as that's - // likely what the user intended to write. - return 1 /* True */; - } - // Definitely not a parenthesized arrow function. - return 0 /* False */; - } - function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120 /* AsyncKeyword */) { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return 0 /* False */; - } - if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { - return 0 /* False */; - } - } - var first = token(); - var second = nextToken(); - if (first === 19 /* OpenParenToken */) { - if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". - // This is an arrow function with no parameters. - // The last one is not actually an arrow function, - // but this is probably what the user intended. - var third = nextToken(); - switch (third) { - case 36 /* EqualsGreaterThanToken */: - case 56 /* ColonToken */: - case 17 /* OpenBraceToken */: - return 1 /* True */; - default: - return 0 /* False */; - } - } - // If encounter "([" or "({", this could be the start of a binding pattern. - // Examples: - // ([ x ]) => { } - // ({ x }) => { } - // ([ x ]) - // ({ x }) - if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { - return 2 /* Unknown */; - } - // Simple case: "(..." - // This is an arrow function with a rest parameter. - if (second === 24 /* DotDotDotToken */) { - return 1 /* True */; - } - // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. - // Note: we could be a little more lenient and allow - // "(public" or "(private". These would not ever actually be allowed, - // but we could provide a good error message instead of bailing out. - if (!isIdentifier()) { - return 0 /* False */; - } - // If we have something like "(a:", then we must have a - // type-annotated parameter in an arrow function expression. - if (nextToken() === 56 /* ColonToken */) { - return 1 /* True */; - } - // This *could* be a parenthesized arrow function. - // Return Unknown to let the caller know. - return 2 /* Unknown */; - } - else { - ts.Debug.assert(first === 27 /* LessThanToken */); - // If we have "<" not followed by an identifier, - // then this definitely is not an arrow function. - if (!isIdentifier()) { - return 0 /* False */; - } - // JSX overrides - if (sourceFile.languageVariant === 1 /* JSX */) { - var isArrowFunctionInJsx = lookAhead(function () { - var third = nextToken(); - if (third === 85 /* ExtendsKeyword */) { - var fourth = nextToken(); - switch (fourth) { - case 58 /* EqualsToken */: - case 29 /* GreaterThanToken */: - return false; - default: - return true; - } - } - else if (third === 26 /* CommaToken */) { - return true; - } - return false; - }); - if (isArrowFunctionInJsx) { - return 1 /* True */; - } - return 0 /* False */; - } - // This *could* be a parenthesized arrow function. - return 2 /* Unknown */; - } - } - function parsePossibleParenthesizedArrowFunctionExpressionHead() { - return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); - } - function tryParseAsyncSimpleArrowFunctionExpression() { - // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 120 /* AsyncKeyword */) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { - var asyncModifier = parseModifiersForArrowFunction(); - var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - return parseSimpleArrowFunctionExpression(expr, asyncModifier); - } - } - return undefined; - } - function isUnParenthesizedAsyncArrowFunctionWorker() { - // AsyncArrowFunctionExpression: - // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] - // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 120 /* AsyncKeyword */) { - nextToken(); - // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function - // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { - return 0 /* False */; - } - // Check for un-parenthesized AsyncArrowFunction - var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { - return 1 /* True */; - } - } - return 0 /* False */; - } - function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187 /* ArrowFunction */); - node.modifiers = parseModifiersForArrowFunction(); - var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); - // Arrow functions are never generators. - // - // If we're speculatively parsing a signature for a parenthesized arrow function, then - // we have to have a complete parameter list. Otherwise we might see something like - // a => (b => c) - // And think that "(b =>" was actually a parenthesized arrow function with a missing - // close paren. - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ !allowAmbiguity, node); - // If we couldn't get parameters, we definitely could not parse out an arrow function. - if (!node.parameters) { - return undefined; - } - // Parsing a signature isn't enough. - // Parenthesized arrow signatures often look like other valid expressions. - // For instance: - // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. - // - "(x,y)" is a comma expression parsed as a signature with two parameters. - // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. - // - // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { - // Returning undefined here will cause our caller to rewind to where we started from. - return undefined; - } - return node; - } - function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17 /* OpenBraceToken */) { - return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); - } - if (token() !== 25 /* SemicolonToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - isStartOfStatement() && - !isStartOfExpressionStatement()) { - // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) - // - // Here we try to recover from a potential error situation in the case where the - // user meant to supply a block. For example, if the user wrote: - // - // a => - // let v = 0; - // } - // - // they may be missing an open brace. Check to see if that's the case so we can - // try to recover better. If we don't do this, then the next close curly we see may end - // up preemptively closing the containing construct. - // - // Note: even when 'ignoreMissingOpenBrace' is passed as true, parseBody will still error. - return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ true); - } - return isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); - } - function parseConditionalExpressionRest(leftOperand) { - // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (!questionToken) { - return leftOperand; - } - // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and - // we do not that for the 'whenFalse' part. - var node = createNode(195 /* ConditionalExpression */, leftOperand.pos); - node.condition = leftOperand; - node.questionToken = questionToken; - node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseBinaryExpressionOrHigher(precedence) { - var leftOperand = parseUnaryExpressionOrHigher(); - return parseBinaryExpressionRest(precedence, leftOperand); - } - function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 142 /* OfKeyword */; - } - function parseBinaryExpressionRest(precedence, leftOperand) { - while (true) { - // We either have a binary operator here, or we're finished. We call - // reScanGreaterToken so that we merge token sequences like > and = into >= - reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); - // Check the precedence to see if we should "take" this operator - // - For left associative operator (all operator but **), consume the operator, - // recursively call the function below, and parse binaryExpression as a rightOperand - // of the caller if the new precedence of the operator is greater then or equal to the current precedence. - // For example: - // a - b - c; - // ^token; leftOperand = b. Return b to the caller as a rightOperand - // a * b - c - // ^token; leftOperand = b. Return b to the caller as a rightOperand - // a - b * c; - // ^token; leftOperand = b. Return b * c to the caller as a rightOperand - // - For right associative operator (**), consume the operator, recursively call the function - // and parse binaryExpression as a rightOperand of the caller if the new precedence of - // the operator is strictly grater than the current precedence - // For example: - // a ** b ** c; - // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand - // a - b ** c; - // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand - // a ** b - c - // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? - newPrecedence >= precedence : - newPrecedence > precedence; - if (!consumeCurrentOperator) { - break; - } - if (token() === 92 /* InKeyword */ && inDisallowInContext()) { - break; - } - if (token() === 118 /* AsKeyword */) { - // Make sure we *do* perform ASI for constructs like this: - // var x = foo - // as (Bar) - // This should be parsed as an initialized variable, followed - // by a function call to 'as' with the argument 'Bar' - if (scanner.hasPrecedingLineBreak()) { - break; - } - else { - nextToken(); - leftOperand = makeAsExpression(leftOperand, parseType()); - } - } - else { - leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); - } - } - return leftOperand; - } - function isBinaryOperator() { - if (inDisallowInContext() && token() === 92 /* InKeyword */) { - return false; - } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54 /* BarBarToken */: - return 1; - case 53 /* AmpersandAmpersandToken */: - return 2; - case 49 /* BarToken */: - return 3; - case 50 /* CaretToken */: - return 4; - case 48 /* AmpersandToken */: - return 5; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 6; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - return 7; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 8; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 9; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 10; - case 40 /* AsteriskAsteriskToken */: - return 11; - } - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; - } - function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194 /* BinaryExpression */, left.pos); - node.left = left; - node.operatorToken = operatorToken; - node.right = right; - return finishNode(node); - } - function makeAsExpression(left, right) { - var node = createNode(202 /* AsExpression */, left.pos); - node.expression = left; - node.type = right; - return finishNode(node); - } - function parsePrefixUnaryExpression() { - var node = createNode(192 /* PrefixUnaryExpression */); - node.operator = token(); - nextToken(); - node.operand = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseDeleteExpression() { - var node = createNode(188 /* DeleteExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseTypeOfExpression() { - var node = createNode(189 /* TypeOfExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseVoidExpression() { - var node = createNode(190 /* VoidExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function isAwaitExpression() { - if (token() === 121 /* AwaitKeyword */) { - if (inAwaitContext()) { - return true; - } - // here we are using similar heuristics as 'isYieldExpression' - return lookAhead(nextTokenIsIdentifierOnSameLine); - } - return false; - } - function parseAwaitExpression() { - var node = createNode(191 /* AwaitExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - /** - * Parse ES7 exponential expression and await expression - * - * ES7 ExponentiationExpression: - * 1) UnaryExpression[?Yield] - * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] - * - */ - function parseUnaryExpressionOrHigher() { - /** - * ES7 UpdateExpression: - * 1) LeftHandSideExpression[?Yield] - * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ - * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- - * 4) ++UnaryExpression[?Yield] - * 5) --UnaryExpression[?Yield] - */ - if (isUpdateExpression()) { - var incrementExpression = parseIncrementExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : - incrementExpression; - } - /** - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] - * 2) delete UpdateExpression[?yield] - * 3) void UpdateExpression[?yield] - * 4) typeof UpdateExpression[?yield] - * 5) + UpdateExpression[?yield] - * 6) - UpdateExpression[?yield] - * 7) ~ UpdateExpression[?yield] - * 8) ! UpdateExpression[?yield] - */ - var unaryOperator = token(); - var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40 /* AsteriskAsteriskToken */) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184 /* TypeAssertionExpression */) { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); - } - else { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); - } - } - return simpleUnaryExpression; - } - /** - * Parse ES7 simple-unary expression or higher: - * - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] - * 2) delete UnaryExpression[?yield] - * 3) void UnaryExpression[?yield] - * 4) typeof UnaryExpression[?yield] - * 5) + UnaryExpression[?yield] - * 6) - UnaryExpression[?yield] - * 7) ~ UnaryExpression[?yield] - * 8) ! UnaryExpression[?yield] - * 9) [+Await] await UnaryExpression[?yield] - */ - function parseSimpleUnaryExpression() { - switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - return parsePrefixUnaryExpression(); - case 80 /* DeleteKeyword */: - return parseDeleteExpression(); - case 103 /* TypeOfKeyword */: - return parseTypeOfExpression(); - case 105 /* VoidKeyword */: - return parseVoidExpression(); - case 27 /* LessThanToken */: - // This is modified UnaryExpression grammar in TypeScript - // UnaryExpression (modified): - // < type > UnaryExpression - return parseTypeAssertion(); - case 121 /* AwaitKeyword */: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - // falls through - default: - return parseIncrementExpression(); - } - } - /** - * Check if the current token can possibly be an ES7 increment expression. - * - * ES7 UpdateExpression: - * LeftHandSideExpression[?Yield] - * LeftHandSideExpression[?Yield][no LineTerminator here]++ - * LeftHandSideExpression[?Yield][no LineTerminator here]-- - * ++LeftHandSideExpression[?Yield] - * --LeftHandSideExpression[?Yield] - */ - function isUpdateExpression() { - // This function is called inside parseUnaryExpression to decide - // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly - switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 121 /* AwaitKeyword */: - return false; - case 27 /* LessThanToken */: - // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression - if (sourceFile.languageVariant !== 1 /* JSX */) { - return false; - } - // We are in JSX context and the token is part of JSXElement. - // falls through - default: - return true; - } - } - /** - * Parse ES7 IncrementExpression. IncrementExpression is used instead of ES6's PostFixExpression. - * - * ES7 IncrementExpression[yield]: - * 1) LeftHandSideExpression[?yield] - * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ - * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- - * 4) ++LeftHandSideExpression[?yield] - * 5) --LeftHandSideExpression[?yield] - * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression - */ - function parseIncrementExpression() { - if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(192 /* PrefixUnaryExpression */); - node.operator = token(); - nextToken(); - node.operand = parseLeftHandSideExpressionOrHigher(); - return finishNode(node); - } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { - // JSXElement is part of primaryExpression - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); - } - var expression = parseLeftHandSideExpressionOrHigher(); - ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193 /* PostfixUnaryExpression */, expression.pos); - node.operand = expression; - node.operator = token(); - nextToken(); - return finishNode(node); - } - return expression; - } - function parseLeftHandSideExpressionOrHigher() { - // Original Ecma: - // LeftHandSideExpression: See 11.2 - // NewExpression - // CallExpression - // - // Our simplification: - // - // LeftHandSideExpression: See 11.2 - // MemberExpression - // CallExpression - // - // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with - // MemberExpression to make our lives easier. - // - // to best understand the below code, it's important to see how CallExpression expands - // out into its own productions: - // - // CallExpression: - // MemberExpression Arguments - // CallExpression Arguments - // CallExpression[Expression] - // CallExpression.IdentifierName - // super ( ArgumentListopt ) - // super.IdentifierName - // - // Because of the recursion in these calls, we need to bottom out first. There are two - // bottom out states we can run into. Either we see 'super' which must start either of - // the last two CallExpression productions. Or we have a MemberExpression which either - // completes the LeftHandSideExpression, or starts the beginning of the first four - // CallExpression productions. - var expression = token() === 97 /* SuperKeyword */ - ? parseSuperExpression() - : parseMemberExpressionOrHigher(); - // Now, we *may* be complete. However, we might have consumed the start of a - // CallExpression. As such, we need to consume the rest of it here to be complete. - return parseCallExpressionRest(expression); - } - function parseMemberExpressionOrHigher() { - // Note: to make our lives simpler, we decompose the the NewExpression productions and - // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. - // like so: - // - // PrimaryExpression : See 11.1 - // this - // Identifier - // Literal - // ArrayLiteral - // ObjectLiteral - // (Expression) - // FunctionExpression - // new MemberExpression Arguments? - // - // MemberExpression : See 11.2 - // PrimaryExpression - // MemberExpression[Expression] - // MemberExpression.IdentifierName - // - // CallExpression : See 11.2 - // MemberExpression - // CallExpression Arguments - // CallExpression[Expression] - // CallExpression.IdentifierName - // - // Technically this is ambiguous. i.e. CallExpression defines: - // - // CallExpression: - // CallExpression Arguments - // - // If you see: "new Foo()" - // - // Then that could be treated as a single ObjectCreationExpression, or it could be - // treated as the invocation of "new Foo". We disambiguate that in code (to match - // the original grammar) by making sure that if we see an ObjectCreationExpression - // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think - // about this is that for every "new" that we see, we will consume an argument list if - // it is there as part of the *associated* object creation node. Any additional - // argument lists we see, will become invocation expressions. - // - // Because there are no other places in the grammar now that refer to FunctionExpression - // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression - // production. - // - // Because CallExpression and MemberExpression are left recursive, we need to bottom out - // of the recursion immediately. So we parse out a primary expression to start with. - var expression = parsePrimaryExpression(); - return parseMemberExpressionRest(expression); - } - function parseSuperExpression() { - var expression = parseTokenNode(); - if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { - return expression; - } - // If we have seen "super" it must be followed by '(' or '.'. - // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(179 /* PropertyAccessExpression */, expression.pos); - node.expression = expression; - parseExpectedToken(23 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); - return finishNode(node); - } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 71 /* Identifier */) { - return lhs.text === rhs.text; - } - if (lhs.kind === 99 /* ThisKeyword */) { - return true; - } - // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only - // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression - // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element - return lhs.name.text === rhs.name.text && - tagNamesAreEquivalent(lhs.expression, rhs.expression); - } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); - var result; - if (opening.kind === 251 /* JsxOpeningElement */) { - var node = createNode(249 /* JsxElement */, opening.pos); - node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); - node.closingElement = parseJsxClosingElement(inExpressionContext); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); - } - result = finishNode(node); - } - else { - ts.Debug.assert(opening.kind === 250 /* JsxSelfClosingElement */); - // Nothing else to do for self-closing elements - result = opening; - } - // If the user writes the invalid code '
' in an expression context (i.e. not wrapped in - // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag - // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX - // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter - // does less damage and we can report a better error. - // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios - // of one sort or another. - if (inExpressionContext && token() === 27 /* LessThanToken */) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); - if (invalidElement) { - parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194 /* BinaryExpression */, result.pos); - badNode.end = invalidElement.end; - badNode.left = result; - badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); - badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; - return badNode; - } - } - return result; - } - function parseJsxText() { - var node = createNode(10 /* JsxText */, scanner.getStartPos()); - node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; - currentToken = scanner.scanJsxToken(); - return finishNode(node); - } - function parseJsxChild() { - switch (token()) { - case 10 /* JsxText */: - case 11 /* JsxTextAllWhiteSpaces */: - return parseJsxText(); - case 17 /* OpenBraceToken */: - return parseJsxExpression(/*inExpressionContext*/ false); - case 27 /* LessThanToken */: - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); - } - ts.Debug.fail("Unknown JSX child kind " + token()); - } - function parseJsxChildren(openingTagName) { - var result = createNodeArray(); - var saveParsingContext = parsingContext; - parsingContext |= 1 << 14 /* JsxChildren */; - while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28 /* LessThanSlashToken */) { - // Closing tag - break; - } - else if (token() === 1 /* EndOfFileToken */) { - // If we hit EOF, issue the error at the tag that lacks the closing element - // rather than at the end of the file (which is useless) - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); - break; - } - else if (token() === 7 /* ConflictMarkerTrivia */) { - break; - } - var child = parseJsxChild(); - if (child) { - result.push(child); - } - } - result.end = scanner.getTokenPos(); - parsingContext = saveParsingContext; - return result; - } - function parseJsxAttributes() { - var jsxAttributes = createNode(254 /* JsxAttributes */); - jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); - return finishNode(jsxAttributes); - } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { - var fullStart = scanner.getStartPos(); - parseExpected(27 /* LessThanToken */); - var tagName = parseJsxElementName(); - var attributes = parseJsxAttributes(); - var node; - if (token() === 29 /* GreaterThanToken */) { - // Closing tag, so scan the immediately-following text with the JSX scanning instead - // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate - // scanning errors - node = createNode(251 /* JsxOpeningElement */, fullStart); - scanJsxText(); - } - else { - parseExpected(41 /* SlashToken */); - if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); - } - else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); - } - node = createNode(250 /* JsxSelfClosingElement */, fullStart); - } - node.tagName = tagName; - node.attributes = attributes; - return finishNode(node); - } - function parseJsxElementName() { - scanJsxIdentifier(); - // JsxElement can have name in the form of - // propertyAccessExpression - // primaryExpression in the form of an identifier and "this" keyword - // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword - // We only want to consider "this" as a primaryExpression - var expression = token() === 99 /* ThisKeyword */ ? - parseTokenNode() : parseIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); - expression = finishNode(propertyAccess); - } - return expression; - } - function parseJsxExpression(inExpressionContext) { - var node = createNode(256 /* JsxExpression */); - parseExpected(17 /* OpenBraceToken */); - if (token() !== 18 /* CloseBraceToken */) { - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - node.expression = parseAssignmentExpressionOrHigher(); - } - if (inExpressionContext) { - parseExpected(18 /* CloseBraceToken */); - } - else { - parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); - } - return finishNode(node); - } - function parseJsxAttribute() { - if (token() === 17 /* OpenBraceToken */) { - return parseJsxSpreadAttribute(); - } - scanJsxIdentifier(); - var node = createNode(253 /* JsxAttribute */); - node.name = parseIdentifierName(); - if (token() === 58 /* EqualsToken */) { - switch (scanJsxAttributeValue()) { - case 9 /* StringLiteral */: - node.initializer = parseLiteralNode(); - break; - default: - node.initializer = parseJsxExpression(/*inExpressionContext*/ true); - break; - } - } - return finishNode(node); - } - function parseJsxSpreadAttribute() { - var node = createNode(255 /* JsxSpreadAttribute */); - parseExpected(17 /* OpenBraceToken */); - parseExpected(24 /* DotDotDotToken */); - node.expression = parseExpression(); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252 /* JsxClosingElement */); - parseExpected(28 /* LessThanSlashToken */); - node.tagName = parseJsxElementName(); - if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); - } - else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); - } - return finishNode(node); - } - function parseTypeAssertion() { - var node = createNode(184 /* TypeAssertionExpression */); - parseExpected(27 /* LessThanToken */); - node.type = parseType(); - parseExpected(29 /* GreaterThanToken */); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseMemberExpressionRest(expression) { - while (true) { - var dotToken = parseOptionalToken(23 /* DotToken */); - if (dotToken) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); - expression = finishNode(propertyAccess); - continue; - } - if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var nonNullExpression = createNode(203 /* NonNullExpression */, expression.pos); - nonNullExpression.expression = expression; - expression = finishNode(nonNullExpression); - continue; - } - // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(180 /* ElementAccessExpression */, expression.pos); - indexedAccess.expression = expression; - // It's not uncommon for a user to write: "new Type[]". - // Check for that common pattern and report a better error message. - if (token() !== 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { - var literal = indexedAccess.argumentExpression; - literal.text = internIdentifier(literal.text); - } - } - parseExpected(22 /* CloseBracketToken */); - expression = finishNode(indexedAccess); - continue; - } - if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { - var tagExpression = createNode(183 /* TaggedTemplateExpression */, expression.pos); - tagExpression.tag = expression; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ - ? parseLiteralNode() - : parseTemplateExpression(); - expression = finishNode(tagExpression); - continue; - } - return expression; - } - } - function parseCallExpressionRest(expression) { - while (true) { - expression = parseMemberExpressionRest(expression); - if (token() === 27 /* LessThanToken */) { - // See if this is the start of a generic invocation. If so, consume it and - // keep checking for postfix expressions. Otherwise, it's just a '<' that's - // part of an arithmetic expression. Break out so we consume it higher in the - // stack. - var typeArguments = tryParse(parseTypeArgumentsInExpression); - if (!typeArguments) { - return expression; - } - var callExpr = createNode(181 /* CallExpression */, expression.pos); - callExpr.expression = expression; - callExpr.typeArguments = typeArguments; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(181 /* CallExpression */, expression.pos); - callExpr.expression = expression; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - return expression; - } - } - function parseArgumentList() { - parseExpected(19 /* OpenParenToken */); - var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(20 /* CloseParenToken */); - return result; - } - function parseTypeArgumentsInExpression() { - if (!parseOptional(27 /* LessThanToken */)) { - return undefined; - } - var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); - if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. - return undefined; - } - // If we have a '<', then only parse this as a argument list if the type arguments - // are complete and we have an open paren. if we don't, rewind and return nothing. - return typeArguments && canFollowTypeArgumentsInExpression() - ? typeArguments - : undefined; - } - function canFollowTypeArgumentsInExpression() { - switch (token()) { - case 19 /* OpenParenToken */: // foo( - // this case are the only case where this token can legally follow a type argument - // list. So we definitely want to treat this as a type arg list. - case 23 /* DotToken */: // foo. - case 20 /* CloseParenToken */: // foo) - case 22 /* CloseBracketToken */: // foo] - case 56 /* ColonToken */: // foo: - case 25 /* SemicolonToken */: // foo; - case 55 /* QuestionToken */: // foo? - case 32 /* EqualsEqualsToken */: // foo == - case 34 /* EqualsEqualsEqualsToken */: // foo === - case 33 /* ExclamationEqualsToken */: // foo != - case 35 /* ExclamationEqualsEqualsToken */: // foo !== - case 53 /* AmpersandAmpersandToken */: // foo && - case 54 /* BarBarToken */: // foo || - case 50 /* CaretToken */: // foo ^ - case 48 /* AmpersandToken */: // foo & - case 49 /* BarToken */: // foo | - case 18 /* CloseBraceToken */: // foo } - case 1 /* EndOfFileToken */: - // these cases can't legally follow a type arg list. However, they're not legal - // expressions either. The user is probably in the middle of a generic type. So - // treat it as such. - return true; - case 26 /* CommaToken */: // foo, - case 17 /* OpenBraceToken */: // foo { - // We don't want to treat these as type arguments. Otherwise we'll parse this - // as an invocation expression. Instead, we want to parse out the expression - // in isolation from the type arguments. - default: - // Anything else treat as an expression. - return false; - } - } - function parsePrimaryExpression() { - switch (token()) { - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - return parseLiteralNode(); - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - return parseTokenNode(); - case 19 /* OpenParenToken */: - return parseParenthesizedExpression(); - case 21 /* OpenBracketToken */: - return parseArrayLiteralExpression(); - case 17 /* OpenBraceToken */: - return parseObjectLiteralExpression(); - case 120 /* AsyncKeyword */: - // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. - // If we encounter `async [no LineTerminator here] function` then this is an async - // function; otherwise, its an identifier. - if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { - break; - } - return parseFunctionExpression(); - case 75 /* ClassKeyword */: - return parseClassExpression(); - case 89 /* FunctionKeyword */: - return parseFunctionExpression(); - case 94 /* NewKeyword */: - return parseNewExpression(); - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { - return parseLiteralNode(); - } - break; - case 14 /* TemplateHead */: - return parseTemplateExpression(); - } - return parseIdentifier(ts.Diagnostics.Expression_expected); - } - function parseParenthesizedExpression() { - var node = createNode(185 /* ParenthesizedExpression */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - return finishNode(node); - } - function parseSpreadElement() { - var node = createNode(198 /* SpreadElement */); - parseExpected(24 /* DotDotDotToken */); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseArgumentOrArrayLiteralElement() { - return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(200 /* OmittedExpression */) : - parseAssignmentExpressionOrHigher(); - } - function parseArgumentExpression() { - return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); - } - function parseArrayLiteralExpression() { - var node = createNode(177 /* ArrayLiteralExpression */); - parseExpected(21 /* OpenBracketToken */); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(22 /* CloseBracketToken */); - return finishNode(node); - } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(153 /* GetAccessor */, fullStart, decorators, modifiers); - } - else if (parseContextualModifier(135 /* SetKeyword */)) { - return parseAccessorDeclaration(154 /* SetAccessor */, fullStart, decorators, modifiers); - } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - if (dotDotDotToken) { - var spreadElement = createNode(263 /* SpreadAssignment */, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); - } - // check if it is short-hand property assignment or normal property assignment - // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production - // CoverInitializedName[Yield] : - // IdentifierReference[?Yield] Initializer[In, ?Yield] - // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); - if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262 /* ShorthandPropertyAssignment */, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(58 /* EqualsToken */); - if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); - } - return addJSDocComment(finishNode(shorthandDeclaration)); - } - else { - var propertyAssignment = createNode(261 /* PropertyAssignment */, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; - parseExpected(56 /* ColonToken */); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); - } - } - function parseObjectLiteralExpression() { - var node = createNode(178 /* ObjectLiteralExpression */); - parseExpected(17 /* OpenBraceToken */); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseFunctionExpression() { - // GeneratorExpression: - // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } - // - // FunctionExpression: - // function BindingIdentifier[opt](FormalParameters){ FunctionBody } - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ false); - } - var node = createNode(186 /* FunctionExpression */); - node.modifiers = parseModifiers(); - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var isGenerator = !!node.asteriskToken; - var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); - node.name = - isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : - isGenerator ? doInYieldContext(parseOptionalIdentifier) : - isAsync ? doInAwaitContext(parseOptionalIdentifier) : - parseOptionalIdentifier(); - fillSignature(56 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ true); - } - return addJSDocComment(finishNode(node)); - } - function parseOptionalIdentifier() { - return isIdentifier() ? parseIdentifier() : undefined; - } - function parseNewExpression() { - var fullStart = scanner.getStartPos(); - parseExpected(94 /* NewKeyword */); - if (parseOptional(23 /* DotToken */)) { - var node_1 = createNode(204 /* MetaProperty */, fullStart); - node_1.keywordToken = 94 /* NewKeyword */; - node_1.name = parseIdentifierName(); - return finishNode(node_1); - } - var node = createNode(182 /* NewExpression */, fullStart); - node.expression = parseMemberExpressionOrHigher(); - node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 19 /* OpenParenToken */) { - node.arguments = parseArgumentList(); - } - return finishNode(node); - } - // STATEMENTS - function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207 /* Block */); - if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseFunctionBlock(allowYield, allowAwait, ignoreMissingOpenBrace, diagnosticMessage) { - var savedYieldContext = inYieldContext(); - setYieldContext(allowYield); - var savedAwaitContext = inAwaitContext(); - setAwaitContext(allowAwait); - // We may be in a [Decorator] context when parsing a function expression or - // arrow function. The body of the function is not in [Decorator] context. - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ false); - } - var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ true); - } - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - return block; - } - function parseEmptyStatement() { - var node = createNode(209 /* EmptyStatement */); - parseExpected(25 /* SemicolonToken */); - return finishNode(node); - } - function parseIfStatement() { - var node = createNode(211 /* IfStatement */); - parseExpected(90 /* IfKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(node); - } - function parseDoStatement() { - var node = createNode(212 /* DoStatement */); - parseExpected(81 /* DoKeyword */); - node.statement = parseStatement(); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html - // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in - // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby - // do;while(0)x will have a semicolon inserted before x. - parseOptional(25 /* SemicolonToken */); - return finishNode(node); - } - function parseWhileStatement() { - var node = createNode(213 /* WhileStatement */); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - node.statement = parseStatement(); - return finishNode(node); - } - function parseForOrForInOrForOfStatement() { - var pos = getNodePos(); - parseExpected(88 /* ForKeyword */); - var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); - parseExpected(19 /* OpenParenToken */); - var initializer = undefined; - if (token() !== 25 /* SemicolonToken */) { - if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { - initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); - } - else { - initializer = disallowInAnd(parseExpression); - } - } - var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142 /* OfKeyword */) : parseOptional(142 /* OfKeyword */)) { - var forOfStatement = createNode(216 /* ForOfStatement */, pos); - forOfStatement.awaitModifier = awaitToken; - forOfStatement.initializer = initializer; - forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20 /* CloseParenToken */); - forOrForInOrForOfStatement = forOfStatement; - } - else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(215 /* ForInStatement */, pos); - forInStatement.initializer = initializer; - forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - forOrForInOrForOfStatement = forInStatement; - } - else { - var forStatement = createNode(214 /* ForStatement */, pos); - forStatement.initializer = initializer; - parseExpected(25 /* SemicolonToken */); - if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { - forStatement.condition = allowInAnd(parseExpression); - } - parseExpected(25 /* SemicolonToken */); - if (token() !== 20 /* CloseParenToken */) { - forStatement.incrementor = allowInAnd(parseExpression); - } - parseExpected(20 /* CloseParenToken */); - forOrForInOrForOfStatement = forStatement; - } - forOrForInOrForOfStatement.statement = parseStatement(); - return finishNode(forOrForInOrForOfStatement); - } - function parseBreakOrContinueStatement(kind) { - var node = createNode(kind); - parseExpected(kind === 218 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); - if (!canParseSemicolon()) { - node.label = parseIdentifier(); - } - parseSemicolon(); - return finishNode(node); - } - function parseReturnStatement() { - var node = createNode(219 /* ReturnStatement */); - parseExpected(96 /* ReturnKeyword */); - if (!canParseSemicolon()) { - node.expression = allowInAnd(parseExpression); - } - parseSemicolon(); - return finishNode(node); - } - function parseWithStatement() { - var node = createNode(220 /* WithStatement */); - parseExpected(107 /* WithKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - node.statement = parseStatement(); - return finishNode(node); - } - function parseCaseClause() { - var node = createNode(257 /* CaseClause */); - parseExpected(73 /* CaseKeyword */); - node.expression = allowInAnd(parseExpression); - parseExpected(56 /* ColonToken */); - node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); - return finishNode(node); - } - function parseDefaultClause() { - var node = createNode(258 /* DefaultClause */); - parseExpected(79 /* DefaultKeyword */); - parseExpected(56 /* ColonToken */); - node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); - return finishNode(node); - } - function parseCaseOrDefaultClause() { - return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); - } - function parseSwitchStatement() { - var node = createNode(221 /* SwitchStatement */); - parseExpected(98 /* SwitchKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(235 /* CaseBlock */, scanner.getStartPos()); - parseExpected(17 /* OpenBraceToken */); - caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(18 /* CloseBraceToken */); - node.caseBlock = finishNode(caseBlock); - return finishNode(node); - } - function parseThrowStatement() { - // ThrowStatement[Yield] : - // throw [no LineTerminator here]Expression[In, ?Yield]; - // Because of automatic semicolon insertion, we need to report error if this - // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' - // directly as that might consume an expression on the following line. - // We just return 'undefined' in that case. The actual error will be reported in the - // grammar walker. - var node = createNode(223 /* ThrowStatement */); - parseExpected(100 /* ThrowKeyword */); - node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); - parseSemicolon(); - return finishNode(node); - } - // TODO: Review for error recovery - function parseTryStatement() { - var node = createNode(224 /* TryStatement */); - parseExpected(102 /* TryKeyword */); - node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; - // If we don't have a catch clause, then we must have a finally clause. Try to parse - // one out no matter what. - if (!node.catchClause || token() === 87 /* FinallyKeyword */) { - parseExpected(87 /* FinallyKeyword */); - node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - } - return finishNode(node); - } - function parseCatchClause() { - var result = createNode(260 /* CatchClause */); - parseExpected(74 /* CatchKeyword */); - if (parseExpected(19 /* OpenParenToken */)) { - result.variableDeclaration = parseVariableDeclaration(); - } - parseExpected(20 /* CloseParenToken */); - result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); - return finishNode(result); - } - function parseDebuggerStatement() { - var node = createNode(225 /* DebuggerStatement */); - parseExpected(78 /* DebuggerKeyword */); - parseSemicolon(); - return finishNode(node); - } - function parseExpressionOrLabeledStatement() { - // Avoiding having to do the lookahead for a labeled statement by just trying to parse - // out an expression, seeing if it is identifier and then seeing if it is followed by - // a colon. - var fullStart = scanner.getStartPos(); - var expression = allowInAnd(parseExpression); - if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - var labeledStatement = createNode(222 /* LabeledStatement */, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); - } - else { - var expressionStatement = createNode(210 /* ExpressionStatement */, fullStart); - expressionStatement.expression = expression; - parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); - } - } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsClassKeywordOnSameLine() { - nextToken(); - return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsFunctionKeywordOnSameLine() { - nextToken(); - return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { - nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); - } - function isDeclaration() { - while (true) { - switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - return true; - // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; - // however, an identifier cannot be followed by another identifier on the same line. This is what we - // count on to parse out the respective declarations. For instance, we exploit this to say that - // - // namespace n - // - // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees - // - // namespace - // n - // - // as the identifier 'namespace' on one line followed by the identifier 'n' on another. - // We need to look one token ahead to see if it permissible to try parsing a declaration. - // - // *Note*: 'interface' is actually a strict mode reserved word. So while - // - // "use strict" - // interface - // I {} - // - // could be legal, it would add complexity for very little gain. - case 109 /* InterfaceKeyword */: - case 138 /* TypeKeyword */: - return nextTokenIsIdentifierOnSameLine(); - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 131 /* ReadonlyKeyword */: - nextToken(); - // ASI takes effect for this modifier. - if (scanner.hasPrecedingLineBreak()) { - return false; - } - continue; - case 141 /* GlobalKeyword */: - nextToken(); - return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; - case 91 /* ImportKeyword */: - nextToken(); - return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 84 /* ExportKeyword */: - nextToken(); - if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || - token() === 118 /* AsKeyword */) { - return true; - } - continue; - case 115 /* StaticKeyword */: - nextToken(); - continue; - default: - return false; - } - } - } - function isStartOfDeclaration() { - return lookAhead(isDeclaration); - } - function isStartOfStatement() { - switch (token()) { - case 57 /* AtToken */: - case 25 /* SemicolonToken */: - case 17 /* OpenBraceToken */: - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 90 /* IfKeyword */: - case 81 /* DoKeyword */: - case 106 /* WhileKeyword */: - case 88 /* ForKeyword */: - case 77 /* ContinueKeyword */: - case 72 /* BreakKeyword */: - case 96 /* ReturnKeyword */: - case 107 /* WithKeyword */: - case 98 /* SwitchKeyword */: - case 100 /* ThrowKeyword */: - case 102 /* TryKeyword */: - case 78 /* DebuggerKeyword */: - // 'catch' and 'finally' do not actually indicate that the code is part of a statement, - // however, we say they are here so that we may gracefully parse them and error later. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - return true; - case 76 /* ConstKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - return isStartOfDeclaration(); - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 109 /* InterfaceKeyword */: - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - case 138 /* TypeKeyword */: - case 141 /* GlobalKeyword */: - // When these don't start a declaration, they're an identifier in an expression statement - return true; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 131 /* ReadonlyKeyword */: - // When these don't start a declaration, they may be the start of a class member if an identifier - // immediately follows. Otherwise they're an identifier in an expression statement. - return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - default: - return isStartOfExpression(); - } - } - function nextTokenIsIdentifierOrStartOfDestructuring() { - nextToken(); - return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; - } - function isLetDeclaration() { - // In ES6 'let' always starts a lexical declaration if followed by an identifier or { - // or [. - return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); - } - function parseStatement() { - switch (token()) { - case 25 /* SemicolonToken */: - return parseEmptyStatement(); - case 17 /* OpenBraceToken */: - return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 104 /* VarKeyword */: - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 110 /* LetKeyword */: - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - } - break; - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 75 /* ClassKeyword */: - return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 90 /* IfKeyword */: - return parseIfStatement(); - case 81 /* DoKeyword */: - return parseDoStatement(); - case 106 /* WhileKeyword */: - return parseWhileStatement(); - case 88 /* ForKeyword */: - return parseForOrForInOrForOfStatement(); - case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(217 /* ContinueStatement */); - case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(218 /* BreakStatement */); - case 96 /* ReturnKeyword */: - return parseReturnStatement(); - case 107 /* WithKeyword */: - return parseWithStatement(); - case 98 /* SwitchKeyword */: - return parseSwitchStatement(); - case 100 /* ThrowKeyword */: - return parseThrowStatement(); - case 102 /* TryKeyword */: - // Include 'catch' and 'finally' for error recovery. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - return parseTryStatement(); - case 78 /* DebuggerKeyword */: - return parseDebuggerStatement(); - case 57 /* AtToken */: - return parseDeclaration(); - case 120 /* AsyncKeyword */: - case 109 /* InterfaceKeyword */: - case 138 /* TypeKeyword */: - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 83 /* EnumKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: - case 131 /* ReadonlyKeyword */: - case 141 /* GlobalKeyword */: - if (isStartOfDeclaration()) { - return parseDeclaration(); - } - break; - } - return parseExpressionOrLabeledStatement(); - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - return parseVariableStatement(fullStart, decorators, modifiers); - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 75 /* ClassKeyword */: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 109 /* InterfaceKeyword */: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 138 /* TypeKeyword */: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 83 /* EnumKeyword */: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141 /* GlobalKeyword */: - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 91 /* ImportKeyword */: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 84 /* ExportKeyword */: - nextToken(); - switch (token()) { - case 79 /* DefaultKeyword */: - case 58 /* EqualsToken */: - return parseExportAssignment(fullStart, decorators, modifiers); - case 118 /* AsKeyword */: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); - default: - return parseExportDeclaration(fullStart, decorators, modifiers); - } - default: - if (decorators || modifiers) { - // We reached this point because we encountered decorators and/or modifiers and assumed a declaration - // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(247 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); - } - } - } - function nextTokenIsIdentifierOrStringLiteralOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); - } - function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; - } - return parseFunctionBlock(isGenerator, isAsync, /*ignoreMissingOpenBrace*/ false, diagnosticMessage); - } - // DECLARATIONS - function parseArrayBindingElement() { - if (token() === 26 /* CommaToken */) { - return createNode(200 /* OmittedExpression */); - } - var node = createNode(176 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); - return finishNode(node); - } - function parseObjectBindingElement() { - var node = createNode(176 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { - node.name = propertyName; - } - else { - parseExpected(56 /* ColonToken */); - node.propertyName = propertyName; - node.name = parseIdentifierOrPattern(); - } - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); - return finishNode(node); - } - function parseObjectBindingPattern() { - var node = createNode(174 /* ObjectBindingPattern */); - parseExpected(17 /* OpenBraceToken */); - node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseArrayBindingPattern() { - var node = createNode(175 /* ArrayBindingPattern */); - parseExpected(21 /* OpenBracketToken */); - node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(22 /* CloseBracketToken */); - return finishNode(node); - } - function isIdentifierOrPattern() { - return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); - } - function parseIdentifierOrPattern() { - if (token() === 21 /* OpenBracketToken */) { - return parseArrayBindingPattern(); - } - if (token() === 17 /* OpenBraceToken */) { - return parseObjectBindingPattern(); - } - return parseIdentifier(); - } - function parseVariableDeclaration() { - var node = createNode(226 /* VariableDeclaration */); - node.name = parseIdentifierOrPattern(); - node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(/*inParameter*/ false); - } - return finishNode(node); - } - function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227 /* VariableDeclarationList */); - switch (token()) { - case 104 /* VarKeyword */: - break; - case 110 /* LetKeyword */: - node.flags |= 1 /* Let */; - break; - case 76 /* ConstKeyword */: - node.flags |= 2 /* Const */; - break; - default: - ts.Debug.fail(); - } - nextToken(); - // The user may have written the following: - // - // for (let of X) { } - // - // In this case, we want to parse an empty declaration list, and then parse 'of' - // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. - // So we need to look ahead to determine if 'of' should be treated as a keyword in - // this context. - // The checker will then give an error that there is an empty declaration list. - if (token() === 142 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { - node.declarations = createMissingList(); - } - else { - var savedDisallowIn = inDisallowInContext(); - setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); - setDisallowInContext(savedDisallowIn); - } - return finishNode(node); - } - function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; - } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208 /* VariableStatement */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228 /* FunctionDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); - var isGenerator = !!node.asteriskToken; - var isAsync = ts.hasModifier(node, 256 /* Async */); - fillSignature(56 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152 /* Constructor */, pos); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(123 /* ConstructorKeyword */); - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151 /* MethodDeclaration */, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; - var isGenerator = !!asteriskToken; - var isAsync = ts.hasModifier(method, 256 /* Async */); - fillSignature(56 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149 /* PropertyDeclaration */, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - // For instance properties specifically, since they are evaluated inside the constructor, - // we do *not * want to parse yield expressions, so we specifically turn the yield context - // off. The grammar would look something like this: - // - // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; - // - // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = ts.hasModifier(property, 32 /* Static */) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); - parseSemicolon(); - return addJSDocComment(finishNode(property)); - } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var name = parsePropertyName(); - // Note: this is not legal as per the grammar. But we allow it in the parser and - // report an error in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); - } - } - function parseNonParameterInitializer() { - return parseInitializer(/*inParameter*/ false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.name = parsePropertyName(); - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false); - return addJSDocComment(finishNode(node)); - } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 131 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } - function isClassMemberStart() { - var idToken; - if (token() === 57 /* AtToken */) { - return true; - } - // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifierKind(token())) { - idToken = token(); - // If the idToken is a class modifier (protected, private, public, and static), it is - // certain that we are starting to parse class member. This allows better error recovery - // Example: - // public foo() ... // true - // public @dec blah ... // true; we will then report an error later - // export public ... // true; we will then report an error later - if (isClassMemberModifier(idToken)) { - return true; - } - nextToken(); - } - if (token() === 39 /* AsteriskToken */) { - return true; - } - // Try to get the first property-like token following all modifiers. - // This can either be an identifier or the 'get' or 'set' keywords. - if (isLiteralPropertyName()) { - idToken = token(); - nextToken(); - } - // Index signatures and computed properties are class members; we can parse. - if (token() === 21 /* OpenBracketToken */) { - return true; - } - // If we were able to get any potential identifier... - if (idToken !== undefined) { - // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 135 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { - return true; - } - // If it *is* a keyword, but not an accessor, check a little farther along - // to see if it should actually be parsed as a class member. - switch (token()) { - case 19 /* OpenParenToken */: // Method declaration - case 27 /* LessThanToken */: // Generic Method declaration - case 56 /* ColonToken */: // Type Annotation for declaration - case 58 /* EqualsToken */: // Initializer for declaration - case 55 /* QuestionToken */: - return true; - default: - // Covers - // - Semicolons (declaration termination) - // - Closing braces (end-of-class, must be declaration) - // - End-of-files (not valid, but permitted so that it gets caught later on) - // - Line-breaks (enabling *automatic semicolon insertion*) - return canParseSemicolon(); - } - } - return false; - } - function parseDecorators() { - var decorators; - while (true) { - var decoratorStart = getNodePos(); - if (!parseOptional(57 /* AtToken */)) { - break; - } - var decorator = createNode(147 /* Decorator */, decoratorStart); - decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); - } - return decorators; - } - /* - * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. - * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect - * and turns it into a standalone declaration), then it is better to parse it and report an error later. - * - * In such situations, 'permitInvalidConstAsModifier' should be set to true. - */ - function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; - while (true) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { - // We need to ensure that any subsequent modifiers appear on the same line - // so that when 'const' is a standalone declaration, we don't issue an error. - if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { - break; - } - } - else { - if (!parseAnyContextualModifier()) { - break; - } - } - var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseModifiersForArrowFunction() { - var modifiers; - if (token() === 120 /* AsyncKeyword */) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - nextToken(); - var modifier = finishNode(createNode(modifierKind, modifierStart)); - modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseClassElement() { - if (token() === 25 /* SemicolonToken */) { - var result = createNode(206 /* SemicolonClassElement */); - nextToken(); - return finishNode(result); - } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - if (token() === 123 /* ConstructorKeyword */) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); - } - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); - } - // It is very important that we check this *after* checking indexers because - // the [ token can start an index signature or a computed property name - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */ || - token() === 39 /* AsteriskToken */ || - token() === 21 /* OpenBracketToken */) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); - } - if (decorators || modifiers) { - // treat this as a property declaration with a missing name. - var name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); - } - // 'isClassMemberStart' should have hinted not to attempt parsing. - ts.Debug.fail("Should not have attempted to parse class member declaration."); - } - function parseClassExpression() { - return parseClassDeclarationOrExpression( - /*fullStart*/ scanner.getStartPos(), - /*decorators*/ undefined, - /*modifiers*/ undefined, 199 /* ClassExpression */); - } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229 /* ClassDeclaration */); - } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(75 /* ClassKeyword */); - node.name = parseNameOfClassDeclarationOrExpression(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17 /* OpenBraceToken */)) { - // ClassTail[Yield,Await] : (Modified) See 14.5 - // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } - node.members = parseClassMembers(); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseNameOfClassDeclarationOrExpression() { - // implements is a future reserved word so - // 'class implements' might mean either - // - class expression with omitted name, 'implements' starts heritage clause - // - class with name 'implements' - // 'isImplementsClause' helps to disambiguate between these two cases - return isIdentifier() && !isImplementsClause() - ? parseIdentifier() - : undefined; - } - function isImplementsClause() { - return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); - } - function parseHeritageClauses() { - // ClassTail[Yield,Await] : (Modified) See 14.5 - // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } - if (isHeritageClause()) { - return parseList(21 /* HeritageClauses */, parseHeritageClause); - } - return undefined; - } - function parseHeritageClause() { - var tok = token(); - if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(259 /* HeritageClause */); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; - } - function parseExpressionWithTypeArguments() { - var node = createNode(201 /* ExpressionWithTypeArguments */); - node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } - return finishNode(node); - } - function isHeritageClause() { - return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; - } - function parseClassMembers() { - return parseList(5 /* ClassMembers */, parseClassElement); - } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230 /* InterfaceDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(109 /* InterfaceKeyword */); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); - } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231 /* TypeAliasDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(138 /* TypeKeyword */); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - parseExpected(58 /* EqualsToken */); - node.type = parseType(); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - // In an ambient declaration, the grammar only allows integer literals as initializers. - // In a non-ambient declaration, the grammar allows uninitialized members only in a - // ConstantEnumMemberSection, which starts at the beginning of an enum declaration - // or any time an integer literal initializer is encountered. - function parseEnumMember() { - var node = createNode(264 /* EnumMember */, scanner.getStartPos()); - node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); - } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232 /* EnumDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(83 /* EnumKeyword */); - node.name = parseIdentifier(); - if (parseExpected(17 /* OpenBraceToken */)) { - node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseModuleBlock() { - var node = createNode(234 /* ModuleBlock */, scanner.getStartPos()); - if (parseExpected(17 /* OpenBraceToken */)) { - node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); - // If we are parsing a dotted namespace name, we want to - // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 16 /* Namespace */; - node.decorators = decorators; - node.modifiers = modifiers; - node.flags |= flags; - node.name = parseIdentifier(); - node.body = parseOptional(23 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) - : parseModuleBlock(); - return addJSDocComment(finishNode(node)); - } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141 /* GlobalKeyword */) { - // parse 'global' as name of global scope augmentation - node.name = parseIdentifier(); - node.flags |= 512 /* GlobalAugmentation */; - } - else { - node.name = parseLiteralNode(/*internName*/ true); - } - if (token() === 17 /* OpenBraceToken */) { - node.body = parseModuleBlock(); - } - else { - parseSemicolon(); - } - return finishNode(node); - } - function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = 0; - if (token() === 141 /* GlobalKeyword */) { - // global augmentation - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - else if (parseOptional(129 /* NamespaceKeyword */)) { - flags |= 16 /* Namespace */; - } - else { - parseExpected(128 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); - } - function isExternalModuleReference() { - return token() === 132 /* RequireKeyword */ && - lookAhead(nextTokenIsOpenParen); - } - function nextTokenIsOpenParen() { - return nextToken() === 19 /* OpenParenToken */; - } - function nextTokenIsSlash() { - return nextToken() === 41 /* SlashToken */; - } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236 /* NamespaceExportDeclaration */, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; - parseExpected(118 /* AsKeyword */); - parseExpected(129 /* NamespaceKeyword */); - exportDeclaration.name = parseIdentifier(); - parseSemicolon(); - return finishNode(exportDeclaration); - } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(91 /* ImportKeyword */); - var afterImportPos = scanner.getStartPos(); - var identifier; - if (isIdentifier()) { - identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 140 /* FromKeyword */) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); - } - } - // Import statement - var importDeclaration = createNode(238 /* ImportDeclaration */, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; - // ImportDeclaration: - // import ImportClause from ModuleSpecifier ; - // import ModuleSpecifier; - if (identifier || - token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140 /* FromKeyword */); - } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); - parseSemicolon(); - return finishNode(importDeclaration); - } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237 /* ImportEqualsDeclaration */, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; - parseExpected(58 /* EqualsToken */); - importEqualsDeclaration.moduleReference = parseModuleReference(); - parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); - } - function parseImportClause(identifier, fullStart) { - // ImportClause: - // ImportedDefaultBinding - // NameSpaceImport - // NamedImports - // ImportedDefaultBinding, NameSpaceImport - // ImportedDefaultBinding, NamedImports - var importClause = createNode(239 /* ImportClause */, fullStart); - if (identifier) { - // ImportedDefaultBinding: - // ImportedBinding - importClause.name = identifier; - } - // If there was no default import or if there is comma token after default import - // parse namespace or named imports - if (!importClause.name || - parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(241 /* NamedImports */); - } - return finishNode(importClause); - } - function parseModuleReference() { - return isExternalModuleReference() - ? parseExternalModuleReference() - : parseEntityName(/*allowReservedWords*/ false); - } - function parseExternalModuleReference() { - var node = createNode(248 /* ExternalModuleReference */); - parseExpected(132 /* RequireKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = parseModuleSpecifier(); - parseExpected(20 /* CloseParenToken */); - return finishNode(node); - } - function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { - var result = parseLiteralNode(); - internIdentifier(result.text); - return result; - } - else { - // We allow arbitrary expressions here, even though the grammar only allows string - // literals. We check to ensure that it is only a string literal later in the grammar - // check pass. - return parseExpression(); - } - } - function parseNamespaceImport() { - // NameSpaceImport: - // * as ImportedBinding - var namespaceImport = createNode(240 /* NamespaceImport */); - parseExpected(39 /* AsteriskToken */); - parseExpected(118 /* AsKeyword */); - namespaceImport.name = parseIdentifier(); - return finishNode(namespaceImport); - } - function parseNamedImportsOrExports(kind) { - var node = createNode(kind); - // NamedImports: - // { } - // { ImportsList } - // { ImportsList, } - // ImportsList: - // ImportSpecifier - // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 241 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); - return finishNode(node); - } - function parseExportSpecifier() { - return parseImportOrExportSpecifier(246 /* ExportSpecifier */); - } - function parseImportSpecifier() { - return parseImportOrExportSpecifier(242 /* ImportSpecifier */); - } - function parseImportOrExportSpecifier(kind) { - var node = createNode(kind); - // ImportSpecifier: - // BindingIdentifier - // IdentifierName as BindingIdentifier - // ExportSpecifier: - // IdentifierName - // IdentifierName as IdentifierName - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - var checkIdentifierStart = scanner.getTokenPos(); - var checkIdentifierEnd = scanner.getTextPos(); - var identifierName = parseIdentifierName(); - if (token() === 118 /* AsKeyword */) { - node.propertyName = identifierName; - parseExpected(118 /* AsKeyword */); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - checkIdentifierStart = scanner.getTokenPos(); - checkIdentifierEnd = scanner.getTextPos(); - node.name = parseIdentifierName(); - } - else { - node.name = identifierName; - } - if (kind === 242 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); - } - return finishNode(node); - } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244 /* ExportDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(140 /* FromKeyword */); - node.moduleSpecifier = parseModuleSpecifier(); - } - else { - node.exportClause = parseNamedImportsOrExports(245 /* NamedExports */); - // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, - // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) - // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 140 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(140 /* FromKeyword */); - node.moduleSpecifier = parseModuleSpecifier(); - } - } - parseSemicolon(); - return finishNode(node); - } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243 /* ExportAssignment */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(58 /* EqualsToken */)) { - node.isExportEquals = true; - } - else { - parseExpected(79 /* DefaultKeyword */); - } - node.expression = parseAssignmentExpressionOrHigher(); - parseSemicolon(); - return finishNode(node); - } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - // Keep scanning all the leading trivia in the file until we get to something that - // isn't trivia. Any single line comment will be analyzed to see if it is a - // reference comment. - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2 /* SingleLineCommentTrivia */) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*".length; - return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function parseQualifiedName(left) { - var result = createNode(143 /* QualifiedName */, left.pos); - result.left = left; - result.right = parseIdentifierName(); - return finishNode(result); - } - function parseJSDocRecordType() { - var result = createNode(275 /* JSDocRecordType */); - result.literal = parseTypeLiteral(); - return finishNode(result); - } - function parseJSDocNonNullableType() { - var result = createNode(274 /* JSDocNonNullableType */); - nextToken(); - result.type = parseJSDocType(); - return finishNode(result); - } - function parseJSDocTupleType() { - var result = createNode(272 /* JSDocTupleType */); - nextToken(); - result.types = parseDelimitedList(26 /* JSDocTupleTypes */, parseJSDocType); - checkForTrailingComma(result.types); - parseExpected(22 /* CloseBracketToken */); - return finishNode(result); - } - function checkForTrailingComma(list) { - if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - var start = list.end - ",".length; - parseErrorAtPosition(start, ",".length, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function parseJSDocUnionType() { - var result = createNode(271 /* JSDocUnionType */); - nextToken(); - result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(20 /* CloseParenToken */); - return finishNode(result); - } - function parseJSDocTypeList(firstType) { - ts.Debug.assert(!!firstType); - var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(49 /* BarToken */)) { - types.push(parseJSDocType()); - } - types.end = scanner.getStartPos(); - return types; - } - function parseJSDocAllType() { - var result = createNode(268 /* JSDocAllType */); - nextToken(); - return finishNode(result); - } - function parseJSDocLiteralType() { - var result = createNode(293 /* JSDocLiteralType */); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } - function parseJSDocUnknownOrNullableType() { - var pos = scanner.getStartPos(); - // skip the ? - nextToken(); - // Need to lookahead to decide if this is a nullable or unknown type. - // Here are cases where we'll pick the unknown type: - // - // Foo(?, - // { a: ? } - // Foo(?) - // Foo - // Foo(?= - // (?| - if (token() === 26 /* CommaToken */ || - token() === 18 /* CloseBraceToken */ || - token() === 20 /* CloseParenToken */ || - token() === 29 /* GreaterThanToken */ || - token() === 58 /* EqualsToken */ || - token() === 49 /* BarToken */) { - var result = createNode(269 /* JSDocUnknownType */, pos); - return finishNode(result); - } - else { - var result = createNode(273 /* JSDocNullableType */, pos); - result.type = parseJSDocType(); - return finishNode(result); - } - } - function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = { languageVariant: 0 /* Standard */, text: content }; - var jsDoc = parseJSDocCommentWorker(start, length); - var diagnostics = parseDiagnostics; - clearState(); - return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; - } - JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var comment = parseJSDocCommentWorker(start, length); - if (comment) { - comment.parent = parent; - } - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - 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; - var end = length === undefined ? content.length : start + length; - length = end - start; - ts.Debug.assert(start >= 0); - ts.Debug.assert(start <= end); - ts.Debug.assert(end <= content.length); - var tags; - var comments = []; - var result; - // Check for /** (JSDoc opening part) - if (!isJsDocStart(content, start)) { - return result; - } - // + 3 for leading /**, - 5 in total for /** */ - scanner.scanRange(start + 3, length - 5, function () { - // Initially we can parse out a tag. We also have seen a starting asterisk. - // This is so that /** * @type */ doesn't parse. - var advanceToken = true; - var state = 1 /* SawAsterisk */; - var margin = undefined; - // + 4 for leading '/** ' - var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); - } - if (token() === 4 /* NewLineTrivia */) { - state = 0 /* BeginningOfLine */; - indent = 0; - nextJSDocToken(); - } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { - case 57 /* AtToken */: - if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { - removeTrailingNewlines(comments); - parseTag(indent); - // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. - // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning - // for malformed examples like `/** @param {string} x @returns {number} the length */` - state = 0 /* BeginningOfLine */; - advanceToken = false; - margin = undefined; - indent++; - } - else { - pushComment(scanner.getTokenText()); - } - break; - case 4 /* NewLineTrivia */: - comments.push(scanner.getTokenText()); - state = 0 /* BeginningOfLine */; - indent = 0; - break; - case 39 /* AsteriskToken */: - var asterisk = scanner.getTokenText(); - if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { - // If we've already seen an asterisk, then we can no longer parse a tag on this line - state = 2 /* SavingComments */; - pushComment(asterisk); - } - else { - // Ignore the first asterisk on a line - state = 1 /* SawAsterisk */; - indent += asterisk.length; - } - break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; - case 5 /* WhitespaceTrivia */: - // only collect whitespace if we're already saving comments or have just crossed the comment indent margin - var whitespace = scanner.getTokenText(); - if (state === 2 /* SavingComments */) { - comments.push(whitespace); - } - else if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - break; - case 1 /* EndOfFileToken */: - break; - default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text - state = 2 /* SavingComments */; - pushComment(scanner.getTokenText()); - break; - } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - result = createJSDocComment(); - }); - return result; - function removeLeadingNewlines(comments) { - while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { - comments.shift(); - } - } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { - comments.pop(); - } - } - function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 /* slash */ && - content.charCodeAt(start + 1) === 42 /* asterisk */ && - content.charCodeAt(start + 2) === 42 /* asterisk */ && - content.charCodeAt(start + 3) !== 42 /* asterisk */; - } - function createJSDocComment() { - var result = createNode(283 /* JSDocComment */, start); - result.tags = tags; - result.comment = comments.length ? comments.join("") : undefined; - return finishNode(result, end); - } - function skipWhitespace() { - while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { - nextJSDocToken(); - } - } - function parseTag(indent) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return; - } - var tag; - if (tagName) { - switch (tagName.text) { - case "augments": - tag = parseAugmentsTag(atToken, tagName); - break; - case "arg": - case "argument": - case "param": - tag = parseParamTag(atToken, tagName); - break; - case "return": - case "returns": - tag = parseReturnTag(atToken, tagName); - break; - case "template": - tag = parseTemplateTag(atToken, tagName); - break; - case "type": - tag = parseTypeTag(atToken, tagName); - break; - case "typedef": - tag = parseTypedefTag(atToken, tagName); - break; - default: - tag = parseUnknownTag(atToken, tagName); - break; - } - } - else { - tag = parseUnknownTag(atToken, tagName); - } - if (!tag) { - // a badly malformed tag should not be added to the list of tags - return; - } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); - } - function parseTagComments(indent) { - var comments = []; - var state = 0 /* BeginningOfLine */; - var margin; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { - case 4 /* NewLineTrivia */: - if (state >= 1 /* SawAsterisk */) { - state = 0 /* BeginningOfLine */; - comments.push(scanner.getTokenText()); - } - indent = 0; - break; - case 57 /* AtToken */: - // Done - break; - case 5 /* WhitespaceTrivia */: - if (state === 2 /* SavingComments */) { - pushComment(scanner.getTokenText()); - } - else { - var whitespace = scanner.getTokenText(); - // if the whitespace crosses the margin, take only the whitespace that passes the margin - if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - } - break; - case 39 /* AsteriskToken */: - if (state === 0 /* BeginningOfLine */) { - // leading asterisks start recording on the *next* (non-whitespace) token - state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; - break; - } - // record the * as a comment - // falls through - default: - state = 2 /* SavingComments */; // leading identifiers start recording as well - pushComment(scanner.getTokenText()); - break; - } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - return comments; - } - function parseUnknownTag(atToken, tagName) { - var result = createNode(284 /* JSDocTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - return finishNode(result); - } - function addTag(tag, comments) { - tag.comment = comments.join(""); - if (!tags) { - tags = createNodeArray([tag], tag.pos); - } - else { - tags.push(tag); - } - tags.end = tag.end; - } - function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17 /* OpenBraceToken */) { - return undefined; - } - return parseJSDocTypeExpression(); - }); - } - function parseParamTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name; - var isBracketed; - // Looking for something like '[foo]' or 'foo' - if (parseOptionalToken(21 /* OpenBracketToken */)) { - name = parseJSDocIdentifierName(); - skipWhitespace(); - isBracketed = true; - // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(58 /* EqualsToken */)) { - parseExpression(); - } - parseExpected(22 /* CloseBracketToken */); - } - else if (ts.tokenIsIdentifierOrKeyword(token())) { - name = parseJSDocIdentifierName(); - } - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var preName, postName; - if (typeExpression) { - postName = name; - } - else { - preName = name; - } - if (!typeExpression) { - typeExpression = tryParseTypeExpression(); - } - var result = createNode(286 /* JSDocParameterTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.preParameterName = preName; - result.typeExpression = typeExpression; - result.postParameterName = postName; - result.parameterName = postName || preName; - result.isBracketed = isBracketed; - return finishNode(result); - } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocReturnTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(287 /* JSDocReturnTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 288 /* JSDocTypeTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(288 /* JSDocTypeTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parsePropertyTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var result = createNode(291 /* JSDocPropertyTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.name = name; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - var result = createNode(285 /* JSDocAugmentsTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseTypedefTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(290 /* JSDocTypedefTag */, atToken.pos); - typedefTag.atToken = atToken; - typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { - // if node is identifier - use it as name - // otherwise use name of the rightmost part that we were able to parse - typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } - typedefTag.typeExpression = typeExpression; - skipWhitespace(); - if (typeExpression) { - if (typeExpression.type.kind === 277 /* JSDocTypeReference */) { - var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 71 /* Identifier */) { - var name = jsDocTypeReference.name; - if (name.text === "Object") { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - } - } - if (!typedefTag.jsDocTypeLiteral) { - typedefTag.jsDocTypeLiteral = typeExpression.type; - } - } - else { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - return finishNode(typedefTag); - function scanChildTags() { - var jsDocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, scanner.getStartPos()); - var resumePos = scanner.getStartPos(); - var canParseTag = true; - var seenAsterisk = false; - var parentTagTerminated = false; - while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { - nextJSDocToken(); - switch (token()) { - case 57 /* AtToken */: - if (canParseTag) { - parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } - } - seenAsterisk = false; - break; - case 4 /* NewLineTrivia */: - resumePos = scanner.getStartPos() - 1; - canParseTag = true; - seenAsterisk = false; - break; - case 39 /* AsteriskToken */: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 71 /* Identifier */: - canParseTag = false; - break; - case 1 /* EndOfFileToken */: - break; - } - } - scanner.setTextPos(resumePos); - return finishNode(jsDocTypeLiteral); - } - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(233 /* ModuleDeclaration */, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); - return jsDocNamespaceNode; - } - if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { - typeNameOrNamespaceName.isInJSDocNamespace = true; - } - return typeNameOrNamespaceName; - } - } - function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getStartPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return false; - } - switch (tagName.text) { - case "type": - if (parentTag.jsDocTypeTag) { - // already has a @type tag, terminate the parent tag now. - return false; - } - parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); - return true; - case "prop": - case "property": - var propertyTag = parsePropertyTag(atToken, tagName); - if (propertyTag) { - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } - parentTag.jsDocPropertyTags.push(propertyTag); - return true; - } - // Error parsing property tag - return false; - } - return false; - } - function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocTemplateTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - // Type parameter list looks like '@template T,U,V' - var typeParameters = createNodeArray(); - while (true) { - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var typeParameter = createNode(145 /* TypeParameter */, name.pos); - typeParameter.name = name; - finishNode(typeParameter); - typeParameters.push(typeParameter); - if (token() === 26 /* CommaToken */) { - nextJSDocToken(); - skipWhitespace(); - } - else { - break; - } - } - var result = createNode(289 /* JSDocTemplateTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeParameters = typeParameters; - finishNode(result); - typeParameters.end = result.end; - return result; - } - function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); - } - function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function createJSDocIdentifier(isIdentifier) { - if (!isIdentifier) { - parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - return undefined; - } - var pos = scanner.getTokenPos(); - var end = scanner.getTextPos(); - var result = createNode(71 /* Identifier */, pos); - result.text = content.substring(pos, end); - finishNode(result, end); - nextJSDocToken(); - return result; - } - } - JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; - })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); - })(Parser || (Parser = {})); - var IncrementalParser; - (function (IncrementalParser) { - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); - checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); - if (ts.textChangeRangeIsUnchanged(textChangeRange)) { - // if the text didn't change, then we can just return our current source file as-is. - return sourceFile; - } - if (sourceFile.statements.length === 0) { - // If we don't have any statements in the current source file, then there's no real - // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); - } - // Make sure we're not trying to incrementally update a source file more than once. Once - // we do an update the original source file is considered unusable from that point onwards. - // - // This is because we do incremental parsing in-place. i.e. we take nodes from the old - // tree and give them new positions and parents. From that point on, trusting the old - // tree at all is not possible as far too much of it may violate invariants. - var incrementalSourceFile = sourceFile; - ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); - incrementalSourceFile.hasBeenIncrementallyParsed = true; - var oldText = sourceFile.text; - var syntaxCursor = createSyntaxCursor(sourceFile); - // Make the actual change larger so that we know to reparse anything whose lookahead - // might have intersected the change. - var changeRange = extendToAffectedRange(sourceFile, textChangeRange); - checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); - // Ensure that extending the affected range only moved the start of the change range - // earlier in the file. - ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); - ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); - ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); - // The is the amount the nodes after the edit range need to be adjusted. It can be - // positive (if the edit added characters), negative (if the edit deleted characters) - // or zero (if this was a pure overwrite with nothing added/removed). - var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; - // If we added or removed characters during the edit, then we need to go and adjust all - // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they - // may move backward (if we deleted chars). - // - // Doing this helps us out in two ways. First, it means that any nodes/tokens we want - // to reuse are already at the appropriate position in the new text. That way when we - // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes - // it very easy to determine if we can reuse a node. If the node's position is at where - // we are in the text, then we can reuse it. Otherwise we can't. If the node's position - // is ahead of us, then we'll need to rescan tokens. If the node's position is behind - // us, then we'll need to skip it or crumble it as appropriate - // - // We will also adjust the positions of nodes that intersect the change range as well. - // By doing this, we ensure that all the positions in the old tree are consistent, not - // just the positions of nodes entirely before/after the change range. By being - // consistent, we can then easily map from positions to nodes in the old tree easily. - // - // Also, mark any syntax elements that intersect the changed span. We know, up front, - // that we cannot reuse these elements. - updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - // Now that we've set up our internal incremental state just proceed and parse the - // source file in the normal fashion. When possible the parser will retrieve and - // reuse nodes from the old tree. - // - // Note: passing in 'true' for setNodeParents is very important. When incrementally - // parsing, we will be reusing nodes from the old tree, and placing it into new - // parents. If we don't set the parents now, we'll end up with an observably - // inconsistent tree. Setting the parents on the new tree should be very fast. We - // will immediately bail out of walking any subtrees when we can see that their parents - // are already correct. - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); - return result; - } - IncrementalParser.updateSourceFile = updateSourceFile; - function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { - if (isArray) { - visitArray(element); - } - else { - visitNode(element); - } - return; - function visitNode(node) { - var text = ""; - if (aggressiveChecks && shouldCheckNode(node)) { - text = oldText.substring(node.pos, node.end); - } - // Ditch any existing LS children we may have created. This way we can avoid - // moving them forward. - if (node._children) { - node._children = undefined; - } - node.pos += delta; - node.end += delta; - if (aggressiveChecks && shouldCheckNode(node)) { - ts.Debug.assert(text === newText.substring(node.pos, node.end)); - } - forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - forEachChild(jsDocComment, visitNode, visitArray); - } - } - checkNodePositions(node, aggressiveChecks); - } - function visitArray(array) { - array._children = undefined; - array.pos += delta; - array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; - visitNode(node); - } - } - } - function shouldCheckNode(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 71 /* Identifier */: - return true; - } - return false; - } - function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { - ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); - ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); - ts.Debug.assert(element.pos <= element.end); - // We have an element that intersects the change range in some way. It may have its - // start, or its end (or both) in the changed range. We want to adjust any part - // that intersects such that the final tree is in a consistent state. i.e. all - // children have spans within the span of their parent, and all siblings are ordered - // properly. - // We may need to update both the 'pos' and the 'end' of the element. - // If the 'pos' is before the start of the change, then we don't need to touch it. - // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have - // something like: - // - // -------------------AAA----------------- - // -------------------BBBCCCCCCC----------------- - // - // In this case, we consider any node that started in the change range to still be - // starting at the same position. - // - // however, if the delta is negative, then we instead have something like this: - // - // -------------------XXXYYYYYYY----------------- - // -------------------ZZZ----------------- - // - // In this case, any element that started in the 'X' range will keep its position. - // However any element that started after that will have their pos adjusted to be - // at the end of the new range. i.e. any node that started in the 'Y' range will - // be adjusted to have their start at the end of the 'Z' range. - // - // The element will keep its position if possible. Or Move backward to the new-end - // if it's in the 'Y' range. - element.pos = Math.min(element.pos, changeRangeNewEnd); - // If the 'end' is after the change range, then we always adjust it by the delta - // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we - // have something like: - // - // -------------------AAA----------------- - // -------------------BBBCCCCCCC----------------- - // - // In this case, we consider any node that ended inside the change range to keep its - // end position. - // - // however, if the delta is negative, then we instead have something like this: - // - // -------------------XXXYYYYYYY----------------- - // -------------------ZZZ----------------- - // - // In this case, any element that ended in the 'X' range will keep its position. - // However any element that ended after that will have their pos adjusted to be - // at the end of the new range. i.e. any node that ended in the 'Y' range will - // be adjusted to have their end at the end of the 'Z' range. - if (element.end >= changeRangeOldEnd) { - // Element ends after the change range. Always adjust the end pos. - element.end += delta; - } - else { - // Element ends in the change range. The element will keep its position if - // possible. Or Move backward to the new-end if it's in the 'Y' range. - element.end = Math.min(element.end, changeRangeNewEnd); - } - ts.Debug.assert(element.pos <= element.end); - if (element.parent) { - ts.Debug.assert(element.pos >= element.parent.pos); - ts.Debug.assert(element.end <= element.parent.end); - } - } - function checkNodePositions(node, aggressiveChecks) { - if (aggressiveChecks) { - var pos_2 = node.pos; - forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; - }); - ts.Debug.assert(pos_2 <= node.end); - } - } - function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { - visitNode(sourceFile); - return; - function visitNode(child) { - ts.Debug.assert(child.pos <= child.end); - if (child.pos > changeRangeOldEnd) { - // Node is entirely past the change range. We need to move both its pos and - // end, forward or backward appropriately. - moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); - return; - } - // Check if the element intersects the change range. If it does, then it is not - // reusable. Also, we'll need to recurse to see what constituent portions we may - // be able to use. - var fullEnd = child.end; - if (fullEnd >= changeStart) { - child.intersectsChange = true; - child._children = undefined; - // Adjust the pos or end (or both) of the intersecting element accordingly. - adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - forEachChild(child, visitNode, visitArray); - checkNodePositions(child, aggressiveChecks); - return; - } - // Otherwise, the node is entirely before the change range. No need to do anything with it. - ts.Debug.assert(fullEnd < changeStart); - } - function visitArray(array) { - ts.Debug.assert(array.pos <= array.end); - if (array.pos > changeRangeOldEnd) { - // Array is entirely after the change range. We need to move it, and move any of - // its children. - moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); - return; - } - // Check if the element intersects the change range. If it does, then it is not - // reusable. Also, we'll need to recurse to see what constituent portions we may - // be able to use. - var fullEnd = array.end; - if (fullEnd >= changeStart) { - array.intersectsChange = true; - array._children = undefined; - // Adjust the pos or end (or both) of the intersecting array accordingly. - adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; - visitNode(node); - } - return; - } - // Otherwise, the array is entirely before the change range. No need to do anything with it. - ts.Debug.assert(fullEnd < changeStart); - } - } - function extendToAffectedRange(sourceFile, changeRange) { - // Consider the following code: - // void foo() { /; } - // - // If the text changes with an insertion of / just before the semicolon then we end up with: - // void foo() { //; } - // - // If we were to just use the changeRange a is, then we would not rescan the { token - // (as it does not intersect the actual original change range). Because an edit may - // change the token touching it, we actually need to look back *at least* one token so - // that the prior token sees that change. - var maxLookahead = 1; - var start = changeRange.span.start; - // the first iteration aligns us with the change start. subsequent iteration move us to - // the left by maxLookahead tokens. We only need to do this as long as we're not at the - // start of the tree. - for (var i = 0; start > 0 && i <= maxLookahead; i++) { - var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); - ts.Debug.assert(nearestNode.pos <= start); - var position = nearestNode.pos; - start = Math.max(0, position - 1); - } - var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); - var finalLength = changeRange.newLength + (changeRange.span.start - start); - return ts.createTextChangeRange(finalSpan, finalLength); - } - function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { - var bestResult = sourceFile; - var lastNodeEntirelyBeforePosition; - forEachChild(sourceFile, visit); - if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); - if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { - bestResult = lastChildOfLastEntireNodeBeforePosition; - } - } - return bestResult; - function getLastChild(node) { - while (true) { - var lastChild = getLastChildWorker(node); - if (lastChild) { - node = lastChild; - } - else { - return node; - } - } - } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } - function visit(child) { - if (ts.nodeIsMissing(child)) { - // Missing nodes are effectively invisible to us. We never even consider them - // When trying to find the nearest node before us. - return; - } - // If the child intersects this position, then this node is currently the nearest - // node that starts before the position. - if (child.pos <= position) { - if (child.pos >= bestResult.pos) { - // This node starts before the position, and is closer to the position than - // the previous best node we found. It is now the new best node. - bestResult = child; - } - // Now, the node may overlap the position, or it may end entirely before the - // position. If it overlaps with the position, then either it, or one of its - // children must be the nearest node before the position. So we can just - // recurse into this child to see if we can find something better. - if (position < child.end) { - // The nearest node is either this child, or one of the children inside - // of it. We've already marked this child as the best so far. Recurse - // in case one of the children is better. - forEachChild(child, visit); - // Once we look at the children of this node, then there's no need to - // continue any further. - return true; - } - else { - ts.Debug.assert(child.end <= position); - // The child ends entirely before this position. Say you have the following - // (where $ is the position) - // - // ? $ : <...> <...> - // - // We would want to find the nearest preceding node in "complex expr 2". - // To support that, we keep track of this node, and once we're done searching - // for a best node, we recurse down this node to see if we can find a good - // result in it. - // - // This approach allows us to quickly skip over nodes that are entirely - // before the position, while still allowing us to find any nodes in the - // last one that might be what we want. - lastNodeEntirelyBeforePosition = child; - } - } - else { - ts.Debug.assert(child.pos > position); - // We're now at a node that is entirely past the position we're searching for. - // This node (and all following nodes) could never contribute to the result, - // so just skip them by returning 'true' here. - return true; - } - } - } - function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { - var oldText = sourceFile.text; - if (textChangeRange) { - ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); - if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { - var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - var newTextPrefix = newText.substr(0, textChangeRange.span.start); - ts.Debug.assert(oldTextPrefix === newTextPrefix); - var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); - var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); - ts.Debug.assert(oldTextSuffix === newTextSuffix); - } - } - } - function createSyntaxCursor(sourceFile) { - var currentArray = sourceFile.statements; - var currentArrayIndex = 0; - ts.Debug.assert(currentArrayIndex < currentArray.length); - var current = currentArray[currentArrayIndex]; - var lastQueriedPosition = -1 /* Value */; - return { - currentNode: function (position) { - // Only compute the current node if the position is different than the last time - // we were asked. The parser commonly asks for the node at the same position - // twice. Once to know if can read an appropriate list element at a certain point, - // and then to actually read and consume the node. - if (position !== lastQueriedPosition) { - // Much of the time the parser will need the very next node in the array that - // we just returned a node from.So just simply check for that case and move - // forward in the array instead of searching for the node again. - if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { - currentArrayIndex++; - current = currentArray[currentArrayIndex]; - } - // If we don't have a node, or the node we have isn't in the right position, - // then try to find a viable node at the position requested. - if (!current || current.pos !== position) { - findHighestListElementThatStartsAtPosition(position); - } - } - // Cache this query so that we don't do any extra work if the parser calls back - // into us. Note: this is very common as the parser will make pairs of calls like - // 'isListElement -> parseListElement'. If we were unable to find a node when - // called with 'isListElement', we don't want to redo the work when parseListElement - // is called immediately after. - lastQueriedPosition = position; - // Either we don'd have a node, or we have a node at the position being asked for. - ts.Debug.assert(!current || current.pos === position); - return current; - } - }; - // Finds the highest element in the tree we can find that starts at the provided position. - // The element must be a direct child of some node list in the tree. This way after we - // return it, we can easily return its next sibling in the list. - function findHighestListElementThatStartsAtPosition(position) { - // Clear out any cached state about the last node we found. - currentArray = undefined; - currentArrayIndex = -1 /* Value */; - current = undefined; - // Recurse into the source file to find the highest node at this position. - forEachChild(sourceFile, visitNode, visitArray); - return; - function visitNode(node) { - if (position >= node.pos && position < node.end) { - // Position was within this node. Keep searching deeper to find the node. - forEachChild(node, visitNode, visitArray); - // don't proceed any further in the search. - return true; - } - // position wasn't in this node, have to keep searching. - return false; - } - function visitArray(array) { - if (position >= array.pos && position < array.end) { - // position was in this array. Search through this array to see if we find a - // viable element. - for (var i = 0; i < array.length; i++) { - var child = array[i]; - if (child) { - if (child.pos === position) { - // Found the right node. We're done. - currentArray = array; - currentArrayIndex = i; - current = child; - return true; - } - else { - if (child.pos < position && position < child.end) { - // Position in somewhere within this child. Search in it and - // stop searching in this array. - forEachChild(child, visitNode, visitArray); - return true; - } - } - } - } - } - // position wasn't in this array, have to keep searching. - return false; - } - } - } - var InvalidPosition; - (function (InvalidPosition) { - InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; - })(InvalidPosition || (InvalidPosition = {})); - })(IncrementalParser || (IncrementalParser = {})); -})(ts || (ts = {})); -/// -/// -/* @internal */ -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) { - // A module is uninstantiated if it contains only - // 1. interface declarations, type alias declarations - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 231 /* TypeAliasDeclaration */) { - return 0 /* NonInstantiated */; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2 /* ConstEnumOnly */; - } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { - return 0 /* NonInstantiated */; - } - else if (node.kind === 234 /* ModuleBlock */) { - var state_1 = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return false; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state_1 = 2 /* ConstEnumOnly */; - return false; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state_1 = 1 /* Instantiated */; - return true; - } - }); - return state_1; - } - else if (node.kind === 233 /* ModuleDeclaration */) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1 /* Instantiated */; - } - else if (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace) { - return 0 /* NonInstantiated */; - } - else { - return 1 /* Instantiated */; - } - } - ts.getModuleInstanceState = getModuleInstanceState; - var ContainerFlags; - (function (ContainerFlags) { - // The current node is not a container, and no container manipulation should happen before - // recursing into it. - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - // The current node is a container. It should be set as the current container (and block- - // container) before recursing into it. The current node does not have locals. Examples: - // - // Classes, ObjectLiterals, TypeLiterals, Interfaces... - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - // The current node is a block-scoped-container. It should be set as the current block- - // container before recursing into it. Examples: - // - // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - // The current node is the container of a control flow path. The current control flow should - // be saved and restored, and a new control flow initialized within the container. - 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"); - binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var languageVersion; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - // state used by control flow analysis - var currentFlow; - var currentBreakTarget; - var currentContinueTarget; - var currentReturnTarget; - var currentTrueTarget; - var currentFalseTarget; - var preSwitchCaseFlow; - var activeLabels; - var hasExplicitReturn; - // state used for emit helpers - var emitFlags; - // If this file is an external module, then it is automatically in strict-mode according to - // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places or if we hit a class/namespace - // or if compiler options contain alwaysStrict. - var inStrictMode; - var symbolCount = 0; - var Symbol; - var classifiableNames; - var unreachableFlow = { flags: 1 /* Unreachable */ }; - var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; - // state used to aggregate transform flags during bind. - var subtreeTransformFlags = 0 /* None */; - var skipTransformFlagAggregation; - function bindSourceFile(f, opts) { - file = f; - options = opts; - languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = ts.createMap(); - symbolCount = 0; - skipTransformFlagAggregation = file.isDeclarationFile; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = 0 /* None */; - subtreeTransformFlags = 0 /* None */; - } - return bindSourceFile; - function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { - // bind in strict mode source files with alwaysStrict option - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = ts.createMap(); - } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = ts.createMap(); - } - if (symbolFlags & 107455 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233 /* ModuleDeclaration */)) { - // 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) { - var name = ts.getNameOfDeclaration(node); - if (name) { - if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; - } - 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; - } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); - } - return name.text; - } - switch (node.kind) { - case 152 /* Constructor */: - return "__constructor"; - case 160 /* FunctionType */: - case 155 /* CallSignature */: - return "__call"; - case 161 /* ConstructorType */: - case 156 /* ConstructSignature */: - return "__new"; - case 157 /* IndexSignature */: - return "__index"; - case 244 /* ExportDeclaration */: - return "__export"; - case 243 /* ExportAssignment */: - return node.isExportEquals ? "export=" : "default"; - case 194 /* BinaryExpression */: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2 /* ModuleExports */: - // module.exports = ... - return "export="; - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - // exports.x = ... or this.y = ... - return node.left.name.text; - case 3 /* PrototypeProperty */: - // className.prototype.methodName = ... - return node.left.expression.name.text; - } - ts.Debug.fail("Unknown binary declaration kind"); - break; - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: - return ts.hasModifier(node, 512 /* Default */) ? "default" : undefined; - case 279 /* JSDocFunctionType */: - return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 146 /* Parameter */: - // Parameters with names are handled at the top of this function. Parameters - // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 279 /* JSDocFunctionType */); - var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); - return "arg" + index; - case 290 /* JSDocTypedefTag */: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71 /* Identifier */) { - nameFromParentNode = nameIdentifier.text; - } - } - } - return nameFromParentNode; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - /** - * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. - * @param symbolTable - The symbol table which node will be added to. - * @param parent - node's parent declaration. - * @param node - The declaration to be added to the symbol table - * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. - */ - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); - // The exported symbol for an export default function/class node is always named "default" - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name === undefined) { - symbol = createSymbol(0 /* None */, "__missing"); - } - else { - // Check and see if the symbol table already has a symbol with this name. If not, - // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict - // with the 'excludes' flags we pass in. - // - // If we do get an existing symbol, see if it conflicts with the new symbol we're - // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this - // declaration. - // - // Note that when properties declared in Javascript constructors - // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. - // Always. This allows the common Javascript pattern of overwriting a prototype method - // with an bound instance method of the same type: `this.method = this.method.bind(this)` - // - // If we created a new symbol, either because we didn't have a symbol with this name - // in the symbol table, or we conflicted with an existing symbol, then just add this - // node as the sole declaration of the new symbol. - // - // Otherwise, we'll be merging into a compatible existing symbol (for example when - // you have multiple 'vars' with the same name in the same container). In this case - // just add this node into the declarations list of the symbol. - symbol = symbolTable.get(name); - if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - } - if (name && (includes & 788448 /* Classifiable */)) { - classifiableNames.set(name, name); - } - if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - // Javascript constructor-declared symbols can be discarded in favor of - // prototype symbols like methods. - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - } - else { - if (node.name) { - node.name.parent = node; - } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - if (symbol.declarations && symbol.declarations.length) { - // If the current node is a default export of some sort, then check if - // there are any other default exports that we need to error on. - // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. - if (isDefaultExport) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. - // Error on multiple export default in the following case: - // 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 === 243 /* ExportAssignment */ && !node.isExportEquals))) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); - } - } - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; - if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 246 /* ExportSpecifier */ || (node.kind === 237 /* ImportEqualsDeclaration */ && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - else { - // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, - // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set - // on it. There are 2 main reasons: - // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. - // That means the binder will issue a Duplicate Identifier error if you mix locals and exports - // with the same name in the same container. - // TODO: Make this a more specific error and decouple it from the exclusion logic. - // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, - // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way - // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge - // 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. - var isJSDocTypedefInJSDocNamespace = node.kind === 290 /* JSDocTypedefTag */ && - node.name && - node.name.kind === 71 /* Identifier */ && - node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); - var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - } - // All container nodes are kept on a linked list in declaration order. This list is used by - // the getLocalNameOfContainer function in the type checker to validate that the local name - // used for a container is unique. - function bindContainer(node, containerFlags) { - // Before we recurse into a node's children, we first save the existing parent, container - // and block-container. Then after we pop out of processing the children, we restore - // these saved values. - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - // Depending on what kind of node this is, we may have to adjust the current container - // and block-container. If the current node is a container, then it is automatically - // considered the current block-container as well. Also, for containers that we know - // may contain locals, we proactively initialize the .locals field. We do this because - // it's highly likely that the .locals will be needed to place some child in (for example, - // a parameter, or variable declaration). - // - // However, we do not proactively create the .locals for block-containers because it's - // totally normal and common for block-containers to never actually have a block-scoped - // variable in them. We don't want to end up allocating an object for every 'block' we - // run into when most of them won't be necessary. - // - // Finally, if this is a block-container, then we clear out any existing .locals object - // it may contain within it. This happens in incremental scenarios. Because we can be - // reusing a node from a previous compilation, that node may have had 'locals' created - // for it. We must clear this so we don't accidentally move any stale data forward from - // a previous compilation. - if (containerFlags & 1 /* IsContainer */) { - container = blockScopeContainer = node; - if (containerFlags & 32 /* HasLocals */) { - container.locals = ts.createMap(); - } - addToContainerChain(container); - } - else if (containerFlags & 2 /* IsBlockScopedContainer */) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveCurrentFlow = currentFlow; - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - var saveReturnTarget = currentReturnTarget; - var saveActiveLabels = activeLabels; - var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); - // A non-async IIFE is considered part of the containing control flow. Return statements behave - // similarly to break statements that exit to a label just past the statement body. - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { - currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { - currentFlow.container = node; - } - currentReturnTarget = undefined; - } - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - // Reset all reachability check related flags on node (for incremental scenarios) - node.flags &= ~1408 /* ReachabilityAndEmitFlags */; - if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { - node.flags |= 128 /* HasImplicitReturn */; - if (hasExplicitReturn) - node.flags |= 256 /* HasExplicitReturn */; - } - if (node.kind === 265 /* SourceFile */) { - node.flags |= emitFlags; - } - if (isIIFE) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - } - else { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & 64 /* IsInterface */) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - function bindChildren(node) { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & 536870912 /* HasComputedFlags */) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - function bindEach(nodes) { - if (nodes === undefined) { - return; - } - if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0 /* None */; - var nodeArrayFlags = 0 /* None */; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; - bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; - } - nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - } - function bindEachChild(node) { - ts.forEachChild(node, bind, bindEach); - } - function bindChildrenWorker(node) { - // 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 (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } - if (checkUnreachable(node)) { - bindEachChild(node); - return; - } - switch (node.kind) { - case 213 /* WhileStatement */: - bindWhileStatement(node); - break; - case 212 /* DoStatement */: - bindDoStatement(node); - break; - case 214 /* ForStatement */: - bindForStatement(node); - break; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - bindForInOrForOfStatement(node); - break; - case 211 /* IfStatement */: - bindIfStatement(node); - break; - case 219 /* ReturnStatement */: - case 223 /* ThrowStatement */: - bindReturnOrThrow(node); - break; - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: - bindBreakOrContinueStatement(node); - break; - case 224 /* TryStatement */: - bindTryStatement(node); - break; - case 221 /* SwitchStatement */: - bindSwitchStatement(node); - break; - case 235 /* CaseBlock */: - bindCaseBlock(node); - break; - case 257 /* CaseClause */: - bindCaseClause(node); - break; - case 222 /* LabeledStatement */: - bindLabeledStatement(node); - break; - case 192 /* PrefixUnaryExpression */: - bindPrefixUnaryExpressionFlow(node); - break; - case 193 /* PostfixUnaryExpression */: - bindPostfixUnaryExpressionFlow(node); - break; - case 194 /* BinaryExpression */: - bindBinaryExpressionFlow(node); - break; - case 188 /* DeleteExpression */: - bindDeleteExpressionFlow(node); - break; - case 195 /* ConditionalExpression */: - bindConditionalExpressionFlow(node); - break; - case 226 /* VariableDeclaration */: - bindVariableDeclarationFlow(node); - break; - case 181 /* CallExpression */: - bindCallExpressionFlow(node); - break; - case 283 /* JSDocComment */: - bindJSDocComment(node); - break; - case 290 /* JSDocTypedefTag */: - bindJSDocTypedefTag(node); - break; - default: - bindEachChild(node); - break; - } - } - function isNarrowingExpression(expr) { - switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 179 /* PropertyAccessExpression */: - return isNarrowableReference(expr); - case 181 /* CallExpression */: - return hasNarrowableArgument(expr); - case 185 /* ParenthesizedExpression */: - return isNarrowingExpression(expr.expression); - case 194 /* BinaryExpression */: - return isNarrowingBinaryExpression(expr); - case 192 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - } - return false; - } - function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 179 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } - function hasNarrowableArgument(expr) { - if (expr.arguments) { - for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === 179 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { - return true; - } - return false; - } - function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; - } - function isNarrowingBinaryExpression(expr) { - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: - return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: - return isNarrowingExpression(expr.right); - } - return false; - } - function isNarrowableOperand(expr) { - switch (expr.kind) { - case 185 /* ParenthesizedExpression */: - return isNarrowableOperand(expr.expression); - case 194 /* BinaryExpression */: - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: - return isNarrowableOperand(expr.right); - } - } - return isNarrowableReference(expr); - } - function createBranchLabel() { - return { - flags: 4 /* BranchLabel */, - antecedents: undefined - }; - } - function createLoopLabel() { - return { - flags: 8 /* LoopLabel */, - antecedents: undefined - }; - } - function setFlowNodeReferenced(flow) { - // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; - } - function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1 /* Unreachable */) { - return antecedent; - } - if (!expression) { - return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; - } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; - } - function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: 128 /* SwitchClause */, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; - } - function createFlowAssignment(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 16 /* Assignment */, - antecedent: antecedent, - node: node - }; - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 256 /* ArrayMutation */, - antecedent: antecedent, - node: node - }; - } - function finishFlowLabel(flow) { - var antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - function isStatementCondition(node) { - var parent = node.parent; - switch (parent.kind) { - case 211 /* IfStatement */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: - return parent.expression === node; - case 214 /* ForStatement */: - case 195 /* ConditionalExpression */: - return parent.condition === node; - } - return false; - } - function isLogicalExpression(node) { - while (true) { - if (node.kind === 185 /* ParenthesizedExpression */) { - node = node.expression; - } - else if (node.kind === 192 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { - node = node.operand; - } - else { - return node.kind === 194 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); - } - } - } - function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 /* ParenthesizedExpression */ || - node.parent.kind === 192 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - function bindCondition(node, trueTarget, falseTarget) { - var saveTrueTarget = currentTrueTarget; - var saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); - } - } - function bindIterativeStatement(node, breakTarget, continueTarget) { - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - function bindWhileStatement(node) { - var preWhileLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - function bindDoStatement(node) { - var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 /* LabeledStatement */ - ? ts.lastOrUndefined(activeLabels) - : undefined; - // if do statement is wrapped in labeled statement then target labels for break/continue with or without - // label should be the same - var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); - var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - function bindForStatement(node) { - var preLoopLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindForInOrForOfStatement(node) { - var preLoopLabel = createLoopLabel(); - var postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - if (node.kind === 216 /* ForOfStatement */) { - bind(node.awaitModifier); - } - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== 227 /* VariableDeclarationList */) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindIfStatement(node) { - var thenLabel = createBranchLabel(); - var elseLabel = createBranchLabel(); - var postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - function bindReturnOrThrow(node) { - bind(node.expression); - if (node.kind === 219 /* ReturnStatement */) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - function findActiveLabel(name) { - if (activeLabels) { - for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { - var label = activeLabels_1[_i]; - if (label.name === name) { - return label; - } - } - } - return undefined; - } - function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 /* BreakStatement */ ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - function bindBreakOrContinueStatement(node) { - bind(node.label); - if (node.label) { - var activeLabel = findActiveLabel(node.label.text); - if (activeLabel) { - activeLabel.referenced = true; - bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - // TODO: Every statement in try block is potentially an exit point! - bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; - } - if (node.finallyBlock) { - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); - bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block - if (!(currentFlow.flags & 1 /* Unreachable */)) { - if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } - } - if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; - } - } - else { - currentFlow = finishFlowLabel(preFinallyLabel); - } - } - function bindSwitchStatement(node) { - var postSwitchLabel = createBranchLabel(); - bind(node.expression); - var saveBreakTarget = currentBreakTarget; - var savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258 /* DefaultClause */; }); - // We mark a switch statement as possibly exhaustive if it has no default clause and if all - // case clauses have unreachable end points (e.g. they all return). - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - function bindCaseBlock(node) { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var clauses = node.clauses; - var fallthroughFlow = unreachableFlow; - for (var i = 0; i < clauses.length; i++) { - var clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - var clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - function bindCaseClause(node) { - var saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - bindEach(node.statements); - } - function pushActiveLabel(name, breakTarget, continueTarget) { - var activeLabel = { - name: name, - breakTarget: breakTarget, - continueTarget: continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - function popActiveLabel() { - activeLabels.pop(); - } - function bindLabeledStatement(node) { - var preStatementLabel = createLoopLabel(); - var postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - var activeLabel = pushActiveLabel(node.label.text, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); - } - if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { - // do statement sets current flow inside bindDoStatement - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - } - function bindDestructuringTargetFlow(node) { - if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { - bindAssignmentTargetFlow(node.left); - } - else { - bindAssignmentTargetFlow(node); - } - } - function bindAssignmentTargetFlow(node) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === 177 /* ArrayLiteralExpression */) { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var e = _a[_i]; - if (e.kind === 198 /* SpreadElement */) { - bindAssignmentTargetFlow(e.expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === 178 /* ObjectLiteralExpression */) { - for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { - var p = _c[_b]; - if (p.kind === 261 /* PropertyAssignment */) { - bindDestructuringTargetFlow(p.initializer); - } - else if (p.kind === 262 /* ShorthandPropertyAssignment */) { - bindAssignmentTargetFlow(p.name); - } - else if (p.kind === 263 /* SpreadAssignment */) { - bindAssignmentTargetFlow(p.expression); - } - } - } - } - function bindLogicalExpression(node, trueTarget, falseTarget) { - var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { - var saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - bindEachChild(node); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - } - function bindPostfixUnaryExpressionFlow(node) { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - function bindBinaryExpressionFlow(node) { - var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - bindEachChild(node); - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 180 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - function bindDeleteExpressionFlow(node) { - bindEachChild(node); - if (node.expression.kind === 179 /* PropertyAccessExpression */) { - bindAssignmentTargetFlow(node.expression); - } - } - function bindConditionalExpressionFlow(node) { - var trueLabel = createBranchLabel(); - var falseLabel = createBranchLabel(); - var postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.questionToken); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.colonToken); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - function bindInitializedVariableFlow(node) { - var name = !ts.isOmittedExpression(node) ? node.name : undefined; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var child = _a[_i]; - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - function bindVariableDeclarationFlow(node) { - bindEachChild(node); - if (node.initializer || node.parent.parent.kind === 215 /* ForInStatement */ || node.parent.parent.kind === 216 /* ForOfStatement */) { - bindInitializedVariableFlow(node); - } - } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 290 /* JSDocTypedefTag */) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - // if the node has a fullName "A.B.C", that means symbol "C" was already bound - // when we visit "fullName"; so when we visit the name "C" as the next child of - // the jsDocTypedefTag, we should skip binding it. - if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { - return; - } - bind(n); - }); - } - function bindCallExpressionFlow(node) { - // If the target of the call expression is a function expression or arrow function we have - // an immediately invoked function expression (IIFE). Initialize the flowNode property to - // the current control flow (which includes evaluation of the IIFE arguments). - var expr = node.expression; - while (expr.kind === 185 /* ParenthesizedExpression */) { - expr = expr.expression; - } - if (expr.kind === 186 /* FunctionExpression */ || expr.kind === 187 /* ArrowFunction */) { - bindEach(node.typeArguments); - bindEach(node.arguments); - bind(node.expression); - } - else { - bindEachChild(node); - } - if (node.expression.kind === 179 /* PropertyAccessExpression */) { - var propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: - case 163 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: - case 275 /* JSDocRecordType */: - case 254 /* JsxAttributes */: - return 1 /* IsContainer */; - case 230 /* InterfaceDeclaration */: - return 1 /* IsContainer */ | 64 /* IsInterface */; - case 279 /* JSDocFunctionType */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: - return 1 /* IsContainer */ | 32 /* HasLocals */; - case 265 /* SourceFile */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 151 /* MethodDeclaration */: - if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; - } - // falls through - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 234 /* ModuleBlock */: - return 4 /* IsControlFlowContainer */; - case 149 /* PropertyDeclaration */: - return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 260 /* CatchClause */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 235 /* CaseBlock */: - return 2 /* IsBlockScopedContainer */; - case 207 /* Block */: - // do not treat blocks directly inside a function as a block-scoped-container. - // Locals that reside in this block should go to the function locals. Otherwise 'x' - // would not appear to be a redeclaration of a block scoped local in the following - // example: - // - // function foo() { - // var x; - // let x; - // } - // - // If we placed 'var x' into the function locals and 'let x' into the locals of - // the block, then there would be no collision. - // - // By not creating a new block-scoped-container here, we ensure that both 'var x' - // and 'let x' go into the Function-container's locals, and we do get a collision - // conflict. - return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; - } - return 0 /* None */; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - // Just call this directly so that the return type of this function stays "void". - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { - switch (container.kind) { - // Modules, source files, and classes need specialized handling for how their - // members are declared (for example, a member of a class will go into a specific - // symbol table depending on if it is static or not). We defer to specialized - // handlers to take care of declaring these child members. - case 233 /* ModuleDeclaration */: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265 /* SourceFile */: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 232 /* EnumDeclaration */: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* TypeLiteral */: - case 178 /* ObjectLiteralExpression */: - case 230 /* InterfaceDeclaration */: - case 275 /* JSDocRecordType */: - case 292 /* JSDocTypeLiteral */: - case 254 /* JsxAttributes */: - // Interface/Object-types always have their children added to the 'members' of - // their container. They are only accessible through an instance of their - // container, and are never in scope otherwise (even inside the body of the - // object / type / interface declaring them). An exception is type parameters, - // which are in scope without qualification (similar to 'locals'). - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 279 /* JSDocFunctionType */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: - // All the children of these container types are never visible through another - // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, - // they're only accessed 'lexically' (i.e. from code that exists underneath - // their container in the tree. To accomplish this, we simply add their declared - // symbol to the 'locals' of the container. These symbols can then be found as - // the type checker walks up the containers, checking them for matching names. - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32 /* Static */) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 265 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 265 /* SourceFile */ || body.kind === 234 /* ModuleBlock */)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 244 /* ExportDeclaration */ || stat.kind === 243 /* ExportAssignment */) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular - // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 32 /* ExportContext */; - } - else { - node.flags &= ~32 /* ExportContext */; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1 /* Export */)) { - errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (ts.isExternalModuleAugmentation(node)) { - declareModuleSymbol(node); - } - else { - var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { - var text = node.name.text; - if (ts.hasZeroOrOneAsteriskCharacter(text)) { - pattern = ts.tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } - } - } - else { - var state = declareModuleSymbol(node); - if (state !== 0 /* NonInstantiated */) { - if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { - // if module was already merged with some function, class or non-const enum - // treat is a non-const-enum-only - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function declareModuleSymbol(node) { - var state = getModuleInstanceState(node); - var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); - return state; - } - function bindFunctionOrConstructorType(node) { - // For a given function symbol "<...>(...) => T" we want to generate a symbol identical - // to the one we would get for: { <...>(...): T } - // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable - // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072 /* Signature */); - var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = ts.createMap(); - 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++) { - var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */ || prop.kind === 151 /* MethodDeclaration */ - ? 1 /* Property */ - : 2 /* Accessor */; - var existingKind = seen.get(identifier.text); - if (!existingKind) { - seen.set(identifier.text, currentKind); - continue; - } - if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span_1 = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object"); - } - function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes"); - } - function bindJsxAttribute(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 233 /* ModuleDeclaration */: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 265 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - // falls through - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); - } - // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized - // check for reserved words used as identifiers in strict mode code. - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && - !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { - // Report error only if there are no parse errors in file - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the - // Catch production is eval or arguments - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { - // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its - // UnaryExpression is a direct reference to a variable, function argument, or function name - var span_2 = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 71 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { - var identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); - } - } - } - function getStrictModeEvalOrArgumentsMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - checkStrictModeEvalOrArguments(node, node.name); - } - } - function getStrictModeBlockScopeFunctionDeclarationMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2 /* ES2015 */) { - // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 265 /* SourceFile */ && - blockScopeContainer.kind !== 233 /* ModuleDeclaration */ && - !ts.isFunctionLike(blockScopeContainer)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var errorSpan = ts.getErrorSpanForNode(file, node); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - function checkStrictModePostfixUnaryExpression(node) { - // Grammar checking - // The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression - // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - function checkStrictModePrefixUnaryExpression(node) { - // Grammar checking - if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - // Grammar checking for withStatement - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var saveInStrictMode = inStrictMode; - // Even though in the AST the jsdoc @typedef node belongs to the current node, - // its symbol might be in the same scope with the current node's symbol. Consider: - // - // /** @typedef {string | number} MyType */ - // function foo(); - // - // 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 (ts.isInJavaScriptFile(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 - // destination symbol tables are: - // - // 1) The 'exports' table of the current container's symbol. - // 2) The 'members' table of the current container's symbol. - // 3) The 'locals' table of the current container. - // - // However, not all symbols will end up in any of these tables. 'Anonymous' symbols - // (like TypeLiterals for example) will not be put in any table. - bindWorker(node); - // Then we recurse into the children of the node to bind them as well. For certain - // symbols we do specialized work when we recurse. For example, we'll keep track of - // the current 'container' node when it changes. This helps us know which symbol table - // a local should go into for example. Since terminal nodes are known not to have - // children, as an optimization we don't process those. - if (node.kind > 142 /* LastToken */) { - var saveParent = parent; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags === 0 /* None */) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; - } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 290 /* JSDocTypedefTag */) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; - } - } - } - } - function updateStrictModeStatementList(statements) { - if (!inStrictMode) { - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the - // string to contain unicode escapes (as per ES5). - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - /* Strict mode checks */ - case 71 /* Identifier */: - // 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) { - var parentNode = node.parent; - while (parentNode && parentNode.kind !== 290 /* JSDocTypedefTag */) { - parentNode = parentNode.parent; - } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - break; - } - // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262 /* ShorthandPropertyAssignment */)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case 179 /* PropertyAccessExpression */: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - break; - case 194 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case 1 /* ExportsProperty */: - bindExportsPropertyAssignment(node); - break; - case 2 /* ModuleExports */: - bindModuleExportsAssignment(node); - break; - case 3 /* PrototypeProperty */: - bindPrototypePropertyAssignment(node); - break; - case 4 /* ThisProperty */: - bindThisPropertyAssignment(node); - break; - case 5 /* Property */: - bindStaticPropertyAssignment(node); - break; - case 0 /* None */: - // Nothing to do - break; - default: - ts.Debug.fail("Unknown special property assignment kind"); - } - return checkStrictModeBinaryExpression(node); - case 260 /* CatchClause */: - return checkStrictModeCatchClause(node); - case 188 /* DeleteExpression */: - return checkStrictModeDeleteExpression(node); - case 8 /* NumericLiteral */: - return checkStrictModeNumericLiteral(node); - case 193 /* PostfixUnaryExpression */: - return checkStrictModePostfixUnaryExpression(node); - case 192 /* PrefixUnaryExpression */: - return checkStrictModePrefixUnaryExpression(node); - case 220 /* WithStatement */: - return checkStrictModeWithStatement(node); - case 169 /* ThisType */: - seenThisKeyword = true; - return; - case 158 /* TypePredicate */: - return checkTypePredicate(node); - case 145 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); - case 146 /* Parameter */: - return bindParameter(node); - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - return bindVariableDeclarationOrBindingElement(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 276 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - case 291 /* JSDocPropertyTag */: - return bindJSDocProperty(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 264 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 263 /* SpreadAssignment */: - case 255 /* JsxSpreadAttribute */: - var root = container; - var hasRest = false; - while (root.parent) { - if (root.kind === 178 /* ObjectLiteralExpression */ && - root.parent.kind === 194 /* BinaryExpression */ && - root.parent.operatorToken.kind === 58 /* EqualsToken */ && - root.parent.left === root) { - hasRest = true; - break; - } - root = root.parent; - } - return; - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - // If this is an ObjectLiteralExpression method, then it sits in the same space - // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes - // so that it will conflict with any other object literal members with the same - // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 228 /* FunctionDeclaration */: - return bindFunctionDeclaration(node); - case 152 /* Constructor */: - return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 153 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 154 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 279 /* JSDocFunctionType */: - return bindFunctionOrConstructorType(node); - case 163 /* TypeLiteral */: - case 172 /* MappedType */: - case 292 /* JSDocTypeLiteral */: - case 275 /* JSDocRecordType */: - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 178 /* ObjectLiteralExpression */: - return bindObjectLiteralExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return bindFunctionExpression(node); - case 181 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - // Members of classes, interfaces, and modules - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - // All classes are automatically in strict mode in ES6. - inStrictMode = true; - return bindClassLikeDeclaration(node); - case 230 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 290 /* JSDocTypedefTag */: - if (!node.fullName || node.fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - } - break; - case 231 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - case 232 /* EnumDeclaration */: - return bindEnumDeclaration(node); - case 233 /* ModuleDeclaration */: - return bindModuleDeclaration(node); - // Jsx-attributes - case 254 /* JsxAttributes */: - return bindJsxAttributes(node); - case 253 /* JsxAttribute */: - return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); - // Imports and exports - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: - return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 236 /* NamespaceExportDeclaration */: - return bindNamespaceExportDeclaration(node); - case 239 /* ImportClause */: - return bindImportClause(node); - case 244 /* ExportDeclaration */: - return bindExportDeclaration(node); - case 243 /* ExportAssignment */: - return bindExportAssignment(node); - case 265 /* SourceFile */: - updateStrictModeStatementList(node.statements); - return bindSourceFileIfExternalModule(); - case 207 /* Block */: - if (!ts.isFunctionLike(node.parent)) { - return; - } - // falls through - case 234 /* ModuleBlock */: - return updateStrictModeStatementList(node.statements); - } - } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71 /* Identifier */) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 169 /* ThisType */) { - seenThisKeyword = true; - } - bind(type); - } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } - function bindExportAssignment(node) { - if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); - } - else { - // An export default clause with an expression exports a value - // We want to exclude both class and function here, this is necessary to issue an error when there are both - // default export-assignment and default export function and class declaration. - var flags = node.kind === 243 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) - ? 8388608 /* Alias */ - : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); - } - } - function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); - } - if (node.parent.kind !== 265 /* SourceFile */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - } - function bindExportDeclaration(node) { - if (!container.symbol || !container.symbol.exports) { - // Export * in some sort of block construct - bindAnonymousDeclaration(node, 33554432 /* ExportStar */, getDeclarationName(node)); - } - else if (!node.exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 33554432 /* ExportStar */, 0 /* None */); - } - } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - } - } - function setCommonJsModuleIndicator(node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } - } - } - function bindExportsPropertyAssignment(node) { - // When we create a property via 'exports.foo = bar', the 'exports.foo' property access - // expression is the declaration - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */); - } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (node.kind === 71 /* Identifier */) { - var symbol = lookupSymbolForName(node.text); - if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* VariableDeclaration */) { - var declaration = symbol.valueDeclaration; - if (declaration.initializer) { - return isExportsOrModuleExportsOrAliasOrAssignemnt(declaration.initializer); - } - } - } - return false; - } - function isExportsOrModuleExportsOrAliasOrAssignemnt(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignemnt(node.left) || isExportsOrModuleExportsOrAliasOrAssignemnt(node.right))); - } - function bindModuleExportsAssignment(node) { - // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' - // is still pointing to 'module.exports'. - // We do not want to consider this as 'export=' since a module can have only one of these. - // Similarlly we do not want to treat 'module.exports = exports' as an 'export='. - var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { - // Mark it as a module in case there are no other exports in the file - setCommonJsModuleIndicator(node); - return; - } - // 'module.exports = expr' assignment - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 7340032 /* Export */ | 512 /* ValueModule */, 0 /* None */); - } - function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - switch (container.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - // Declare a 'member' if the container is an ES5 class or ES6 constructor - container.symbol.members = container.symbol.members || ts.createMap(); - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); - break; - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - // this.foo assignment in a JavaScript class - // Bind this property to the containing class - var containingClass = container.parent; - var symbol = declareSymbol(ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members, containingClass.symbol, node, 4 /* Property */, 0 /* None */); - if (symbol) { - // symbols declared through 'this' property assignements can be overwritten by subsequent method declarations - symbol.isReplaceableByMethod = true; - } - break; - } - } - function bindPrototypePropertyAssignment(node) { - // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. - // Look up the function in the local scope, since prototype assignments should - // follow the function declaration - var leftSideOfAssignment = node.left; - var classPrototype = leftSideOfAssignment.expression; - var constructorFunction = classPrototype.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.text, leftSideOfAssignment, /*isPrototypeProperty*/ true); - } - function bindStaticPropertyAssignment(node) { - // We saw a node of the form 'x.y = z'. Declare a 'member' y on x if x was a function. - // Look up the function in the local scope, since prototype assignments should - // follow the function declaration - var leftSideOfAssignment = node.left; - var target = leftSideOfAssignment.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.text, leftSideOfAssignment, /*isPrototypeProperty*/ false); - } - } - function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; - } - if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */))) { - return; - } - // Set up the members collection if it doesn't exist already - var symbolTable = isPrototypeProperty ? - (targetSymbol.members || (targetSymbol.members = ts.createMap())) : - (targetSymbol.exports || (targetSymbol.exports = ts.createMap())); - // Declare the method/property - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4 /* Property */, 0 /* PropertyExcludes */); - } - function bindCallExpression(node) { - // We're only inspecting call expressions to detect CommonJS modules, so we can skip - // this check if we've already seen the module indicator - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { - setCommonJsModuleIndicator(node); - } - } - function bindClassLikeDeclaration(node) { - if (node.kind === 229 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32 /* Class */, bindingName); - // Add name of class expression into the map for semantic classifier - if (node.name) { - classifiableNames.set(node.name.text, node.name.text); - } - } - var symbol = node.symbol; - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the - // type of which is an instantiation of the class type with type Any supplied as a type - // argument for each type parameter. It is an error to explicitly declare a static - // property member with the name 'prototype'. - // - // Note: we check for this here because this class may be merging into a module. The - // module might have an exported variable called 'prototype'. We can't allow that as - // that would clash with the built-in 'prototype' for the class. - var prototypeSymbol = createSymbol(4 /* Property */ | 16777216 /* Prototype */, "prototype"); - var symbolExport = symbol.exports.get(prototypeSymbol.name); - if (symbolExport) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports.set(prototypeSymbol.name, prototypeSymbol); - prototypeSymbol.parent = symbol; - } - function bindEnumDeclaration(node) { - return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) - : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); - } - function bindVariableDeclarationOrBindingElement(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (!ts.isBindingPattern(node.name)) { - if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration - // because its parent chain has already been set up, since parents are set before descending into children. - // - // If node is a binding element in parameter declaration, we need to use ParameterExcludes. - // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration - // For example: - // function foo([a,a]) {} // Duplicate Identifier error - // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter - // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); - } - } - } - function bindParameter(node) { - 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); - } - if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); - } - // If this is a property-parameter, then also declare the property symbol into the - // containing class. - if (ts.isParameterPropertyDeclaration(node)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - } - } - function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); - } - } - function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4 /* Property */, 0 /* PropertyExcludes */); - } - // reachability checks - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); - } - function checkUnreachable(node) { - if (!(currentFlow.flags & 1 /* Unreachable */)) { - return false; - } - if (currentFlow === unreachableFlow) { - var reportError = - // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 209 /* EmptyStatement */) || - // report error on class declarations - node.kind === 229 /* ClassDeclaration */ || - // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 233 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 232 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - } - return true; - } - } - /** - * Computes the transform flags for a node, given the transform flags of its subtree - * - * @param node The node to analyze - * @param subtreeFlags Transform flags computed for this node's subtree - */ - function computeTransformFlagsForNode(node, subtreeFlags) { - var kind = node.kind; - switch (kind) { - case 181 /* CallExpression */: - return computeCallExpression(node, subtreeFlags); - case 182 /* NewExpression */: - return computeNewExpression(node, subtreeFlags); - case 233 /* ModuleDeclaration */: - return computeModuleDeclaration(node, subtreeFlags); - case 185 /* ParenthesizedExpression */: - return computeParenthesizedExpression(node, subtreeFlags); - case 194 /* BinaryExpression */: - return computeBinaryExpression(node, subtreeFlags); - case 210 /* ExpressionStatement */: - return computeExpressionStatement(node, subtreeFlags); - case 146 /* Parameter */: - return computeParameter(node, subtreeFlags); - case 187 /* ArrowFunction */: - return computeArrowFunction(node, subtreeFlags); - case 186 /* FunctionExpression */: - return computeFunctionExpression(node, subtreeFlags); - case 228 /* FunctionDeclaration */: - return computeFunctionDeclaration(node, subtreeFlags); - case 226 /* VariableDeclaration */: - return computeVariableDeclaration(node, subtreeFlags); - case 227 /* VariableDeclarationList */: - return computeVariableDeclarationList(node, subtreeFlags); - case 208 /* VariableStatement */: - return computeVariableStatement(node, subtreeFlags); - case 222 /* LabeledStatement */: - return computeLabeledStatement(node, subtreeFlags); - case 229 /* ClassDeclaration */: - return computeClassDeclaration(node, subtreeFlags); - case 199 /* ClassExpression */: - return computeClassExpression(node, subtreeFlags); - case 259 /* HeritageClause */: - return computeHeritageClause(node, subtreeFlags); - case 260 /* CatchClause */: - return computeCatchClause(node, subtreeFlags); - case 201 /* ExpressionWithTypeArguments */: - return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152 /* Constructor */: - return computeConstructor(node, subtreeFlags); - case 149 /* PropertyDeclaration */: - return computePropertyDeclaration(node, subtreeFlags); - case 151 /* MethodDeclaration */: - return computeMethod(node, subtreeFlags); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return computeAccessor(node, subtreeFlags); - case 237 /* ImportEqualsDeclaration */: - return computeImportEquals(node, subtreeFlags); - case 179 /* PropertyAccessExpression */: - return computePropertyAccess(node, subtreeFlags); - default: - return computeOther(node, kind, subtreeFlags); - } - } - ts.computeTransformFlagsForNode = computeTransformFlagsForNode; - function computeCallExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { - // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; - } - function computeNewExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadElementExpression then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function computeBinaryExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var operatorTokenKind = node.operatorToken.kind; - var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ObjectLiteralExpression */) { - // Destructuring object assignments with are ES2015 syntax - // and possibly ESNext if they contain rest - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 177 /* ArrayLiteralExpression */) { - // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { - // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeParameter(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var name = node.name; - var initializer = node.initializer; - var dotDotDotToken = node.dotDotDotToken; - // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript - // syntax. - if (node.questionToken - || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ - || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If a parameter has an accessibility modifier, then it is TypeScript syntax. - if (modifierFlags & 92 /* ParameterPropertyModifier */) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; - } - // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a parameter has an initializer, a binding pattern or a dotDotDot token, then - // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; - } - function computeParenthesizedExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; - // If the node is synthesized, it means the emitter put the parentheses there, - // not the user. If we didn't want them, the emitter would not have put them - // there. - if (expressionKind === 202 /* AsExpression */ - || expressionKind === 184 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeClassDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2 /* Ambient */) { - // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - // An exported declaration may be TypeScript syntax, but is handled by the visitor - // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; - } - function computeClassExpression(node, subtreeFlags) { - // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; - } - function computeHeritageClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - switch (node.token) { - case 85 /* ExtendsKeyword */: - // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 108 /* ImplementsKeyword */: - // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - default: - ts.Debug.fail("Unexpected token for heritage clause"); - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeCatchClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; - } - function computeExpressionWithTypeArguments(node, subtreeFlags) { - // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the - // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // If an ExpressionWithTypeArguments contains type arguments, then it - // is TypeScript syntax. - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeConstructor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers and overloads are TypeScript syntax - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; - } - function computeMethod(node, subtreeFlags) { - // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and - // overloads are TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // An async method declaration is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; - } - function computeAccessor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // Decorators, TypeScript-specific modifiers, type annotations, and overloads are - // TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.type - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; - } - function computePropertyDeclaration(node, subtreeFlags) { - // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; - // If the PropertyDeclaration has an initializer, we need to inform its ancestor - // so that it handle the transformation. - if (node.initializer) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeFunctionDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body || (modifierFlags & 2 /* Ambient */)) { - // An ambient declaration is TypeScript syntax. - // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (modifierFlags & 2270 /* TypeScriptModifier */ - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function declaration is ES2017 syntax. - if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionDeclaration is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - // Currently we do not support transforming any other generator fucntions - // down level. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; - } - function computeFunctionExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function expression is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionExpression is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; - } - function computeArrowFunction(node, subtreeFlags) { - // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async arrow function is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; - } - // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; - } - function computePropertyAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - // If a PropertyAccessExpression starts with a super keyword, then it is - // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeVariableDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // Type annotations are TypeScript syntax. - if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeVariableStatement(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var declarationListTransformFlags = node.declarationList.transformFlags; - // An ambient declaration is TypeScript syntax. - if (modifierFlags & 2 /* Ambient */) { - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeLabeledStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ - && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeImportEquals(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // An ImportEqualsDeclaration with a namespace reference is TypeScript. - if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeExpressionStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; - var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2 /* Ambient */) === 0) { - transformFlags |= subtreeFlags; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; - } - function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. - if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; - } - function computeOther(node, kind, subtreeFlags) { - // Mark transformations needed for each node - var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; - switch (kind) { - case 120 /* AsyncKeyword */: - case 191 /* AwaitExpression */: - // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) - transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; - break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - case 203 /* NonNullExpression */: - case 131 /* ReadonlyKeyword */: - // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 252 /* JsxClosingElement */: - case 253 /* JsxAttribute */: - case 254 /* JsxAttributes */: - case 255 /* JsxSpreadAttribute */: - case 256 /* JsxExpression */: - // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; - break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 196 /* TemplateExpression */: - case 183 /* TaggedTemplateExpression */: - case 262 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 204 /* MetaProperty */: - // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 9 /* StringLiteral */: - if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 8 /* NumericLiteral */: - if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 216 /* ForOfStatement */: - // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). - if (node.awaitModifier) { - transformFlags |= 8 /* AssertESNext */; - } - transformFlags |= 192 /* AssertES2015 */; - break; - case 197 /* YieldExpression */: - // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async - // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; - break; - case 119 /* AnyKeyword */: - case 133 /* NumberKeyword */: - case 130 /* NeverKeyword */: - case 134 /* ObjectKeyword */: - case 136 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 158 /* TypePredicate */: - case 159 /* TypeReference */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 162 /* TypeQuery */: - case 163 /* TypeLiteral */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 169 /* ThisType */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 173 /* LiteralType */: - // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; - break; - case 144 /* ComputedPropertyName */: - // Even though computed property names are ES6, we don't treat them as such. - // This is so that they can flow through PropertyName transforms unaffected. - // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; - } - break; - case 198 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; - break; - case 263 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; - break; - case 97 /* SuperKeyword */: - // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 99 /* ThisKeyword */: - // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; - break; - case 174 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; - } - excludeFlags = 537396545 /* BindingPatternExcludes */; - break; - case 175 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; - break; - case 176 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; - if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; - } - break; - case 147 /* Decorator */: - // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; - break; - case 178 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { - // If an ObjectLiteralExpression contains a ComputedPropertyName, then it - // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { - // If an ObjectLiteralExpression contains a spread element, then it - // is an ES next node. - transformFlags |= 8 /* AssertESNext */; - } - break; - case 177 /* ArrayLiteralExpression */: - case 182 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 265 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 219 /* ReturnStatement */: - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~excludeFlags; - } - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - /* @internal */ - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) { - return -3 /* TypeExcludes */; - } - switch (kind) { - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 177 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; - case 233 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; - case 146 /* Parameter */: - return 536872257 /* ParameterExcludes */; - case 187 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; - case 227 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - return 539358529 /* ClassExcludes */; - case 152 /* Constructor */: - return 601015617 /* ConstructorExcludes */; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 133 /* NumberKeyword */: - case 130 /* NeverKeyword */: - case 136 /* StringKeyword */: - case 134 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; - case 178 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; - case 260 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; - default: - return 536872257 /* NodeExcludes */; - } - } - ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; -})(ts || (ts = {})); -/// -/// -var ts; -(function (ts) { - function trace(host) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - /* @internal */ - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - /** - * Kinds of file that we are currently looking for. - * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. - */ - var Extensions; - (function (Extensions) { - Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; - Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ - })(Extensions || (Extensions = {})); - /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ - function resolvedTypeScriptOnly(resolved) { - if (!resolved) { - return undefined; - } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; - } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, - failedLookupLocations: failedLookupLocations - }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); - } - return path; - } - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - if (currentDirectory !== undefined) { - return getDefaultTypeRoots(currentDirectory, host); - } - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - // And if it doesn't exist, tough. - } - var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { - var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - return undefined; - }); - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - var resolved = primaryLookup(); - var primary = true; - if (!resolved) { - resolved = secondaryLookup(); - primary = false; - } - var resolvedTypeReferenceDirective; - if (resolved) { - resolved = realpath(resolved, host, traceEnabled); - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); - } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; - } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; - function primaryLookup() { - // Check primary library paths - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - return ts.forEach(typeRoots, function (typeRoot) { - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); - if (!directoryExists && traceEnabled) { - trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); - } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); - }); - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - } - function secondaryLookup() { - var resolvedFile; - var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - return resolvedFile; - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - } - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createFileMap(); - var moduleNameToDirectoryMap = ts.createMap(); - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { - var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; - } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (!moduleHasNonRelativeName(nonRelativeModuleName)) { - return undefined; - } - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); - } - return perModuleNameCache; - } - function createPerModuleNameCache() { - var directoryPathMap = ts.createFileMap(); - return { get: get, set: set }; - function get(directory) { - return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); - } - /** - * At first this function add entry directory -> module resolution result to the table. - * Then it computes the set of parent folders for 'directory' that should have the same module resolution result - * and for every parent folder in set it adds entry: parent -> module resolution. . - * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. - * Set of parent folders that should have the same result will be: - * [ - * /a/b/c/d, /a/b/c, /a/b - * ] - * this means that request for module resolution from file in any of these folder will be immediately found in cache. - */ - function set(directory, result) { - var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); - // if entry is already in cache do nothing - if (directoryPathMap.contains(path)) { - return; - } - directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; - // find common prefix between directory and resolved file name - // this common prefix should be the shorted path that has the same resolution - // directory: /a/b/c/d/e - // resolvedFileName: /a/b/foo.d.ts - var commonPrefix = getCommonPrefix(path, resolvedFileName); - var current = path; - while (true) { - var parent = ts.getDirectoryPath(current); - if (parent === current || directoryPathMap.contains(parent)) { - break; - } - directoryPathMap.set(parent, result); - current = parent; - if (current === commonPrefix) { - break; - } - } - } - function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } - var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); - // find first position where directory and resolution differs - var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { - i++; - } - // find last directory separator before position i - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { - return undefined; - } - return directory.substr(0, sep); - } - } - } - ts.createModuleResolutionCache = createModuleResolutionCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); - var result = perFolderCache && perFolderCache.get(moduleName); - if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); - } - } - else { - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); - break; - 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); - // put result in per-module name cache - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); - } - } - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); - } - else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); - } - } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have a ".ts" extension; in contrast to an import, which should omit it. - var tsExtension = ts.tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - return path_1 && { path: path_1, extension: tsExtension }; - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - /** - * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. - * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 - * Throws an error if the module can't be resolved. - */ - /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; - 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 }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); - if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); - } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); - if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); - } - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); - } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); - // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); - } - } - } - function realpath(path, host, traceEnabled) { - if (!host.realpath) { - return path; - } - var real = ts.normalizePath(host.realpath(path)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); - } - return real; - } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); - } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { - if (!onlyRecordFailures) { - var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); - } - onlyRecordFailures = true; - } - } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); - if (resolvedFromFile) { - return resolvedFromFile; - } - } - if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); - if (!candidateExists) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); - } - onlyRecordFailures = true; - } - } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - switch (extensions) { - case Extensions.DtsOnly: - return tryExtension(".d.ts", ts.Extension.Dts); - case Extensions.TypeScript: - return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); - case Extensions.JavaScript: - return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); - } - function tryExtension(ext, extension) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; - } - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - if (state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - } - } - failedLookupLocations.push(fileName); - return undefined; - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { - if (considerPackageJson === void 0) { considerPackageJson = true; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - } - } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); - if (!file) { - return undefined; - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); - } - } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - } - /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ - function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; - } - /** True if `extension` is one of the supported `extensions`. */ - function extensionIsOk(extensions, extension) { - switch (extensions) { - case Extensions.JavaScript: - return extension === ts.Extension.Js || extension === ts.Extension.Jsx; - case Extensions.TypeScript: - return extension === ts.Extension.Ts || extension === ts.Extension.Tsx || extension === ts.Extension.Dts; - case Extensions.DtsOnly: - return extension === ts.Extension.Dts; - } - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - } - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); - } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); - } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { - if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); - if (resolutionFromCache) { - return resolutionFromCache; - } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); - } - }); - } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - if (!nodeModulesFolderExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); - } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); - if (packageResult) { - return packageResult; - } - if (extensions !== Extensions.JavaScript) { - var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); - var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); - } - nodeModulesAtTypesExists = false; - } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); - } - } - /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, "__"); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); // Take off the "@" - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; - } - } - return moduleName; - } - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { - var result = cache && cache.get(containingDirectory); - if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); - } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; - } - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var failedLookupLocations = []; - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); - function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); - if (resolvedUsingSettings) { - return { value: resolvedUsingSettings }; - } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - if (moduleHasNonRelativeName(moduleName)) { - // Climb up parent directories looking for a module. - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); - if (resolutionFromCache) { - return resolutionFromCache; - } - var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); - }); - if (resolved_3) { - return resolved_3; - } - if (extensions === Extensions.TypeScript) { - // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); - } - } - } - ts.classicNameResolver = classicNameResolver; - /** - * LSHost may load a module from a global cache of typings. - * This is the minumum code needed to expose that functionality; the rest is in LSHost. - */ - /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); - } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); - } - ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; - /** - * Wraps value to SearchResult. - * @returns undefined if value is undefined or { value } otherwise - */ - function toSearchResult(value) { - return value !== undefined ? { value: value } : undefined; - } - /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } -})(ts || (ts = {})); -/// -/// -/* @internal */ -var ts; -(function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; - var nextSymbolId = 1; - var nextNodeId = 1; - var nextMergeId = 1; - var nextFlowId = 1; - function getNodeId(node) { - if (!node.id) { - node.id = nextNodeId; - nextNodeId++; - } - return node.id; - } - ts.getNodeId = getNodeId; - function getSymbolId(symbol) { - if (!symbol.id) { - symbol.id = nextSymbolId; - nextSymbolId++; - } - return symbol.id; - } - ts.getSymbolId = getSymbolId; - function createTypeChecker(host, produceDiagnostics) { - // Cancellation that controls whether or not we can cancel in the middle of type checking. - // In general cancelling is *not* safe for the type checker. We might be in the middle of - // computing something, and we will leave our internals in an inconsistent state. Callers - // who set the cancellation token should catch if a cancellation exception occurs, and - // should throw away and create a new TypeChecker. - // - // Currently we only support setting the cancellation token when getting diagnostics. This - // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if - // they no longer need the information (for example, if the user started editing again). - var cancellationToken; - var requestedExternalEmitHelpers; - var externalHelpersModule; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var Type = ts.objectAllocator.getTypeConstructor(); - var Signature = ts.objectAllocator.getSignatureConstructor(); - var typeCount = 0; - var symbolCount = 0; - var enumCount = 0; - var symbolInstantiationDepth = 0; - var emptyArray = []; - var emptySymbols = ts.createMap(); - var compilerOptions = host.getCompilerOptions(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); - var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; - var emitResolver = createResolver(); - var nodeBuilder = createNodeBuilder(); - var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); - undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); - // for public members that accept a Node or one of its subtypes, we must guard against - // synthetic nodes created during transformations by calling `getParseTreeNode`. - // for most of these, we perform the guard only on `checker` to avoid any possible - // extra cost of calling `getParseTreeNode` when calling these functions from inside the - // checker. - var checker = { - getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCount: function () { return typeCount; }, - isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, - isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, - isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, - getMergedSymbol: getMergedSymbol, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeOfSymbolAtLocation: function (symbol, location) { - location = ts.getParseTreeNode(location); - return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; - }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); - return getSymbolsOfParameterPropertyDeclaration(parameter, parameterName); - }, - getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, - getPropertiesOfType: getPropertiesOfType, - getPropertyOfType: getPropertyOfType, - getIndexInfoOfType: getIndexInfoOfType, - getSignaturesOfType: getSignaturesOfType, - getIndexTypeOfType: getIndexTypeOfType, - getBaseTypes: getBaseTypes, - getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, - getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); - return node ? getTypeFromTypeNode(node) : unknownType; - }, - getParameterType: getTypeAtPosition, - getReturnTypeOfSignature: getReturnTypeOfSignature, - getNonNullableType: getNonNullableType, - typeToTypeNode: nodeBuilder.typeToTypeNode, - indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, - signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, - getSymbolsInScope: function (location, meaning) { - location = ts.getParseTreeNode(location); - return location ? getSymbolsInScope(location, meaning) : []; - }, - getSymbolAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getSymbolAtLocation(node) : undefined; - }, - getShorthandAssignmentValueSymbol: function (node) { - node = ts.getParseTreeNode(node); - return node ? getShorthandAssignmentValueSymbol(node) : undefined; - }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); - return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; - }, - getTypeAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getTypeOfNode(node) : unknownType; - }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); - return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; - }, - signatureToString: function (signature, enclosingDeclaration, flags, kind) { - return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); - }, - typeToString: function (type, enclosingDeclaration, flags) { - return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); - }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); - }, - getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, - getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); - return node ? getContextualType(node) : undefined; - }, - getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); - return node ? getResolvedSignature(node, candidatesOutArray) : undefined; - }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, propertyName) : false; - }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); - return declaration ? getSignatureFromDeclaration(declaration) : undefined; - }, - isImplementationOfOverload: function (node) { - node = ts.getParseTreeNode(node, ts.isFunctionLike); - return node ? isImplementationOfOverload(node) : undefined; - }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - return links.immediateTarget; - }, - getAliasedSymbol: resolveAlias, - getEmitResolver: getEmitResolver, - getExportsOfModule: getExportsOfModuleAsArray, - getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); - return node ? isOptionalParameter(node) : false; - }, - tryGetMemberInModuleExports: tryGetMemberInModuleExports, - tryFindAmbientModuleWithoutAugmentations: function (moduleName) { - // we deliberately exclude augmentations - // since we are only interested in declarations of the module itself - return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); - }, - getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, - getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, - getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, - getBaseConstraintOfType: getBaseConstraintOfType, - }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var literalTypes = ts.createMap(); - var indexedAccessTypes = ts.createMap(); - var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4 /* Property */, "unknown"); - var resolvingSymbol = createSymbol(0, "__resolving__"); - var anyType = createIntrinsicType(1 /* Any */, "any"); - var autoType = createIntrinsicType(1 /* Any */, "any"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); - var stringType = createIntrinsicType(2 /* String */, "string"); - var numberType = createIntrinsicType(4 /* Number */, "number"); - var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); - var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(1024 /* Void */, "void"); - var neverType = createIntrinsicType(8192 /* Never */, "never"); - var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); - var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); - emptyTypeLiteralSymbol.members = ts.createMap(); - var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); - var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated - // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; - var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); - var globals = ts.createMap(); - /** - * List of every ambient module with a "*" wildcard. - * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. - * This is only used if there is no exact match. - */ - var patternAmbientModules; - var globalObjectType; - var globalFunctionType; - var globalArrayType; - var globalReadonlyArrayType; - var globalStringType; - var globalNumberType; - var globalBooleanType; - var globalRegExpType; - var globalThisType; - var anyArrayType; - var autoArrayType; - var anyReadonlyArrayType; - // The library files are only loaded when the feature is used. - // This allows users to just specify library files they want to used through --lib - // and they will not get an error from not having unrelated library files - var deferredGlobalESSymbolConstructorSymbol; - var deferredGlobalESSymbolType; - var deferredGlobalTypedPropertyDescriptorType; - var deferredGlobalPromiseType; - var deferredGlobalPromiseConstructorSymbol; - var deferredGlobalPromiseConstructorLikeType; - var deferredGlobalIterableType; - var deferredGlobalIteratorType; - var deferredGlobalIterableIteratorType; - var deferredGlobalAsyncIterableType; - var deferredGlobalAsyncIteratorType; - var deferredGlobalAsyncIterableIteratorType; - var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; - var deferredNodes; - var deferredUnusedIdentifierNodes; - var flowLoopStart = 0; - var flowLoopCount = 0; - var visitedFlowCount = 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 = []; - var flowLoopCaches = []; - var flowLoopNodes = []; - var flowLoopKeys = []; - var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; - var potentialThisCollisions = []; - 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"; - // The following members encode facts about particular kinds of types for use in the getTypeFacts function. - // The presence of a particular fact means that the given test is true for some (and possibly all) values - // of that kind of type. - 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 /* TypeofEQString */, - "number": 2 /* TypeofEQNumber */, - "boolean": 4 /* TypeofEQBoolean */, - "symbol": 8 /* TypeofEQSymbol */, - "undefined": 16384 /* EQUndefined */, - "object": 16 /* TypeofEQObject */, - "function": 32 /* TypeofEQFunction */ - }); - var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128 /* TypeofNEString */, - "number": 256 /* TypeofNENumber */, - "boolean": 512 /* TypeofNEBoolean */, - "symbol": 1024 /* TypeofNESymbol */, - "undefined": 131072 /* NEUndefined */, - "object": 2048 /* TypeofNEObject */, - "function": 4096 /* TypeofNEFunction */ - }); - var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType - }); - var typeofType = createTypeofType(); - var _jsxNamespace; - var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - /** Things we lazy load from the JSX namespace */ - var jsxTypes = ts.createMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - var identityRelation = ts.createMap(); - var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - 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(); - return checker; - function getJsxNamespace() { - if (!_jsxNamespace) { - _jsxNamespace = "React"; - if (compilerOptions.jsxFactory) { - _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); - if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; - } - } - else if (compilerOptions.reactNamespace) { - _jsxNamespace = compilerOptions.reactNamespace; - } - } - return _jsxNamespace; - } - function getEmitResolver(sourceFile, cancellationToken) { - // Ensure we have all the type information in place for this file so that all the - // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); - return emitResolver; - } - function error(location, message, arg0, arg1, arg2) { - var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); - diagnostics.add(diagnostic); - } - function createSymbol(flags, name) { - symbolCount++; - var symbol = (new Symbol(flags | 134217728 /* Transient */, name)); - symbol.checkFlags = 0; - return symbol; - } - function isTransientSymbol(symbol) { - return (symbol.flags & 134217728 /* Transient */) !== 0; - } - function getExcludedSymbolFlags(flags) { - var result = 0; - if (flags & 2 /* BlockScopedVariable */) - result |= 107455 /* BlockScopedVariableExcludes */; - if (flags & 1 /* FunctionScopedVariable */) - result |= 107454 /* FunctionScopedVariableExcludes */; - if (flags & 4 /* Property */) - result |= 0 /* PropertyExcludes */; - if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; - if (flags & 16 /* Function */) - result |= 106927 /* FunctionExcludes */; - if (flags & 32 /* Class */) - result |= 899519 /* ClassExcludes */; - if (flags & 64 /* Interface */) - result |= 792968 /* InterfaceExcludes */; - if (flags & 256 /* RegularEnum */) - result |= 899327 /* RegularEnumExcludes */; - if (flags & 128 /* ConstEnum */) - result |= 899967 /* ConstEnumExcludes */; - if (flags & 512 /* ValueModule */) - result |= 106639 /* ValueModuleExcludes */; - if (flags & 8192 /* Method */) - result |= 99263 /* MethodExcludes */; - if (flags & 32768 /* GetAccessor */) - result |= 41919 /* GetAccessorExcludes */; - if (flags & 65536 /* SetAccessor */) - result |= 74687 /* SetAccessorExcludes */; - if (flags & 262144 /* TypeParameter */) - result |= 530920 /* TypeParameterExcludes */; - if (flags & 524288 /* TypeAlias */) - result |= 793064 /* TypeAliasExcludes */; - if (flags & 8388608 /* Alias */) - result |= 8388608 /* AliasExcludes */; - return result; - } - function recordMergedSymbol(target, source) { - if (!source.mergeId) { - source.mergeId = nextMergeId; - nextMergeId++; - } - mergedSymbols[source.mergeId] = target; - } - function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags, symbol.name); - result.declarations = symbol.declarations.slice(0); - result.parent = symbol.parent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = ts.cloneMap(symbol.members); - if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); - recordMergedSymbol(result, symbol); - return result; - } - function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { - if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { - // reset flag when merging instantiated module into value module that has only const enums - target.constEnumOnlyModule = false; - } - target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 233 /* ModuleDeclaration */))) { - // other kinds of value declarations take precedence over modules - target.valueDeclaration = source.valueDeclaration; - } - ts.addRange(target.declarations, source.declarations); - if (source.members) { - if (!target.members) - target.members = ts.createMap(); - mergeSymbolTable(target.members, source.members); - } - if (source.exports) { - if (!target.exports) - target.exports = ts.createMap(); - mergeSymbolTable(target.exports, source.exports); - } - recordMergedSymbol(target, source); - } - else if (target.flags & 1024 /* NamespaceModule */) { - 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - } - } - function mergeSymbolTable(target, source) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - } - else { - if (!(targetSymbol.flags & 134217728 /* Transient */)) { - targetSymbol = cloneSymbol(targetSymbol); - target.set(id, targetSymbol); - } - mergeSymbol(targetSymbol, sourceSymbol); - } - }); - } - function mergeModuleAugmentation(moduleName) { - var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { - // this is a combined symbol for multiple augmentations within the same file. - // its symbol already has accumulated information for all declarations - // so we need to add it just once - do the work only for first declaration - ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); - return; - } - if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports); - } - else { - // find a module that about to be augmented - // do not validate names of augmentations that are defined in ambient context - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) - ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found - : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); - if (!mainModule) { - return; - } - // obtain item referenced by 'export=' - mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920 /* Namespace */) { - // if module symbol has already been merged - it is safe to use it. - // otherwise clone it - mainModule = mainModule.flags & 134217728 /* Transient */ ? mainModule : cloneSymbol(mainModule); - mergeSymbol(mainModule, moduleAugmentation.symbol); - } - else { - error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); - } - } - } - function addToSymbolTable(target, source, message) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (targetSymbol) { - // Error on redeclarations - ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(id, message)); - } - else { - target.set(id, sourceSymbol); - } - }); - function addDeclarationDiagnostic(id, message) { - return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; - } - } - function getSymbolLinks(symbol) { - if (symbol.flags & 134217728 /* Transient */) - return symbol; - var id = getSymbolId(symbol); - return symbolLinks[id] || (symbolLinks[id] = {}); - } - function getNodeLinks(node) { - var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); - } - function getObjectFlags(type) { - return type.flags & 32768 /* Object */ ? type.objectFlags : 0; - } - function isGlobalSourceFile(node) { - return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); - } - function getSymbol(symbols, name, meaning) { - if (meaning) { - var symbol = symbols.get(name); - if (symbol) { - ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608 /* Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } - } - } - // return undefined if we can't find a symbol. - } - /** - * Get symbols that represent parameter-property-declaration as parameter and as property declaration - * @param parameter a parameterDeclaration node - * @param parameterName a name of the parameter to get the symbols for. - * @return a tuple of two symbols - */ - function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { - var constructorDeclaration = parameter.parent; - var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); - if (parameterSymbol && propertySymbol) { - return [parameterSymbol, propertySymbol]; - } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); - } - function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { - var declarationFile = ts.getSourceFileOfNode(declaration); - var useFile = ts.getSourceFileOfNode(usage); - if (declarationFile !== useFile) { - if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out) || - ts.isInAmbientContext(declaration)) { - // nodes are in different files and order cannot be determined - return true; - } - // declaration is after usage - // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) - if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - return true; - } - var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); - } - if (declaration.pos <= usage.pos) { - // declaration is before usage - if (declaration.kind === 176 /* BindingElement */) { - // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 176 /* BindingElement */); - if (errorBindingElement) { - return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || - declaration.pos < errorBindingElement.pos; - } - // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226 /* VariableDeclaration */), usage); - } - else if (declaration.kind === 226 /* VariableDeclaration */) { - // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) - return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); - } - return true; - } - // declaration is after usage, but it can still be legal if usage is deferred: - // 1. inside an export specifier - // 2. inside a function - // 3. inside an instance property initializer, a reference to a non-instance property - // 4. inside a static property initializer, a reference to a static method in the same class - // or if usage is in a type context: - // 1. inside a type query (typeof in type position) - if (usage.parent.kind === 246 /* ExportSpecifier */) { - // export specifiers do not use the variable, they only make it available for use - return true; - } - var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); - function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); - switch (declaration.parent.parent.kind) { - case 208 /* VariableStatement */: - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: - // variable statement/for/for-of statement case, - // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { - return true; - } - break; - } - switch (declaration.parent.parent.kind) { - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - // ForIn/ForOf case - use site should not be used in expression part - if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { - return true; - } - } - return false; - } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { - return !!ts.findAncestor(usage, function (current) { - if (current === container) { - return "quit"; - } - if (ts.isFunctionLike(current)) { - return true; - } - var initializerOfProperty = current.parent && - current.parent.kind === 149 /* PropertyDeclaration */ && - current.parent.initializer === current; - if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32 /* Static */) { - if (declaration.kind === 151 /* MethodDeclaration */) { - return true; - } - } - else { - var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !(ts.getModifierFlags(declaration) & 32 /* Static */); - if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { - return true; - } - } - } - }); - } - } - // 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, 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; - var errorLocation = location; - var grandparent; - var isInExternalModule = false; - 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 = lookup(location.locals, name, meaning)) { - var useResult = true; - if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - // symbol lookup restrictions for function-like declarations - // - Type parameters of a function are in scope in the entire function declaration, including the parameter - // list and return type. However, local types are only in scope in the function body. - // - parameters are only in the scope of function body - // This restriction does not apply to JSDoc comment types because they are parented - // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) { - useResult = result.flags & 262144 /* TypeParameter */ - ? lastLocation === location.type || - lastLocation.kind === 146 /* Parameter */ || - lastLocation.kind === 145 /* TypeParameter */ - : false; - } - if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 146 /* Parameter */ || - (lastLocation === location.type && - result.valueDeclaration.kind === 146 /* Parameter */); - } - } - if (useResult) { - break loop; - } - else { - result = undefined; - } - } - } - switch (location.kind) { - case 265 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) - break; - isInExternalModule = true; - // falls through - case 233 /* ModuleDeclaration */: - var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 /* SourceFile */ || ts.isAmbientModule(location)) { - // It's an external module. First see if the module has an export default and if the local - // name of that export default matches. - if (result = moduleExports.get("default")) { - var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { - break loop; - } - result = undefined; - } - // Because of module/namespace merging, a module's exports are in scope, - // yet we never want to treat an export specifier as putting a member in scope. - // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. - // Two things to note about this: - // 1. We have to check this without calling getSymbol. The problem with calling getSymbol - // on an export specifier is that it might find the export specifier itself, and try to - // resolve it as an alias. This will cause the checker to consider the export specifier - // a circular alias reference when it might not be. - // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* - // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, - // which is not the desired behavior. - var moduleExport = moduleExports.get(name); - if (moduleExport && - moduleExport.flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 246 /* ExportSpecifier */)) { - break; - } - } - if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { - break loop; - } - break; - case 232 /* EnumDeclaration */: - if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { - break loop; - } - break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - // TypeScript 1.0 spec (April 2014): 8.4.1 - // Initializer expressions for instance member variables are evaluated in the scope - // of the class constructor body but are not permitted to reference parameters or - // local variables of the constructor. This effectively means that entities from outer scopes - // by the same name as a constructor parameter or local variable are inaccessible - // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { - var ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { - // Remember the property node, it will be used later to report appropriate error - propertyWithInvalidInitializer = location; - } - } - } - break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { - if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { - // ignore type parameters not declared in this container - result = undefined; - break; - } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // The scope of a type parameter extends over the entire declaration with which the type - // parameter list is associated, with the exception of static member declarations in classes. - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); - return undefined; - } - break loop; - } - if (location.kind === 199 /* ClassExpression */ && meaning & 32 /* Class */) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; - // It is not legal to reference a class's own type parameters from a computed property name that - // belongs to the class. For example: - // - // function foo() { return '' } - // class C { // <-- Class's own type parameter T - // [foo()]() { } // <-- Reference to T from class's own computed property - // } - // - case 144 /* ComputedPropertyName */: - 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 = 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; - } - } - break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - if (meaning & 3 /* Variable */ && name === "arguments") { - result = argumentsSymbol; - break loop; - } - break; - case 186 /* FunctionExpression */: - if (meaning & 3 /* Variable */ && name === "arguments") { - result = argumentsSymbol; - break loop; - } - if (meaning & 16 /* Function */) { - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; - } - } - break; - case 147 /* Decorator */: - // Decorators are resolved at the class declaration. Resolving at the parameter - // or member would result in looking up locals in the method. - // - // function y() {} - // class C { - // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. - // } - // - if (location.parent && location.parent.kind === 146 /* Parameter */) { - location = location.parent; - } - // - // function y() {} - // class C { - // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. - // } - // - if (location.parent && ts.isClassElement(location.parent)) { - location = location.parent; - } - break; - } - lastLocation = location; - location = location.parent; - } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { - result.isReferenced = true; - } - if (!result) { - result = lookup(globals, name, meaning); - } - if (!result) { - if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation) && - !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && - !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - 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; - } - // Perform extra checks only if error reporting was requested - if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return undefined; - } - // Only check for block-scoped variable if we are looking for the - // name with variable meaning - // For example, - // declare module foo { - // interface bar {} - // } - // const foo/*1*/: foo/*2*/.bar; - // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: - // block-scoped variable and namespace module. However, only when we - // try to resolve name in /*1*/ which is used in variable position, - // we want to check for block-scoped - if (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */)) { - var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); - if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { - checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); - } - } - // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); - } - } - } - return result; - } - function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 145 /* TypeParameter */ && decl.parent === container) { - return true; - } - } - return false; - } - function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 71 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { - return false; - } - var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true); - var location = container; - while (location) { - if (ts.isClassLike(location.parent)) { - var classSymbol = getSymbolOfNode(location.parent); - if (!classSymbol) { - break; - } - // Check to see if a static member exists. - var constructorType = getTypeOfSymbol(classSymbol); - if (getPropertyOfType(constructorType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); - return true; - } - // No static member is present. - // Check if we're in an instance method and look for a relevant instance member. - if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; - if (getPropertyOfType(instanceType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return true; - } - } - } - location = location.parent; - } - return false; - } - function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { - error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - } - return isError; - } - /** - * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, - * but returns undefined if that expression is not an EntityNameExpression. - */ - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201 /* ExpressionWithTypeArguments */: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } - } - function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); - return true; - } - } - return false; - } - 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); - return true; - } - } - return false; - } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, name); - return true; - } - } - else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, name); - return true; - } - } - return false; - } - function checkResolvedBlockScopedVariable(result, errorLocation) { - ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); - // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232 /* EnumDeclaration */) ? d : undefined; }); - 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(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 256 /* RegularEnum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - } - } - /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. - * If at any point current node is equal to 'parent' node - return true. - * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. - */ - function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); - } - function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); - } - } - function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); - } - function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { - return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); - } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); - } - function getTargetOfImportClause(node, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); - if (moduleSymbol) { - var exportDefaultSymbol = void 0; - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - exportDefaultSymbol = moduleSymbol; - } - else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); - } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { - return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - return exportDefaultSymbol; - } - } - function getTargetOfNamespaceImport(node, dontResolveAlias) { - var moduleSpecifier = node.parent.parent.moduleSpecifier; - return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); - } - // This function creates a synthetic symbol that combines the value side of one symbol with the - // type/namespace side of another symbol. Consider this example: - // - // declare module graphics { - // interface Point { - // x: number; - // y: number; - // } - // } - // declare var graphics: { - // Point: new (x: number, y: number) => graphics.Point; - // } - // declare module "graphics" { - // export = graphics; - // } - // - // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' - // property with the type/namespace side interface 'Point'. - function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { - return valueSymbol; - } - var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); - result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); - result.parent = valueSymbol.parent || typeSymbol.parent; - if (valueSymbol.valueDeclaration) - result.valueDeclaration = valueSymbol.valueDeclaration; - if (typeSymbol.members) - result.members = typeSymbol.members; - if (valueSymbol.exports) - result.exports = valueSymbol.exports; - return result; - } - function getExportOfModule(symbol, name, dontResolveAlias) { - if (symbol.flags & 1536 /* Module */) { - return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); - } - } - function getPropertyOfVariable(symbol, name) { - if (symbol.flags & 3 /* Variable */) { - var typeAnnotation = symbol.valueDeclaration.type; - if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); - } - } - } - function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); - if (targetSymbol) { - var name = specifier.propertyName || specifier.name; - if (name.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return moduleSymbol; - } - var symbolFromVariable = void 0; - // First check if module was specified with "export=". If so, get the member from the resolved type - if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text); - } - else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); - } - // if symbolFromVariable is export - get its final target - symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name.text, dontResolveAlias); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - var symbol = symbolFromModule && symbolFromVariable ? - combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : - symbolFromModule || symbolFromVariable; - if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); - } - return symbol; - } - } - } - function getTargetOfImportSpecifier(node, dontResolveAlias) { - return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); - } - function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { - return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); - } - function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node, 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); - } - function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { - switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: - return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239 /* ImportClause */: - return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240 /* NamespaceImport */: - return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242 /* ImportSpecifier */: - return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 243 /* ExportAssignment */: - return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236 /* NamespaceExportDeclaration */: - return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - } - } - function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */)); - return shouldResolve ? resolveAlias(symbol) : symbol; - } - function resolveAlias(symbol) { - ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.target) { - links.target = resolvingSymbol; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - var target = getTargetOfAliasDeclaration(node); - if (links.target === resolvingSymbol) { - links.target = target || unknownSymbol; - } - else { - error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); - } - } - else if (links.target === resolvingSymbol) { - links.target = unknownSymbol; - } - return links.target; - } - function markExportAsReferenced(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target) { - var markAlias = target === unknownSymbol || - ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); - if (markAlias) { - markAliasSymbolAsReferenced(symbol); - } - } - } - // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until - // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of - // the alias as an expression (which recursively takes us back here if the target references another alias). - function markAliasSymbolAsReferenced(symbol) { - var links = getSymbolLinks(symbol); - if (!links.referenced) { - links.referenced = true; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - if (node.kind === 243 /* ExportAssignment */) { - // export default - checkExpressionCached(node.expression); - } - else if (node.kind === 246 /* ExportSpecifier */) { - // export { } or export { as foo } - checkExpressionCached(node.propertyName || node.name); - } - else if (ts.isInternalModuleImportEqualsDeclaration(node)) { - // import foo = - checkExpressionCached(node.moduleReference); - } - } - } - // This function is only for imports with entity names - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - // There are three things we might try to look for. In the following examples, - // the search term is enclosed in |...|: - // - // import a = |b|; // Namespace - // import a = |b.c|; // Value, type, namespace - // import a = |b.c|.d; // Namespace - if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 143 /* QualifiedName */) { - return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); - } - else { - // Case 2 in above example - // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 237 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); - } - } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); - } - /** - * Resolves a qualified name and any involved aliases. - */ - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { - if (ts.nodeIsMissing(name)) { - return undefined; - } - var symbol; - if (name.kind === 71 /* Identifier */) { - var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); - if (!symbol) { - return undefined; - } - } - else if (name.kind === 143 /* QualifiedName */ || name.kind === 179 /* PropertyAccessExpression */) { - var left = void 0; - if (name.kind === 143 /* QualifiedName */) { - left = name.left; - } - else if (name.kind === 179 /* PropertyAccessExpression */ && - (name.expression.kind === 185 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { - left = name.expression; - } - else { - // If the expression in property-access expression is not entity-name or parenthsizedExpression (e.g. it is a call expression), it won't be able to successfully resolve the name. - // This is the case when we are trying to do any language service operation in heritage clauses. By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression - // will attempt to checkPropertyAccessExpression to resolve symbol. - // i.e class C extends foo()./*do language service operation here*/B {} - return undefined; - } - var right = name.kind === 143 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); - if (!namespace || ts.nodeIsMissing(right)) { - return undefined; - } - else if (namespace === unknownSymbol) { - return namespace; - } - symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); - if (!symbol) { - if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); - } - return undefined; - } - } - else if (name.kind === 185 /* ParenthesizedExpression */) { - // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name. - // This is the case when we are trying to do any language service operation in heritage clauses. - // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol. - // i.e class C extends foo()./*do language service operation here*/B {} - return ts.isEntityNameExpression(name.expression) ? - resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : - undefined; - } - else { - ts.Debug.fail("Unknown entity name kind."); - } - 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) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); - } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - if (moduleReferenceExpression.kind !== 9 /* StringLiteral */ && moduleReferenceExpression.kind !== 13 /* NoSubstitutionTemplateLiteral */) { - return; - } - var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); - } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - // Module names are escaped in our symbol table. However, string literal values aren't. - // Escape the name in the "require(...)" clause to ensure we find the right symbol. - var moduleName = ts.escapeIdentifier(moduleReference); - 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; - } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); - var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); - if (sourceFile) { - if (sourceFile.symbol) { - // merged symbol is module declaration symbol combined with all augmentations - return getMergedSymbol(sourceFile.symbol); - } - if (moduleNotFoundError) { - // report errors only if it was requested - error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - } - return undefined; - } - if (patternAmbientModules) { - var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleName); - if (pattern) { - return getMergedSymbol(pattern.symbol); - } - } - // May be an untyped module. If so, ignore resolutionDiagnostic. - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { - if (isForAugmentation) { - var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); - } - else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. - return undefined; - } - if (moduleNotFoundError) { - // report errors only if it was requested - if (resolutionDiagnostic) { - error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); - } - else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(errorNode, moduleNotFoundError, moduleName); - } - } - } - return undefined; - } - // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, - // and an external module with no 'export =' declaration resolves to the module itself. - function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; - } - // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' - // 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, moduleReferenceExpression, dontResolveAlias) { - 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)); - } - return symbol; - } - function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; - } - function getExportsOfModuleAsArray(moduleSymbol) { - return symbolsToArray(getExportsOfModule(moduleSymbol)); - } - function getExportsAndPropertiesOfModule(moduleSymbol) { - var exports = getExportsOfModuleAsArray(moduleSymbol); - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); - } - return exports; - } - function tryGetMemberInModuleExports(memberName, moduleSymbol) { - var symbolTable = getExportsOfModule(moduleSymbol); - if (symbolTable) { - return symbolTable.get(memberName); - } - } - function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; - } - function getExportsOfModule(moduleSymbol) { - var links = getSymbolLinks(moduleSymbol); - return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); - } - /** - * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument - * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables - */ - function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { - if (id === "default") - return; - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - if (lookupTable && exportNode) { - lookupTable.set(id, { - specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) - }); - } - } - else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { - var collisionTracker = lookupTable.get(id); - if (!collisionTracker.exportsWithDuplicate) { - collisionTracker.exportsWithDuplicate = [exportNode]; - } - else { - collisionTracker.exportsWithDuplicate.push(exportNode); - } - } - }); - } - function getExportsForModule(moduleSymbol) { - var visitedSymbols = []; - // A module defined by an 'export=' consists on one export that needs to be resolved - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - return visit(moduleSymbol) || moduleSymbol.exports; - // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, - // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. - function visit(symbol) { - if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { - return; - } - visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); - // All export * declarations are collected in an __export symbol by the binder - var exportStars = symbol.exports.get("__export"); - if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable_1 = ts.createMap(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); - } - lookupTable_1.forEach(function (_a, id) { - var exportsWithDuplicate = _a.exportsWithDuplicate; - // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { - return; - } - for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { - var node = exportsWithDuplicate_1[_i]; - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, id)); - } - }); - extendExportSymbols(symbols, nestedSymbols); - } - return symbols; - } - } - function getMergedSymbol(symbol) { - var merged; - return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; - } - function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); - } - function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); - } - function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; - } - function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 8388608 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); - } - function findConstructorDeclaration(node) { - var members = node.members; - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var member = members_1[_i]; - if (member.kind === 152 /* Constructor */ && ts.nodeIsPresent(member.body)) { - return member; - } - } - } - function createType(flags) { - var result = new Type(checker, flags); - typeCount++; - result.id = typeCount; - return result; - } - function createIntrinsicType(kind, intrinsicName) { - var type = createType(kind); - type.intrinsicName = intrinsicName; - return type; - } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8 /* Boolean */; - type.intrinsicName = "boolean"; - return type; - } - function createObjectType(objectFlags, symbol) { - var type = createType(32768 /* Object */); - type.objectFlags = objectFlags; - type.symbol = symbol; - return type; - } - function createTypeofType() { - 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 - // with at least two underscores. The @ character indicates that the name is denoted by a well known ES - // Symbol instance. - function isReservedMemberName(name) { - return name.charCodeAt(0) === 95 /* _ */ && - name.charCodeAt(1) === 95 /* _ */ && - name.charCodeAt(2) !== 95 /* _ */ && - name.charCodeAt(2) !== 64 /* at */; - } - function getNamedMembers(members) { - var result; - members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } - } - }); - return result || emptyArray; - } - function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; - return type; - } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function forEachSymbolTableInScope(enclosingDeclaration, callback) { - var result; - for (var location = enclosingDeclaration; location; location = location.parent) { - // 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 = callback(location.locals)) { - return result; - } - } - switch (location.kind) { - case 265 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - // falls through - case 233 /* ModuleDeclaration */: - if (result = callback(getSymbolOfNode(location).exports)) { - return result; - } - break; - } - } - return callback(globals); - } - function getQualifiedLeftMeaning(rightMeaning) { - // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; - } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); - } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { - return undefined; - } - visitedSymbolTables.push(symbols); - var result = trySymbolTable(symbols); - visitedSymbolTables.pop(); - return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolFromSymbolTable or alias resolution matches the symbol, - // check the symbol can be qualified, it is only then this symbol is accessible - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } - } - function trySymbolTable(symbols) { - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.name))) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 /* Alias */ - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } - } - }); - } - } - if (symbol) { - if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - } - } - } - function needsQualification(symbol, enclosingDeclaration, meaning) { - var qualify = false; - forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.name); - if (!symbolFromSymbolTable) { - // Continue to the next symbol table - return false; - } - // If the symbol with this name is present it should refer to the symbol - if (symbolFromSymbolTable === symbol) { - // No need to qualify - return true; - } - // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { - qualify = true; - return true; - } - // Continue to the next symbol table - return false; - }); - return qualify; - } - function isPropertyOrMethodDeclarationSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - continue; - default: - return false; - } - } - return true; - } - return false; - } - /** - * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested - * - * @param symbol a Symbol to check if accessible - * @param enclosingDeclaration a Node containing reference to the symbol - * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible - * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible - */ - function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); - } - // This could be a symbol that is not exported in the external module - // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); - if (symbolExternalModule) { - var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); - if (symbolExternalModule !== enclosingExternalModule) { - // name from different external module that is not visible - return { - accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) - }; - } - } - // Just a local name that is not accessible - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - }; - } - return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } - } - function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); - } - function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { - var aliasesToMakeVisible; - if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { - return undefined; - } - return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; - function getIsDeclarationVisible(declaration) { - if (!isDeclarationVisible(declaration)) { - // Mark the unexported alias as visible if its parent is visible - // because these kind of aliases can be used to name types in declaration file - var anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && - isDeclarationVisible(anyImportSyntax.parent)) { - // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, - // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time - // since we will do the emitting later in trackSymbol. - if (shouldComputeAliasToMakeVisible) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } - } - return true; - } - // Declaration is not visible - return false; - } - return true; - } - } - function isEntityNameVisible(entityName, enclosingDeclaration) { - // get symbol of the first identifier of the entityName - var meaning; - if (entityName.parent.kind === 162 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - // Typeof value - meaning = 107455 /* Value */ | 1048576 /* ExportValue */; - } - else if (entityName.kind === 143 /* QualifiedName */ || entityName.kind === 179 /* PropertyAccessExpression */ || - entityName.parent.kind === 237 /* ImportEqualsDeclaration */) { - // Left identifier from type reference or TypeAlias - // Entity name of the import declaration - meaning = 1920 /* Namespace */; - } - else { - // Type Reference or TypeAlias entity = Identifier - meaning = 793064 /* Type */; - } - var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); - // Verify if the symbol is accessible - return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { - accessibility: 1 /* NotAccessible */, - errorSymbolName: ts.getTextOfNode(firstIdentifier), - errorNode: firstIdentifier - }; - } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function typeToString(type, enclosingDeclaration, flags) { - 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) { - 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() { - return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - 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) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - } - }; - function createNodeBuilderContext(enclosingDeclaration, flags) { - return { - enclosingDeclaration: enclosingDeclaration, - flags: flags, - encounteredError: false, - symbolStack: undefined - }; - } - function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; - if (!type) { - context.encounteredError = true; - return undefined; - } - if (type.flags & 1 /* Any */) { - return ts.createKeywordTypeNode(119 /* AnyKeyword */); - } - if (type.flags & 2 /* String */) { - return ts.createKeywordTypeNode(136 /* StringKeyword */); - } - if (type.flags & 4 /* Number */) { - return ts.createKeywordTypeNode(133 /* NumberKeyword */); - } - if (type.flags & 8 /* Boolean */) { - return ts.createKeywordTypeNode(122 /* BooleanKeyword */); - } - 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.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); - } - if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.value))); - } - if (type.flags & 128 /* BooleanLiteral */) { - return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); - } - if (type.flags & 1024 /* Void */) { - return ts.createKeywordTypeNode(105 /* VoidKeyword */); - } - if (type.flags & 2048 /* Undefined */) { - return ts.createKeywordTypeNode(139 /* UndefinedKeyword */); - } - if (type.flags & 4096 /* Null */) { - return ts.createKeywordTypeNode(95 /* NullKeyword */); - } - if (type.flags & 8192 /* Never */) { - return ts.createKeywordTypeNode(130 /* NeverKeyword */); - } - if (type.flags & 512 /* ESSymbol */) { - return ts.createKeywordTypeNode(137 /* SymbolKeyword */); - } - if (type.flags & 16777216 /* NonPrimitive */) { - return ts.createKeywordTypeNode(134 /* ObjectKeyword */); - } - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { - context.encounteredError = true; - } - } - return ts.createThis(); - } - var objectFlags = getObjectFlags(type); - if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - return typeReferenceToTypeNode(type); - } - 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 (!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); - } - 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)) { - context.encounteredError = true; - } - return undefined; - } - } - if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - // The type is an object literal type. - return createAnonymousTypeNode(type); - } - if (type.flags & 262144 /* Index */) { - var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType, context); - return ts.createTypeOperatorNode(indexTypeNode); - } - if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); - var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); - return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); - } - ts.Debug.fail("Should be unreachable."); - function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; - var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - 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; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || - shouldWriteTypeOfFunctionSymbol()) { - 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, context, 793064 /* Type */, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); - } - else { - return ts.createKeywordTypeNode(119 /* AnyKeyword */); - } - } - 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 - if (!context.symbolStack) { - context.symbolStack = []; - } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; - } - } - else { - // Anonymous types without a symbol are never circular. - return createTypeNodeFromObjectType(type); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - return createMappedTypeNodeFromType(type); - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); - return signatureNode; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); - return signatureNode; - } - } - var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; - var members = createTypeNodesFromResolvedType(resolved); - context.flags = savedFlags; - var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); - } - 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) { - 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - return ts.createTupleTypeNode(tupleConstituentNodes); - } - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { - context.encounteredError = true; - } - return undefined; - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - var qualifiedName = void 0; - if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - // 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 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 { - qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); - } - } - } - } - var entityName = undefined; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } - 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 */, context)); - } - for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); - } - if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); - } - if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); - } - var properties = resolvedType.properties; - if (!properties) { - return typeElements; - } - for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { - var propertySymbol = properties_2[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); - 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 */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - typeElements.push(methodDeclaration); - } - } - else { - 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 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 indexingParameter = ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, name, - /*questionToken*/ undefined, indexerTypeNode, - /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); - return ts.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : 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 /* 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, context); - } - 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, context) { - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); - var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); - } - 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); - 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, 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 || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { - chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); - ts.Debug.assert(chain && chain.length > 0); - } - else { - chain = [symbol]; - } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(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 typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - 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. */ - function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); - var parentSymbol; - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); - } - } - } - if (accessibleSymbolChain) { - return accessibleSymbolChain; - } - if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || - // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - return [symbol]; - } - } - } - 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; - } - } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144 /* Nullable */)) { - if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - 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); - } - } - if (flags & 4096 /* Null */) - result.push(nullType); - if (flags & 2048 /* Undefined */) - result.push(undefinedType); - return result || types; - } - function visibilityToString(flags) { - if (flags === 8 /* Private */) { - return "private"; - } - if (flags === 16 /* Protected */) { - return "protected"; - } - return "public"; - } - function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168 /* ParenthesizedType */; }); - if (node.kind === 231 /* TypeAliasDeclaration */) { - return getSymbolOfNode(node); - } - } - return undefined; - } - function isTopLevelInExternalModuleAugmentation(node) { - return node && node.parent && - node.parent.kind === 234 /* ModuleBlock */ && - ts.isExternalModuleAugmentation(node.parent.parent); - } - function literalTypeToString(type) { - 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]; - 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); - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } - } - return symbol.name; - } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - writePunctuation(writer, 21 /* OpenBracketToken */); - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); - } - } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || - // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 128 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & 16 /* WriteOwnNameForAnyLike */; - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~512 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 16793231 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - 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 & (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); - } - else if (!(flags & 512 /* InTypeAlias */) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 262144 /* Index */) { - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 64 /* InElementType */); - } - else if (type.flags & 524288 /* IndexedAccess */) { - writeType(type.objectType, 64 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 64 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 256 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 64 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - 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 - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - // 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)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 65536 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); - } - else if (ts.contains(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 - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - 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 - if (!symbolStack) { - symbolStack = []; - } - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 2 /* UseTypeOfFunction */) || - (ts.contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 67108864 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 64 /* InElementType */) { - return true; - } - else if (flags & 256 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - writeMappedType(type); - return; - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048 /* Undefined */); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 176 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 256 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 2048 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 8 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } - function isDeclarationVisible(node) { - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } - return false; - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 176 /* BindingElement */: - return isDeclarationVisible(node.parent.parent); - case 226 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - // If the binding pattern is empty, this variable declaration is not visible - return false; - } - // falls through - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 228 /* FunctionDeclaration */: - case 232 /* EnumDeclaration */: - case 237 /* ImportEqualsDeclaration */: - // external module augmentation is always visible - if (ts.isExternalModuleAugmentation(node)) { - return true; - } - var parent = getDeclarationContainer(node); - // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 237 /* ImportEqualsDeclaration */ && parent.kind !== 265 /* SourceFile */ && ts.isInAmbientContext(parent))) { - return isGlobalSourceFile(parent); - } - // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { - // Private/protected properties/methods are not visible - return false; - } - // Public properties/methods are visible if its parents are visible, so: - // falls through - case 152 /* Constructor */: - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 157 /* IndexSignature */: - case 146 /* Parameter */: - case 234 /* ModuleBlock */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 159 /* TypeReference */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - return isDeclarationVisible(node.parent); - // Default binding, import specifier and namespace import is visible - // only on demand so by default it is not visible - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - return false; - // Type parameters are always visible - case 145 /* TypeParameter */: - // Source file and namespace export are always visible - case 265 /* SourceFile */: - case 236 /* NamespaceExportDeclaration */: - return true; - // Export assignments do not create name bindings outside the module - case 243 /* ExportAssignment */: - return false; - default: - return false; - } - } - } - function collectLinkedAliases(node) { - var exportSymbol; - if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { - 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 */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); - } - var result = []; - if (exportSymbol) { - buildVisibleNodeList(exportSymbol.declarations); - } - return result; - function buildVisibleNodeList(declarations) { - ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; - var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } - if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { - // Add the referenced top container visible - var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); - if (importSymbol) { - buildVisibleNodeList(importSymbol.declarations); - } - } - }); - } - } - /** - * Push an entry on the type resolution stack. If an entry with the given target and the given property name - * is already on the stack, and no entries in between already have a type, then a circularity has occurred. - * In this case, the result values of the existing entry and all entries pushed after it are changed to false, - * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. - * In order to see if the same query has already been done before, the target object and the propertyName both - * must match the one passed in. - * - * @param target The symbol, type, or signature whose type is being queried - * @param propertyName The property name that should be used to query the target for its type - */ - function pushTypeResolution(target, propertyName) { - var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); - if (resolutionCycleStartIndex >= 0) { - // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { - resolutionResults[i] = false; - } - return false; - } - resolutionTargets.push(target); - resolutionResults.push(/*items*/ true); - resolutionPropertyNames.push(propertyName); - return true; - } - function findResolutionCycleStartIndex(target, propertyName) { - for (var i = resolutionTargets.length - 1; i >= 0; i--) { - if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { - return -1; - } - if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { - return i; - } - } - return -1; - } - function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return getSymbolLinks(target).type; - } - if (propertyName === 2 /* DeclaredType */) { - return getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return target.resolvedReturnType; - } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); - } - // Pop an entry from the type resolution stack and return its associated result value. The result value will - // be true if no circularities were detected, or false if a circularity was found. - function popTypeResolution() { - resolutionTargets.pop(); - resolutionPropertyNames.pop(); - return resolutionResults.pop(); - } - function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { - switch (node.kind) { - case 226 /* VariableDeclaration */: - case 227 /* VariableDeclarationList */: - case 242 /* ImportSpecifier */: - case 241 /* NamedImports */: - case 240 /* NamespaceImport */: - case 239 /* ImportClause */: - return false; - default: - return true; - } - }); - return node && node.parent; - } - function getTypeOfPrototypeProperty(prototype) { - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', - // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. - // It is an error to explicitly declare a static property member with the name 'prototype'. - var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); - return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; - } - // Return the type of the given property in the given type, or undefined if no such property exists - function getTypeOfPropertyOfType(type, name) { - var prop = getPropertyOfType(type, name); - return prop ? getTypeOfSymbol(prop) : undefined; - } - function isTypeAny(type) { - return type && (type.flags & 1 /* Any */) !== 0; - } - // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been - // assigned by contextual typing. - function getTypeForBindingElementParent(node) { - var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); - } - function isComputedNonLiteralName(name) { - return name.kind === 144 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); - } - function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (source.flags & 8192 /* Never */) { - return emptyObjectType; - } - if (source.flags & 65536 /* Union */) { - return mapType(source, function (t) { return getRestType(t, properties, symbol); }); - } - var members = ts.createMap(); - var names = ts.createMap(); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var name = properties_3[_i]; - names.set(ts.getTextOfPropertyName(name), true); - } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - var inNamesToRemove = names.has(prop.name); - 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); - } - } - var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); - var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); - return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - /** Return the inferred type for a binding element */ - function getTypeForBindingElement(declaration) { - var pattern = declaration.parent; - var parentType = getTypeForBindingElementParent(pattern.parent); - // If parent has the unknown (error) type, then so does this binding element - if (parentType === unknownType) { - return unknownType; - } - // If no type was specified or inferred for parent, or if the specified or inferred type is any, - // infer from the initializer of the binding element if one is present. Otherwise, go with the - // undefined or any type of the parent. - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } - return parentType; - } - var type; - if (pattern.kind === 174 /* ObjectBindingPattern */) { - if (declaration.dotDotDotToken) { - if (!isValidSpreadType(parentType)) { - error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); - return unknownType; - } - var literalMembers = []; - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!element.dotDotDotToken) { - literalMembers.push(element.propertyName || element.name); - } - } - type = getRestType(parentType, literalMembers, declaration.symbol); - } - else { - // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - // computed properties with non-literal names are treated as 'any' - return anyType; - } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, - // or otherwise the type of the string index signature. - var text = ts.getTextOfPropertyName(name); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return unknownType; - } - } - } - else { - // This elementType will be used if the specific property corresponding to this index is not - // present (aka the tuple element property). This call also checks that the parentType is in - // fact an iterable or array (depending on target language). - var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterable*/ false); - if (declaration.dotDotDotToken) { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); - } - else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); - } - return unknownType; - } - } - } - // In strict null checking mode, if a default value of a non-undefined type is specified, remove - // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { - type = getTypeWithFacts(type, 131072 /* NEUndefined */); - } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : - type; - } - function getTypeForDeclarationFromJSDocComment(declaration) { - var jsdocType = ts.getJSDocType(declaration); - if (jsdocType) { - return getTypeFromTypeNode(jsdocType); - } - return undefined; - } - function isNullOrUndefined(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; - } - function isEmptyArrayLiteral(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; - } - function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; - } - // Return the inferred type for a variable, parameter, or property declaration - function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 65536 /* JavaScriptFile */) { - // If this is a variable in a JavaScript file, then use the JSDoc type (if it has - // one as its type), otherwise fallback to the below standard TS codepaths to - // try to figure it out. - var type = getTypeForDeclarationFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - // A variable declared in a for..in statement is of type string, or of type keyof T when the - // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === 215 /* ForInStatement */) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; - } - if (declaration.parent.parent.kind === 216 /* ForOfStatement */) { - // checkRightHandSideOfForOf will return undefined if the for-of expression type was - // missing properties/signatures required to get its iteratedType (like - // [Symbol.iterator] or next). This may be because we accessed properties from anyType, - // or it may have led to an error inside getElementTypeOfIterable. - var forOfStatement = declaration.parent.parent; - return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; - } - if (ts.isBindingPattern(declaration.parent)) { - return getTypeForBindingElement(declaration); - } - // Use type from type annotation if one is present - if (declaration.type) { - var declaredType = getTypeFromTypeNode(declaration.type); - return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); - } - if ((noImplicitAny || declaration.flags & 65536 /* JavaScriptFile */) && - declaration.kind === 226 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { - // If --noImplicitAny is on or the declaration is in a Javascript file, - // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no - // initializer or a 'null' or 'undefined' initializer. - if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { - return autoType; - } - // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array - // literal initializer. - if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { - return autoArrayType; - } - } - if (declaration.kind === 146 /* Parameter */) { - var func = declaration.parent; - // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 154 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153 /* GetAccessor */); - if (getter) { - var getterSignature = getSignatureFromDeclaration(getter); - var thisParameter = getAccessorThisParameter(func); - if (thisParameter && declaration === thisParameter) { - // Use the type from the *getter* - ts.Debug.assert(!thisParameter.type); - return getTypeOfSymbol(getterSignature.thisParameter); - } - return getReturnTypeOfSignature(getterSignature); - } - } - // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.name === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } - if (type) { - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); - } - } - // Use the type of the initializer expression if one is present - if (declaration.initializer) { - var type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); - } - if (ts.isJsxAttribute(declaration)) { - // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. - // I.e is sugar for - return trueType; - } - // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 262 /* ShorthandPropertyAssignment */) { - return checkIdentifier(declaration.name); - } - // If the declaration specifies a binding pattern, use the type implied by the binding pattern - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); - } - // No type specified and nothing can be inferred - return undefined; - } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { - 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 : - declaration.kind === 179 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 194 /* BinaryExpression */) : - undefined; - if (!expression) { - return unknownType; - } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 152 /* Constructor */) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - // 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)); - } - } - else if (!jsDocType) { - // If we don't have an explicit JSDoc type, get the type from the expression. - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); - } - } - 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 - // pattern. Otherwise, it is the type any. - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { - if (element.initializer) { - return checkDeclarationInitializer(element); - } - if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); - } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); - } - return anyType; - } - // Return the type implied by an object binding pattern - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); - var stringIndexInfo; - var hasComputedProperties = false; - ts.forEach(pattern.elements, function (e) { - var name = e.propertyName || e.name; - if (isComputedNonLiteralName(name)) { - // do not include computed properties in the implied type - hasComputedProperties = true; - return; - } - if (e.dotDotDotToken) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); - return; - } - var text = ts.getTextOfPropertyName(name); - var flags = 4 /* Property */ | (e.initializer ? 67108864 /* Optional */ : 0); - var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); - symbol.bindingElement = e; - members.set(symbol.name, symbol); - }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); - if (includePatternInType) { - result.pattern = pattern; - } - if (hasComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } - return result; - } - // Return the type implied by an array binding pattern - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { - var elements = pattern.elements; - var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; - } - // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); - if (includePatternInType) { - result = cloneTypeReference(result); - result.pattern = pattern; - } - return result; - } - // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself - // and without regard to its context (i.e. without regard any type annotation or initializer associated with the - // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] - // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is - // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring - // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of - // the parameter. - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 /* ObjectBindingPattern */ - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); - } - // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type - // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it - // is a bit more involved. For example: - // - // var [x, s = ""] = [1, "one"]; - // - // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the - // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the - // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. - function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); - if (type) { - if (reportErrors) { - reportErrorsFromWidening(declaration, type); - } - // During a normal type check we'll never get to here with a property assignment (the check of the containing - // object literal uses a different path). We exclude widening only so that language services and type verification - // tools see the actual type. - if (declaration.kind === 261 /* PropertyAssignment */) { - return type; - } - return getWidenedType(type); - } - // Rest parameters default to type any[], other parameters default to type any - type = declaration.dotDotDotToken ? anyArrayType : anyType; - // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { - if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); - } - } - return type; - } - function declarationBelongsToPrivateAmbientMember(declaration) { - var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 /* Parameter */ ? root.parent : root; - return isPrivateWithinAmbient(memberDeclaration); - } - function getTypeOfVariableOrParameterOrProperty(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - // Handle prototype property - if (symbol.flags & 16777216 /* Prototype */) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - // Handle catch clause variables - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - // Handle export default expressions - if (declaration.kind === 243 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); - } - if (declaration.flags & 65536 /* JavaScriptFile */ && declaration.kind === 291 /* JSDocPropertyTag */ && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } - // Handle variable, parameter or property - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; - } - var type = void 0; - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - if (declaration.kind === 194 /* BinaryExpression */ || - declaration.kind === 179 /* PropertyAccessExpression */ && declaration.parent.kind === 194 /* BinaryExpression */) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; - } - function getAnnotatedAccessorType(accessor) { - if (accessor) { - if (accessor.kind === 153 /* GetAccessor */) { - return accessor.type && getTypeFromTypeNode(accessor.type); - } - else { - var setterTypeAnnotation = ts.getSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); - } - } - return undefined; - } - function getAnnotatedAccessorThisParameter(accessor) { - var parameter = getAccessorThisParameter(accessor); - return parameter && parameter.symbol; - } - function getThisTypeOfDeclaration(declaration) { - return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); - } - function getTypeOfAccessors(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 154 /* SetAccessor */); - if (getter && getter.flags & 65536 /* JavaScriptFile */) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; - } - var type = void 0; - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; - } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; - } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - type = anyType; - } - } - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); - error(getter_1, 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, symbolToString(symbol)); - } - } - links.type = type; - } - return links.type; - } - function getBaseTypeVariableOfClass(symbol) { - var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 /* TypeVariable */ ? baseConstructorType : undefined; - } - function getTypeOfFuncClassEnumModule(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else { - var type = createObjectType(16 /* Anonymous */, symbol); - if (symbol.flags & 32 /* Class */) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; - } - else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; - } - } - } - return links.type; - } - function getTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; - } - function getTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var targetSymbol = resolveAlias(symbol); - // It only makes sense to get the type of a value symbol. If the result of resolving - // the alias is not a value, then it has no type. To get the type associated with a - // type symbol, call getDeclaredTypeOfSymbol. - // This check is important because without it, a call to getTypeOfSymbol could end - // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 107455 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : unknownType; - } - return links.type; - } - function getTypeOfInstantiatedSymbol(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = unknownType; - } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - } - return links.type; - } - function reportCircularityError(symbol) { - // Check if variable has type annotation that circularly references the variable itself - if (symbol.valueDeclaration.type) { - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - return unknownType; - } - // Otherwise variable has initializer that circularly references the variable itself - if (noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - return anyType; - } - function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - return getTypeOfInstantiatedSymbol(symbol); - } - if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { - return getTypeOfVariableOrParameterOrProperty(symbol); - } - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); - } - if (symbol.flags & 8 /* EnumMember */) { - return getTypeOfEnumMember(symbol); - } - if (symbol.flags & 98304 /* Accessor */) { - return getTypeOfAccessors(symbol); - } - if (symbol.flags & 8388608 /* Alias */) { - return getTypeOfAlias(symbol); - } - return unknownType; - } - function isReferenceToType(type, target) { - return type !== undefined - && target !== undefined - && (getObjectFlags(type) & 4 /* Reference */) !== 0 - && type.target === target; - } - function getTargetType(type) { - return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; - } - function hasBaseType(type, checkBase) { - return check(type); - function check(type) { - if (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { - var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); - } - else if (type.flags & 131072 /* Intersection */) { - return ts.forEach(type.types, check); - } - } - } - // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. - // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set - // in-place and returns the same array. - function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } - } - return typeParameters; - } - // Appends the outer type parameters of a node to a set of type parameters and returns the resulting set. The function - // allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set in-place and - // returns the same array. - function appendOuterTypeParameters(typeParameters, node) { - while (true) { - node = node.parent; - if (!node) { - return typeParameters; - } - if (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || - node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */ || node.kind === 187 /* ArrowFunction */) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } - } - } - } - // The outer type parameters are those defined by enclosing generic classes, methods, or functions. - function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); - return appendOuterTypeParameters(/*typeParameters*/ undefined, declaration); - } - // The local type parameters are the combined set of type parameters from all declarations of the class, - // interface, or type alias. - function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { - var result; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 229 /* ClassDeclaration */ || - node.kind === 199 /* ClassExpression */ || node.kind === 231 /* TypeAliasDeclaration */) { - var declaration = node; - if (declaration.typeParameters) { - result = appendTypeParameters(result, declaration.typeParameters); - } - } - } - return result; - } - // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus - // its locally declared type parameters. - function getTypeParametersOfClassOrInterface(symbol) { - return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); - } - // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single - // rest parameter of type any[]. - function isMixinConstructorType(type) { - var signatures = getSignaturesOfType(type, 1 /* Construct */); - if (signatures.length === 1) { - var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; - } - return false; - } - function isConstructorType(type) { - if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { - return true; - } - if (type.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); - } - return false; - } - function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); - } - function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); - } - function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; - } - /** - * The base constructor of a class can resolve to - * * undefinedType if the class has no extends clause, - * * unknownType if an error occurred during resolution of the extends expression, - * * nullType if the extends expression is the null value, - * * anyType if the extends expression has type any, or - * * an object type with at least one construct signature. - */ - function getBaseConstructorTypeOfClass(type) { - if (!type.resolvedBaseConstructorType) { - var baseTypeNode = getBaseTypeNodeOfClass(type); - if (!baseTypeNode) { - return type.resolvedBaseConstructorType = undefinedType; - } - if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { - return unknownType; - } - var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */)) { - // Resolving the members of a class requires us to resolve the base class of that class. - // We force resolution here such that we catch circularities now. - resolveStructuredTypeMembers(baseConstructorType); - } - if (!popTypeResolution()) { - error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = unknownType; - } - if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); - return type.resolvedBaseConstructorType = unknownType; - } - type.resolvedBaseConstructorType = baseConstructorType; - } - return type.resolvedBaseConstructorType; - } - function getBaseTypes(type) { - if (!type.resolvedBaseTypes) { - if (type.objectFlags & 8 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - if (type.symbol.flags & 32 /* Class */) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64 /* Interface */) { - resolveBaseTypesOfInterface(type); - } - } - else { - ts.Debug.fail("type must be class or interface"); - } - } - return type.resolvedBaseTypes; - } - function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { - 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 */ && - areAllOuterTypeParametersApplied(originalBaseType)) { - // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the - // 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, typeArgs); - } - else if (baseConstructorType.flags & 1 /* Any */) { - baseType = baseConstructorType; - } - else { - // The class derives from a "class-like" constructor function, check that we have at least one construct signature - // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere - // we check that all instantiated signatures return the same type. - var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); - if (!constructors.length) { - error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; - } - baseType = getReturnTypeOfSignature(constructors[0]); - } - // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } - if (baseType === unknownType) { - return; - } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; - } - if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); - return; - } - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - function areAllOuterTypeParametersApplied(type) { - // An unapplied type parameter has its symbol still the same as the matching argument symbol. - // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. - var outerTypeParameters = type.outerTypeParameters; - if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; - var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; - } - return true; - } - // A valid base type is `any`, any non-generic object type or intersection of non-generic - // object types. - function isValidBaseType(type) { - return type.flags & (32768 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 131072 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); - } - function resolveBaseTypesOfInterface(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); - } - } - else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); - } - } - } - } - } - } - // Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is - // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, - // and if none of the base interfaces have a "this" type. - function isIndependentInterface(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */) { - if (declaration.flags & 64 /* ContainsThis */) { - return false; - } - var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); - if (baseTypeNodes) { - for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { - var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); - if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { - return false; - } - } - } - } - } - } - return true; - } - function getDeclaredTypeOfClassOrInterface(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; - var type = links.declaredType = createObjectType(kind, symbol); - var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); - var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type - // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, - // property types inferred from initializers and method return types inferred from return statements are very hard - // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of - // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { - type.objectFlags |= 4 /* Reference */; - type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); - type.outerTypeParameters = outerTypeParameters; - type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); - type.thisType.isThisType = true; - type.thisType.symbol = symbol; - type.thisType.constraint = type; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - // Note that we use the links object as the target here because the symbol object is used as the unique - // identity for resolution of the 'type' property in SymbolLinks. - if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { - return unknownType; - } - var declaration = ts.getDeclarationOfKind(symbol, 290 /* JSDocTypedefTag */); - var type = void 0; - if (declaration) { - if (declaration.jsDocTypeLiteral) { - type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); - } - else { - type = getTypeFromTypeNode(declaration.typeExpression.type); - } - } - else { - declaration = ts.getDeclarationOfKind(symbol, 231 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type); - } - if (popTypeResolution()) { - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (typeParameters) { - // Initialize the instantiation cache for generic type aliases. The declared type corresponds to - // an instantiation of the type alias with the type parameters supplied as type arguments. - links.typeParameters = typeParameters; - links.instantiations = ts.createMap(); - links.instantiations.set(getTypeListId(typeParameters), type); - } - } - else { - type = unknownType; - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); - } - links.declaredType = type; - } - return links.declaredType; - } - function isLiteralEnumMember(member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - 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 */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); - } - 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 (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { - return links.enumKind = 1 /* Literal */; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; - } - } - } - } - return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; - } - 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) { - 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); - } - } - } - 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; - } - } - 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)); - if (!links.declaredType) { - links.declaredType = enumType; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeParameter(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(16384 /* TypeParameter */); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; - } - function getDeclaredTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; - } - function getDeclaredTypeOfSymbol(symbol) { - if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getDeclaredTypeOfClassOrInterface(symbol); - } - if (symbol.flags & 524288 /* TypeAlias */) { - return getDeclaredTypeOfTypeAlias(symbol); - } - if (symbol.flags & 262144 /* TypeParameter */) { - return getDeclaredTypeOfTypeParameter(symbol); - } - if (symbol.flags & 384 /* Enum */) { - return getDeclaredTypeOfEnum(symbol); - } - if (symbol.flags & 8 /* EnumMember */) { - return getDeclaredTypeOfEnumMember(symbol); - } - if (symbol.flags & 8388608 /* Alias */) { - return getDeclaredTypeOfAlias(symbol); - } - return unknownType; - } - // A type reference is considered independent if each type argument is considered independent. - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; - } - // A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string - // literal type, an array with an element type that is considered independent, or a type reference that is - // considered independent. - function isIndependentType(node) { - switch (node.kind) { - case 119 /* AnyKeyword */: - case 136 /* StringKeyword */: - case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 134 /* ObjectKeyword */: - case 105 /* VoidKeyword */: - case 139 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 130 /* NeverKeyword */: - case 173 /* LiteralType */: - return true; - case 164 /* ArrayType */: - return isIndependentType(node.elementType); - case 159 /* TypeReference */: - return isIndependentTypeReference(node); - } - return false; - } - // A variable-like declaration is considered independent (free of this references) if it has a type annotation - // that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any). - function isIndependentVariableLikeDeclaration(node) { - return node.type && isIndependentType(node.type) || !node.type && !node.initializer; - } - // A function-like declaration is considered independent (free of this references) if it has a return type - // annotation that is considered independent and if each parameter is considered independent. - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { - return false; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; - } - // Returns true if the class or interface member given by the symbol is free of "this" references. The - // function may return false for symbols that are actually free of "this" references because it is not - // feasible to perform a complete analysis in all cases. In particular, property members with types - // inferred from their initializers and function members with inferred return types are conservatively - // assumed not to be free of "this" references. - function isIndependentMember(symbol) { - if (symbol.declarations && symbol.declarations.length === 1) { - var declaration = symbol.declarations[0]; - if (declaration) { - switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return isIndependentVariableLikeDeclaration(declaration); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - return isIndependentFunctionLikeDeclaration(declaration); - } - } - } - return false; - } - function createSymbolTable(symbols) { - var result = ts.createMap(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - result.set(symbol.name, symbol); - } - return result; - } - // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, - // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. - function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; - result.set(symbol.name, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); - } - return result; - } - function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { - var s = baseSymbols_1[_i]; - if (!symbols.has(s.name)) { - symbols.set(s.name, s); - } - } - } - function resolveDeclaredMembers(type) { - if (!type.declaredProperties) { - var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); - type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); - type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); - } - return type; - } - function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4 /* Reference */) { - var target = type.target; - var typeArguments = type.typeArguments; - if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); - } - } - else if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); - } - return type; - } - function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { - mapper = createTypeMapper(typeParameters, typeArguments); - members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); - callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); - constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); - stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); - numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); - } - var baseTypes = getBaseTypes(source); - if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { - members = createSymbolTable(source.declaredProperties); - } - var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { - var baseType = baseTypes_1[_i]; - var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; - addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); - constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); - if (!stringIndexInfo) { - stringIndexInfo = instantiatedBaseType === anyType ? - createIndexInfo(anyType, /*isReadonly*/ false) : - getIndexInfoOfType(instantiatedBaseType, 0 /* String */); - } - numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); - } - } - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveClassOrInterfaceMembers(type) { - resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); - } - function resolveTypeReferenceMembers(type) { - var source = resolveDeclaredMembers(type.target); - var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); - var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? - type.typeArguments : ts.concatenate(type.typeArguments, [type]); - resolveObjectTypeMembers(type, source, typeParameters, typeArguments); - } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); - sig.declaration = declaration; - sig.typeParameters = typeParameters; - sig.parameters = parameters; - sig.thisParameter = thisParameter; - sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; - sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; - return sig; - } - function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); - } - function getDefaultConstructSignatures(classType) { - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); - if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; - } - var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); - var typeArgCount = ts.length(typeArguments); - var result = []; - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var baseSig = baseSignatures_1[_i]; - var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); - var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); - sig.typeParameters = classType.localTypeParameters; - sig.resolvedReturnType = classType; - result.push(sig); - } - } - return result; - } - function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { - for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { - var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { - return s; - } - } - } - function findMatchingSignatures(signatureLists, signature, listIndex) { - if (signature.typeParameters) { - // We require an exact match for generic signatures, so we only return signatures from the first - // signature list and only if they have exact matches in the other signature lists. - if (listIndex > 0) { - return undefined; - } - for (var i = 1; i < signatureLists.length; i++) { - if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { - return undefined; - } - } - return [signature]; - } - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - // Allow matching non-generic signatures to have excess parameters and different return types - var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); - if (!match) { - return undefined; - } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } - } - return result; - } - // The signatures of a union type are those signatures that are present in each of the constituent types. - // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional - // parameters and may differ in return types. When signatures differ in return types, the resulting return - // type is the union of the constituent return types. - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { - var signature = _a[_i]; - // Only process signatures with parameter lists that aren't already in the result list - if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { - var unionSignatures = findMatchingSignatures(signatureLists, signature, i); - if (unionSignatures) { - var s = signature; - // Union the result types when more than one signature matches - if (unionSignatures.length > 1) { - s = cloneSignature(signature); - if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); - } - // Clear resolved return type we possibly got from cloneSignature - s.resolvedReturnType = undefined; - s.unionSignatures = unionSignatures; - } - (result || (result = [])).push(s); - } - } - } - } - return result || emptyArray; - } - function getUnionIndexInfo(types, kind) { - var indexTypes = []; - var isAnyReadonly = false; - 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; - } - indexTypes.push(indexInfo.type); - isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; - } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); - } - function resolveUnionTypeMembers(type) { - // The members and properties collections are empty for union types. To get all properties of a union - // type use getPropertiesOfType (only the language service uses this). - var callSignatures = getUnionSignatures(type.types, 0 /* Call */); - var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); - var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); - var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function intersectTypes(type1, type2) { - return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); - } - function intersectIndexInfos(info1, info2) { - return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); - } - function unionSpreadIndexInfos(info1, info2) { - return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); - } - function includeMixinType(type, types, index) { - var mixedTypes = []; - for (var i = 0; i < types.length; i++) { - if (i === index) { - mixedTypes.push(type); - } - else if (isMixinConstructorType(types[i])) { - mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); - } - } - return getIntersectionType(mixedTypes); - } - function resolveIntersectionTypeMembers(type) { - // The members and properties collections are empty for intersection types. To get all properties of an - // intersection type use getPropertiesOfType (only the language service uses this). - var callSignatures = emptyArray; - var constructSignatures = emptyArray; - var stringIndexInfo; - var numberIndexInfo; - var types = type.types; - var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_3 = function (i) { - var t = type.types[i]; - // When an intersection type contains mixin constructor types, the construct signatures from - // those types are discarded and their return types are mixed into the return types of all - // other construct signatures in the intersection type. For example, the intersection type - // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature - // 'new(s: string) => A & B'. - if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { - var signatures = getSignaturesOfType(t, 1 /* Construct */); - if (signatures.length && mixinCount > 0) { - signatures = ts.map(signatures, function (s) { - var clone = cloneSignature(s); - clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); - return clone; - }); - } - constructSignatures = ts.concatenate(constructSignatures, signatures); - } - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); - stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); - numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); - }; - for (var i = 0; i < types.length; i++) { - _loop_3(i); - } - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - /** - * Converts an AnonymousType to a ResolvedType. - */ - function resolveAnonymousTypeMembers(type) { - var symbol = type.symbol; - if (type.target) { - var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); - var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); - var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); - var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else if (symbol.flags & 2048 /* TypeLiteral */) { - var members = symbol.members; - var callSignatures = getSignaturesOfSymbol(members.get("__call")); - var constructSignatures = getSignaturesOfSymbol(members.get("__new")); - var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); - var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else { - // Combinations of function, class, enum and module - var members = emptySymbols; - var constructSignatures = emptyArray; - var stringIndexInfo = undefined; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - } - if (symbol.flags & 32 /* Class */) { - var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { - members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); - } - else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); - } - } - var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); - // We resolve the members before computing the signatures because a signature may use - // typeof with a qualified name expression that circularly references the type we are - // in the process of resolving (see issue #6072). The temporarily empty signature list - // will never be observed because a qualified name can't reference signatures. - if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { - type.callSignatures = getSignaturesOfSymbol(symbol); - } - } - } - /** Resolve the members of a mapped type { [P in K]: T } */ - function resolveMappedTypeMembers(type) { - var members = ts.createMap(); - var stringIndexInfo; - // Resolve upfront such that recursive references see an empty object type. - setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); - // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, - // and T as the template type. - var typeParameter = getTypeParameterFromMappedType(type); - var constraintType = getConstraintTypeFromMappedType(type); - var templateType = getTemplateTypeFromMappedType(type); - var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' - var templateReadonly = !!type.declaration.readonlyToken; - var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170 /* TypeOperator */) { - // We have a { [P in keyof T]: X } - for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { - var propertySymbol = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); - } - if (getIndexInfoOfType(modifiersType, 0 /* String */)) { - addMemberForKeyType(stringType); - } - } - else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; - forEachType(iterationType, addMemberForKeyType); - } - setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { - // Create a mapper from T to the current iteration type constituent. Then, if the - // mapped type is itself an instantiated type, combine the iteration mapper with the - // instantiation mapper. - var iterationMapper = createTypeMapper([typeParameter], [t]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; - var propType = instantiateType(templateType, templateMapper); - // 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.value; - var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); - var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; - prop.type = propType; - if (propertySymbol) { - prop.syntheticOrigin = propertySymbol; - } - members.set(propName, prop); - } - else if (t.flags & 2 /* String */) { - stringIndexInfo = createIndexInfo(propType, templateReadonly); - } - } - } - function getTypeParameterFromMappedType(type) { - return type.typeParameter || - (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); - } - function getConstraintTypeFromMappedType(type) { - return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); - } - function getTemplateTypeFromMappedType(type) { - return type.templateType || - (type.templateType = type.declaration.type ? - instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : - unknownType); - } - function getModifiersTypeFromMappedType(type) { - if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170 /* TypeOperator */) { - // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check - // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves - // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); - } - else { - // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, - // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', - // the modifiers type is T. Otherwise, the modifiers type is {}. - var declaredType = getTypeFromMappedTypeNode(type.declaration); - var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; - } - } - return type.modifiersType; - } - function isGenericMappedType(type) { - if (getObjectFlags(type) & 32 /* Mapped */) { - var constraintType = getConstraintTypeFromMappedType(type); - return maybeTypeOfKind(constraintType, 540672 /* TypeVariable */ | 262144 /* Index */); - } - return false; - } - function resolveStructuredTypeMembers(type) { - if (!type.members) { - if (type.flags & 32768 /* Object */) { - if (type.objectFlags & 4 /* Reference */) { - resolveTypeReferenceMembers(type); - } - else if (type.objectFlags & 3 /* ClassOrInterface */) { - resolveClassOrInterfaceMembers(type); - } - else if (type.objectFlags & 16 /* Anonymous */) { - resolveAnonymousTypeMembers(type); - } - else if (type.objectFlags & 32 /* Mapped */) { - resolveMappedTypeMembers(type); - } - } - else if (type.flags & 65536 /* Union */) { - resolveUnionTypeMembers(type); - } - else if (type.flags & 131072 /* Intersection */) { - resolveIntersectionTypeMembers(type); - } - } - return type; - } - /** Return properties of an object type or an empty array for other types */ - function getPropertiesOfObjectType(type) { - if (type.flags & 32768 /* Object */) { - return resolveStructuredTypeMembers(type).properties; - } - return emptyArray; - } - /** If the given type is an object type and that type has a property by the given name, - * return the symbol for that property. Otherwise return undefined. - */ - function getPropertyOfObjectType(type, name) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - } - } - function getPropertiesOfUnionOrIntersectionType(type) { - if (!type.resolvedProperties) { - var members = ts.createMap(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var current = _a[_i]; - for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { - var prop = _c[_b]; - if (!members.has(prop.name)) { - var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.name); - if (combinedProp) { - members.set(prop.name, combinedProp); - } - } - } - // The properties of a union type are those that are present in all constituent types, so - // we only need to check the properties of the first type - if (type.flags & 65536 /* Union */) { - break; - } - } - type.resolvedProperties = getNamedMembers(members); - } - return type.resolvedProperties; - } - function getPropertiesOfType(type) { - type = getApparentType(type); - return type.flags & 196608 /* UnionOrIntersection */ ? - 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) : - getBaseConstraintOfType(type); - } - function getConstraintOfTypeParameter(typeParameter) { - return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; - } - function getConstraintOfIndexedAccess(type) { - var baseObjectType = getBaseConstraintOfType(type.objectType); - var baseIndexType = getBaseConstraintOfType(type.indexType); - return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; - } - function getBaseConstraintOfType(type) { - if (type.flags & (540672 /* TypeVariable */ | 196608 /* UnionOrIntersection */)) { - var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } - } - else if (type.flags & 262144 /* Index */) { - return stringType; - } - return undefined; - } - function hasNonCircularBaseConstraint(type) { - return getResolvedBaseConstraint(type) !== circularConstraintType; - } - /** - * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the - * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint - * circularly references the type variable. - */ - function getResolvedBaseConstraint(type) { - var typeStack; - var circular; - if (!type.resolvedBaseConstraint) { - typeStack = []; - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); - } - return type.resolvedBaseConstraint; - function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { - circular = true; - return undefined; - } - typeStack.push(t); - var result = computeBaseConstraint(t); - typeStack.pop(); - return result; - } - function computeBaseConstraint(t) { - if (t.flags & 16384 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; - } - if (t.flags & 196608 /* UnionOrIntersection */) { - var types = t.types; - var baseTypes = []; - 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); - } - } - return t.flags & 65536 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : - undefined; - } - if (t.flags & 262144 /* Index */) { - return stringType; - } - if (t.flags & 524288 /* IndexedAccess */) { - var baseObjectType = getBaseConstraint(t.objectType); - var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; - return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; - } - return t; - } - } - function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); - } - /** - * Gets the default type for a type parameter. - * - * If the type parameter is the result of an instantiation, this gets the instantiated - * default type of its target. If the type parameter has no default type, `undefined` - * is returned. - * - * This function *does not* perform a circularity check. - */ - function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameter(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; - } - /** - * For a type parameter, return the base constraint of the type parameter. For the string, number, - * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. - */ - function getApparentType(type) { - var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 84 /* NumberLike */ ? globalNumberType : - t.flags & 136 /* BooleanLike */ ? globalBooleanType : - t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t; - } - function createUnionOrIntersectionProperty(containingType, name) { - var props; - var types = containingType.types; - var isUnion = containingType.flags & 65536 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; - // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; - var syntheticFlag = 4 /* SyntheticMethod */; - var checkFlags = 0; - 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { - commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } - checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | - (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | - (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | - (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | - (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); - if (!isMethodLike(prop)) { - syntheticFlag = 2 /* SyntheticProperty */; - } - } - else if (isUnion) { - checkFlags |= 16 /* Partial */; - } - } - } - if (!props) { - return undefined; - } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { - return props[0]; - } - var propTypes = []; - var declarations = []; - var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; - if (prop.declarations) { - ts.addRange(declarations, prop.declarations); - } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; - } - propTypes.push(type); - } - var result = createSymbol(4 /* Property */ | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; - result.containingType = containingType; - result.declarations = declarations; - result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); - return result; - } - // Return the symbol for a given property in a union or intersection type, or undefined if the property - // does not exist in any constituent type. Note that the returned property may only be present in some - // constituents, in which case the isPartial flag is set when the containing type is union type. We need - // these partial properties when identifying discriminant properties, but otherwise they are filtered out - // and do not appear to be present in the union type. - function getUnionOrIntersectionProperty(type, name) { - var properties = type.propertyCache || (type.propertyCache = ts.createMap()); - var property = properties.get(name); - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties.set(name, property); - } - } - return property; - } - function getPropertyOfUnionOrIntersectionType(type, name) { - var property = getUnionOrIntersectionProperty(type, name); - // We need to filter out partial properties in union types - 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 - * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from - * Object and Function as appropriate. - * - * @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, name) { - type = getApparentType(type); - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; - } - } - return getPropertyOfObjectType(globalObjectType, name); - } - if (type.flags & 196608 /* UnionOrIntersection */) { - return getPropertyOfUnionOrIntersectionType(type, name); - } - return undefined; - } - function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; - } - return emptyArray; - } - /** - * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and - * maps primitive types and type parameters are to their apparent types. - */ - function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); - } - function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; - } - } - function getIndexTypeOfStructuredType(type, kind) { - var info = getIndexInfoOfStructuredType(type, kind); - return info && info.type; - } - // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and - // maps primitive types and type parameters are to their apparent types. - function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); - } - // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and - // maps primitive types and type parameters are to their apparent types. - function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); - } - function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { - var propTypes = []; - for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { - propTypes.push(getTypeOfSymbol(prop)); - } - } - if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); - } - } - return undefined; - } - function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 65536 /* JavaScriptFile */) { - var templateTag = ts.getJSDocTemplateTag(declaration); - if (templateTag) { - return getTypeParametersFromDeclaration(templateTag.typeParameters); - } - } - return undefined; - } - // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual - // type checking functions). - function getTypeParametersFromDeclaration(typeParameterDeclarations) { - var result = []; - ts.forEach(typeParameterDeclarations, function (node) { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - result.push(tp); - } - }); - return result; - } - function symbolsToArray(symbols) { - var result = []; - symbols.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - result.push(symbol); - } - }); - return result; - } - function isJSDocOptionalParameter(node) { - if (node.flags & 65536 /* JavaScriptFile */) { - if (node.type && node.type.kind === 278 /* JSDocOptionalType */) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 278 /* JSDocOptionalType */; - } - } - } - } - } - function tryFindAmbientModule(moduleName, withAugmentations) { - if (ts.isExternalModuleNameRelative(moduleName)) { - return undefined; - } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); - // merged symbol is module declaration symbol combined with all augmentations - return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; - } - function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { - return true; - } - if (node.initializer) { - var signatureDeclaration = node.parent; - var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); - ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; - } - var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); - if (iife) { - return !node.type && - !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; - } - return false; - } - function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 71 /* Identifier */) { - var parameterName = node.parameterName; - return { - kind: 1 /* Identifier */, - parameterName: parameterName ? parameterName.text : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; - } - else { - return { - kind: 0 /* This */, - type: getTypeFromTypeNode(node.type) - }; - } - } - /** - * Gets the minimum number of type arguments needed to satisfy all non-optional type - * parameters. - */ - function getMinTypeArgumentCount(typeParameters) { - var minTypeArgumentCount = 0; - if (typeParameters) { - for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { - minTypeArgumentCount = i + 1; - } - } - } - return minTypeArgumentCount; - } - /** - * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined - * when a default type is supplied, a new array will be created and returned. - * - * @param typeArguments The supplied type arguments. - * @param typeParameters The requested type parameters. - * @param minTypeArgumentCount The minimum number of required type arguments. - */ - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { - var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { - if (!typeArguments) { - typeArguments = []; - } - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = isJavaScript ? anyType : emptyObjectType; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : isJavaScript ? anyType : emptyObjectType; - } - } - } - return typeArguments; - } - function getSignatureFromDeclaration(declaration) { - var links = getNodeLinks(declaration); - if (!links.resolvedSignature) { - var parameters = []; - var hasLiteralTypes = false; - var minArgumentCount = 0; - var thisParameter = undefined; - var hasThisParameter = void 0; - var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); - var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); - // If this is a JSDoc construct signature, then skip the first parameter in the - // parameter list. The first parameter represents the return type of the construct - // signature. - for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { - var param = declaration.parameters[i]; - var paramSymbol = param.symbol; - // Include parameter symbol instead of property symbol in the signature - if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.name, 107455 /* Value */, undefined, undefined); - paramSymbol = resolvedSymbol; - } - if (i === 0 && paramSymbol.name === "this") { - hasThisParameter = true; - thisParameter = param.symbol; - } - else { - parameters.push(paramSymbol); - } - if (param.type && param.type.kind === 173 /* LiteralType */) { - hasLiteralTypes = true; - } - // Record a new minimum argument count if this is not an optional parameter - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; - if (!isOptionalParameter_1) { - minArgumentCount = parameters.length; - } - } - // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 153 /* GetAccessor */ || declaration.kind === 154 /* SetAccessor */) && - !ts.hasDynamicName(declaration) && - (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); - if (other) { - thisParameter = getAnnotatedAccessorThisParameter(other); - } - } - var classType = declaration.kind === 152 /* Constructor */ ? - getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) - : undefined; - var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : - getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); - } - return links.resolvedSignature; - } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); - } - else if (classType) { - return classType; - } - else if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.flags & 65536 /* JavaScriptFile */) { - var type = getReturnTypeFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - // 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 === 153 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154 /* SetAccessor */); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } - } - function containsArgumentsReference(declaration) { - var links = getNodeLinks(declaration); - if (links.containsArgumentsReference === undefined) { - if (links.flags & 8192 /* CaptureArguments */) { - links.containsArgumentsReference = true; - } - else { - links.containsArgumentsReference = traverse(declaration.body); - } - } - return links.containsArgumentsReference; - function traverse(node) { - if (!node) - return false; - switch (node.kind) { - case 71 /* Identifier */: - return node.text === "arguments" && ts.isPartOfExpression(node); - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return node.name.kind === 144 /* ComputedPropertyName */ - && traverse(node.name); - default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); - } - } - } - function getSignaturesOfSymbol(symbol) { - if (!symbol) - return emptyArray; - var result = []; - for (var i = 0; i < symbol.declarations.length; i++) { - var node = symbol.declarations[i]; - switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 279 /* JSDocFunctionType */: - // Don't include signature if node is the implementation of an overloaded function. A node is considered - // an implementation node if it has a body and the previous node is of the same kind and immediately - // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); - } - } - return result; - } - function resolveExternalModuleTypeByLiteral(name) { - var moduleSym = resolveExternalModuleName(name, name); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - return getTypeOfSymbol(resolvedModuleSymbol); - } - } - return anyType; - } - function getThisTypeOfSignature(signature) { - if (signature.thisParameter) { - return getTypeOfSymbol(signature.thisParameter); - } - } - function getReturnTypeOfSignature(signature) { - if (!signature.resolvedReturnType) { - if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { - return unknownType; - } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - 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); - } - } - } - signature.resolvedReturnType = type; - } - return signature.resolvedReturnType; - } - function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; - } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); - var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); - var id = getTypeListId(typeArguments); - var instantiation = instantiations.get(id); - if (!instantiation) { - instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); - } - return instantiation; - } - function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); - } - function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); - } - return signature.erasedSignatureCache; - } - function getOrCreateTypeFromSignature(signature) { - // There are two ways to declare a construct signature, one is by declaring a class constructor - // using the constructor keyword, and the other is declaring a bare construct signature in an - // object type literal or interface (using the new keyword). Each way of declaring a constructor - // will result in a different declaration kind. - if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 /* Constructor */ || signature.declaration.kind === 156 /* ConstructSignature */; - var type = createObjectType(16 /* Anonymous */); - type.members = emptySymbols; - type.properties = emptyArray; - type.callSignatures = !isConstructor ? [signature] : emptyArray; - type.constructSignatures = isConstructor ? [signature] : emptyArray; - signature.isolatedSignatureType = type; - } - return signature.isolatedSignatureType; - } - function getIndexSymbol(symbol) { - return symbol.members.get("__index"); - } - function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 133 /* NumberKeyword */ : 136 /* StringKeyword */; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var node = decl; - if (node.parameters.length === 1) { - var parameter = node.parameters[0]; - if (parameter && parameter.type && parameter.type.kind === syntaxKind) { - return node; - } - } - } - } - return undefined; - } - function createIndexInfo(type, isReadonly, declaration) { - return { type: type, isReadonly: isReadonly, declaration: declaration }; - } - function getIndexInfoOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); - } - return undefined; - } - function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145 /* TypeParameter */).constraint; - } - function getConstraintFromTypeParameter(typeParameter) { - if (!typeParameter.constraint) { - if (typeParameter.target) { - var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); - typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; - } - else { - var constraintDeclaration = getConstraintDeclaration(typeParameter); - typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; - } - } - return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; - } - function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145 /* TypeParameter */).parent); - } - function getTypeListId(types) { - var result = ""; - if (types) { - var length_4 = types.length; - var i = 0; - while (i < length_4) { - var startId = types[i].id; - var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; - } - } - return result; - } - // This function is used to propagate certain flags when creating new object type references and union types. - // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker - // 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_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; - if (!(type.flags & excludeKinds)) { - result |= type.flags; - } - } - return result & 14680064 /* PropagatingFlags */; - } - function createTypeReference(target, typeArguments) { - var id = getTypeListId(typeArguments); - var type = target.instantiations.get(id); - if (!type) { - type = createObjectType(4 /* Reference */, target.symbol); - target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - type.target = target; - type.typeArguments = typeArguments; - } - return type; - } - function cloneTypeReference(source) { - var type = createType(source.flags); - type.symbol = source.symbol; - type.objectFlags = source.objectFlags; - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return ts.length(type.target.typeParameters); - } - // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { - var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); - var typeParameters = type.localTypeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); - return unknownType; - } - // 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(typeArgs, typeParameters, minTypeArgumentCount, node)); - return createTypeReference(type, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - return unknownType; - } - return type; - } - function getTypeAliasInstantiation(symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var links = getSymbolLinks(symbol); - var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); - var instantiation = links.instantiations.get(id); - if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); - } - 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, symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeParameters = getSymbolLinks(symbol).typeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); - return unknownType; - } - return getTypeAliasInstantiation(symbol, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return type; - } - // Get type from reference to named type that cannot be generic (enum or type parameter) - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } - function getTypeReferenceName(node) { - switch (node.kind) { - case 159 /* TypeReference */: - return node.typeName; - case 277 /* JSDocTypeReference */: - return node.name; - case 201 /* ExpressionWithTypeArguments */: - // We only support expressions that are simple qualified names. For other - // expressions this produces undefined. - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; - } - } - return undefined; - } - function resolveTypeReferenceName(typeReferenceName) { - if (!typeReferenceName) { - return unknownSymbol; - } - 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, typeArguments); - } - if (symbol.flags & 524288 /* TypeAlias */) { - 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 - // that case, the type of this reference is just the type of the value we resolved - // to. - return getTypeOfSymbol(symbol); - } - return getTypeFromNonGenericTypeReference(node, symbol); - } - function getPrimitiveTypeFromJSDocTypeReference(node) { - if (ts.isIdentifier(node.name)) { - switch (node.name.text) { - case "String": - return stringType; - case "Number": - return numberType; - case "Boolean": - return booleanType; - case "Void": - return voidType; - case "Undefined": - return undefinedType; - case "Null": - return nullType; - case "Object": - return anyType; - case "Function": - return anyFunctionType; - case "Array": - case "array": - return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined; - case "Promise": - case "promise": - return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; - } - } - } - function getTypeFromJSDocNullableTypeNode(node) { - var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; - } - function getTypeFromTypeReference(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var symbol = void 0; - var type = void 0; - if (node.kind === 277 /* JSDocTypeReference */) { - type = getPrimitiveTypeFromJSDocTypeReference(node); - if (!type) { - var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(typeReferenceName); - type = getTypeReferenceType(node, symbol); - } - } - else { - // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 159 /* TypeReference */ - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - 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. - 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) { - // TypeScript 1.0 spec (April 2014): 3.6.3 - // The expression is processed as an identifier expression (section 4.3) - // or property access expression(section 4.10), - // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); - } - return links.resolvedType; - } - function getTypeOfGlobalSymbol(symbol, arity) { - function getTypeDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; - switch (declaration.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - return declaration; - } - } - } - if (!symbol) { - return arity ? emptyGenericType : emptyObjectType; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768 /* Object */)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return arity ? emptyGenericType : emptyObjectType; - } - if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return arity ? emptyGenericType : emptyObjectType; - } - return type; - } - function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); - } - function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); - } - function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); - } - function getGlobalType(name, arity, reportErrors) { - var symbol = getGlobalTypeSymbol(name, reportErrors); - return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; - } - function getGlobalTypedPropertyDescriptorType() { - return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; - } - function getGlobalTemplateStringsArrayType() { - return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; - } - function getGlobalESSymbolConstructorSymbol(reportErrors) { - return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); - } - function getGlobalESSymbolType(reportErrors) { - return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; - } - function getGlobalPromiseType(reportErrors) { - return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalPromiseConstructorSymbol(reportErrors) { - return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); - } - function getGlobalPromiseConstructorLikeType(reportErrors) { - return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; - } - function getGlobalAsyncIterableType(reportErrors) { - return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIteratorType(reportErrors) { - return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIterableIteratorType(reportErrors) { - return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableType(reportErrors) { - return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalIteratorType(reportErrors) { - return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableIteratorType(reportErrors) { - return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalTypeOrUndefined(name, arity) { - if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); - return symbol && getTypeOfGlobalSymbol(symbol, arity); - } - /** - * Returns a type that is inside a namespace at the global scope, e.g. - * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type - */ - function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); - return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); - } - /** - * Instantiates a global type that is generic with some element type, and returns that instantiation. - */ - function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { - return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; - } - function createTypedPropertyDescriptorType(propertyType) { - return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); - } - function createAsyncIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); - } - function createAsyncIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); - } - function createIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); - } - function createIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); - } - function createArrayType(elementType) { - return createTypeFromGenericGlobalType(globalArrayType, [elementType]); - } - function getTypeFromArrayTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); - } - return links.resolvedType; - } - // We represent tuple types as type references to synthesized generic interface types created by - // this function. The types are of the form: - // - // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } - // - // Note that the generic type created by this function has no symbol associated with it. The same - // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384 /* TypeParameter */); - typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); - type.thisType.isThisType = true; - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); - } - function getTypeFromTupleTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); - } - return links.resolvedType; - } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - var flags = type.flags; - if (flags & 65536 /* Union */) { - addTypesToUnion(typeSet, type.types); - } - else if (flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && flags & 6144 /* Nullable */) { - if (flags & 2048 /* Undefined */) - typeSet.containsUndefined = true; - if (flags & 4096 /* Null */) - typeSet.containsNull = true; - if (!(flags & 2097152 /* ContainsWideningType */)) - typeSet.containsNonWideningType = true; - } - else if (!(flags & 8192 /* Never */)) { - if (flags & 2 /* String */) - typeSet.containsString = true; - if (flags & 4 /* Number */) - typeSet.containsNumber = true; - if (flags & 96 /* StringOrNumberLiteral */) - typeSet.containsStringOrNumberLiteral = true; - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } - } - } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. - function addTypesToUnion(typeSet, types) { - 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_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function isSubtypeOfAny(candidate, types) { - 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; - } - } - return false; - } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 256 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types) { - if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { - return; - } - var i = types.length; - while (i > 0) { - i--; - if (isSubtypeOfAny(types[i], types)) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function removeRedundantLiteralTypes(types) { - var i = types.length; - while (i > 0) { - i--; - var t = types[i]; - var remove = t.flags & 32 /* StringLiteral */ && types.containsString || - t.flags & 64 /* NumberLiteral */ && types.containsNumber || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); - if (remove) { - ts.orderedRemoveItemAt(types, i); - } - } - } - // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction - // flag is specified we also reduce the constituent type set to only include types that aren't subtypes - // of other types. Subtype reduction is expensive for large union types and is possible only when union - // types are known not to circularly reference themselves (as is the case with union types created by - // expression constructs such as array literals and the || and ?: operators). Named types can - // circularly reference themselves and therefore cannot be subtype reduced during their declaration. - // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var typeSet = []; - addTypesToUnion(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsStringOrNumberLiteral) { - removeRedundantLiteralTypes(typeSet); - } - if (typeSet.length === 0) { - return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : - typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); - var type = unionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(65536 /* Union */ | propagatedFlags); - unionTypes.set(id, type); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromUnionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072 /* Intersection */) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - typeSet.containsEmptyObject = true; - } - else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768 /* Object */) { - typeSet.containsObjectType = true; - } - if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { - typeSet.unionIndex = typeSet.length; - } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.push(type); - } - } - } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - addTypeToIntersection(typeSet, type); - } - } - // We normalize combinations of intersection and union types based on the distributive property of the '&' - // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection - // types with union type constituents into equivalent union types with intersection type constituents and - // effectively ensure that union types are always at the top level in type representations. - // - // We do not perform structural deduplication on intersection types. Intersection types are created only by the & - // type operator and we can't reduce those because we want to support recursive intersection types. For example, - // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. - // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution - // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } - var typeSet = []; - addTypesToIntersection(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { - typeSet.push(emptyObjectType); - } - if (typeSet.length === 1) { - return typeSet[0]; - } - var unionIndex = typeSet.unionIndex; - if (unionIndex !== undefined) { - // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of - // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), - /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); - } - var id = getTypeListId(typeSet); - var type = intersectionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(131072 /* Intersection */ | propagatedFlags); - intersectionTypes.set(id, type); - type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromIntersectionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function getIndexTypeForGenericType(type) { - if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144 /* Index */); - type.resolvedIndexType.type = type; - } - return type.resolvedIndexType; - } - function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? - neverType : - getLiteralType(ts.unescapeIdentifier(prop.name)); - } - function getLiteralTypeFromPropertyNames(type) { - return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); - } - function getIndexType(type) { - return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : - type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : - getLiteralTypeFromPropertyNames(type); - } - function getIndexTypeOrString(type) { - var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; - } - function getTypeFromTypeOperatorNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); - } - return links.resolvedType; - } - function createIndexedAccessType(objectType, indexType) { - var type = createType(524288 /* IndexedAccess */); - type.objectType = objectType; - type.indexType = indexType; - return type; - } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? - "" + indexType.value : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : - undefined; - if (propName !== undefined) { - var prop = getPropertyOfType(objectType, propName); - if (prop) { - if (accessExpression) { - if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return unknownType; - } - if (cacheSymbol) { - getNodeLinks(accessNode).resolvedSymbol = prop; - } - } - return getTypeOfSymbol(prop); - } - } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { - if (isTypeAny(objectType)) { - return anyType; - } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || - getIndexInfoOfType(objectType, 0 /* String */) || - undefined; - if (indexInfo) { - if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; - } - return indexInfo.type; - } - if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1 /* Number */)) { - error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); - } - } - return anyType; - } - } - 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.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)); - } - else { - error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); - } - return unknownType; - } - return anyType; - } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } - function getIndexedAccessType(objectType, indexType, accessNode) { - // If the index type is generic, if the object type is generic and doesn't originate in an expression, - // or if the object type is a mapped type with a generic constraint, we are performing a higher-order - // index access where we cannot meaningfully access the properties of the object type. Note that for a - // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to - // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved - // eagerly using the constraint type of 'this' at the given location. - if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || - maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) || - isGenericMappedType(objectType)) { - if (objectType.flags & 1 /* Any */) { - return objectType; - } - // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes - // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the - // type Box. - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - // Otherwise we defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id; - var type = indexedAccessTypes.get(id); - if (!type) { - indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); - } - return type; - } - // In the following we resolve T[K] to the type of the property in T selected by K. - var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { - var propTypes = []; - for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { - var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === unknownType) { - return unknownType; - } - propTypes.push(propType); - } - return getUnionType(propTypes); - } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); - } - function getTypeFromIndexedAccessTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); - } - return links.resolvedType; - } - function getTypeFromMappedTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = createObjectType(32 /* Mapped */, node.symbol); - type.declaration = node; - type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - // Eagerly resolve the constraint type which forces an error if the constraint type circularly - // references itself through one or more type aliases. - getConstraintTypeFromMappedType(type); - } - return links.resolvedType; - } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - // Deferred resolution of members is handled by resolveObjectTypeMembers - var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { - links.resolvedType = emptyTypeLiteralType; - } - else { - var type = createObjectType(16 /* Anonymous */, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - } - } - return links.resolvedType; - } - function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; - } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); - return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; - } - /** - * Since the source of spread types are object literals, which are not binary, - * this function should be called in a left folding style, with left = previous result of getSpreadType - * and right = the new element to be spread. - */ - function getSpreadType(left, right) { - if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { - return anyType; - } - left = filterType(left, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (left.flags & 8192 /* Never */) { - return right; - } - right = filterType(right, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (right.flags & 8192 /* Never */) { - return left; - } - if (left.flags & 65536 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right); }); - } - if (right.flags & 65536 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t); }); - } - if (right.flags & 16777216 /* NonPrimitive */) { - return emptyObjectType; - } - var members = ts.createMap(); - var skippedPrivateMembers = ts.createMap(); - var stringIndexInfo; - var numberIndexInfo; - if (left === emptyObjectType) { - // for the first spread element, left === emptyObjectType, so take the right's string indexer - stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); - numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); - } - else { - stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); - numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); - } - for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { - 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 (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { - skippedPrivateMembers.set(rightProp.name, true); - } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { - members.set(rightProp.name, getNonReadonlySymbol(rightProp)); - } - } - for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { - var leftProp = _c[_b]; - if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) - || skippedPrivateMembers.has(leftProp.name) - || isClassMethod(leftProp)) { - continue; - } - if (members.has(leftProp.name)) { - var rightProp = members.get(leftProp.name); - var rightType = getTypeOfSymbol(rightProp); - 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), rightType]); - result.leftSpread = leftProp; - result.rightSpread = rightProp; - result.declarations = declarations; - members.set(leftProp.name, result); - } - } - else { - members.set(leftProp.name, getNonReadonlySymbol(leftProp)); - } - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { - return prop; - } - var flags = 4 /* Property */ | (prop.flags & 67108864 /* Optional */); - var result = createSymbol(flags, prop.name); - result.type = getTypeOfSymbol(prop); - result.declarations = prop.declarations; - result.syntheticOrigin = prop; - return result; - } - function isClassMethod(prop) { - return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } - function createLiteralType(flags, value, symbol) { - var type = createType(flags); - 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.value, type.symbol); - freshType.regularType = type; - type.freshType = freshType; - } - return type.freshType; - } - return type; - } - function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; - } - 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) { - var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); - literalTypes.set(key, type = createLiteralType(flags, value, symbol)); - } - return type; - } - function getTypeFromLiteralTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); - } - return links.resolvedType; - } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; - } - return links.resolvedType; - } - function getTypeFromJSDocTupleType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); - links.resolvedType = createTupleType(types); - } - return links.resolvedType; - } - function getThisType(node) { - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { - if (!(ts.getModifierFlags(container) & 32 /* Static */) && - (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { - return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; - } - } - error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); - return unknownType; - } - function getTypeFromThisTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getThisType(node); - } - return links.resolvedType; - } - function getTypeFromTypeNode(node) { - switch (node.kind) { - case 119 /* AnyKeyword */: - case 268 /* JSDocAllType */: - case 269 /* JSDocUnknownType */: - return anyType; - case 136 /* StringKeyword */: - return stringType; - case 133 /* NumberKeyword */: - return numberType; - case 122 /* BooleanKeyword */: - return booleanType; - case 137 /* SymbolKeyword */: - return esSymbolType; - case 105 /* VoidKeyword */: - return voidType; - case 139 /* UndefinedKeyword */: - return undefinedType; - case 95 /* NullKeyword */: - return nullType; - case 130 /* NeverKeyword */: - return neverType; - case 134 /* ObjectKeyword */: - return nonPrimitiveType; - case 169 /* ThisType */: - case 99 /* ThisKeyword */: - return getTypeFromThisTypeNode(node); - case 173 /* LiteralType */: - return getTypeFromLiteralTypeNode(node); - case 293 /* JSDocLiteralType */: - return getTypeFromLiteralTypeNode(node.literal); - case 159 /* TypeReference */: - case 277 /* JSDocTypeReference */: - return getTypeFromTypeReference(node); - case 158 /* TypePredicate */: - return booleanType; - case 201 /* ExpressionWithTypeArguments */: - return getTypeFromTypeReference(node); - case 162 /* TypeQuery */: - return getTypeFromTypeQueryNode(node); - case 164 /* ArrayType */: - case 270 /* JSDocArrayType */: - return getTypeFromArrayTypeNode(node); - case 165 /* TupleType */: - return getTypeFromTupleTypeNode(node); - case 166 /* UnionType */: - case 271 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node); - case 167 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node); - case 273 /* JSDocNullableType */: - return getTypeFromJSDocNullableTypeNode(node); - case 168 /* ParenthesizedType */: - case 274 /* JSDocNonNullableType */: - case 281 /* JSDocConstructorType */: - case 282 /* JSDocThisType */: - case 278 /* JSDocOptionalType */: - return getTypeFromTypeNode(node.type); - case 275 /* JSDocRecordType */: - return getTypeFromTypeNode(node.literal); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: - case 279 /* JSDocFunctionType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170 /* TypeOperator */: - return getTypeFromTypeOperatorNode(node); - case 171 /* IndexedAccessType */: - return getTypeFromIndexedAccessTypeNode(node); - case 172 /* MappedType */: - return getTypeFromMappedTypeNode(node); - // This function assumes that an identifier or qualified name is a type expression - // Callers should first ensure this by calling isTypeNode - case 71 /* Identifier */: - case 143 /* QualifiedName */: - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - case 272 /* JSDocTupleType */: - return getTypeFromJSDocTupleType(node); - case 280 /* JSDocVariadicType */: - return getTypeFromJSDocVariadicType(node); - default: - return unknownType; - } - } - function instantiateList(items, mapper, instantiator) { - if (items && items.length) { - var result = []; - for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { - var v = items_1[_i]; - result.push(instantiator(v, mapper)); - } - return result; - } - return items; - } - function instantiateTypes(types, mapper) { - return instantiateList(types, mapper, instantiateType); - } - function instantiateSignatures(signatures, mapper) { - return instantiateList(signatures, mapper, instantiateSignature); - } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } - function makeUnaryTypeMapper(source, target) { - return function (t) { return t === source ? target : t; }; - } - function makeBinaryTypeMapper(source1, target1, source2, target2) { - return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; - } - function makeArrayTypeMapper(sources, targets) { - return function (t) { - for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) { - return targets ? targets[i] : anyType; - } - } - return t; - }; - } - function createTypeMapper(sources, targets) { - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : - sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : - makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; - } - function createTypeEraser(sources) { - return createTypeMapper(sources, /*targets*/ undefined); - } - /** - * Maps forward-references to later types parameters to the empty object type. - * This is used during inference when instantiating type parameter defaults. - */ - function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; - } - function getInferenceMapper(context) { - if (!context.mapper) { - var mapper = function (t) { - var typeParameters = context.signature.typeParameters; - for (var i = 0; i < typeParameters.length; i++) { - if (t === typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); - } - } - return t; - }; - mapper.mappedTypes = context.signature.typeParameters; - mapper.context = context; - context.mapper = mapper; - } - return context.mapper; - } - function identityMapper(type) { - return type; - } - function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; - } - function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; - } - function cloneTypeParameter(typeParameter) { - var result = createType(16384 /* TypeParameter */); - result.symbol = typeParameter.symbol; - result.target = typeParameter; - return result; - } - function cloneTypePredicate(predicate, mapper) { - if (ts.isIdentifierTypePredicate(predicate)) { - return { - kind: 1 /* Identifier */, - parameterName: predicate.parameterName, - parameterIndex: predicate.parameterIndex, - type: instantiateType(predicate.type, mapper) - }; - } - else { - return { - kind: 0 /* This */, - type: instantiateType(predicate.type, mapper) - }; - } - } - function instantiateSignature(signature, mapper, eraseTypeParameters) { - var freshTypeParameters; - var freshTypePredicate; - if (signature.typeParameters && !eraseTypeParameters) { - // First create a fresh set of type parameters, then include a mapping from the old to the - // new type parameters in the mapper function. Finally store this mapper in the new type - // parameters such that we can use it when instantiating constraints. - freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); - mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); - for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { - var tp = freshTypeParameters_1[_i]; - tp.mapper = mapper; - } - } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); - result.target = signature; - result.mapper = mapper; - return result; - } - function instantiateSymbol(symbol, mapper) { - 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 - // always reference a non-aliases. - symbol = links.target; - mapper = combineTypeMappers(links.mapper, mapper); - } - // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and - // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.name); - result.checkFlags = 1 /* Instantiated */; - result.declarations = symbol.declarations; - result.parent = symbol.parent; - result.target = symbol; - result.mapper = mapper; - if (symbol.valueDeclaration) { - result.valueDeclaration = symbol.valueDeclaration; - } - return result; - } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); - result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; - result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function instantiateMappedType(type, mapper) { - // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some - // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated - // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for - // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a - // union type A | undefined, we produce { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); - } - return t; - }); - } - } - } - return instantiateMappedObjectType(type, mapper); - } - function isMappableType(type) { - return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); - } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - // Starting with the parent of the symbol's declaration, check if the mapper maps any of - // the type parameters introduced by enclosing declarations. We just pick the first - // declaration since multiple declarations will all have the same parent anyway. - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 /* ModuleDeclaration */ || node.kind === 265 /* SourceFile */) { - return "quit"; - } - switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - var declaration = node; - if (declaration.typeParameters) { - for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { - var d = _a[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230 /* InterfaceDeclaration */) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172 /* MappedType */: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 279 /* JSDocFunctionType */: - var func = node; - for (var _b = 0, _c = func.parameters; _b < _c.length; _b++) { - var p = _c[_b]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 /* SourceFile */ || parentKind === 234 /* ModuleBlock */; - } - return false; - } - function instantiateType(type, mapper) { - if (type && mapper !== identityMapper) { - // If we are instantiating a type that has a top-level type alias, obtain the instantiation through - // the type alias instead in order to share instantiations for the same type arguments. This can - // dramatically reduce the number of structurally identical types we generate. Note that we can only - // perform this optimization for top-level type aliases. Consider: - // - // function f1(x: T) { - // type Foo = { x: X, t: T }; - // let obj: Foo = { x: x }; - // return obj; - // } - // function f2(x: U) { return f1(x); } - // let z = f2(42); - // - // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo - // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's - // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been - // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - return type; - } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 32768 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. We skip instantiation - // if none of the type parameters that are in scope in the type's declaration are mapped by - // the given mapper, however we can only do that analysis if the type isn't itself an - // instantiation. - return type.symbol && - type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return instantiateCached(type, mapper, instantiateMappedType); - } - if (type.objectFlags & 4 /* Reference */) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); - } - } - if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - return type; - } - function instantiateIndexInfo(info, mapper) { - return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); - } - // Returns true if the given expression contains (at any level of nesting) a function or arrow expression - // that is subject to contextual typing. - function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return isContextSensitiveFunctionLikeDeclaration(node); - case 178 /* ObjectLiteralExpression */: - return ts.forEach(node.properties, isContextSensitive); - case 177 /* ArrayLiteralExpression */: - return ts.forEach(node.elements, isContextSensitive); - case 195 /* ConditionalExpression */: - return isContextSensitive(node.whenTrue) || - isContextSensitive(node.whenFalse); - case 194 /* BinaryExpression */: - return node.operatorToken.kind === 54 /* BarBarToken */ && - (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261 /* PropertyAssignment */: - return isContextSensitive(node.initializer); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - return isContextSensitiveFunctionLikeDeclaration(node); - case 185 /* ParenthesizedExpression */: - return isContextSensitive(node.expression); - case 254 /* JsxAttributes */: - return ts.forEach(node.properties, isContextSensitive); - case 253 /* JsxAttribute */: - // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - return node.initializer && isContextSensitive(node.initializer); - case 256 /* JsxExpression */: - // It is possible to that node.expression is undefined (e.g
) - return node.expression && isContextSensitive(node.expression); - } - return false; - } - function isContextSensitiveFunctionLikeDeclaration(node) { - // Functions with type parameters are not context sensitive. - if (node.typeParameters) { - return false; - } - // Functions with any parameters that lack type annotations are context sensitive. - if (ts.forEach(node.parameters, function (p) { return !p.type; })) { - return true; - } - // For arrow functions we now know we're not context sensitive. - if (node.kind === 187 /* ArrowFunction */) { - return false; - } - // If the first parameter is not an explicit 'this' parameter, then the function has - // an implicit 'this' parameter which is subject to contextual typing. Otherwise we - // know that all parameters (including 'this') have type annotations and nothing is - // subject to contextual typing. - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); - } - function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); - } - function getTypeWithoutSignatures(type) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { - var result = createObjectType(16 /* Anonymous */, type.symbol); - result.members = resolved.members; - result.properties = resolved.properties; - result.callSignatures = emptyArray; - result.constructSignatures = emptyArray; - return result; - } - } - else if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); - } - return type; - } - // TYPE CHECKING - function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); - } - function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; - } - function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; - } - function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); - } - function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - // A type S is considered to be an instance of a type T if S and T are the same type or if S is a - // subtype of T but not structurally identical to T. This specifically means that two distinct but - // structurally identical types (such as two classes) are not considered instances of each other. - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); - } - /** - * This is *not* a bi-directional relationship. - * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. - */ - function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); - } - function areTypesComparable(type1, type2) { - return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); - } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); - } - /** - * This is *not* a bi-directional relationship. - * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. - */ - function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); - } - function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, - /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; - } - /** - * See signatureRelatedTo, compareSignaturesIdentical - */ - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { - // TODO (drosen): De-duplicate code between related functions. - if (source === target) { - return -1 /* True */; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0 /* False */; - } - // Spec 1.0 Section 3.8.3 & 3.8.4: - // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1 /* True */; - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType && sourceThisType !== voidType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - // void sources are assignable to anything. - var related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) - || compareTypes(targetThisType, sourceThisType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); - } - return 0 /* False */; - } - result &= related; - } - } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); - // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter - // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, - // they naturally relate only contra-variantly). However, if the source and target parameters both have - // function types with a single call signature, we known we are relating two callback parameters. In - // that case it is sufficient to only relate the parameters of the signatures co-variantly because, - // similar to return values, callback parameters are output positions. This means that a Promise, - // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) - // with respect to T. - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); - var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); - } - return 0 /* False */; - } - result &= related; - } - if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) { - return result; - } - var sourceReturnType = getReturnTypeOfSignature(source); - // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); - } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0 /* False */; - } - } - else { - // When relating callback signatures, we still need to relate return types bi-variantly as otherwise - // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } - // wouldn't be co-variant for T without this rule. - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || - compareTypes(sourceReturnType, targetReturnType, reportErrors); - } - } - return result; - } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { - if (source.kind !== target.kind) { - if (reportErrors) { - errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0 /* False */; - } - if (source.kind === 1 /* Identifier */) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0 /* False */; - } - } - var related = compareTypes(source.type, target.type, reportErrors); - if (related === 0 /* False */ && reportErrors) { - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return related; - } - function isImplementationCompatibleWithOverload(implementation, overload) { - var erasedSource = getErasedSignature(implementation); - var erasedTarget = getErasedSignature(overload); - // First see if the return types are compatible in either direction. - var sourceReturnType = getReturnTypeOfSignature(erasedSource); - var targetReturnType = getReturnTypeOfSignature(erasedTarget); - if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); - } - return false; - } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - // If both have rest parameters, get the max and add 1 to - // compensate for the rest parameter. - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - // Return the count for whichever signature doesn't have rest parameters. - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } - function isEmptyResolvedType(t) { - return t.properties.length === 0 && - t.callSignatures.length === 0 && - t.constructSignatures.length === 0 && - !t.stringIndexInfo && - !t.numberIndexInfo; - } - function isEmptyObjectType(type) { - return type.flags & 32768 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 65536 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : - false; - } - function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { - if (sourceSymbol === targetSymbol) { - return true; - } - var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); - var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; - } - if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { - enumRelation.set(id, false); - return false; - } - 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(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); - } - enumRelation.set(id, false); - return false; - } - } - } - enumRelation.set(id, true); - return true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - var s = source.flags; - var t = target.flags; - if (t & 8192 /* Never */) - return false; - if (t & 1 /* Any */ || s & 8192 /* Never */) - return true; - if (s & 262178 /* StringLike */ && t & 2 /* String */) - return true; - if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && - t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && - source.value === target.value) - return true; - if (s & 84 /* NumberLike */ && t & 4 /* Number */) - return true; - if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && - t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && - source.value === target.value) - return true; - if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) - return true; - if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; - 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 (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) - return true; - if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1 /* 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 & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) - return true; - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { - source = source.regularType; - } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { - target = target.regularType; - } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - return related === 1 /* Succeeded */; - } - } - if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { - return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); - } - return false; - } - /** - * Checks if 'source' is related to 'target' (e.g.: is a assignable to). - * @param source The left-hand-side of the relation. - * @param target The right-hand-side of the relation. - * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. - * Used as both to determine which checks are performed and as a cache of previously computed results. - * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. - * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. - * @param containingMessageChain A chain of errors to prepend any new errors found. - */ - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { - var errorInfo; - var sourceStack; - var targetStack; - var maybeStack; - var expandingFlags; - var depth = 0; - var overflow = false; - ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); - if (overflow) { - error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); - } - else if (errorInfo) { - if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return result !== 0 /* False */; - function reportError(message, arg0, arg1, arg2) { - ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - } - function reportRelationError(message, source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); - } - if (!message) { - if (relation === comparableRelation) { - message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; - } - else if (sourceType === targetType) { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; - } - else { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; - } - } - reportError(message, sourceType, targetType); - } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } - function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608 /* UnionOrIntersection */)) { - return false; - } - // at this point we know that this is union or intersection type possibly with nullable constituents. - // check if we still will have compound type if we ignore nullable components. - var seenNonNullable = false; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 6144 /* Nullable */) { - continue; - } - if (seenNonNullable) { - return true; - } - seenNonNullable = true; - } - return false; - } - /** - * Compare two types and return - * * Ternary.True if they are related with no assumptions, - * * Ternary.Maybe if they are related with assumptions of other relationships, or - * * Ternary.False if they are not related. - */ - function isRelatedTo(source, target, reportErrors, headMessage) { - var result; - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { - source = source.regularType; - } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { - target = target.regularType; - } - // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases - if (source === target) - return -1 /* True */; - if (relation === identityRelation) { - return isIdenticalTo(source, target); - } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1 /* True */; - if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { - if (hasExcessProperties(source, target, reportErrors)) { - if (reportErrors) { - reportRelationError(headMessage, source, target); - } - return 0 /* False */; - } - // Above we check for excess properties with respect to the entire target type. When union - // and intersection types are further deconstructed on the target side, we don't want to - // make the check again (as it might fail for a partial target type). Therefore we obtain - // the regular source type and proceed with that. - if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { - source = getRegularTypeOfObjectLiteral(source); - } - } - var saveErrorInfo = errorInfo; - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 65536 /* Union */) { - if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); - } - else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); - } - if (result) { - return result; - } - } - else { - if (target.flags & 65536 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { - return result; - } - } - else if (target.flags & 131072 /* Intersection */) { - if (result = typeRelatedToEachType(source, target, reportErrors)) { - return result; - } - } - else if (source.flags & 131072 /* Intersection */) { - // Check to see if any constituents of the intersection are immediately related to the target. - // - // Don't report errors though. Checking whether a constituent is related to the source is not actually - // useful and leads to some confusing error messages. Instead it is better to let the below checks - // take care of this, or to not elaborate at all. For instance, - // - // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. - // - // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection - // than to report that 'D' is not assignable to 'A' or 'B'. - // - // - For a primitive type or type parameter (such as 'number = A & B') there is no point in - // breaking the intersection apart. - if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { - return result; - } - } - if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (reportErrors) { - if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - reportRelationError(headMessage, source, target); - } - return 0 /* False */; - } - function isIdenticalTo(source, target) { - var result; - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); - } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || - source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { - if (result = eachTypeRelatedToSomeType(source, target)) { - if (result &= eachTypeRelatedToSomeType(target, source)) { - return result; - } - } - } - return 0 /* False */; - } - function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { - var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); - if ((relation === assignableRelation || relation === comparableRelation) && - (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { - return false; - } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { - if (reportErrors) { - // We know *exactly* where things went wrong when comparing the types. - // Use this property as the error node as this will be more helpful in - // reasoning about what went wrong. - ts.Debug.assert(!!errorNode); - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { - // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. - // However, using an object-literal error message will be very confusing to the users so we give different a message. - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); - } - else { - errorNode = prop.valueDeclaration; - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); - } - } - return true; - } - } - } - return false; - } - function eachTypeRelatedToSomeType(source, target) { - var result = -1 /* True */; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { - var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function typeRelatedToSomeType(source, target, reportErrors) { - var targetTypes = target.types; - if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; - } - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var type = targetTypes_1[_i]; - var related = isRelatedTo(source, type, /*reportErrors*/ false); - if (related) { - return related; - } - } - if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); - } - return 0 /* False */; - } - function findMatchingDiscriminantType(source, target) { - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.name)) { - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); - if (targetType && isRelatedTo(sourceType, targetType)) { - return type; - } - } - } - } - } - } - function typeRelatedToEachType(source, target, reportErrors) { - var result = -1 /* True */; - var targetTypes = target.types; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function someTypeRelatedToType(source, target, reportErrors) { - var sourceTypes = source.types; - if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { - return -1 /* True */; - } - var len = sourceTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); - if (related) { - return related; - } - } - return 0 /* False */; - } - function eachTypeRelatedToType(source, target, reportErrors) { - var result = -1 /* True */; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; - var related = isRelatedTo(sourceType, target, reportErrors); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function typeArgumentsRelatedTo(source, target, reportErrors) { - var sources = source.typeArguments || emptyArray; - var targets = target.typeArguments || emptyArray; - if (sources.length !== targets.length && relation === identityRelation) { - return 0 /* False */; - } - var length = sources.length <= targets.length ? sources.length : targets.length; - var result = -1 /* True */; - for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. - // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. - // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are - // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion - // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source, target, reportErrors) { - if (overflow) { - return 0 /* False */; - } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - if (reportErrors && related === 2 /* Failed */) { - // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported - // failure and continue computing the relation such that errors get reported. - relation.set(id, 3 /* FailedAndReported */); - } - else { - return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; - } - } - if (depth > 0) { - for (var i = 0; i < depth; i++) { - // If source and target are already being compared, consider them related with assumptions - if (maybeStack[i].get(id)) { - return 1 /* Maybe */; - } - } - if (depth === 100) { - overflow = true; - return 0 /* False */; - } - } - else { - sourceStack = []; - targetStack = []; - maybeStack = []; - expandingFlags = 0; - } - sourceStack[depth] = source; - targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); - maybeStack[depth].set(id, 1 /* Succeeded */); - depth++; - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; - expandingFlags = saveExpandingFlags; - depth--; - if (result) { - var maybeCache = maybeStack[depth]; - // If result is definitely true, copy assumptions to global cache, else copy to next level up - var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyEntries(maybeCache, destinationCache); - } - else { - // A false result goes straight into global cache (when something is false under assumptions it - // will also be false without assumptions) - relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); - } - return result; - } - function structuredTypeRelatedTo(source, target, reportErrors) { - var result; - var saveErrorInfo = errorInfo; - if (target.flags & 16384 /* TypeParameter */) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { - if (!source.declaration.questionToken) { - var templateType = getTemplateTypeFromMappedType(source); - var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); - if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { - return result; - } - } - } - } - else if (target.flags & 262144 /* Index */) { - // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 262144 /* Index */) { - if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { - return result; - } - } - // A type S is assignable to keyof T if S is assignable to keyof C, where C is the - // constraint of T. - var constraint = getConstraintOfType(target.type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { - return result; - } - } - } - else if (target.flags & 524288 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. - var constraint = getConstraintOfType(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (source.flags & 16384 /* TypeParameter */) { - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else { - var constraint = getConstraintOfTypeParameter(source); - // A type parameter with no constraint is not related to the non-primitive object type. - if (constraint || !(target.flags & 16777216 /* NonPrimitive */)) { - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; - } - // The constraint may need to be further instantiated with its 'this' type. - constraint = getTypeWithThisArgument(constraint, source); - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - } - else if (source.flags & 524288 /* IndexedAccess */) { - // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. - var constraint = getConstraintOfType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else if (target.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - return result; - } - } - } - else { - if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { - // We have type references to same target type, see if relationship holds for all type arguments - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { - return result; - } - } - // Even if relationship doesn't hold for unions, intersections, or generic type references, - // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 8190 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } - // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates - // to X. Failing both of those we want to check if the aggregation of A and B's members structurally - // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { - // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isGenericMappedType(source) || isGenericMappedType(target)) { - result = mappedTypeRelatedTo(source, target, reportStructuralErrors); - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } - } - } - } - } - if (result) { - errorInfo = saveErrorInfo; - return result; - } - } - } - return 0 /* False */; - } - // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is - // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice - // that S and T are contra-variant whereas X and Y are co-variant. - function mappedTypeRelatedTo(source, target, reportErrors) { - if (isGenericMappedType(target)) { - if (isGenericMappedType(source)) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; - if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); - } - } - } - else if (target.declaration.questionToken && isEmptyObjectType(source)) { - return -1 /* True */; - } - } - else if (relation !== identityRelation) { - var resolved = resolveStructuredTypeMembers(target); - if (isEmptyResolvedType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & 1 /* Any */) { - return -1 /* True */; - } - } - return 0 /* False */; - } - function propertiesRelatedTo(source, target, reportErrors) { - if (relation === identityRelation) { - return propertiesIdenticalTo(source, target); - } - var result = -1 /* True */; - var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var targetProp = properties_4[_i]; - var sourceProp = getPropertyOfType(source, targetProp.name); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 67108864 /* Optional */) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0 /* False */; - } - } - else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); - if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - 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)); - } - return 0 /* False */; - } - if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { - if (reportErrors) { - if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { - reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); - } - else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); - } - } - return 0 /* False */; - } - } - else if (targetPropFlags & 16 /* Protected */) { - if (!isValidOverrideOf(sourceProp, targetProp)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); - } - return 0 /* False */; - } - } - else if (sourcePropFlags & 16 /* Protected */) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0 /* False */; - } - var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); - } - return 0 /* False */; - } - result &= related; - // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 67108864 /* Optional */ && !(targetProp.flags & 67108864 /* Optional */)) { - // TypeScript 1.0 spec (April 2014): 3.8.3 - // S is a subtype of a type T, and T is a supertype of S if ... - // S' and T are object types and, for each member M in T.. - // M is a property and S' contains a property N where - // if M is a required property, N is also a required property - // (M - property in T) - // (N - property in S) - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0 /* False */; - } - } - } - } - return result; - } - function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { - return 0 /* False */; - } - var sourceProperties = getPropertiesOfObjectType(source); - var targetProperties = getPropertiesOfObjectType(target); - if (sourceProperties.length !== targetProperties.length) { - return 0 /* False */; - } - var result = -1 /* True */; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; - var targetProp = getPropertyOfObjectType(target, sourceProp.name); - if (!targetProp) { - return 0 /* False */; - } - var related = compareProperties(sourceProp, targetProp, isRelatedTo); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function signaturesRelatedTo(source, target, kind, reportErrors) { - if (relation === identityRelation) { - return signaturesIdenticalTo(source, target, kind); - } - if (target === anyFunctionType || source === anyFunctionType) { - return -1 /* True */; - } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { - // An abstract constructor type is not assignable to a non-abstract constructor type - // as it would otherwise be possible to new an abstract class. Note that the assignability - // check we perform for an extends clause excludes construct signatures from the target, - // so this check never proceeds. - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0 /* False */; - } - if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { - return 0 /* False */; - } - } - var result = -1 /* True */; - var saveErrorInfo = errorInfo; - 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 */; - } - result &= related; - } - } - 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 result; - } - /** - * See signatureAssignableTo, compareSignaturesIdentical - */ - function signatureRelatedTo(source, target, reportErrors) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); - } - function signaturesIdenticalTo(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (sourceSignatures.length !== targetSignatures.length) { - return 0 /* False */; - } - var result = -1 /* True */; - for (var i = 0; i < sourceSignatures.length; i++) { - var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function eachPropertyRelatedTo(source, target, kind, reportErrors) { - var result = -1 /* True */; - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { - var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); - } - return 0 /* False */; - } - result &= related; - } - } - return result; - } - function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { - var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); - if (!related && reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return related; - } - function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(source, target, kind); - } - var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives - return -1 /* True */; - } - var sourceInfo = getIndexInfoOfType(source, kind) || - kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); - if (sourceInfo) { - return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); - } - if (isObjectLiteralType(source)) { - var related = -1 /* True */; - if (kind === 0 /* String */) { - var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); - if (sourceNumberInfo) { - related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); - } - } - if (related) { - related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); - } - return related; - } - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0 /* False */; - } - function indexTypesIdenticalTo(source, target, indexKind) { - var targetInfo = getIndexInfoOfType(target, indexKind); - var sourceInfo = getIndexInfoOfType(source, indexKind); - if (!sourceInfo && !targetInfo) { - return -1 /* True */; - } - if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { - return isRelatedTo(sourceInfo.type, targetInfo.type); - } - return 0 /* False */; - } - function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { - if (!sourceSignature.declaration || !targetSignature.declaration) { - return true; - } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; - // A public, protected and private signature is assignable to a private signature. - if (targetAccessibility === 8 /* Private */) { - return true; - } - // A public and protected signature is assignable to a protected signature. - if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { - return true; - } - // Only a public signature is assignable to public signature. - if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { - return true; - } - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); - } - return false; - } - } - // 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 (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); - var result = p && forEachProperty(p, callback); - if (result) { - return result; - } - } - return undefined; - } - return callback(prop); - } - // Return the declaring class type of a property or undefined if property not declared in class - function getDeclaringClass(prop) { - return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; - } - // Return true if some underlying source property is declared in a class that derives - // from the given base class. - function isPropertyInClassDerivedFrom(prop, baseClass) { - return forEachProperty(prop, function (sp) { - var sourceClass = getDeclaringClass(sp); - return sourceClass ? hasBaseType(sourceClass, baseClass) : false; - }); - } - // 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 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 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 - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16 /* Anonymous */) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32 /* Class */) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { - return true; - } - } - } - return false; - } - // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons - // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, - // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely - // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 - // levels, but unequal at some level beyond that. - function isDeeplyNestedType(type, stack, depth) { - // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 32768 /* Object */) { - var symbol = type.symbol; - if (symbol) { - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 32768 /* Object */ && t.symbol === symbol) { - count++; - if (count >= 5) - return true; - } - } - } - } - return false; - } - function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; - } - function compareProperties(sourceProp, targetProp, compareTypes) { - // Two members are considered identical when - // - they are public properties with identical names, optionality, and types, - // - they are private or protected properties originating in the same declaration and having identical types - if (sourceProp === targetProp) { - return -1 /* True */; - } - var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; - if (sourcePropAccessibility !== targetPropAccessibility) { - return 0 /* False */; - } - if (sourcePropAccessibility) { - if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { - return 0 /* False */; - } - } - else { - if ((sourceProp.flags & 67108864 /* Optional */) !== (targetProp.flags & 67108864 /* Optional */)) { - return 0 /* False */; - } - } - if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { - return 0 /* False */; - } - return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - function isMatchingSignature(source, target, partialMatch) { - // A source signature matches a target signature if the two signatures have the same number of required, - // optional, and rest parameters. - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { - return true; - } - // A source signature partially matches a target signature if the target signature has no fewer required - // parameters and no more overall parameters than the source signature (where a signature with a rest - // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { - return true; - } - return false; - } - /** - * See signatureRelatedTo, compareSignaturesIdentical - */ - function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { - // TODO (drosen): De-duplicate code between related functions. - if (source === target) { - return -1 /* True */; - } - if (!(isMatchingSignature(source, target, partialMatch))) { - return 0 /* False */; - } - // Check that the two signatures have the same number of type parameters. We might consider - // also checking that any type parameter constraints match, but that would require instantiating - // the constraints with a common set of type arguments to get relatable entities in places where - // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, - // particularly as we're comparing erased versions of the signatures below. - if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { - return 0 /* False */; - } - // Spec 1.0 Section 3.8.3 & 3.8.4: - // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1 /* True */; - if (!ignoreThisTypes) { - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType); - if (!related) { - return 0 /* False */; - } - result &= related; - } - } - } - var targetLen = target.parameters.length; - for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); - var related = compareTypes(s, t); - if (!related) { - return 0 /* False */; - } - result &= related; - } - if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - return result; - } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } - function isSupertypeOfEach(candidate, types) { - 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; - } - return true; - } - function literalTypesWithSameBaseType(types) { - var commonBaseType; - 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; - } - if (baseType === t || baseType !== commonBaseType) { - return false; - } - } - return true; - } - // When the candidate types are all literal types with the same base type, the common - // supertype is a union of those literal types. Otherwise, the common supertype is the - // first type that is a supertype of each of the other types. - function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); - } - function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); - } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (!primaryTypes.length) { - return getUnionType(types, /*subtypeReduction*/ true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - 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 - // to not be the common supertype. So if it weren't for this one downfallType (and possibly others), - // the type in question could have been the common supertype. - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - // types.length - 1 is the maximum score, given that getCommonSupertype returned false - if (bestSupertypeScore === types.length - 1) { - break; - } - } - // In the following errors, the {1} slot is before the {0} slot because checkTypeSubtypeOf supplies the - // subtype as the first argument to the error - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); - } - function isArrayType(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; - } - function isArrayLikeType(type) { - // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, - // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); - } - function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); - } - function isUnitType(type) { - 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 & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfLiteralType(type) { - 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 & 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; - } - /** - * Check if a Type was written as a tuple type literal. - * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. - */ - function isTupleType(type) { - return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); - } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // 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.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 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; - } - /** - * Return true if type was inferred from an object literal or written as an object type literal - * with no call or construct signatures. - */ - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && - getSignaturesOfType(type, 0 /* Call */).length === 0 && - getSignaturesOfType(type, 1 /* Construct */).length === 0; - } - function createSymbolWithType(source, type) { - var symbol = createSymbol(source.flags, source.name); - symbol.declarations = source.declarations; - symbol.parent = source.parent; - symbol.type = type; - symbol.target = source; - if (source.valueDeclaration) { - symbol.valueDeclaration = source.valueDeclaration; - } - return symbol; - } - function transformTypeOfMembers(type, f) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var property = _a[_i]; - var original = getTypeOfSymbol(property); - var updated = f(original); - members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); - } - return members; - } - /** - * If the the provided object literal is subject to the excess properties check, - * create a new that is exempt. Recursively mark object literal members as exempt. - * Leave signatures alone since they are not subject to the check. - */ - function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { - return type; - } - var regularType = type.regularType; - if (regularType) { - return regularType; - } - var resolved = type; - var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); - var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; - regularNew.objectFlags |= 128 /* ObjectLiteral */; - type.regularType = regularNew; - return regularNew; - } - function getWidenedProperty(prop) { - var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); - return widened === original ? prop : createSymbolWithType(prop, widened); - } - function getWidenedTypeOfObjectLiteral(type) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - // Since get accessors already widen their return value there is no need to - // widen accessor based properties here. - members.set(prop.name, prop.flags & 4 /* Property */ ? getWidenedProperty(prop) : prop); - } - var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); - var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - } - function getWidenedConstituentType(type) { - return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); - } - function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { - if (type.flags & 6144 /* Nullable */) { - return anyType; - } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - return getWidenedTypeOfObjectLiteral(type); - } - if (type.flags & 65536 /* Union */) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); - } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); - } - } - return type; - } - /** - * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' - * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to - * getWidenedType. But in some cases getWidenedType is called without reporting errors - * (type argument inference is an example). - * - * The return value indicates whether an error was in fact reported. The particular circumstances - * are on a best effort basis. Currently, if the null or undefined that causes widening is inside - * an object literal property (arbitrarily deeply), this function reports an error. If no error is - * reported, reportImplicitAnyError is a suitable fallback to report a general error. - */ - function reportWideningErrorsInType(type) { - var errorReported = false; - if (type.flags & 65536 /* Union */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152 /* ContainsWideningType */) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); - } - errorReported = true; - } - } - } - return errorReported; - } - function reportImplicitAnyError(declaration, type) { - var typeAsString = typeToString(getWidenedType(type)); - var diagnostic; - switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; - break; - case 146 /* Parameter */: - diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; - break; - case 176 /* BindingElement */: - diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; - break; - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - if (!declaration.name) { - error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); - return; - } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; - break; - default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; - } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); - } - function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { - // Report implicit any error within type if possible, otherwise report error on declaration - if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); - } - } - } - function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { - callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); - } - } - function createInferenceContext(signature, inferUnionTypes, useAnyForNoInferences) { - var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); - return { - signature: signature, - inferUnionTypes: inferUnionTypes, - inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length), - useAnyForNoInferences: useAnyForNoInferences - }; - } - function createTypeInferencesObject() { - return { - primary: undefined, - secondary: undefined, - topLevel: true, - isFixed: false, - }; - } - // Return true if the given type could possibly reference a type parameter for which - // we perform type inference (i.e. a type parameter of a generic function). We cache - // results for union and intersection types for performance reasons. - function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 /* TypeVariable */ || - objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || - objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || - objectFlags & 32 /* Mapped */ || - type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); - } - function couldUnionOrIntersectionContainTypeVariables(type) { - if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); - } - return type.couldContainTypeVariables; - } - function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); - } - // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct - // an object type with the same set of properties as the source type, where the type of each - // property is computed by inferring from the source property type to X for the type - // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). - function inferTypeForHomomorphicMappedType(source, target) { - var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0 /* String */); - if (properties.length === 0 && !indexInfo) { - return undefined; - } - var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var typeVariableArray = [typeVariable]; - var typeInferences = createTypeInferencesObject(); - var typeInferencesArray = [typeInferences]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - 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)); - if (!inferredPropType) { - return undefined; - } - var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.name); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; - inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; - members.set(prop.name, inferredProp); - } - if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - typeInferences.primary = undefined; - typeInferences.secondary = undefined; - inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); - var inferences = typeInferences.primary || typeInferences.secondary; - return inferences && getUnionType(inferences, /*subtypeReduction*/ true); - } - } - function inferTypesWithContext(context, originalSource, originalTarget) { - inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); - } - function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var symbolStack; - var visited; - var inferiority = 0; - inferFromTypes(originalSource, originalTarget); - function inferFromTypes(source, target) { - if (!couldContainTypeVariables(target)) { - return; - } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - var sourceTypes = source.aliasTypeArguments; - var targetTypes = target.aliasTypeArguments; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - return; - } - 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. - if (source === target) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } - // Find each source constituent type that has an identically matching target constituent - // type, and for each such type infer from the type to itself. When inferring from a - // type to itself we effectively find all type parameter occurrences within that type - // and infer themselves as their type arguments. We have special handling for numeric - // and string literals because the number and string types are not represented as unions - // of all their possible values. - var matchingTypes = void 0; - for (var _b = 0, _c = source.types; _b < _c.length; _b++) { - var t = _c[_b]; - if (typeIdenticalToSomeType(t, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t); - inferFromTypes(t, t); - } - else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { - var b = getBaseTypeOfLiteralType(t); - if (typeIdenticalToSomeType(b, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t, b); - } - } - } - // Next, to improve the quality of inferences, reduce the source and target types by - // removing the identically matched constituents. For example, when inferring from - // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. - if (matchingTypes) { - source = removeTypesFromUnionOrIntersection(source, matchingTypes); - target = removeTypesFromUnionOrIntersection(target, matchingTypes); - } - } - if (target.flags & 540672 /* TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. - if (source.flags & 8388608 /* ContainsAnyFunctionType */) { - return; - } - for (var i = 0; i < typeVariables.length; i++) { - if (target === typeVariables[i]) { - var inferences = typeInferences[i]; - if (!inferences.isFixed) { - // Any inferences that are made to a type parameter in a union type are inferior - // to inferences made to a flat (non-union) type. This is because if we infer to - // T | string[], we really don't know if we should be inferring to T or not (because - // the correct constituent on the target side could be string[]). Therefore, we put - // such inferior inferences into a secondary bucket, and only use them if the primary - // bucket is empty. - var candidates = inferiority ? - inferences.secondary || (inferences.secondary = []) : - inferences.primary || (inferences.primary = []); - if (!ts.contains(candidates, source)) { - candidates.push(source); - } - if (target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { - inferences.topLevel = false; - } - } - return; - } - } - } - else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { - // If source and target are references to the same generic type, infer from type arguments - var sourceTypes = source.typeArguments || emptyArray; - var targetTypes = target.typeArguments || emptyArray; - var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; - for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 196608 /* UnionOrIntersection */) { - var targetTypes = target.types; - var typeVariableCount = 0; - var typeVariable = void 0; - // First infer to each type in union or intersection that isn't a type variable - for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { - var t = targetTypes_3[_d]; - if (t.flags & 540672 /* TypeVariable */ && ts.contains(typeVariables, t)) { - typeVariable = t; - typeVariableCount++; - } - else { - inferFromTypes(source, t); - } - } - // Next, if target containings a single naked type variable, make a secondary inference to that type - // variable. This gives meaningful results for union types in co-variant positions and intersection - // types in contra-variant positions (such as callback parameters). - if (typeVariableCount === 1) { - inferiority++; - inferFromTypes(source, typeVariable); - inferiority--; - } - } - else if (source.flags & 196608 /* UnionOrIntersection */) { - // Source is a union or intersection type, infer from each constituent type - var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; - inferFromTypes(sourceType, target); - } - } - else { - source = getApparentType(source); - if (source.flags & 32768 /* Object */) { - var key = source.id + "," + target.id; - if (visited && visited.get(key)) { - return; - } - (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); - } - } - } - } - function inferFromObjectTypes(source, target) { - if (getObjectFlags(target) & 32 /* Mapped */) { - var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144 /* Index */) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - var index = ts.indexOf(typeVariables, constraintType.type); - if (index >= 0 && !typeInferences[index].isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - inferiority++; - inferFromTypes(inferredType, typeVariables[index]); - inferiority--; - } - } - return; - } - if (constraintType.flags & 16384 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - inferFromTypes(getIndexType(source), constraintType); - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); - return; - } - } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target); - } - function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.name); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - } - } - function inferFromSignatures(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - var sourceLen = sourceSignatures.length; - var targetLen = targetSignatures.length; - var len = sourceLen < targetLen ? sourceLen : targetLen; - for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); - } - } - function inferFromParameterTypes(source, target) { - return inferFromTypes(source, target); - } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromParameterTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - } - function inferFromIndexTypes(source, target) { - var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); - if (targetStringIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || - getImplicitIndexTypeOfType(source, 0 /* String */); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetStringIndexType); - } - } - var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); - if (targetNumberIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || - getIndexTypeOfType(source, 0 /* String */) || - getImplicitIndexTypeOfType(source, 1 /* Number */); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetNumberIndexType); - } - } - } - } - function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - /** - * Return a new union or intersection type computed by removing a given set of types - * from a given union or intersection type. - */ - function removeTypesFromUnionOrIntersection(type, typesToRemove) { - var reducedTypes = []; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!typeIdenticalToSomeType(t, typesToRemove)) { - reducedTypes.push(t); - } - } - return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); - } - function getInferenceCandidates(context, index) { - var inferences = context.inferences[index]; - return inferences.primary || inferences.secondary || emptyArray; - } - function hasPrimitiveConstraint(type) { - var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); - } - function getInferredType(context, index) { - var inferredType = context.inferredTypes[index]; - var inferenceSucceeded; - if (!inferredType) { - var inferences = getInferenceCandidates(context, index); - if (inferences.length) { - // We widen inferred literal types if - // all inferences were made to top-level ocurrences of the type parameter, and - // the type parameter has no constraint or its constraint includes no primitive or literal types, and - // the type parameter was fixed during inference or does not occur at top-level in the return type. - var signature = context.signature; - var widenLiteralTypes = context.inferences[index].topLevel && - !hasPrimitiveConstraint(signature.typeParameters[index]) && - (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; - // Infer widened union or supertype, or the unknown type for no common supertype - var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; - } - else { - // Infer either the default or the empty object type when no inferences were - // made. It is important to remember that in this case, inference still - // succeeds, meaning there is no error for not having inference candidates. An - // inference error only occurs when there are *conflicting* candidates, i.e. - // candidates with no common supertype. - var defaultType = getDefaultFromTypeParameter(context.signature.typeParameters[index]); - if (defaultType) { - // Instantiate the default type. Any forward reference to a type - // parameter should be instantiated to the empty object type. - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), getInferenceMapper(context))); - } - else { - inferredType = context.useAnyForNoInferences ? anyType : emptyObjectType; - } - inferenceSucceeded = true; - } - context.inferredTypes[index] = inferredType; - // Only do the constraint check if inference succeeded (to prevent cascading errors) - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - context.inferredTypes[index] = inferredType = instantiatedConstraint; - } - } - } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). - // It might be that inference has already failed on a later type parameter on a previous call to inferTypeArguments. - // So if this failure is on preceding type parameter, this type parameter is the new failure index. - context.failedTypeParameterIndex = index; - } - } - return inferredType; - } - function getInferredTypes(context) { - for (var i = 0; i < context.inferredTypes.length; i++) { - getInferredType(context, i); - } - return context.inferredTypes; - } - // EXPRESSION TYPE CHECKING - 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, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; - } - return links.resolvedSymbol; - } - function isInTypeQuery(node) { - // TypeScript 1.0 spec (April 2014): 3.6.3 - // A type query consists of the keyword typeof followed by an expression. - // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 162 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 143 /* QualifiedName */ ? false : "quit"; }); - } - // 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. 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 ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 99 /* ThisKeyword */) { - return "0"; - } - if (node.kind === 179 /* PropertyAccessExpression */) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + node.name.text; - } - return undefined; - } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - return node; - case 179 /* PropertyAccessExpression */: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } - function isMatchingReference(source, target) { - switch (source.kind) { - case 71 /* Identifier */: - return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 /* VariableDeclaration */ || target.kind === 176 /* BindingElement */) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99 /* ThisKeyword */: - return target.kind === 99 /* ThisKeyword */; - case 97 /* SuperKeyword */: - return target.kind === 97 /* SuperKeyword */; - case 179 /* PropertyAccessExpression */: - return target.kind === 179 /* PropertyAccessExpression */ && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } - return false; - } - function containsMatchingReference(source, target) { - while (source.kind === 179 /* PropertyAccessExpression */) { - source = source.expression; - if (isMatchingReference(source, target)) { - return true; - } - } - return false; - } - // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared - // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property - // a possible discriminant if its type differs in the constituents of containing union type, and if every - // choice is a unit type or a union of unit types. - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 /* PropertyAccessExpression */ && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71 /* Identifier */) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 179 /* PropertyAccessExpression */) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536 /* Union */) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } - function isOrContainsMatchingReference(source, target) { - return isMatchingReference(source, target) || containsMatchingReference(source, target); - } - function hasMatchingArgument(callExpression, reference) { - if (callExpression.arguments) { - for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isOrContainsMatchingReference(reference, argument)) { - return true; - } - } - } - if (callExpression.expression.kind === 179 /* PropertyAccessExpression */ && - isOrContainsMatchingReference(reference, callExpression.expression.expression)) { - return true; - } - return false; - } - function getFlowNodeId(flow) { - if (!flow.id) { - flow.id = nextFlowId; - nextFlowId++; - } - return flow.id; - } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536 /* Union */)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } - // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. - // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, - // we remove type string. - function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 8192 /* Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192 /* Never */)) { - return reducedType; - } - } - return declaredType; - } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - // We do a quick check for a "bind" property before performing the more expensive subtype - // check. This gives us a quicker out in the common case where an object type is not a function. - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); - } - function getTypeFacts(type) { - var flags = type.flags; - if (flags & 2 /* String */) { - return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; - } - if (flags & 32 /* StringLiteral */) { - var isEmpty = type.value === ""; - return strictNullChecks ? - 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 */) { - var isZero = type.value === 0; - return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; - } - if (flags & 8 /* Boolean */) { - return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; - } - if (flags & 136 /* BooleanLike */) { - return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; - } - if (flags & 32768 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : - strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; - } - if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { - return 2457472 /* UndefinedFacts */; - } - if (flags & 4096 /* Null */) { - return 2340752 /* NullFacts */; - } - if (flags & 512 /* ESSymbol */) { - return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; - } - if (flags & 16777216 /* NonPrimitive */) { - return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; - } - if (flags & 540672 /* TypeVariable */) { - return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); - } - if (flags & 196608 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); - } - return 8388607 /* All */; - } - function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); - } - function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); - } - return type; - } - function getTypeOfDestructuredProperty(type, name) { - var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || - isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || - getIndexTypeOfType(type, 0 /* String */) || - unknownType; - } - function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || - checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || - unknownType; - } - function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType); - } - function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); - return isDestructuringDefaultAssignment ? - getTypeWithDefault(getAssignedType(node), node.right) : - getTypeOfExpression(node.right); - } - function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 216 /* ForOfStatement */ && parent.parent.initializer === parent; - } - function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); - } - function getAssignedTypeOfSpreadExpression(node) { - return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); - } - function getAssignedTypeOfPropertyAssignment(node) { - return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); - } - function getAssignedTypeOfShorthandPropertyAssignment(node) { - return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); - } - function getAssignedType(node) { - var parent = node.parent; - switch (parent.kind) { - case 215 /* ForInStatement */: - return stringType; - case 216 /* ForOfStatement */: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194 /* BinaryExpression */: - return getAssignedTypeOfBinaryExpression(parent); - case 188 /* DeleteExpression */: - return undefinedType; - case 177 /* ArrayLiteralExpression */: - return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198 /* SpreadElement */: - return getAssignedTypeOfSpreadExpression(parent); - case 261 /* PropertyAssignment */: - return getAssignedTypeOfPropertyAssignment(parent); - case 262 /* ShorthandPropertyAssignment */: - return getAssignedTypeOfShorthandPropertyAssignment(parent); - } - return unknownType; - } - function getInitialTypeOfBindingElement(node) { - var pattern = node.parent; - var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 /* ObjectBindingPattern */ ? - getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : - !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadExpression(parentType); - return getTypeWithDefault(type, node.initializer); - } - function getTypeOfInitializer(node) { - // Return the cached type if one is available. If the type of the variable was inferred - // from its initializer, we'll already have cached the type. Otherwise we compute it now - // without caching such that transient types are reflected. - var links = getNodeLinks(node); - return links.resolvedType || getTypeOfExpression(node); - } - function getInitialTypeOfVariableDeclaration(node) { - if (node.initializer) { - return getTypeOfInitializer(node.initializer); - } - if (node.parent.parent.kind === 215 /* ForInStatement */) { - return stringType; - } - if (node.parent.parent.kind === 216 /* ForOfStatement */) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; - } - return unknownType; - } - function getInitialType(node) { - return node.kind === 226 /* VariableDeclaration */ ? - getInitialTypeOfVariableDeclaration(node) : - getInitialTypeOfBindingElement(node); - } - function getInitialOrAssignedType(node) { - return node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */ ? - getInitialType(node) : - getAssignedType(node); - } - function isEmptyArrayAssignment(node) { - return node.kind === 226 /* VariableDeclaration */ && node.initializer && - isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 /* BindingElement */ && node.parent.kind === 194 /* BinaryExpression */ && - isEmptyArrayLiteral(node.parent.right); - } - function getReferenceCandidate(node) { - switch (node.kind) { - case 185 /* ParenthesizedExpression */: - return getReferenceCandidate(node.expression); - case 194 /* BinaryExpression */: - switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: - return getReferenceCandidate(node.left); - case 26 /* CommaToken */: - return getReferenceCandidate(node.right); - } - } - return node; - } - function getReferenceRoot(node) { - var parent = node.parent; - return parent.kind === 185 /* ParenthesizedExpression */ || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? - getReferenceRoot(parent) : node; - } - function getTypeOfSwitchClause(clause) { - if (clause.kind === 257 /* CaseClause */) { - var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); - return isUnitType(caseType) ? caseType : undefined; - } - return neverType; - } - function getSwitchClauseTypes(switchStatement) { - var links = getNodeLinks(switchStatement); - if (!links.switchTypes) { - // If all case clauses specify expressions that have unit types, we return an array - // of those unit types. Otherwise we return an empty array. - var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; - } - return links.switchTypes; - } - function eachTypeContainedIn(source, types) { - return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536 /* Union */) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { - return true; - } - return containsType(target.types, source); - } - function forEachType(type, f) { - return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); - } - function filterType(type, f) { - if (type.flags & 65536 /* Union */) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; - } - // Apply a mapping function to a type and return the resulting type. If the source type - // is a union type, the mapping function is applied to each constituent type and a union - // of the resulting types is returned. - function mapType(type, mapper) { - if (!(type.flags & 65536 /* Union */)) { - return mapper(type); - } - var types = type.types; - var mappedType; - var mappedTypes; - 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) { - mappedType = t; - } - else if (!mappedTypes) { - mappedTypes = [mappedType, t]; - } - else { - mappedTypes.push(t); - } - } - } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; - } - function extractTypesOfKind(type, kind) { - return filterType(type, function (t) { return (t.flags & kind) !== 0; }); - } - // Return a new type in which occurrences of the string and number primitive types in - // typeWithPrimitives have been replaced with occurrences of string literals and numeric - // literals in typeWithLiterals, respectively. - function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { - return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : - t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : - t; - }); - } - return typeWithPrimitives; - } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - // An evolving array type tracks the element types that have so far been seen in an - // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving - // array types are ultimately converted into manifest array types (using getFinalArrayType) - // and never escape the getFlowTypeOfReference function. - function createEvolvingArrayType(elementType) { - var result = createObjectType(256 /* EvolvingArray */); - result.elementType = elementType; - return result; - } - function getEvolvingArrayType(elementType) { - return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); - } - // When adding evolving array element types we do not perform subtype reduction. Instead, - // we defer subtype reduction until the evolving array type is finalized into a manifest - // array type. - function addEvolvingArrayElementType(evolvingArrayType, node) { - var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); - return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); - } - function createFinalArrayType(elementType) { - return elementType.flags & 8192 /* Never */ ? - autoArrayType : - createArrayType(elementType.flags & 65536 /* Union */ ? - getUnionType(elementType.types, /*subtypeReduction*/ true) : - elementType); - } - // We perform subtype reduction upon obtaining the final array type from an evolving array type. - function getFinalArrayType(evolvingArrayType) { - return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); - } - function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; - } - function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; - } - function isEvolvingArrayTypeList(types) { - var hasEvolvingArrayType = false; - 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; - } - hasEvolvingArrayType = true; - } - } - return hasEvolvingArrayType; - } - // At flow control branch or loop junctions, if the type along every antecedent code path - // is an evolving array type, we construct a combined evolving array type. Otherwise we - // finalize all evolving array types. - function getUnionOrEvolvingArrayType(types, subtypeReduction) { - return isEvolvingArrayTypeList(types) ? - getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : - getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); - } - // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or - // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. - function isEvolvingArrayOperationTarget(node) { - var root = getReferenceRoot(node); - var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 /* PropertyAccessExpression */ && (parent.name.text === "length" || - parent.parent.kind === 181 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 /* ElementAccessExpression */ && - parent.expression === root && - parent.parent.kind === 194 /* BinaryExpression */ && - parent.parent.operatorToken.kind === 58 /* EqualsToken */ && - parent.parent.left === parent && - !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); - return isLengthPushOrUnshift || isElementAssignment; - } - function maybeTypePredicateCall(node) { - var links = getNodeLinks(node); - if (links.maybeTypePredicate === undefined) { - links.maybeTypePredicate = getMaybeTypePredicate(node); - } - return links.maybeTypePredicate; - } - function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97 /* SuperKeyword */) { - var funcType = checkNonNullExpression(node.expression); - if (funcType !== silentNeverType) { - var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } - } - } - return false; - } - function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { - if (initialType === void 0) { initialType = declaredType; } - var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { - return declaredType; - } - var visitedFlowStart = visitedFlowCount; - var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; - // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, - // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations - // on empty arrays are possible without implicit any errors and new element types can be inferred without - // type mismatch errors. - var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { - return declaredType; - } - return resultType; - function getTypeAtFlowNode(flow) { - while (true) { - if (flow.flags & 1024 /* Shared */) { - // We cache results of flow type resolution for shared nodes that were previously visited in - // the same getFlowTypeOfReference invocation. A node is considered shared when it is the - // antecedent of more than one node. - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; - } - } - } - var type = void 0; - if (flow.flags & 4096 /* AfterFinally */) { - // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement - flow.locked = true; - type = getTypeAtFlowNode(flow.antecedent); - flow.locked = false; - } - else if (flow.flags & 2048 /* PreFinally */) { - // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel - // so here just redirect to antecedent - flow = flow.antecedent; - continue; - } - else if (flow.flags & 16 /* Assignment */) { - type = getTypeAtFlowAssignment(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 96 /* Condition */) { - type = getTypeAtFlowCondition(flow); - } - else if (flow.flags & 128 /* SwitchClause */) { - type = getTypeAtSwitchClause(flow); - } - else if (flow.flags & 12 /* Label */) { - if (flow.antecedents.length === 1) { - flow = flow.antecedents[0]; - continue; - } - type = flow.flags & 4 /* BranchLabel */ ? - getTypeAtFlowBranchLabel(flow) : - getTypeAtFlowLoopLabel(flow); - } - else if (flow.flags & 256 /* ArrayMutation */) { - type = getTypeAtFlowArrayMutation(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 2 /* Start */) { - // Check if we should continue with the control flow of the containing function. - var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { - flow = container.flowNode; - continue; - } - // At the top of the flow we have the initial type. - type = initialType; - } - else { - // Unreachable code errors are reported in the binding phase. Here we - // simply return the non-auto declared type to reduce follow-on errors. - type = convertAutoToAny(declaredType); - } - if (flow.flags & 1024 /* Shared */) { - // Record visited node and the associated type in the cache. - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; - } - return type; - } - } - function getTypeAtFlowAssignment(flow) { - var node = flow.node; - // Assignments only narrow the computed type if the declared type is a union type. Thus, we - // only need to evaluate the assigned type if the declared type is a union type. - if (isMatchingReference(reference, node)) { - if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { - var flowType = getTypeAtFlowNode(flow.antecedent); - return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); - } - if (declaredType === autoType || declaredType === autoArrayType) { - if (isEmptyArrayAssignment(node)) { - return getEvolvingArrayType(neverType); - } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); - return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; - } - if (declaredType.flags & 65536 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); - } - return declaredType; - } - // We didn't have a direct match. However, if the reference is a dotted name, this - // may be an assignment to a left hand part of the reference. For example, for a - // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, - // return the declared type. - if (containsMatchingReference(reference, node)) { - return declaredType; - } - // Assignment doesn't affect reference - return undefined; - } - function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 /* CallExpression */ ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256 /* EvolvingArray */) { - var evolvedType_1 = type; - if (node.kind === 181 /* CallExpression */) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); - } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); - } - } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); - } - return flowType; - } - return undefined; - } - function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (type.flags & 8192 /* Never */) { - return flowType; - } - // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by switching to the silent never type which - // doesn't report errors when operators are applied to it. Note that this is the - // *only* place a silent never type is ever generated. - var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; - var nonEvolvingType = finalizeEvolvingArrayType(type); - var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); - if (narrowedType === nonEvolvingType) { - return flowType; - } - var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; - return createFlowType(resultType, incomplete); - } - function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); - } - function getTypeAtFlowBranchLabel(flow) { - var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { - // if flow correspond to branch from pre-try to finally and this branch is locked - this means that - // we initially have started following the flow outside the finally block. - // in this case we should ignore this branch. - continue; - } - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); - // If the type at a particular antecedent path is the declared type and the - // reference is known to always be assigned (i.e. when declared and initial types - // are the same), there is no reason to process more antecedents since the only - // possible outcome is subtypes that will be removed in the final union type anyway. - if (type === declaredType && declaredType === initialType) { - return type; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } - } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); - } - function getTypeAtFlowLoopLabel(flow) { - // If we have previously computed the control flow type for the reference at - // this flow loop junction, return the cached type. - var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); - if (!key) { - key = getFlowCacheKey(reference); - } - var cached = cache.get(key); - if (cached) { - return cached; - } - // If this flow loop junction and reference are already being processed, return - // the union of the types computed for each branch so far, marked as incomplete. - // It is possible to see an empty array in cases where loops are nested and the - // back edge of the outer loop reaches an inner loop that is already being analyzed. - // In such cases we restart the analysis of the inner loop, which will then see - // a non-empty in-process array for the outer loop and eventually terminate because - // the first antecedent of a loop junction is always the non-looping control flow - // path that leads to the top. - for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); - } - } - // Add the flow loop junction and reference to the in-process stack and analyze - // each antecedent code path. - var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; - flowLoopNodes[flowLoopCount] = flow; - flowLoopKeys[flowLoopCount] = key; - flowLoopTypes[flowLoopCount] = antecedentTypes; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); - flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis - // was restarted and completed by checkExpressionCached. We can simply pick up - // the resulting type and bail out. - var cached_1 = cache.get(key); - if (cached_1) { - return cached_1; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - // If the type at a particular antecedent path is the declared type there is no - // reason to process more antecedents since the only possible outcome is subtypes - // that will be removed in the final union type anyway. - if (type === declaredType) { - break; - } - } - // The result is incomplete if the first antecedent (the non-looping control flow path) - // is incomplete. - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, /*incomplete*/ true); - } - cache.set(key, result); - return result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 179 /* PropertyAccessExpression */ && - declaredType.flags & 65536 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); - } - function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; - } - function narrowTypeByBinaryExpression(type, expr, assumeTrue) { - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); - } - if (right_1.kind === 189 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); - } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); - } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); - } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); - } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; - } - break; - case 93 /* InstanceOfKeyword */: - return narrowTypeByInstanceof(type, expr, assumeTrue); - case 26 /* CommaToken */: - return narrowType(type, expr.right, assumeTrue); - } - return type; - } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1 /* Any */) { - return type; - } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } - var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144 /* Nullable */) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; - var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 95 /* NullKeyword */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; - return getTypeWithFacts(type, facts); - } - if (type.flags & 16810497 /* NotUnionOrUnit */) { - return type; - } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); - } - if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); - } - return type; - } - function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands - var target = getReferenceCandidate(typeOfExpr.expression); - if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { - return declaredType; - } - return type; - } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } - if (assumeTrue && !(type.flags & 65536 /* Union */)) { - // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed - // to one of the primitive types. - var targetType = typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } - } - } - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); - } - function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - // We only narrow if all case expressions specify values with unit types - var switchTypes = getSwitchClauseTypes(switchStatement); - if (!switchTypes.length) { - return type; - } - var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); - if (!hasDefaultClause) { - return caseType; - } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); - } - function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); - if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { - return declaredType; - } - return type; - } - // Check that right operand is a function type with a prototype property - var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { - return type; - } - var targetType; - var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (prototypeProperty) { - // Target type is type of the prototype property - var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (!isTypeAny(prototypePropertyType)) { - targetType = prototypePropertyType; - } - } - // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } - if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } - } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); - } - return type; - } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { - if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); - } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 65536 /* Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192 /* Never */)) { - return assignableType; - } - } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); - } - function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { - return type; - } - var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; - if (!predicate) { - return type; - } - // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; - if (predicateArgument) { - if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } - } - } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 /* ElementAccessExpression */ || invokedExpression.kind === 179 /* PropertyAccessExpression */) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } - return type; - } - // Narrow the given type based on the given expression having the assumed boolean value. The returned type - // will be a subtype or the same type as the argument. - function narrowType(type, expr, assumeTrue) { - switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 179 /* PropertyAccessExpression */: - return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181 /* CallExpression */: - return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185 /* ParenthesizedExpression */: - return narrowType(type, expr.expression, assumeTrue); - case 194 /* BinaryExpression */: - return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192 /* PrefixUnaryExpression */: - if (expr.operator === 51 /* ExclamationToken */) { - return narrowType(type, expr.operand, !assumeTrue); - } - break; - } - return type; - } - } - function getTypeOfSymbolAtLocation(symbol, location) { - // If we have an identifier or a property access at the given location, if the location is - // an dotted name expression, and if the location is not an assignment target, obtain the type - // of the expression (which will reflect control flow analysis). If the expression indeed - // resolved to the given symbol, return the narrowed type. - if (location.kind === 71 /* Identifier */) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { - location = location.parent; - } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { - var type = getTypeOfExpression(location); - if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { - return type; - } - } - } - // The location isn't a reference to the given symbol, meaning we're being asked - // a hypothetical question of what type the symbol would have if there was a reference - // to it at the given location. Since we have no control flow information for the - // hypothetical reference (control flow information is created and attached by the - // binder), we simply return the declared type of the symbol. - return getTypeOfSymbol(symbol); - } - function getControlFlowContainer(node) { - return ts.findAncestor(node.parent, function (node) { - return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 /* ModuleBlock */ || - node.kind === 265 /* SourceFile */ || - node.kind === 149 /* PropertyDeclaration */; - }); - } - // Check if a parameter is assigned anywhere within its declaring function. - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); - } - function markParameterAssignments(node) { - if (node.kind === 71 /* Identifier */) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146 /* Parameter */) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); - } - } - function isConstVariable(symbol) { - return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; - } - /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ - function removeOptionalityFromDeclaredType(declaredType, declaration) { - var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 /* Parameter */ && - declaration.initializer && - getFalsyFlags(declaredType) & 2048 /* Undefined */ && - !(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) { - return unknownType; - } - // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. - // Although in down-level emit of arrow function, we emit it using function expression which means that - // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects - // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. - // To avoid that we will give an error to users if they use arguments objects in arrow function so that they - // can explicitly bound arguments objects - if (symbol === argumentsSymbol) { - var container = ts.getContainingFunction(node); - if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 187 /* ArrowFunction */) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); - } - else if (ts.hasModifier(container, 256 /* Async */)) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); - } - } - getNodeLinks(container).flags |= 8192 /* CaptureArguments */; - return getTypeOfSymbol(symbol); - } - if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); - } - var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (localOrExportSymbol.flags & 32 /* Class */) { - var declaration_1 = localOrExportSymbol.valueDeclaration; - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - if (declaration_1.kind === 229 /* ClassDeclaration */ - && ts.nodeIsDecorated(declaration_1)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === declaration_1 && container.name !== node) { - getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; - break; - } - container = ts.getContainingClass(container); - } - } - else if (declaration_1.kind === 199 /* ClassExpression */) { - // When we emit a class expression with static members that contain a reference - // to the constructor in the initializer, we will need to substitute that - // binding with an alias as the class name is not in scope. - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container !== undefined) { - if (container.parent === declaration_1) { - if (container.kind === 149 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; - } - break; - } - container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); - } - } - } - checkCollisionWithCapturedSuperVariable(node, node); - checkCollisionWithCapturedThisVariable(node, node); - checkCollisionWithCapturedNewTargetVariable(node, node); - checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); - var declaration = localOrExportSymbol.valueDeclaration; - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3 /* Variable */)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); - return unknownType; - } - if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); - return unknownType; - } - } - // We only narrow variables and parameters occurring in a non-assignment position. For all other - // entities we simply return the declared type. - if (!(localOrExportSymbol.flags & 3 /* Variable */) || assignmentKind === 1 /* Definite */ || !declaration) { - return type; - } - // The declaration container is the innermost function that encloses the declaration of the variable - // or parameter. The flow container is the innermost function starting with which we analyze the control - // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 146 /* Parameter */; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - // When the control flow originates in a function expression or arrow function and we are referencing - // a const variable or parameter from an outer function, we extend the origin of the control flow - // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 /* FunctionExpression */ || - flowContainer.kind === 187 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && - (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - // We only look for uninitialized variables in strict null checking mode, and only when we can analyze - // the entire control flow graph from the variable's declaration (i.e. when the flow container and - // declaration container are the same). - var assumeInitialized = isParameter || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 246 /* ExportSpecifier */) || - ts.isInAmbientContext(declaration); - var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : - type === autoType || type === autoArrayType ? undefinedType : - 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 - // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { - if (flowType === autoType || flowType === autoArrayType) { - if (noImplicitAny) { - 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); - } - } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - // Return the declared type to reduce follow-on errors - return type; - } - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); - } - function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 /* ES2015 */ || - (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 260 /* CatchClause */) { - return; - } - // 1. walk from the use site up to the declaration and check - // if there is anything function like between declaration and use-site (is binding/class is captured in function). - // 2. walk from the declaration up to the boundary of lexical environment and check - // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { - // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; - } - // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. - // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 214 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 227 /* VariableDeclarationList */).parent === container && - isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; - } - // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; - } - if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; - } - } - function isAssignedInBodyOfForStatement(node, container) { - // skip parenthesized nodes - var current = node; - while (current.parent.kind === 185 /* ParenthesizedExpression */) { - current = current.parent; - } - // check if node is used as LHS in some assignment expression - var isAssigned = false; - if (ts.isAssignmentTarget(current)) { - isAssigned = true; - } - else if ((current.parent.kind === 192 /* PrefixUnaryExpression */ || current.parent.kind === 193 /* PostfixUnaryExpression */)) { - var expr = current.parent; - isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; - } - if (!isAssigned) { - return false; - } - // at this point we know that node is the target of assignment - // now check that modification happens inside the statement part of the ForStatement - return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); - } - function captureLexicalThis(node, container) { - getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 149 /* PropertyDeclaration */ || container.kind === 152 /* Constructor */) { - var classNode = container.parent; - getNodeLinks(classNode).flags |= 4 /* CaptureThis */; - } - else { - getNodeLinks(container).flags |= 4 /* CaptureThis */; - } - } - function findFirstSuperCall(n) { - if (ts.isSuperCall(n)) { - return n; - } - else if (ts.isFunctionLike(n)) { - return undefined; - } - return ts.forEachChild(n, findFirstSuperCall); - } - /** - * Return a cached result if super-statement is already found. - * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor - * - * @param constructor constructor-function to look for super statement - */ - function getSuperCallInConstructor(constructor) { - var links = getNodeLinks(constructor); - // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result - if (links.hasSuperCall === undefined) { - links.superCall = findFirstSuperCall(constructor.body); - links.hasSuperCall = links.superCall ? true : false; - } - return links.superCall; - } - /** - * Check if the given class-declaration extends null then return true. - * Otherwise, return false - * @param classDecl a class declaration to check if it extends null - */ - function classDeclarationExtendsNull(classDecl) { - var classSymbol = getSymbolOfNode(classDecl); - var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); - return baseConstructorType === nullWideningType; - } - function checkThisBeforeSuper(node, container, diagnosticMessage) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - // If a containing class does not have extends clause or the class extends null - // skip checking whether super statement is called before "this" accessing. - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - // We should give an error in the following cases: - // - No super-call - // - "this" is accessing before super-call. - // i.e super(this) - // this.x; super(); - // We want to make sure that super-call is done before accessing "this" so that - // "this" is not accessed as a parameter of the super-call. - if (!superCall || superCall.end > node.pos) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, diagnosticMessage); - } - } - } - function checkThisExpression(node) { - // Stop at the first arrow function so that we can - // tell whether 'this' needs to be captured. - var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; - if (container.kind === 152 /* Constructor */) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 187 /* ArrowFunction */) { - container = ts.getThisContainer(container, /* includeArrowFunctions */ false); - // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); - } - switch (container.kind) { - case 233 /* ModuleDeclaration */: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - break; - case 232 /* EnumDeclaration */: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - break; - case 152 /* Constructor */: - if (isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - } - break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - if (ts.getModifierFlags(container) & 32 /* Static */) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - } - break; - case 144 /* ComputedPropertyName */: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); - break; - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node, container); - } - if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. Check if it's the RHS - // of a x.prototype.y = function [name]() { .... } - if (container.kind === 186 /* FunctionExpression */ && - container.parent.kind === 194 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x - var classSymbol = checkExpression(className).symbol; - if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getInferredClassType(classSymbol); - } - } - var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); - if (thisType) { - return thisType; - } - } - if (ts.isClassLike(container.parent)) { - var symbol = getSymbolOfNode(container.parent); - var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type); - } - if (ts.isInJavaScriptFile(node)) { - var type = getTypeForThisExpressionFromJSDoc(container); - if (type && type !== unknownType) { - return type; - } - } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; - } - function getTypeForThisExpressionFromJSDoc(node) { - var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 279 /* JSDocFunctionType */) { - var jsDocFunctionType = jsdocType; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 282 /* JSDocThisType */) { - return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); - } - } - } - function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146 /* Parameter */; }); - } - function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 /* CallExpression */ && node.parent.expression === node; - var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); - var needToCaptureLexicalThis = false; - // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting - if (!isCallExpression) { - while (container && container.kind === 187 /* ArrowFunction */) { - container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); - needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; - } - } - var canUseSuperExpression = isLegalUsageOfSuperExpression(container); - var nodeCheckFlag = 0; - if (!canUseSuperExpression) { - // issue more specific error if super is used in computed property name - // class A { foo() { return "1" }} - // class B { - // [super.foo()]() {} - // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144 /* ComputedPropertyName */; }); - if (current && current.kind === 144 /* ComputedPropertyName */) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); - } - else if (isCallExpression) { - error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); - } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); - } - else { - error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); - } - return unknownType; - } - if (!isCallExpression && container.kind === 152 /* Constructor */) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); - } - if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { - nodeCheckFlag = 512 /* SuperStatic */; - } - else { - nodeCheckFlag = 256 /* SuperInstance */; - } - getNodeLinks(node).flags |= nodeCheckFlag; - // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. - // This is due to the fact that we emit the body of an async function inside of a generator function. As generator - // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper - // uses an arrow function, which is permitted to reference `super`. - // - // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property - // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value - // of a property or indexed access, either as part of an assignment expression or destructuring assignment. - // - // The simplest case is reading a value, in which case we will emit something like the following: - // - // // ts - // ... - // async asyncMethod() { - // let x = await super.asyncMethod(); - // return x; - // } - // ... - // - // // js - // ... - // asyncMethod() { - // const _super = name => super[name]; - // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); - // return x; - // }); - // } - // ... - // - // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: - // - // // ts - // ... - // async asyncMethod(ar: Promise) { - // [super.a, super.b] = await ar; - // } - // ... - // - // // js - // ... - // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; - // }); - // } - // ... - // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. - if (container.kind === 151 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { - if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; - } - else { - getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; - } - } - if (needToCaptureLexicalThis) { - // call expressions are allowed only in constructors so they should always capture correct 'this' - // super property access expressions can also appear in arrow functions - - // in this case they should also use correct lexical this - captureLexicalThis(node.parent, container); - } - if (container.parent.kind === 178 /* ObjectLiteralExpression */) { - if (languageVersion < 2 /* ES2015 */) { - error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); - return unknownType; - } - else { - // for object literal assume that type of 'super' is 'any' - return anyType; - } - } - // at this point the only legal case for parent is ClassLikeDeclaration - var classLikeDeclaration = container.parent; - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } - if (container.kind === 152 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { - // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) - error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); - return unknownType; - } - return nodeCheckFlag === 512 /* SuperStatic */ - ? getBaseConstructorTypeOfClass(classType) - : getTypeWithThisArgument(baseClassType, classType.thisType); - function isLegalUsageOfSuperExpression(container) { - if (!container) { - return false; - } - if (isCallExpression) { - // TS 1.0 SPEC (April 2014): 4.8.1 - // Super calls are only permitted in constructors of derived classes - return container.kind === 152 /* Constructor */; - } - else { - // TS 1.0 SPEC (April 2014) - // 'super' property access is allowed - // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance - // - In a static member function or static member accessor - // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { - if (ts.getModifierFlags(container) & 32 /* Static */) { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */; - } - else { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */ || - container.kind === 149 /* PropertyDeclaration */ || - container.kind === 148 /* PropertySignature */ || - container.kind === 152 /* Constructor */; - } - } - } - return false; - } - } - function getContainingObjectLiteral(func) { - return (func.kind === 151 /* MethodDeclaration */ || - func.kind === 153 /* GetAccessor */ || - func.kind === 154 /* SetAccessor */) && func.parent.kind === 178 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 186 /* FunctionExpression */ && func.parent.kind === 261 /* PropertyAssignment */ ? func.parent.parent : - undefined; - } - function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; - } - function getThisTypeFromContextualType(type) { - return mapType(type, function (t) { - return t.flags & 131072 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); - }); - } - function getContextualThisParameterType(func) { - if (func.kind === 187 /* ArrowFunction */) { - return undefined; - } - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var thisParameter = contextualSignature.thisParameter; - if (thisParameter) { - return getTypeOfSymbol(thisParameter); - } - } - } - if (noImplicitThis) { - var containingLiteral = getContainingObjectLiteral(func); - if (containingLiteral) { - // We have an object literal method. Check if the containing object literal has a contextual type - // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in - // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); - var literal = containingLiteral; - var type = contextualType; - while (type) { - var thisType = getThisTypeFromContextualType(type); - if (thisType) { - return instantiateType(thisType, getContextualMapper(containingLiteral)); - } - if (literal.parent.kind !== 261 /* PropertyAssignment */) { - break; - } - literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); - } - // There was no contextual ThisType for the containing object literal, so the contextual type - // for 'this' is the non-null form of the contextual type for the containing object literal or - // the type of the object literal itself. - return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); - } - // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the - // contextual type for 'this' is 'obj'. - if (func.parent.kind === 194 /* BinaryExpression */ && func.parent.operatorToken.kind === 58 /* EqualsToken */) { - var target = func.parent.left; - if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { - return checkExpressionCached(target.expression); - } - } - } - return undefined; - } - // Return contextual type of parameter or undefined if no contextual type is available - function getContextuallyTypedParameterType(parameter) { - var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; - } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; - } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } - } - } - return undefined; - } - // In a variable, parameter or property declaration with a type annotation, - // the contextual type of an initializer expression is the type of the variable, parameter or property. - // Otherwise, in a parameter declaration of a contextually typed function expression, - // the contextual type of an initializer expression is the contextual type of the parameter. - // Otherwise, in a variable or parameter declaration with a binding pattern name, - // the contextual type of an initializer expression is the type implied by the binding pattern. - // Otherwise, in a binding pattern inside a variable or parameter declaration, - // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. - function getContextualTypeForInitializerExpression(node) { - var declaration = node.parent; - if (node === declaration.initializer) { - if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.kind === 146 /* Parameter */) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); - } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176 /* BindingElement */ && - parentDeclaration.type && - !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); - } - } - } - } - return undefined; - } - function getContextualTypeForReturnExpression(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { - return undefined; - } - var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function - } - return undefined; - } - function getContextualTypeForYieldOperand(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); - if (contextualReturnType) { - return node.asteriskToken - ? contextualReturnType - : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); - } - } - return undefined; - } - function isInParameterInitializerBeforeContainingFunction(node) { - while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 /* Parameter */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } - function getContextualReturnType(functionDecl) { - // If the containing function has a return type annotation, is a constructor, or is a get accessor whose - // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.type || - functionDecl.kind === 152 /* Constructor */ || - functionDecl.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 154 /* SetAccessor */))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); - } - // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature - // and that call signature is non-generic, return statements are contextually typed by the return type of the signature - var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { - return getReturnTypeOfSignature(signature); - } - return undefined; - } - // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); - if (argIndex >= 0) { - var signature = getResolvedOrAnySignature(callTarget); - return getTypeAtPosition(signature, argIndex); - } - return undefined; - } - function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183 /* TaggedTemplateExpression */) { - return getContextualTypeForArgument(template.parent, substitutionExpression); - } - return undefined; - } - function getContextualTypeForBinaryOperand(node) { - var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (operator >= 58 /* FirstAssignment */ && operator <= 70 /* LastAssignment */) { - // Don't do this for special property assignments to avoid circularity - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { - return undefined; - } - // In an assignment expression, the right operand is contextually typed by the type of the left operand. - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } - } - else if (operator === 54 /* BarBarToken */) { - // When an || expression has a contextual type, the operands are contextually typed by that type. When an || - // expression has no contextual type, the right operand is contextually typed by the type of the left operand. - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); - } - return type; - } - else if (operator === 53 /* AmpersandAmpersandToken */ || operator === 26 /* CommaToken */) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } - } - return undefined; - } - function getTypeOfPropertyOfContextualType(type, name) { - return mapType(type, function (t) { - var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; - }); - } - function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); - } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } - // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of - // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one - // exists. Otherwise, it is the type of the string index signature in T, if one exists. - function getContextualTypeForObjectLiteralMethod(node) { - ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return undefined; - } - return getContextualTypeForObjectLiteralElement(node); - } - function getContextualTypeForObjectLiteralElement(element) { - var objectLiteral = element.parent; - var type = getApparentTypeOfContextualType(objectLiteral); - if (type) { - if (!ts.hasDynamicName(element)) { - // For a (non-symbol) computed property, there is no reason to look up the name - // in the type. It will just be "__computed", which does not appear in any - // SymbolTable. - var symbolName = getSymbolOfNode(element).name; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); - if (propertyType) { - return propertyType; - } - } - return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || - getIndexTypeOfContextualType(type, 0 /* String */); - } - return undefined; - } - // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is - // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, - // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated - // type of T. - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1 /* Number */) - || getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false); - } - return undefined; - } - // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. - function getContextualTypeForConditionalOperand(node) { - var conditional = node.parent; - return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; - } - function getContextualTypeForJsxExpression(node) { - // JSX expression can appear in two position : JSX Element's children or JSX attribute - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - node.parent.openingElement.attributes; // node.parent is JsxElement - // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type - // which is a type of the parameter of the signature we are trying out. - // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - // JSX expression is in JSX attribute - return getTypeOfPropertyOfType(attributesType, node.parent.name.text); - } - else if (node.parent.kind === 249 /* JsxElement */) { - // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - // JSX expression is in JSX spread attribute - return attributesType; - } - } - function getContextualTypeForJsxAttribute(attribute) { - // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type - // which is a type of the parameter of the signature we are trying out. - // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(attribute.parent); - if (ts.isJsxAttribute(attribute)) { - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - return getTypeOfPropertyOfType(attributesType, attribute.name.text); - } - else { - return attributesType; - } - } - // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily - // be "pushed" onto a node using the contextualType property. - function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); - } - /** - * Woah! Do you really want to use this function? - * - * Unless you're trying to get the *non-apparent* type for a - * value-literal type or you're authoring relevant portions of this algorithm, - * you probably meant to use 'getApparentTypeOfContextualType'. - * Otherwise this may not be very useful. - * - * In cases where you *are* working on this function, you should understand - * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. - * - * - Use 'getContextualType' when you are simply going to propagate the result to the expression. - * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. - * - * @param node the expression whose contextual type will be returned. - * @returns the contextual type of an expression. - */ - function getContextualType(node) { - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return undefined; - } - if (node.contextualType) { - return node.contextualType; - } - var parent = node.parent; - switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 176 /* BindingElement */: - return getContextualTypeForInitializerExpression(node); - case 187 /* ArrowFunction */: - case 219 /* ReturnStatement */: - return getContextualTypeForReturnExpression(node); - case 197 /* YieldExpression */: - return getContextualTypeForYieldOperand(parent); - case 181 /* CallExpression */: - case 182 /* NewExpression */: - return getContextualTypeForArgument(parent, node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - return getTypeFromTypeNode(parent.type); - case 194 /* BinaryExpression */: - return getContextualTypeForBinaryOperand(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - return getContextualTypeForObjectLiteralElement(parent); - case 263 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent); - case 177 /* ArrayLiteralExpression */: - return getContextualTypeForElementExpression(node); - case 195 /* ConditionalExpression */: - return getContextualTypeForConditionalOperand(node); - case 205 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); - return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185 /* ParenthesizedExpression */: - return getContextualType(parent); - case 256 /* JsxExpression */: - return getContextualTypeForJsxExpression(parent); - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - return getAttributesTypeFromJsxOpeningLikeElement(parent); - } - return undefined; - } - function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; - } - // If the given type is an object or union type, if that type has a single signature, and if - // that signature is non-generic, return the signature. Otherwise return undefined. - function getNonGenericSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!signature.typeParameters && !isAritySmaller(signature, node)) { - return signature; - } - } - } - /** If the contextual signature has fewer parameters than the function expression, do not use it */ - function isAritySmaller(signature, target) { - var targetParameterCount = 0; - for (; targetParameterCount < target.parameters.length; targetParameterCount++) { - var param = target.parameters[targetParameterCount]; - if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { - break; - } - } - if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { - targetParameterCount--; - } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; - } - function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */; - } - function getContextualSignatureForFunctionLikeDeclaration(node) { - // Only function expressions, arrow functions, and object literal methods are contextually typed. - return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) - ? getContextualSignature(node) - : undefined; - } - function getContextualTypeForFunctionLikeDeclaration(node) { - return ts.isObjectLiteralMethod(node) ? - getContextualTypeForObjectLiteralMethod(node) : - getApparentTypeOfContextualType(node); - } - // Return the contextual signature for a given expression node. A contextual type provides a - // contextual signature if it has a single call signature and if that call signature is non-generic. - // If the contextual type is a union type, get the signature from each type possible and if they are - // all identical ignoring their return type, the result is same signature but with return type as - // union type of return types from these signatures - function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); - if (!type) { - return undefined; - } - if (!(type.flags & 65536 /* Union */)) { - return getNonGenericSignature(type, node); - } - var signatureList; - var types = type.types; - 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) { - // This signature will contribute to contextual union signature - signatureList = [signature]; - } - else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { - // Signatures aren't identical, do not use - return undefined; - } - else { - // Use this signature for contextual union signature - signatureList.push(signature); - } - } - } - // Result is union of signatures collected (return type is union of return types of this signature set) - var result; - if (signatureList) { - result = cloneSignature(signatureList[0]); - // Clear resolved return type we possibly got from cloneSignature - result.resolvedReturnType = undefined; - result.unionSignatures = signatureList; - } - return result; - } - function checkSpreadExpression(node, checkMode) { - if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); - } - var arrayOrIterableType = checkExpression(node.expression, checkMode); - return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterable*/ false); - } - function hasDefaultValue(node) { - return (node.kind === 176 /* BindingElement */ && !!node.initializer) || - (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); - } - function checkArrayLiteral(node, checkMode) { - var elements = node.elements; - var hasSpreadElement = false; - var elementTypes = []; - var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { - // Given the following situation: - // var c: {}; - // [...c] = ["", 0]; - // - // c is represented in the tree as a spread element in an array literal. - // But c really functions as a rest element, and its purpose is to provide - // a contextual type for the right hand side of the assignment. Therefore, - // instead of calling checkExpression on "...c", which will give an error - // if c is not iterable/array-like, we need to act as if we are trying to - // get the contextual element type from it. So we do something similar to - // getContextualTypeForElementExpression, which will crucially not error - // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); - var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || - getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false); - if (restElementType) { - elementTypes.push(restElementType); - } - } - else { - var type = checkExpressionForMutableLocation(e, checkMode); - elementTypes.push(type); - } - hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; - } - if (!hasSpreadElement) { - // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such - // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); - type.pattern = node; - return type; - } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else { - if (patternElement.kind !== 200 /* OmittedExpression */) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(unknownType); - } - } - } - if (elementTypes.length) { - return createTupleType(elementTypes); - } - } - } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : - strictNullChecks ? neverType : undefinedWideningType); - } - function isNumericName(name) { - return name.kind === 144 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); - } - 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), 84 /* NumberLike */); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); - } - function isInfinityOrNaNString(name) { - return name === "Infinity" || name === "-Infinity" || name === "NaN"; - } - function isNumericLiteralName(name) { - // The intent of numeric names is that - // - they are names with text in a numeric form, and that - // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', - // acquired by applying the abstract 'ToNumber' operation on the name's text. - // - // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. - // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. - // - // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' - // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. - // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names - // because their 'ToString' representation is not equal to their original text. - // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. - // - // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. - // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. - // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. - // - // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. - // This is desired behavior, because when indexing with them as numeric entities, you are indexing - // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. - return (+name).toString() === name; - } - function checkComputedPropertyName(node) { - var links = getNodeLinks(node.expression); - if (!links.resolvedType) { - 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, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { - error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); - } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } - } - return links.resolvedType; - } - function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { - var propTypes = []; - for (var i = 0; i < properties.length; i++) { - if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { - propTypes.push(getTypeOfSymbol(properties[i])); - } - } - var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; - return createIndexInfo(unionType, /*isReadonly*/ false); - } - function checkObjectLiteral(node, checkMode) { - var inDestructuringPattern = ts.isAssignmentTarget(node); - // Grammar checking - checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); - var propertiesArray = []; - var spread = emptyObjectType; - var propagatedFlags = 0; - var contextualType = getApparentTypeOfContextualType(node); - var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 /* ObjectBindingPattern */ || contextualType.pattern.kind === 178 /* ObjectLiteralExpression */); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); - var typeFlags = 0; - var patternWithComputedProperties = false; - var hasComputedStringProperty = false; - var hasComputedNumberProperty = false; - var offset = 0; - for (var i = 0; i < node.properties.length; i++) { - var memberDecl = node.properties[i]; - var member = memberDecl.symbol; - if (memberDecl.kind === 261 /* PropertyAssignment */ || - memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || - ts.isObjectLiteralMethod(memberDecl)) { - var type = void 0; - if (memberDecl.kind === 261 /* PropertyAssignment */) { - type = checkPropertyAssignment(memberDecl, checkMode); - } - else if (memberDecl.kind === 151 /* MethodDeclaration */) { - type = checkObjectLiteralMethod(memberDecl, checkMode); - } - else { - ts.Debug.assert(memberDecl.kind === 262 /* ShorthandPropertyAssignment */); - type = checkExpressionForMutableLocation(memberDecl.name, checkMode); - } - typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | member.flags, member.name); - if (inDestructuringPattern) { - // If object literal is an assignment pattern and if the assignment pattern specifies a default value - // for the property, make the property optional. - var isOptional = (memberDecl.kind === 261 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); - if (isOptional) { - prop.flags |= 67108864 /* Optional */; - } - if (ts.hasDynamicName(memberDecl)) { - patternWithComputedProperties = true; - } - } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { - // If object literal is contextually typed by the implied type of a binding pattern, and if the - // binding pattern specifies a default value for the property, make the property optional. - var impliedProp = getPropertyOfType(contextualType, member.name); - if (impliedProp) { - prop.flags |= impliedProp.flags & 67108864 /* Optional */; - } - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { - error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); - } - } - prop.declarations = member.declarations; - prop.parent = member.parent; - if (member.valueDeclaration) { - prop.valueDeclaration = member.valueDeclaration; - } - prop.type = type; - prop.target = member; - member = prop; - } - else if (memberDecl.kind === 263 /* SpreadAssignment */) { - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(memberDecl, 2 /* Assign */); - } - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - propertiesArray = []; - propertiesTable = ts.createMap(); - hasComputedStringProperty = false; - hasComputedNumberProperty = false; - typeFlags = 0; - } - var type = checkExpression(memberDecl.expression); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return unknownType; - } - spread = getSpreadType(spread, type); - offset = i + 1; - continue; - } - else { - // TypeScript 1.0 spec (April 2014) - // A get accessor declaration is processed in the same manner as - // an ordinary function declaration(section 6.1) with no parameters. - // A set accessor declaration is processed in the same manner - // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); - checkNodeDeferred(memberDecl); - } - if (ts.hasDynamicName(memberDecl)) { - if (isNumericName(memberDecl.name)) { - hasComputedNumberProperty = true; - } - else { - hasComputedStringProperty = true; - } - } - else { - propertiesTable.set(member.name, member); - } - propertiesArray.push(member); - } - // If object literal is contextually typed by the implied type of a binding pattern, augment the result - // type with those properties for which the binding pattern specifies a default value. - if (contextualTypeHasPattern) { - for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 67108864 /* Optional */)) { - error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - propertiesTable.set(prop.name, prop); - propertiesArray.push(prop); - } - } - } - if (spread !== emptyObjectType) { - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768 /* Object */) { - // only set the symbol and flags if this is a (fresh) object type - spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; - spread.objectFlags |= 128 /* ObjectLiteral */; - spread.symbol = node.symbol; - } - return spread; - } - return createObjectLiteralType(); - function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); - result.objectFlags |= 128 /* ObjectLiteral */; - if (patternWithComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } - if (inDestructuringPattern) { - result.pattern = node; - } - if (!(result.flags & 6144 /* Nullable */)) { - propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); - } - return result; - } - } - function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */ | 16777216 /* NonPrimitive */) || - type.flags & 32768 /* Object */ && !isGenericMappedType(type) || - type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); - } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); - return getJsxGlobalElementType() || anyType; - } - function checkJsxElement(node) { - // Check attributes - checkJsxOpeningLikeElement(node.openingElement); - // Perform resolution on the closing tag so that rename/go to definition/etc work - if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { - getIntrinsicTagSymbol(node.closingElement); - } - else { - checkExpression(node.closingElement.tagName); - } - return getJsxGlobalElementType() || anyType; - } - /** - * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers - */ - function isUnhyphenatedJsxName(name) { - // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers - return name.indexOf("-") < 0; - } - /** - * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name - */ - function isJsxIntrinsicIdentifier(tagName) { - // TODO (yuisu): comment - if (tagName.kind === 179 /* PropertyAccessExpression */ || tagName.kind === 99 /* ThisKeyword */) { - return false; - } - else { - return ts.isIntrinsicJsxName(tagName.text); - } - } - /** - * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. - * - * @param openingLikeElement a JSX opening-like element - * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable - * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. - * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, - * which also calls getSpreadType. - */ - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { - var attributes = openingLikeElement.attributes; - 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; - if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; // is sugar for - var attributeSymbol = createSymbol(4 /* Property */ | 134217728 /* Transient */ | member.flags, member.name); - attributeSymbol.declarations = member.declarations; - attributeSymbol.parent = member.parent; - if (member.valueDeclaration) { - attributeSymbol.valueDeclaration = member.valueDeclaration; - } - attributeSymbol.type = exprType; - 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 */); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - var exprType = checkExpression(attributeDecl.expression); - if (isTypeAny(exprType)) { - hasSpreadAnyType = true; - } - if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); - } - else { - typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; - } - } - } - if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - } - attributesArray = getPropertiesOfType(spread); - } - 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 _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 */) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } - 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 - var childrenPropSymbol = createSymbol(4 /* Property */ | 134217728 /* Transient */, jsxChildrenPropertyName); - childrenPropSymbol.type = childrenTypes.length === 1 ? - childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); - } - } - 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 - * @param attributesTable a symbol table of attributes property - */ - function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; - result.objectFlags |= 128 /* ObjectLiteral */; - return result; - } - } - /** - * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. - * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) - * @param node a JSXAttributes to be resolved of its type - */ - function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); - } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; - } - /** - * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic - * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic - * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). - * May also return unknownSymbol if both of these lookups fail. - */ - function getIntrinsicTagSymbol(node) { - var links = getNodeLinks(node); - if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - // Property case - var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); - if (intrinsicProp) { - links.jsxFlags |= 1 /* IntrinsicNamedElement */; - return links.resolvedSymbol = intrinsicProp; - } - // Intrinsic string indexer case - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - links.jsxFlags |= 2 /* IntrinsicIndexedElement */; - return links.resolvedSymbol = intrinsicElementsType.symbol; - } - // Wasn't found - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return links.resolvedSymbol = unknownSymbol; - } - else { - if (noImplicitAny) { - error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); - } - return links.resolvedSymbol = unknownSymbol; - } - } - return links.resolvedSymbol; - } - /** - * Given a JSX element that is a class element, finds the Element Instance Type. If the - * element is not a class element, or the class element type cannot be determined, returns 'undefined'. - * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). - */ - function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); - return unknownType; - } - } - 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. - * Get a single property from that container if existed. Report an error if there are more than one property. - * - * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer - * if other string is given or the container doesn't exist, return undefined. - */ - function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { - // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); - // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); - // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] - var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); - // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute - var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); - if (propertiesOfJsxElementAttribPropInterface) { - // Element Attributes has zero properties, so the element attributes type will be the class instance type - if (propertiesOfJsxElementAttribPropInterface.length === 0) { - return ""; - } - else if (propertiesOfJsxElementAttribPropInterface.length === 1) { - return propertiesOfJsxElementAttribPropInterface[0].name; - } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { - // More than one property on ElementAttributesProperty is an error - error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, nameOfAttribPropContainer); - } - } - return undefined; - } - /// e.g. "props" for React.d.ts, - /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all - /// non-intrinsic elements' attributes type is 'any'), - /// or '' if it has 0 properties (which means every - /// non-intrinsic elements' attributes type is the element instance type) - function getJsxElementPropertiesName() { - if (!_hasComputedJsxElementPropertiesName) { - _hasComputedJsxElementPropertiesName = true; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; - } - function getJsxElementChildrenPropertyname() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - 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. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); - 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); - if (intrinsicAttributes !== unknownType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - 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++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.text) && - !getPropertyOfType(paramType, attribute.name.text)) { - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttributes !== unknownType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } - if (elementType.flags & 65536 /* Union */) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), /*subtypeReduction*/ true); - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (elementType.flags & 2 /* String */) { - return anyType; - } - else if (elementType.flags & 32 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; - } - // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - // There is no type ElementAttributesProperty, return 'any' - return anyType; - } - else if (propsName === "") { - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - // There is no property named 'props' on this instance type - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - // Props is of type 'any' or unknown - return attributesType; - } - else { - // Normal case -- add in IntrinsicClassElements and IntrinsicElements - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } - } - /** - * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. - * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. - * @param node an intrinsic JSX opening-like element - */ - function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { - ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var symbol = getIntrinsicTagSymbol(node); - if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); - } - else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { - return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; - } - else { - return links.resolvedJsxElementAttributesType = unknownType; - } - } - return links.resolvedJsxElementAttributesType; - } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); - } - return links.resolvedJsxElementAttributesType; - } - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.text); - return prop || unknownSymbol; - } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; - } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; - } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } - } - return deferredJsxStatelessElementType; - } - /** - * Returns all the properties of the Jsx.IntrinsicElements interface - */ - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); - return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; - } - function checkJsxPreconditions(errorNode) { - // Preconditions for using JSX - if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { - error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); - } - if (getJsxGlobalElementType() === undefined) { - if (noImplicitAny) { - error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); - } - } - } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); - checkJsxPreconditions(node); - // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. - // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. - var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); - if (reactSym) { - // Mark local symbol as referenced here because it might not have been marked - // if jsx emit was not react as there wont be error being emitted - reactSym.isReferenced = true; - // If react symbol is alias, mark it as refereced - if (reactSym.flags & 8388608 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { - markAliasSymbolAsReferenced(reactSym); - } - } - 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" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.name) || !!(getPropertyOfType(targetAttributesType, attribute.name)); - }); - // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. - // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. - if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); - } - else { - // 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) { - if (node.expression) { - var type = checkExpression(node.expression, checkMode); - if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); - } - return type; - } - else { - return unknownType; - } - } - // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized - // '.prototype' property as well as synthesized tuple index properties. - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; - } - function getDeclarationNodeFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; - } - function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); - } - /** - * Check whether the requested property access is valid. - * Returns true if node is a valid property access, and false otherwise. - * @param node The node to be checked. - * @param left The left hand side of the property access (e.g.: the super in `super.foo`). - * @param type The type of left. - * @param prop The symbol for the right hand side of the property access. - */ - function checkPropertyAccessibility(node, left, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? - node.name : - node.right; - 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; - } - if (left.kind === 97 /* SuperKeyword */) { - // TS 1.0 spec (April 2014): 4.8.2 - // - In a constructor, instance member function, instance member accessor, or - // instance member variable initializer where this references a derived class instance, - // a super property access is permitted and must specify a public instance member function of the base class. - // - In a static member function or static member accessor - // where this references the constructor function object of a derived class, - // a super property access is permitted and must specify a public static member function of the base class. - if (languageVersion < 2 /* ES2015 */) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 /* MethodDeclaration */ && propKind !== 150 /* MethodSignature */; - }); - if (hasNonMethodDeclaration) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - return false; - } - } - if (flags & 128 /* Abstract */) { - // A method cannot be accessed in a super property access if the method is abstract. - // This error could mask a private property access error. But, a member - // cannot simultaneously be private and abstract, so this will trigger an - // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - } - // Public properties are otherwise accessible. - if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { - return true; - } - // Property is known to be private or protected at this point - // Private property is accessible if the property is within the declaring class - if (flags & 8 /* Private */) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - return true; - } - // Property is known to be protected at this point - // All protected properties of a supertype are accessible in a super access - if (left.kind === 97 /* SuperKeyword */) { - return true; - } - // Find the first enclosing class that has the declaring classes of the protected constituents - // of the property as base classes - var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { - var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; - }); - // A protected property is accessible if the property is within the declaring class or classes derived from it - if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); - return false; - } - // No further restrictions for static properties - if (flags & 32 /* Static */) { - return true; - } - // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - // get the original type -- represented as the type constraint of the 'this' type - type = getConstraintOfTypeParameter(type); - } - if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); - return false; - } - return true; - } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); - } - function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144 /* Nullable */; - if (kind) { - error(errorNode, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); - var t = getNonNullableType(type); - return t.flags & (6144 /* Nullable */ | 8192 /* Never */) ? unknownType : t; - } - return type; - } - function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); - } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); - } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { - // handle cases when type is Type parameter with invalid or any constraint - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent && node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - // Only compute control flow type if this is a property access expression that isn't an - // assignment target, and the referenced property was declared as a variable, property, - // accessor, or optional method. - if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { - return propType; - } - 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 - : node.left; - var type = checkExpression(left); - if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop) { - return checkPropertyAccessibility(node, left, type, prop); - } - } - return true; - } - /** - * Return the symbol of the for-in variable declared or referenced by the given for-in statement. - */ - function getForInVariableSymbol(node) { - var initializer = node.initializer; - if (initializer.kind === 227 /* VariableDeclarationList */) { - var variable = initializer.declarations[0]; - if (variable && !ts.isBindingPattern(variable.name)) { - return getSymbolOfNode(variable); - } - } - else if (initializer.kind === 71 /* Identifier */) { - return getResolvedSymbol(initializer); - } - return undefined; - } - /** - * Return true if the given type is considered to have numeric property names. - */ - function hasNumericPropertyNames(type) { - return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); - } - /** - * Return true if given node is an expression consisting of an identifier (possibly parenthesized) - * that references a for-in variable for an object with numeric property names. - */ - function isForInVariableForNumericPropertyNames(expr) { - var e = ts.skipParentheses(expr); - if (e.kind === 71 /* Identifier */) { - var symbol = getResolvedSymbol(e); - if (symbol.flags & 3 /* Variable */) { - var child = expr; - var node = expr.parent; - while (node) { - if (node.kind === 215 /* ForInStatement */ && - child === node.statement && - getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(getTypeOfExpression(node.expression))) { - return true; - } - child = node; - node = node.parent; - } - } - } - return false; - } - function checkIndexedAccess(node) { - var objectType = checkNonNullExpression(node.expression); - var indexExpression = node.argumentExpression; - if (!indexExpression) { - var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 /* NewExpression */ && node.parent.expression === node) { - var start = ts.skipTrivia(sourceFile.text, node.expression.end); - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); - } - else { - var start = node.end - "]".length; - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); - } - return unknownType; - } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); - if (objectType === unknownType || objectType === silentNeverType) { - return objectType; - } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { - error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); - return unknownType; - } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === unknownType) { - // There is already an error, so no need to report one. - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 512 /* ESSymbol */) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - 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); - } - else if (node.kind !== 147 /* Decorator */) { - ts.forEach(node.arguments, function (argument) { - checkExpression(argument); - }); - } - return anySignature; - } - function resolveErrorCall(node) { - resolveUntypedCall(node); - return unknownSignature; - } - // Re-order candidate signatures into the result array. Assumes the result array to be empty. - // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order - // A nit here is that we reorder only signatures that belong to the same symbol, - // so order how inherited signatures are processed is still preserved. - // interface A { (x: string): void } - // interface B extends A { (x: 'foo'): string } - // const b: B; - // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures, result) { - var lastParent; - var lastSymbol; - var cutoffIndex = 0; - var index; - var specializedIndex = -1; - var spliceIndex; - ts.Debug.assert(!result.length); - 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) { - if (lastParent && parent === lastParent) { - index++; - } - else { - lastParent = parent; - index = cutoffIndex; - } - } - else { - // current declaration belongs to a different symbol - // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex - index = cutoffIndex = result.length; - lastParent = parent; - } - lastSymbol = symbol; - // specialized signatures always need to be placed before non-specialized signatures regardless - // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { - specializedIndex++; - spliceIndex = specializedIndex; - // The cutoff index always needs to be greater than or equal to the specialized signature index - // in order to prevent non-specialized signatures from being added before a specialized - // signature. - cutoffIndex++; - } - else { - spliceIndex = index; - } - result.splice(spliceIndex, 0, signature); - } - } - function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 198 /* SpreadElement */) { - return i; - } - } - return -1; - } - function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) - var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments - var isDecorator; - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - if (node.kind === 183 /* TaggedTemplateExpression */) { - var tagExpression = node; - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length - argCount = args.length; - typeArguments = undefined; - if (tagExpression.template.kind === 196 /* TemplateExpression */) { - // If a tagged template expression lacks a tail literal, the call is incomplete. - // Specifically, a template only can end in a TemplateTail or a Missing literal. - var templateExpression = tagExpression.template; - var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); - ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. - callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; - } - else { - // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, - // then this might actually turn out to be a TemplateHead in the future; - // so we consider the call to be incomplete. - var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); - callIsIncomplete = !!templateLiteral.isUnterminated; - } - } - else if (node.kind === 147 /* Decorator */) { - isDecorator = true; - typeArguments = undefined; - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); - } - else { - var callExpression = node; - if (!callExpression.arguments) { - // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 182 /* NewExpression */); - return signature.minArgumentCount === 0; - } - argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; - // If we are missing the close parenthesis, the call is incomplete. - callIsIncomplete = callExpression.arguments.end === callExpression.end; - typeArguments = callExpression.typeArguments; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If the user supplied type arguments, but the number of type arguments does not match - // the declared number of type parameters, the call has an incorrect arity. - var numTypeParameters = ts.length(signature.typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { - return false; - } - // 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) || spreadArgIndex >= signature.minArgumentCount; - } - // Too many arguments implies incorrect arity. - if (!signature.hasRestParameter && argCount > signature.parameters.length) { - return false; - } - // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= signature.minArgumentCount; - return callIsIncomplete || hasEnoughArguments; - } - // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. - function getSingleCallSignature(type) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - return resolved.callSignatures[0]; - } - } - return undefined; - } - // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, /*inferUnionTypes*/ true, /*useAnyForNoInferences*/ false); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypesWithContext(context, instantiateType(source, contextualMapper), target); - }); - return getSignatureInstantiation(signature, getInferredTypes(context)); - } - function inferTypeArguments(node, signature, args, excludeArgument, context) { - var typeParameters = signature.typeParameters; - var inferenceMapper = getInferenceMapper(context); - // Clear out all the inference results from the last time inferTypeArguments was called on this context - for (var i = 0; i < typeParameters.length; i++) { - // As an optimization, we don't have to clear (and later recompute) inferred types - // for type parameters that have already been fixed on the previous call to inferTypeArguments. - // It would be just as correct to reset all of them. But then we'd be repeating the same work - // for the type parameters that were fixed, namely the work done by getInferredType. - if (!context.inferences[i].isFixed) { - context.inferredTypes[i] = undefined; - } - } - // On this call to inferTypeArguments, we may get more inferences for certain type parameters that were not - // fixed last time. This means that a type parameter that failed inference last time may succeed this time, - // or vice versa. Therefore, the failedTypeParameterIndex is useless if it points to an unfixed type parameter, - // because it may change. So here we reset it. However, getInferredType will not revisit any type parameters - // that were previously fixed. So if a fixed type parameter failed previously, it will fail again because - // it will contain the exact same set of inferences. So if we reset the index from a fixed type parameter, - // we will lose information that we won't recover this time around. - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } - var thisType = getThisTypeOfSignature(signature); - if (thisType) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypesWithContext(context, thisArgumentType, thisType); - } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } - inferTypesWithContext(context, argType, paramType); - } - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); - } - } - } - getInferredTypes(context); - } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { - var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; - var mapper; - for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } - } - } - return typeArgumentsAreAssignable; - } - /** - * Check if the given signature can possibly be a signature called by the JSX opening-like element. - * @param node a JSX opening-like element we are trying to figure its call signature - * @param signature a candidate signature we are trying whether it is a call signature - * @param relation a relationship to check parameter and argument type - * @param excludeArgument - */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - // Stateless function components can have maximum of three arguments: "props", "context", and "updater". - // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, - // can be specified by users through attributes property. - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.name) && isUnhyphenatedJsxName(arg.name)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); - } - function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); - } - var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182 /* NewExpression */) { - // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType - // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. - // If the expression is a new expression, then the check is skipped. - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; - var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { - return false; - } - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - } - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { - return false; - } - } - } - return true; - } - /** - * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. - */ - function getThisArgumentOfCall(node) { - if (node.kind === 181 /* CallExpression */) { - var callee = node.expression; - if (callee.kind === 179 /* PropertyAccessExpression */) { - return callee.expression; - } - else if (callee.kind === 180 /* ElementAccessExpression */) { - return callee.expression; - } - } - } - /** - * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. - */ - function getEffectiveCallArguments(node) { - var args; - if (node.kind === 183 /* TaggedTemplateExpression */) { - var template = node.template; - args = [undefined]; - if (template.kind === 196 /* TemplateExpression */) { - ts.forEach(template.templateSpans, function (span) { - args.push(span.expression); - }); - } - } - else if (node.kind === 147 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - args = node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; - } - else { - args = node.arguments || emptyArray; - } - return args; - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147 /* Decorator */) { - switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 149 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 146 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - } - } - else { - return args.length; - } - } - /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. - */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 229 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 146 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 152 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. - */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 229 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return unknownType; - } - if (node.kind === 146 /* Parameter */) { - node = node.parent; - if (node.kind === 152 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - switch (element.name.kind) { - case 71 /* Identifier */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(element.name.text); - case 144 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return unknownType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 229 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 146 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 149 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return unknownType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 147 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 147 /* Decorator */ || - (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; - } - } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 147 /* Decorator */; - var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); - var typeArguments; - if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { - typeArguments = node.typeArguments; - // We already perform checking on the type arguments on the class declaration itself. - if (node.expression.kind !== 97 /* SuperKeyword */) { - ts.forEach(typeArguments, checkSourceElement); - } - } - if (signatures.length === 1) { - var declaration = signatures[0].declaration; - if (declaration && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration)) { - if (containsArgumentsReference(declaration)) { - var signatureWithRest = cloneSignature(signatures[0]); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - signatureWithRest.parameters = ts.concatenate(signatureWithRest.parameters, [syntheticArgsSymbol]); - signatureWithRest.hasRestParameter = true; - signatures = [signatureWithRest]; - } - } - } - var candidates = candidatesOutArray || []; - // reorderCandidates fills up the candidates array directly - reorderCandidates(signatures, candidates); - if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); - return resolveErrorCall(node); - } - var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. - // - // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those - // parameters, contextually typing each as we go along. - // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. - // - // For a decorator, no arguments are susceptible to contextual typing due to the fact - // decorators are applied to a declaration by the emitter, and not to an expression. - var excludeArgument; - if (!isDecorator) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - } - } - } - // The following variables are captured and modified by calls to chooseOverload. - // If overload resolution or type argument inference fails, we want to report the - // best error possible. The best error is one which says that an argument was not - // assignable to a parameter. This implies that everything else about the overload - // was fine. So if there is any overload that is only incorrect because of an - // argument, we will report an error on that one. - // - // function foo(s: string) {} - // function foo(n: number) {} // Report argument error on this overload - // function foo() {} - // foo(true); - // - // If none of the overloads even made it that far, there are two possibilities. - // There was a problem with type arguments for some overload, in which case - // report an error on that. Or none of the overloads even had correct arity, - // in which case give an arity error. - // - // function foo(x: T, y: T) {} // Report type argument inference error - // function foo() {} - // foo(0, true); - // - var candidateForArgumentError; - var candidateForTypeArgumentError; - var resultOfFailedInference; - var result; - // If we are in signature help, a trailing comma indicates that we intend to provide another argument, - // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 /* CallExpression */ && node.arguments.hasTrailingComma; - // Section 4.12.1: - // if the candidate list contains one or more signatures for which the type of each argument - // expression is a subtype of each corresponding parameter type, the return type of the first - // of those signatures becomes the return type of the function call. - // Otherwise, the return type of the first signature in the candidate list becomes the return - // type of the function call. - // - // Whether the call is an error is determined by assignability of the arguments. The subtype pass - // is just important for choosing the best signature. So in the case where there is only one - // signature, the subtype pass is useless. So skipping it is an optimization. - if (candidates.length > 1) { - result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); - } - if (!result) { - // Reinitialize these pointers for round two - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; - result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); - } - if (result) { - return result; - } - // No signatures were applicable. Now report errors based on the last applicable signature with - // no arguments excluded from assignability checks. - // If candidate is undefined, it means that no candidates had a suitable arity. In that case, - // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; - } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ 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(/*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 (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } - } - 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. - // Pick the first candidate that matches the arity. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }); - // f({ | - if (!produceDiagnostics) { - 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)); - } - return candidate; - } - } - } - return resolveErrorCall(node); - function chooseOverload(candidates, relation, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { - var originalCandidate = candidates_2[_i]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { - continue; - } - var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false, /*useAnyForNoInferences*/ ts.isInJavaScriptFile(node)) - : undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); - } - else { - inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentTypes = inferenceContext.inferredTypes; - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; - } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - break; - } - var index = excludeArgument ? ts.indexOf(excludeArgument, /*value*/ true) : -1; - if (index < 0) { - return candidate; - } - excludeArgument[index] = false; - } - // A post-mortem of this iteration of the loop. The signature was not applicable, - // so we want to track it as a candidate for reporting an error. If the candidate - // had no type parameters, or had no issues related to type arguments, we can - // report an error based on the arguments. If there was an issue with type - // arguments, then we can only report an error based on the type arguments. - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } - } - return undefined; - } - } - function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 97 /* SuperKeyword */) { - var superType = checkSuperExpression(node.expression); - if (superType !== unknownType) { - // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated - // with the type arguments specified in the extends clause. - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - if (baseTypeNode) { - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); - } - } - return resolveUntypedCall(node); - } - var funcType = checkNonNullExpression(node.expression); - if (funcType === silentNeverType) { - return silentNeverSignature; - } - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - // Another error has already been reported - return resolveErrorCall(node); - } - // Technically, this signatures list may be incomplete. We are taking the apparent type, - // but we are not including call signatures that may have been added to the Object or - // Function interface, since they have none by default. This is a bit of a leap of faith - // that the user will not add any. - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - // TS 1.0 Spec: 4.12 - // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual - // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - // The unknownType indicates that an error already occurred (and was reported). No - // need to report another error in this case. - if (funcType !== unknownType && node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. - // TypeScript employs overload resolution in typed function calls in order to support functions - // with multiple call signatures. - if (!callSignatures.length) { - if (constructSignatures.length) { - error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); - } - else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - } - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - /** - * TS 1.0 spec: 4.12 - * If FuncExpr is of type Any, or of an object type that has no call or construct signatures - * but is a subtype of the Function interface, the call is an untyped function call. - */ - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (funcType.flags & 65536 /* Union */) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } - function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 1 /* ES5 */) { - var spreadIndex = getSpreadArgumentIndex(node.arguments); - if (spreadIndex >= 0) { - error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); - } - } - var expressionType = checkNonNullExpression(node.expression); - if (expressionType === silentNeverType) { - return silentNeverSignature; - } - // If expressionType's apparent type(section 3.8.1) is an object type with one or - // more construct signatures, the expression is processed in the same manner as a - // function call, but using the construct signatures as the initial set of candidate - // signatures for overload resolution. The result type of the function call becomes - // the result type of the operation. - expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { - // Another error has already been reported - return resolveErrorCall(node); - } - // If the expression is a class of abstract type, then it cannot be instantiated. - // Note, only class declarations can be declared abstract. - // In the case of a merged class-module or class-interface declaration, - // 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(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } - // TS 1.0 spec: 4.11 - // If expressionType is of type Any, Args can be any argument - // list and the result of the operation is of type Any. - if (isTypeAny(expressionType)) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - // Technically, this signatures list may be incomplete. We are taking the apparent type, - // but we are not including construct signatures that may have been added to the Object or - // Function interface, since they have none by default. This is a bit of a leap of faith - // that the user will not add any. - var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); - if (constructSignatures.length) { - if (!isConstructorAccessible(node, constructSignatures[0])) { - return resolveErrorCall(node); - } - return resolveCall(node, constructSignatures, candidatesOutArray); - } - // If expressionType's apparent type is an object type with no construct signatures but - // one or more call signatures, the expression is processed as a function call. A compile-time - // error occurs if the result of the function call is not Void. The type of the result of the - // operation is Any. It is an error to have a Void this type. - var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); - if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); - } - return signature; - } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); - return resolveErrorCall(node); - } - function isConstructorAccessible(node, signature) { - if (!signature || !signature.declaration) { - return true; - } - var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - // Public constructor is accessible. - if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { - return true; - } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); - var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); - } - } - if (modifiers & 8 /* Private */) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - if (modifiers & 16 /* Protected */) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - return false; - } - return true; - } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { - var tagType = checkExpression(node.tag); - var apparentType = getApparentType(tagType); - if (apparentType === unknownType) { - // Another error has already been reported - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - /** - * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. - */ - function getDiagnosticHeadMessageForDecoratorResolution(node) { - switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146 /* Parameter */: - return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149 /* PropertyDeclaration */: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; - } - } - /** - * Resolves a decorator as if it were a call expression. - */ - function resolveDecorator(node, candidatesOutArray) { - var funcType = checkExpression(node.expression); - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); - } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; - } - /** - * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. - * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible - * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. - * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures - */ - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 65536 /* Union */) { - var types = elementType.types; - var result = void 0; - 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; - } - var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); - if (callSignatures && callSignatures.length > 0) { - var callSignature = void 0; - callSignature = resolveCall(openingLikeElement, callSignatures, candidatesOutArray); - return callSignature; - } - return undefined; - } - function resolveSignature(node, candidatesOutArray) { - switch (node.kind) { - case 181 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray); - case 182 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray); - case 183 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147 /* Decorator */: - return resolveDecorator(node, candidatesOutArray); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); - } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); - } - /** - * Resolve a signature of a given call-like expression. - * @param node a call-like expression to try resolve a signature for - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a signature of the call-like expression or undefined if one can't be found - */ - function getResolvedSignature(node, candidatesOutArray) { - var links = getNodeLinks(node); - // If getResolvedSignature has already been called, we will have cached the resolvedSignature. - // However, it is possible that either candidatesOutArray was not passed in the first time, - // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work - // to correctly fill the candidatesOutArray. - var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { - return cached; - } - links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); - // If signature resolution originated in control flow type analysis (for example to compute the - // assigned type in a flow assignment) we don't cache the result as it may be based on temporary - // types from the control flow analysis. - links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; - return result; - } - function getResolvedOrAnySignature(node) { - // If we're already in the process of resolving the given signature, don't resolve again as - // that could cause infinite recursion. Instead, return anySignature. - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); - } - function getInferredClassType(symbol) { - var links = getSymbolLinks(symbol); - if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); - } - return links.inferredClassType; - } - /** - * Syntactically and semantically checks a call or new expression. - * @param node The call/new expression to be checked. - * @returns On success, the expression's signature's return type. On failure, anyType. - */ - function checkCallExpression(node) { - // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - var signature = getResolvedSignature(node); - if (node.expression.kind === 97 /* SuperKeyword */) { - return voidType; - } - if (node.kind === 182 /* NewExpression */) { - var declaration = signature.declaration; - if (declaration && - declaration.kind !== 152 /* Constructor */ && - declaration.kind !== 156 /* ConstructSignature */ && - declaration.kind !== 161 /* ConstructorType */ && - !ts.isJSDocConstructSignature(declaration)) { - // When resolved signature is a call signature (and not a construct signature) the result type is any, unless - // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations - // in a JS file - // Note:JS inferred classes might come from a variable declaration instead of a function declaration. - // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. - var funcSymbol = node.expression.kind === 71 /* Identifier */ ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.members && funcSymbol.flags & 16 /* Function */) { - return getInferredClassType(funcSymbol); - } - else if (noImplicitAny) { - error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); - } - return anyType; - } - } - // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { - return resolveExternalModuleTypeByLiteral(node.arguments[0]); - } - return getReturnTypeOfSignature(signature); - } - function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - return false; - } - // Make sure require is not a local function - var resolvedRequire = resolveName(node.expression, node.expression.text, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (!resolvedRequire) { - // project does not contain symbol named 'require' - assume commonjs require - return true; - } - // project includes symbol named 'require' - make sure that it it ambient and local non-alias - if (resolvedRequire.flags & 8388608 /* Alias */) { - return false; - } - var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 228 /* FunctionDeclaration */ - : resolvedRequire.flags & 3 /* Variable */ - ? 226 /* VariableDeclaration */ - : 0 /* Unknown */; - if (targetDeclarationKind !== 0 /* Unknown */) { - var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - // function/variable declaration should be ambient - return ts.isInAmbientContext(decl); - } - return false; - } - function checkTaggedTemplateExpression(node) { - return getReturnTypeOfSignature(getResolvedSignature(node)); - } - function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); - checkSourceElement(node.type); - var targetType = getTypeFromTypeNode(node.type); - if (produceDiagnostics && targetType !== unknownType) { - var widenedType = getWidenedType(exprType); - if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, node, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); - } - } - return targetType; - } - function checkNonNullAssertion(node) { - return getNonNullableType(checkExpression(node.expression)); - } - function checkMetaProperty(node) { - checkGrammarMetaProperty(node); - var container = ts.getNewTargetContainer(node); - if (!container) { - error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); - return unknownType; - } - else if (container.kind === 152 /* Constructor */) { - var symbol = getSymbolOfNode(container.parent); - return getTypeOfSymbol(symbol); - } - else { - var symbol = getSymbolOfNode(container); - return getTypeOfSymbol(symbol); - } - } - function getTypeOfParameter(symbol) { - var type = getTypeOfSymbol(symbol); - if (strictNullChecks) { - var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { - return getNullableType(type, 2048 /* Undefined */); - } - } - return type; - } - function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; - } - function getTypeOfFirstParameterOfSignature(signature) { - return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; - } - function assignContextualParameterTypes(signature, context, mapper, checkMode) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (checkMode === 2 /* Inferential */) { - for (var i = 0; i < len; i++) { - var declaration = signature.parameters[i].valueDeclaration; - if (declaration.type) { - inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); - } - } - } - if (context.thisParameter) { - var parameter = signature.thisParameter; - if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { - if (!parameter) { - signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper, checkMode); - } - } - for (var i = 0; i < len; i++) { - var parameter = signature.parameters[i]; - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - var parameter = ts.lastOrUndefined(signature.parameters); - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - } - // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push - // the destructured type into the contained binding elements. - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); - } - } - } - } - function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper, checkMode) { - 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 && - (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(name); - } - assignBindingElementTypes(parameter.valueDeclaration); - } - else if (checkMode === 2 /* Inferential */) { - // Even if the parameter already has a type, it might be because it was given a type while - // processing the function as an argument to a prior signature during overload resolution. - // If this was the case, it may have caused some type parameters to be fixed. So here, - // we need to ensure that type parameters at the same positions get fixed again. This is - // done by calling instantiateType to attach the mapper to the contextualType, and then - // calling inferTypes to force a walk of contextualType so that all the correct fixing - // happens. The choice to pass in links.type may seem kind of arbitrary, but it serves - // to make sure that all the correct positions in contextualType are reached by the walk. - // Here is an example: - // - // interface Base { - // baseProp; - // } - // interface Derived extends Base { - // toBase(): Base; - // } - // - // var derived: Derived; - // - // declare function foo(x: T, func: (p: T) => T): T; - // declare function foo(x: T, func: (p: T) => T): T; - // - // var result = foo(derived, d => d.toBase()); - // - // We are typing d while checking the second overload. But we've already given d - // a type (Derived) from the first overload. However, we still want to fix the - // T in the second overload so that we do not infer Base as a candidate for T - // (inferring Base would make type argument inference inconsistent between the two - // overloads). - inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); - } - } - function getReturnTypeFromJSDocComment(func) { - var returnTag = ts.getJSDocReturnTag(func); - if (returnTag && returnTag.typeExpression) { - return getTypeFromTypeNode(returnTag.typeExpression.type); - } - return undefined; - } - function createPromiseType(promisedType) { - // creates a `Promise` type where `T` is the promisedType argument - var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); - if (globalPromiseType !== emptyGenericType) { - // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type - promisedType = getAwaitedType(promisedType) || emptyObjectType; - return createTypeReference(globalPromiseType, [promisedType]); - } - return emptyObjectType; - } - function createPromiseReturnType(func, promisedType) { - var promiseType = createPromiseType(promisedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); - return unknownType; - } - else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { - error(func, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - return promiseType; - } - function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!func.body) { - return unknownType; - } - var functionFlags = ts.getFunctionFlags(func); - var type; - if (func.body.kind !== 207 /* Block */) { - type = checkExpressionCached(func.body, checkMode); - if (functionFlags & 2 /* Async */) { - // 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 should be unwrapped to its awaited type, which we will wrap in - // the native Promise type later in this function. - type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - } - else { - var types = void 0; - if (functionFlags & 1 /* Generator */) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); - if (!types || types.length === 0) { - var iterableIteratorAny = functionFlags & 2 /* Async */ - ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function - : createIterableIteratorType(anyType); // Generator function - if (noImplicitAny) { - error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); - } - return iterableIteratorAny; - } - } - else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (!types) { - // For an async function, the return type will not be never, but rather a Promise for never. - return functionFlags & 2 /* Async */ - ? createPromiseReturnType(func, neverType) // Async function - : neverType; // Normal function - } - if (types.length === 0) { - // For an async function, the return type will not be void, but rather a Promise for void. - return functionFlags & 2 /* Async */ - ? createPromiseReturnType(func, voidType) // Async function - : voidType; // Normal function - } - } - // Return a union of the return expression types. - type = getUnionType(types, /*subtypeReduction*/ true); - if (functionFlags & 1 /* Generator */) { - type = functionFlags & 2 /* Async */ - ? createAsyncIterableIteratorType(type) // AsyncGenerator function - : createIterableIteratorType(type); // Generator function - } - } - if (!contextualSignature) { - reportErrorsFromWidening(func, type); - } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); - } - var widenedType = getWidenedType(type); - // 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 /* AsyncGenerator */) === 2 /* Async */ - ? createPromiseReturnType(func, widenedType) // Async function - : widenedType; // Generator function, AsyncGenerator function, or normal function - } - function checkAndAggregateYieldOperandTypes(func, checkMode) { - var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); - ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - // A yield* expression effectively yields everything that its operand yields - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); - } - if (functionFlags & 2 /* Async */) { - type = checkAwaitedType(type, expr, yieldExpression.asteriskToken - ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - }); - return aggregatedTypes; - } - function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { - return false; - } - var type = getTypeOfExpression(node.expression); - if (!isLiteralType(type)) { - return false; - } - var switchTypes = getSwitchClauseTypes(node); - if (!switchTypes.length) { - return false; - } - return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); - } - function functionHasImplicitReturn(func) { - if (!(func.flags & 128 /* HasImplicitReturn */)) { - return false; - } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { - return false; - } - return true; - } - function checkAndAggregateReturnExpressionTypes(func, checkMode) { - var functionFlags = ts.getFunctionFlags(func); - var aggregatedTypes = []; - var hasReturnWithNoExpression = functionHasImplicitReturn(func); - var hasReturnOfTypeNever = false; - ts.forEachReturnStatement(func.body, function (returnStatement) { - var expr = returnStatement.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (functionFlags & 2 /* Async */) { - // 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 should be unwrapped to its awaited type, which should be wrapped in - // the native Promise type by the caller. - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (type.flags & 8192 /* Never */) { - hasReturnOfTypeNever = true; - } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - else { - hasReturnWithNoExpression = true; - } - }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */)) { - return undefined; - } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } - } - return aggregatedTypes; - } - /** - * TypeScript Specification 1.0 (6.3) - July 2014 - * An explicitly typed function whose return type isn't the Void type, - * the Any type, or a union type containing the Void or Any type as a constituent - * must have at least one return statement somewhere in its body. - * An exception to this rule is if the function implementation consists of a single 'throw' statement. - * - * @param returnType - return type of the function, can be undefined if return type is not explicitly specified - */ - function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { - if (!produceDiagnostics) { - return; - } - // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { - return; - } - // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 /* Block */ || !functionHasImplicitReturn(func)) { - return; - } - var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 8192 /* Never */) { - error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); - } - else if (returnType && !hasExplicitReturn) { - // minimal check: function has syntactic return type annotation and no explicit return statements in the body - // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); - } - else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { - error(func.type, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); - } - else if (compilerOptions.noImplicitReturns) { - if (!returnType) { - // If return type annotation is omitted check if function has any explicit return statements. - // If it does not have any - its inferred return type is void - don't do any checks. - // Otherwise get inferred return type from function body and report error only if it is not void / anytype - if (!hasExplicitReturn) { - return; - } - var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { - return; - } - } - error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - // Grammar checking - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { - checkGrammarForGenerator(node); - } - // The identityMapper object is used to indicate that function expressions are wildcards - if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { - checkNodeDeferred(node); - return anyFunctionType; - } - var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); - var contextSensitive = isContextSensitive(node); - var mightFixTypeParameters = contextSensitive && checkMode === 2 /* Inferential */; - // Check if function expression is contextually typed and assign parameter types if so. - // See the comment in assignTypeToParameterAndFixTypeParameters to understand why we need to - // check mightFixTypeParameters. - if (mightFixTypeParameters || !(links.flags & 1024 /* ContextChecked */)) { - var contextualSignature = getContextualSignature(node); - // If a type check is started at a function expression that is an argument of a function call, obtaining the - // contextual type may recursively get back to here during overload resolution of the call. If so, we will have - // already assigned contextual types. - var contextChecked = !!(links.flags & 1024 /* ContextChecked */); - if (mightFixTypeParameters || !contextChecked) { - links.flags |= 1024 /* ContextChecked */; - if (contextualSignature) { - var signature = getSignaturesOfType(type, 0 /* Call */)[0]; - if (contextSensitive) { - assignContextualParameterTypes(signature, contextualSignature, getContextualMapper(node), checkMode); - } - if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { - var returnType = getReturnTypeFromBody(node, checkMode); - if (!signature.resolvedReturnType) { - signature.resolvedReturnType = returnType; - } - } - } - if (!contextChecked) { - checkSignatureDeclaration(node); - checkNodeDeferred(node); - } - } - } - if (produceDiagnostics && node.kind !== 151 /* MethodDeclaration */) { - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - } - return type; - } - function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var functionFlags = ts.getFunctionFlags(node); - var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : - getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function - if ((functionFlags & 1 /* Generator */) === 0) { - // return is not necessary in the body of generators - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (node.body) { - if (!node.type) { - // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors - // we need. An example is the noImplicitAny errors resulting from widening the return expression - // of a function. Because checking of function expression bodies is deferred, there was never an - // appropriate time to do this during the main walk of the file (see the comment at the top of - // checkFunctionExpressionBodies). So it must be done now. - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - if (node.body.kind === 207 /* Block */) { - checkSourceElement(node.body); - } - else { - // 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 we - // should not be checking assignability of a promise to the return type. Instead, we need to - // check assignability of the awaited type of the expression body against the promised type of - // its return type annotation. - var exprType = checkExpression(node.body); - if (returnOrPromisedType) { - 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); - } - else { - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); - } - } - } - registerForUnusedIdentifiersCheck(node); - } - } - function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { - error(operand, diagnostic); - return false; - } - return true; - } - function isReadonlySymbol(symbol) { - // The following symbols are considered read-only: - // Properties with a 'readonly' modifier - // Variables declared with 'const' - // Get accessors without matching set accessors - // Enum members - // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - 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 */); - } - function isReferenceToReadonlyEntity(expr, symbol) { - if (isReadonlySymbol(symbol)) { - // Allow assignments to readonly properties within constructors of the same class declaration. - if (symbol.flags & 4 /* Property */ && - (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) && - expr.expression.kind === 99 /* ThisKeyword */) { - // Look for if this is the constructor for the class that `symbol` is a property of. - var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152 /* Constructor */)) - return true; - // If func.parent is a class and symbol is a (readonly) property of that class, or - // if func is a constructor and symbol is a (readonly) parameter property declared in it, - // then symbol is writeable here. - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); - } - return true; - } - return false; - } - function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) { - var node = ts.skipParentheses(expr.expression); - if (node.kind === 71 /* Identifier */) { - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol.flags & 8388608 /* Alias */) { - var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240 /* NamespaceImport */; - } - } - } - return false; - } - function checkReferenceExpression(expr, invalidReferenceMessage) { - // References are combinations of identifiers, parentheses, and property accesses. - var node = ts.skipParentheses(expr); - if (node.kind !== 71 /* Identifier */ && node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { - error(expr, invalidReferenceMessage); - return false; - } - return true; - } - function checkDeleteExpression(node) { - checkExpression(node.expression); - var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 /* PropertyAccessExpression */ && expr.kind !== 180 /* ElementAccessExpression */) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); - return booleanType; - } - var links = getNodeLinks(expr); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); - } - return booleanType; - } - function checkTypeOfExpression(node) { - checkExpression(node.expression); - return typeofType; - } - function checkVoidExpression(node) { - checkExpression(node.expression); - return undefinedWideningType; - } - function checkAwaitExpression(node) { - // Grammar checking - if (produceDiagnostics) { - if (!(node.flags & 16384 /* AwaitContext */)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - var operandType = checkExpression(node.expression); - return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkPrefixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - switch (node.operator) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { - error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); - } - return numberType; - case 51 /* ExclamationToken */: - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : - booleanType; - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - return unknownType; - } - function checkPostfixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - // Return true if type might be of the given kind. A union or intersection type might be of a given - // kind if at least one constituent type is of the given kind. - function maybeTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 196608 /* UnionOrIntersection */) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (maybeTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - // Return true if type is of the given kind. A union type is of a given kind if all constituent types - // are of the given kind. An intersection type is of a given kind if at least one constituent type is - // of the given kind. - function isTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 65536 /* Union */) { - var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; - } - if (type.flags & 131072 /* Intersection */) { - var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); - } - function isConstEnumSymbol(symbol) { - return (symbol.flags & 128 /* ConstEnum */) !== 0; - } - function checkInstanceOfExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - // TypeScript 1.0 spec (April 2014): 4.15.4 - // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, - // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. - // The result is always of the Boolean primitive type. - // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 8190 /* Primitive */)) { - error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - // NOTE: do not raise error if right is unknown as related error was already reported - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0 /* Call */).length || - getSignaturesOfType(rightType, 1 /* Construct */).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); - } - return booleanType; - } - function checkInExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - // TypeScript 1.0 spec (April 2014): 4.15.5 - // 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, 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 */)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - return booleanType; - } - function checkObjectLiteralAssignment(node, sourceType) { - var properties = node.properties; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); - } - return sourceType; - } - /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 /* PropertyAssignment */ || property.kind === 262 /* ShorthandPropertyAssignment */) { - var name = property.name; - if (name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || - getIndexTypeOfType(objectLiteralType, 0 /* String */); - if (type) { - if (property.kind === 262 /* ShorthandPropertyAssignment */) { - return checkDestructuringAssignment(property, type); - } - else { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.initializer, type); - } - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); - } - } - else if (property.kind === 263 /* SpreadAssignment */) { - if (languageVersion < 5 /* ESNext */) { - checkExternalEmitHelpers(property, 4 /* Rest */); - } - var nonRestNames = []; - if (allProperties) { - for (var i = 0; i < allProperties.length - 1; i++) { - nonRestNames.push(allProperties[i].name); - } - } - var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); - return checkDestructuringAssignment(property.expression, type); - } - else { - error(property, ts.Diagnostics.Property_assignment_expected); - } - } - function checkArrayLiteralAssignment(node, sourceType, checkMode) { - if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512 /* Read */); - } - // This elementType will be used if the specific property corresponding to this index is not - // present (aka the tuple element property). This call also checks that the parentType is in - // fact an iterable or array (depending on target language). - var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType; - var elements = node.elements; - for (var i = 0; i < elements.length; i++) { - checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); - } - return sourceType; - } - function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { - var elements = node.elements; - var element = elements[elementIndex]; - if (element.kind !== 200 /* OmittedExpression */) { - if (element.kind !== 198 /* SpreadElement */) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; - if (type) { - return checkDestructuringAssignment(element, type, checkMode); - } - else { - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } - } - } - else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - else { - var restExpression = element.expression; - if (restExpression.kind === 194 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); - } - } - } - } - return undefined; - } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { - var target; - if (exprOrAssignment.kind === 262 /* ShorthandPropertyAssignment */) { - var prop = exprOrAssignment; - if (prop.objectAssignmentInitializer) { - // In strict null checking mode, if a default value of a non-undefined type is specified, remove - // undefined from the final type. - if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { - sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); - } - checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); - } - target = exprOrAssignment.name; - } - else { - target = exprOrAssignment; - } - if (target.kind === 194 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { - checkBinaryExpression(target, checkMode); - target = target.left; - } - if (target.kind === 178 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType); - } - if (target.kind === 177 /* ArrayLiteralExpression */) { - return checkArrayLiteralAssignment(target, sourceType, checkMode); - } - return checkReferenceAssignment(target, sourceType, checkMode); - } - function checkReferenceAssignment(target, sourceType, checkMode) { - var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 /* SpreadAssignment */ ? - ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : - ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); - } - return sourceType; - } - /** - * This is a *shallow* check: An expression is side-effect-free if the - * evaluation of the expression *itself* cannot produce side effects. - * For example, x++ / 3 is side-effect free because the / operator - * does not have side effects. - * The intent is to "smell test" an expression for correctness in positions where - * its value is discarded (e.g. the left side of the comma operator). - */ - function isSideEffectFree(node) { - node = ts.skipParentheses(node); - switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 183 /* TaggedTemplateExpression */: - case 196 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 139 /* UndefinedKeyword */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: - case 187 /* ArrowFunction */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 189 /* TypeOfExpression */: - case 203 /* NonNullExpression */: - case 250 /* JsxSelfClosingElement */: - case 249 /* JsxElement */: - return true; - case 195 /* ConditionalExpression */: - return isSideEffectFree(node.whenTrue) && - isSideEffectFree(node.whenFalse); - case 194 /* BinaryExpression */: - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return false; - } - return isSideEffectFree(node.left) && - isSideEffectFree(node.right); - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: - // Unary operators ~, !, +, and - have no side effects. - // The rest do. - switch (node.operator) { - case 51 /* ExclamationToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - return true; - } - return false; - // Some forms listed here for clarity - case 190 /* VoidExpression */: // Explicit opt-out - case 184 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 202 /* AsExpression */: // Not SEF, but can produce useful type warnings - default: - return false; - } - } - function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], /*subtypeReduction*/ true); - } - function checkBinaryExpression(node, checkMode) { - return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); - } - function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { - var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 178 /* ObjectLiteralExpression */ || left.kind === 177 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); - } - var leftType = checkExpression(left, checkMode); - var rightType = checkExpression(right, checkMode); - switch (operator) { - case 39 /* AsteriskToken */: - case 40 /* AsteriskAsteriskToken */: - case 61 /* AsteriskEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 42 /* PercentToken */: - case 64 /* PercentEqualsToken */: - case 38 /* MinusToken */: - case 60 /* MinusEqualsToken */: - case 45 /* LessThanLessThanToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - var suggestedOperator = void 0; - // if a user tries to apply a bitwise operator to 2 boolean operands - // try and return them a helpful suggestion - if ((leftType.flags & 136 /* BooleanLike */) && - (rightType.flags & 136 /* BooleanLike */) && - (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { - error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); - } - else { - // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); - } - } - return numberType; - case 37 /* PlusToken */: - case 59 /* PlusEqualsToken */: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (!isTypeOfKind(leftType, 1 /* Any */ | 262178 /* StringLike */) && !isTypeOfKind(rightType, 1 /* Any */ | 262178 /* StringLike */)) { - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - } - var resultType = void 0; - 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; - } - else { - if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { - // If one or both operands are of the String primitive type, the result is of the String primitive type. - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - // Otherwise, the result is of type Any. - // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - // Symbols are not allowed at all in arithmetic expressions - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } - } - if (!resultType) { - reportOperatorError(); - return anyType; - } - if (operator === 59 /* PlusEqualsToken */) { - checkAssignmentOperator(resultType); - } - return resultType; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - if (checkForDisallowedESSymbolOperand(operator)) { - leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); - rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { - reportOperatorError(); - } - } - return booleanType; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - var leftIsLiteral = isLiteralType(leftType); - var rightIsLiteral = isLiteralType(rightType); - if (!leftIsLiteral || !rightIsLiteral) { - leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; - rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; - } - if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { - reportOperatorError(); - } - return booleanType; - case 93 /* InstanceOfKeyword */: - return checkInstanceOfExpression(left, right, leftType, rightType); - case 92 /* InKeyword */: - return checkInExpression(left, right, leftType, rightType); - case 53 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : - leftType; - case 54 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; - case 58 /* EqualsToken */: - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); - case 26 /* CommaToken */: - if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { - error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); - } - return rightType; - } - function isEvalNode(node) { - return node.kind === 71 /* Identifier */ && node.text === "eval"; - } - // Return true if there was no error, false if there was an error. - function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : - undefined; - if (offendingSymbolOperand) { - error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); - return false; - } - return true; - } - function getSuggestedBooleanOperator(operator) { - switch (operator) { - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - return 54 /* BarBarToken */; - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - return 35 /* ExclamationEqualsEqualsToken */; - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - return 53 /* AmpersandAmpersandToken */; - default: - return undefined; - } - } - function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 58 /* FirstAssignment */ && operator <= 70 /* LastAssignment */) { - // TypeScript 1.0 spec (April 2014): 4.17 - // An assignment of the form - // VarExpr = ValueExpr - // requires VarExpr to be classified as a reference - // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) - // and the type of the non - compound operation to be assignable to the type of VarExpr. - if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { - // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported - checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); - } - } - } - function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); - } - } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } - function checkYieldExpression(node) { - // Grammar checking - if (produceDiagnostics) { - if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - if (node.expression) { - var func = ts.getContainingFunction(node); - // If the user's code is syntactically correct, the func should always have a star. After all, - // we are in a yield context. - var functionFlags = func && ts.getFunctionFlags(func); - if (node.asteriskToken) { - // 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 */); - } - // Generator functions prior to ES2015 require the __values helper - if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && - languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256 /* Values */); - } - } - if (functionFlags & 1 /* Generator */) { - var expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); - } - // There is no point in doing an assignability check if the function - // has no explicit return type because the return type is directly computed - // from the yield expressions. - if (func.type) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(func.type), (functionFlags & 2 /* Async */) !== 0) || anyType; - if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 /* Async */ - ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionElementType, signatureElementType, node.expression, - /*headMessage*/ undefined); - } - else { - checkTypeAssignableTo(functionFlags & 2 /* Async */ - ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionType, signatureElementType, node.expression, - /*headMessage*/ undefined); - } - } - } - } - // Both yield and yield* expressions have type 'any' - return anyType; - } - function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); - var type1 = checkExpression(node.whenTrue, checkMode); - var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); - } - function checkLiteralExpression(node) { - if (node.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: - return trueType; - case 86 /* FalseKeyword */: - return falseType; - } - } - function checkTemplateExpression(node) { - // We just want to check each expressions, but we are unconcerned with - // the type of each expression, as any value may be coerced into a string. - // It is worth asking whether this is what we really want though. - // A place where we actually *are* concerned with the expressions' types are - // in tagged templates. - ts.forEach(node.templateSpans, function (templateSpan) { - checkExpression(templateSpan.expression); - }); - return stringType; - } - function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; - var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : - contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; - var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; - return result; - } - function checkExpressionCached(node, checkMode) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - // When computing a type that we're going to cache, we need to ignore any ongoing control flow - // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart - // to the top of the stack ensures all transient types are computed from a known point. - var saveFlowLoopStart = flowLoopStart; - flowLoopStart = flowLoopCount; - links.resolvedType = checkExpression(node, checkMode); - flowLoopStart = saveFlowLoopStart; - } - return links.resolvedType; - } - function isTypeAssertion(node) { - node = ts.skipParentheses(node); - return node.kind === 184 /* TypeAssertionExpression */ || node.kind === 202 /* AsExpression */; - } - function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); - return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); - } - function isLiteralContextualType(contextualType) { - if (contextualType) { - if (contextualType.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (constraint.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { - return true; - } - contextualType = constraint; - } - return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); - } - return false; - } - function checkExpressionForMutableLocation(node, checkMode) { - var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); - } - function checkPropertyAssignment(node, checkMode) { - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - } - return checkExpressionForMutableLocation(node.initializer, checkMode); - } - function checkObjectLiteralMethod(node, checkMode) { - // Grammar checking - checkGrammarMethod(node); - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - } - var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { - if (checkMode === 2 /* Inferential */) { - var signature = getSingleCallSignature(type); - if (signature && signature.typeParameters) { - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType) { - var contextualSignature = getSingleCallSignature(contextualType); - if (contextualSignature && !contextualSignature.typeParameters) { - return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); - } - } - } - } - return type; - } - /** - * Returns the type of an expression. Unlike checkExpression, this function is simply concerned - * with computing the type and may not fully check all contained sub-expressions for errors. - * A cache argument of true indicates that if the function performs a full type check, it is ok - * to cache the result. - */ - function getTypeOfExpression(node, cache) { - // Optimize for the common case of a call to a function with a single non-generic call - // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 181 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - var funcType = checkNonNullExpression(node.expression); - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return getReturnTypeOfSignature(signature); - } - } - // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions - // should have a parameter that indicates whether full error checking is required such that - // we can perform the optimizations locally. - return cache ? checkExpressionCached(node) : checkExpression(node); - } - /** - * Returns the type of an expression. Unlike checkExpression, this function is simply concerned - * with computing the type and may not fully check all contained sub-expressions for errors. - * It is intended for uses where you know there is no contextual type, - * and requesting the contextual type might cause a circularity or other bad behaviour. - * It sets the contextual type of the node to any before calling getTypeOfExpression. - */ - function getContextFreeTypeOfExpression(node) { - var saveContextualType = node.contextualType; - node.contextualType = anyType; - var type = getTypeOfExpression(node); - node.contextualType = saveContextualType; - return type; - } - // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When - // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the - // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in - // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function - // object, it serves as an indicator that all contained function and arrow expressions should be considered to - // have the wildcard function type; this form of type check is used during overload resolution to exclude - // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { - var type; - if (node.kind === 143 /* QualifiedName */) { - type = checkQualifiedName(node); - } - else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); - type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - if (isConstEnumObjectType(type)) { - // enum object type for const enums are only permitted in: - // - 'left' in property access - // - 'object' in indexed access - // - target in rhs of import statement - var ok = (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); - if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); - } - } - return type; - } - function checkExpressionWorker(node, checkMode) { - switch (node.kind) { - case 71 /* Identifier */: - return checkIdentifier(node); - case 99 /* ThisKeyword */: - return checkThisExpression(node); - case 97 /* SuperKeyword */: - return checkSuperExpression(node); - case 95 /* NullKeyword */: - return nullWideningType; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - return checkLiteralExpression(node); - case 196 /* TemplateExpression */: - return checkTemplateExpression(node); - case 13 /* NoSubstitutionTemplateLiteral */: - return stringType; - case 12 /* RegularExpressionLiteral */: - return globalRegExpType; - case 177 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); - case 178 /* ObjectLiteralExpression */: - return checkObjectLiteral(node, checkMode); - case 179 /* PropertyAccessExpression */: - return checkPropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: - return checkIndexedAccess(node); - case 181 /* CallExpression */: - case 182 /* NewExpression */: - return checkCallExpression(node); - case 183 /* TaggedTemplateExpression */: - return checkTaggedTemplateExpression(node); - case 185 /* ParenthesizedExpression */: - return checkExpression(node.expression, checkMode); - case 199 /* ClassExpression */: - return checkClassExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189 /* TypeOfExpression */: - return checkTypeOfExpression(node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - return checkAssertion(node); - case 203 /* NonNullExpression */: - return checkNonNullAssertion(node); - case 204 /* MetaProperty */: - return checkMetaProperty(node); - case 188 /* DeleteExpression */: - return checkDeleteExpression(node); - case 190 /* VoidExpression */: - return checkVoidExpression(node); - case 191 /* AwaitExpression */: - return checkAwaitExpression(node); - case 192 /* PrefixUnaryExpression */: - return checkPrefixUnaryExpression(node); - case 193 /* PostfixUnaryExpression */: - return checkPostfixUnaryExpression(node); - case 194 /* BinaryExpression */: - return checkBinaryExpression(node, checkMode); - case 195 /* ConditionalExpression */: - return checkConditionalExpression(node, checkMode); - case 198 /* SpreadElement */: - return checkSpreadExpression(node, checkMode); - case 200 /* OmittedExpression */: - return undefinedWideningType; - case 197 /* YieldExpression */: - return checkYieldExpression(node); - case 256 /* JsxExpression */: - return checkJsxExpression(node, checkMode); - case 249 /* JsxElement */: - return checkJsxElement(node); - case 250 /* JsxSelfClosingElement */: - return checkJsxSelfClosingElement(node); - case 254 /* JsxAttributes */: - return checkJsxAttributes(node, checkMode); - case 251 /* JsxOpeningElement */: - ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); - } - return unknownType; - } - // DECLARATION AND STATEMENT TYPE CHECKING - function checkTypeParameter(node) { - // Grammar Checking - if (node.expression) { - grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); - } - checkSourceElement(node.constraint); - checkSourceElement(node.default); - var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); - } - var constraintType = getConstraintOfTypeParameter(typeParameter); - var defaultType = getDefaultFromTypeParameter(typeParameter); - if (constraintType && defaultType) { - checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); - } - } - function checkParameter(node) { - // Grammar checking - // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the - // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code - // or if its FunctionBody is strict code(11.1.5). - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkVariableLikeDeclaration(node); - var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { - error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); - } - } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { - error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); - } - if (node.name.text === "this") { - if (ts.indexOf(func.parameters, node) !== 0) { - error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); - } - if (func.kind === 152 /* Constructor */ || func.kind === 156 /* ConstructSignature */ || func.kind === 161 /* ConstructorType */) { - error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); - } - } - // Only check rest parameter type if it's not a binding pattern. Since binding patterns are - // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { - error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); - } - } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && - param.name.text === parameter.text) { - return i; - } - } - } - return -1; - } - function checkTypePredicate(node) { - var parent = getTypePredicateParent(node); - if (!parent) { - // The parent must not be valid. - error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - return; - } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; - if (!typePredicate) { - return; - } - var parameterName = node.parameterName; - if (ts.isThisTypePredicate(typePredicate)) { - getTypeFromThisTypeNode(parameterName); - } - else { - if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { - error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); - } - else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, - /*headMessage*/ undefined, leadingError); - } - } - else if (parameterName) { - var hasReportedError = false; - for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name = _a[_i].name; - if (ts.isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { - hasReportedError = true; - break; - } - } - if (!hasReportedError) { - error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); - } - } - } - } - function getTypePredicateParent(node) { - switch (node.parent.kind) { - case 187 /* ArrowFunction */: - case 155 /* CallSignature */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 160 /* FunctionType */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - var parent = node.parent; - if (node === parent.type) { - return parent; - } - } - } - function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (ts.isOmittedExpression(element)) { - continue; - } - var name = element.name; - if (name.kind === 71 /* Identifier */ && - name.text === predicateVariableName) { - error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); - return true; - } - else if (name.kind === 175 /* ArrayBindingPattern */ || - name.kind === 174 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { - return true; - } - } - } - } - function checkSignatureDeclaration(node) { - // Grammar checking - if (node.kind === 157 /* IndexSignature */) { - checkGrammarIndexSignature(node); - } - else if (node.kind === 160 /* FunctionType */ || node.kind === 228 /* FunctionDeclaration */ || node.kind === 161 /* ConstructorType */ || - node.kind === 155 /* CallSignature */ || node.kind === 152 /* Constructor */ || - node.kind === 156 /* ConstructSignature */) { - checkGrammarFunctionLikeDeclaration(node); - } - var functionFlags = ts.getFunctionFlags(node); - 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 */); - } - // Async functions prior to ES2017 require the __awaiter helper - if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - } - // 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 */); - } - } - checkTypeParameters(node.typeParameters); - ts.forEach(node.parameters, checkParameter); - if (node.type) { - checkSourceElement(node.type); - } - if (produceDiagnostics) { - checkCollisionWithArgumentsInGeneratedCode(node); - if (noImplicitAny && !node.type) { - switch (node.kind) { - case 156 /* ConstructSignature */: - error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - case 155 /* CallSignature */: - error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - } - } - if (node.type) { - var functionFlags_1 = ts.getFunctionFlags(node); - 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); - } - else { - var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; - var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ - ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function - : createIterableIteratorType(generatorElementType); // Generator function - // Naively, one could check that IterableIterator is assignable to the return type annotation. - // However, that would not catch the error in the following case. - // - // interface BadGenerator extends Iterable, Iterator { } - // function* g(): BadGenerator { } // Iterable and Iterator have different types! - // - checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); - } - } - else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); - } - } - if (noUnusedIdentifiers && !node.body) { - checkUnusedTypeParameters(node); - } - } - } - 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++) { - var member = _a[_i]; - if (member.kind === 152 /* Constructor */) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var param = _c[_b]; - if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3 /* Property */); - } - } - } - else { - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; - var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { - switch (member.kind) { - case 153 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); - break; - case 154 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); - break; - case 149 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); - break; - case 151 /* MethodDeclaration */: - addName(names, member.name, memberName, 4 /* Method */); - break; - } - } - } - } - function addName(names, location, name, meaning) { - var prev = names.get(name); - if (prev) { - if (prev & 4 /* Method */) { - if (meaning !== 4 /* Method */) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - else { - names.set(name, prev | meaning); - } - } - else { - names.set(name, meaning); - } - } - } - /** - * Static members being set on a constructor function may conflict with built-in properties - * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable - * built-in properties. This check issues a transpile error when a class has a static - * member with the same name as a non-writable built-in property. - * - * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 - * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 - * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor - * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances - */ - function checkClassForStaticPropertyNameConflicts(node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; - if (isStatic && memberNameNode) { - var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); - switch (memberName) { - case "name": - case "length": - case "caller": - case "arguments": - case "prototype": - var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); - error(memberNameNode, message, memberName, className); - break; - } - } - } - } - function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148 /* PropertySignature */) { - var memberName = void 0; - switch (member.name.kind) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 71 /* Identifier */: - memberName = member.name.text; - break; - default: - continue; - } - if (names.get(memberName)) { - error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); - error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); - } - else { - names.set(memberName, true); - } - } - } - } - function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230 /* InterfaceDeclaration */) { - var nodeSymbol = getSymbolOfNode(node); - // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration - // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { - return; - } - } - // TypeScript 1.0 spec (April 2014) - // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. - // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration - var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { - var seenNumericIndexer = false; - var seenStringIndexer = false; - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var declaration = decl; - if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type.kind) { - case 136 /* StringKeyword */: - if (!seenStringIndexer) { - seenStringIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_string_index_signature); - } - break; - case 133 /* NumberKeyword */: - if (!seenNumericIndexer) { - seenNumericIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_number_index_signature); - } - break; - } - } - } - } - } - function checkPropertyDeclaration(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); - checkVariableLikeDeclaration(node); - } - function checkMethodDeclaration(node) { - // Grammar checking - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionOrMethodDeclaration(node); - // Abstract methods cannot have an implementation. - // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { - error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); - } - } - function checkConstructorDeclaration(node) { - // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. - checkSignatureDeclaration(node); - // Grammar check for checking only related to constructorDeclaration - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - var symbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); - // Only type check the symbol once - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(symbol); - } - // exit early in the case of signature - super checks are not relevant to them - if (ts.nodeIsMissing(node.body)) { - return; - } - if (!produceDiagnostics) { - return; - } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } - function markThisReferencesAsErrors(n) { - if (n.kind === 99 /* ThisKeyword */) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 /* FunctionExpression */ && n.kind !== 228 /* FunctionDeclaration */) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } - function isInstancePropertyWithInitializer(n) { - return n.kind === 149 /* PropertyDeclaration */ && - !(ts.getModifierFlags(n) & 32 /* Static */) && - !!n.initializer; - } - // TS 1.0 spec (April 2014): 8.3.2 - // Constructors of classes with no extends clause may not contain super calls, whereas - // constructors of derived classes must contain at least one super call somewhere in their function body. - var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - captureLexicalThis(node.parent, containingClassDecl); - var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); - var superCall = getSuperCallInConstructor(node); - if (superCall) { - if (classExtendsNull) { - error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); - } - // The first statement in the body of a constructor (excluding prologue directives) must be a super call - // if both of the following are true: - // - The containing class is a derived class. - // - The constructor declares parameter properties - // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); - // Skip past any prologue directives to find the first statement - // to ensure that it was a super call. - if (superCallShouldBeFirst) { - var statements = node.body.statements; - var superCallStatement = void 0; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { - superCallStatement = statement; - break; - } - if (!ts.isPrologueDirective(statement)) { - break; - } - } - if (!superCallStatement) { - error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); - } - } - } - else if (!classExtendsNull) { - error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); - } - } - } - function checkAccessorDeclaration(node) { - if (produceDiagnostics) { - // Grammar checking accessors - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - checkDecorators(node); - checkSignatureDeclaration(node); - if (node.kind === 153 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { - if (!(node.flags & 256 /* HasExplicitReturn */)) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); - } - } - } - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - // TypeScript 1.0 spec (April 2014): 8.4.3 - // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); - if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); - } - if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); - } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); - } - } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153 /* GetAccessor */) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } - } - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } - } - function checkMissingDeclaration(node) { - checkDecorators(node); - } - function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var typeArguments; - var mapper; - var result = true; - for (var i = 0; i < typeParameters.length; i++) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); - mapper = createTypeMapper(typeParameters, typeArguments); - } - var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - } - return result; - } - function checkTypeReferenceNode(node) { - checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReference(node); - if (type !== unknownType) { - if (node.typeArguments) { - // Do type argument local checks only if referenced type is successfully resolved - ts.forEach(node.typeArguments, checkSourceElement); - if (produceDiagnostics) { - var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 /* TypeAlias */ ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; - checkTypeArgumentConstraints(typeParameters, node.typeArguments); - } - } - 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)); - } - } - } - function checkTypeQuery(node) { - getTypeFromTypeQueryNode(node); - } - function checkTypeLiteral(node) { - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - checkObjectTypeForDuplicateDeclarations(node); - } - } - function checkArrayType(node) { - checkSourceElement(node.elementType); - } - function checkTupleType(node) { - // Grammar checking - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); - } - ts.forEach(node.elementTypes, checkSourceElement); - } - function checkUnionOrIntersectionType(node) { - ts.forEach(node.types, checkSourceElement); - } - function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288 /* IndexedAccess */)) { - return type; - } - // Check if the index type is assignable to 'keyof T' for the object type. - var objectType = type.objectType; - var indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - return type; - } - // 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, 84 /* NumberLike */)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { - return type; - } - } - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); - return type; - } - function checkIndexedAccessType(node) { - checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); - } - function checkMappedType(node) { - checkSourceElement(node.typeParameter); - checkSourceElement(node.type); - var type = getTypeFromMappedTypeNode(node); - var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); - } - function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); - } - function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedModifierFlags(n); - // children of classes (even ambient classes) should not be marked as ambient or export - // because those flags have no useful semantics there. - if (n.parent.kind !== 230 /* InterfaceDeclaration */ && - n.parent.kind !== 229 /* ClassDeclaration */ && - n.parent.kind !== 199 /* ClassExpression */ && - ts.isInAmbientContext(n)) { - if (!(flags & 2 /* Ambient */)) { - // It is nested in an ambient context, which means it is automatically exported - flags |= 1 /* Export */; - } - flags |= 2 /* Ambient */; - } - return flags & flagsToCheck; - } - function checkFunctionOrConstructorSymbol(symbol) { - if (!produceDiagnostics) { - return; - } - function getCanonicalOverload(overloads, implementation) { - // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration - // Error on all deviations from this canonical set of flags - // The caveat is that if some overloads are defined in lib.d.ts, we don't want to - // report the errors on those. To achieve this, we will say that the implementation is - // the canonical signature only if it is in the same container as the first overload - var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; - return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; - } - function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { - // Error if some overloads have a flag that is not shared by all overloads. To find the - // deviations, we XOR someOverloadFlags with allOverloadFlags - var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; - if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); - ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; - if (deviation & 1 /* Export */) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - } - else if (deviation & 2 /* Ambient */) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - } - else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - } - else if (deviation & 128 /* Abstract */) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); - } - }); - } - } - function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { - if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); - ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; - if (deviation) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); - } - }); - } - } - var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; - var someNodeFlags = 0 /* None */; - var allNodeFlags = flagsToCheck; - var someHaveQuestionToken = false; - var allHaveQuestionToken = true; - var hasOverloads = false; - var bodyDeclaration; - var lastSeenNonAmbientDeclaration; - var previousDeclaration; - var declarations = symbol.declarations; - var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; - function reportImplementationExpectedError(node) { - if (node.name && ts.nodeIsMissing(node.name)) { - return; - } - var seen = false; - var subsequentNode = ts.forEachChild(node.parent, function (c) { - if (seen) { - return c; - } - else { - seen = c === node; - } - }); - // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. - // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. - if (subsequentNode && subsequentNode.pos === node.end) { - if (subsequentNode.kind === node.kind) { - var errorNode_1 = subsequentNode.name || subsequentNode; - // TODO(jfreeman): These are methods, so handle computed name case - if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && - (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); - // we can get here in two cases - // 1. mixed static and instance class members - // 2. something with the same name was defined before the set of overloads that prevents them from merging - // here we'll report error only for the first case since for second we should already report error in binder - if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); - } - return; - } - else if (ts.nodeIsPresent(subsequentNode.body)) { - error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); - return; - } - } - } - var errorNode = node.name || node; - if (isConstructor) { - error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); - } - else { - // Report different errors regarding non-consecutive blocks of declarations depending on whether - // the node in question is abstract. - if (ts.getModifierFlags(node) & 128 /* Abstract */) { - error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); - } - else { - error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); - } - } - } - var duplicateFunctionDeclaration = false; - var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; - var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - if (node.kind === 228 /* FunctionDeclaration */ || node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */ || node.kind === 152 /* Constructor */) { - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - if (ts.nodeIsPresent(node.body) && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; - } - else { - duplicateFunctionDeclaration = true; - } - } - else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (ts.nodeIsPresent(node.body)) { - if (!bodyDeclaration) { - bodyDeclaration = node; - } - } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } - } - } - if (multipleConstructorImplementation) { - ts.forEach(declarations, function (declaration) { - error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); - }); - } - if (duplicateFunctionDeclaration) { - ts.forEach(declarations, function (declaration) { - error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); - }); - } - // Abstract methods can't have an implementation -- in particular, they don't need one. - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { - reportImplementationExpectedError(lastSeenNonAmbientDeclaration); - } - if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); - if (bodyDeclaration) { - var signatures = getSignaturesOfSymbol(symbol); - var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - 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; - } - } - } - } - } - function checkExportsOnMergedDeclarations(node) { - if (!produceDiagnostics) { - return; - } - // if localSymbol is defined on node then node itself is exported - check is required - var symbol = node.localSymbol; - if (!symbol) { - // local symbol is undefined => this declaration is non-exported. - // however symbol might contain other declarations that are exported - symbol = getSymbolOfNode(node); - if (!(symbol.flags & 7340032 /* Export */)) { - // this is a pure local symbol (all declarations are non-exported) - no need to check anything - return; - } - } - // run the check only for the first declaration in the list - if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { - return; - } - // we use SymbolFlags.ExportValue, SymbolFlags.ExportType and SymbolFlags.ExportNamespace - // to denote disjoint declarationSpaces (without making new enum type). - var exportedDeclarationSpaces = 0 /* None */; - var nonExportedDeclarationSpaces = 0 /* None */; - var defaultExportedDeclarationSpaces = 0 /* None */; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var d = _a[_i]; - var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); - if (effectiveDeclarationFlags & 1 /* Export */) { - if (effectiveDeclarationFlags & 512 /* Default */) { - defaultExportedDeclarationSpaces |= declarationSpaces; - } - else { - exportedDeclarationSpaces |= declarationSpaces; - } - } - else { - nonExportedDeclarationSpaces |= declarationSpaces; - } - } - // Spaces for anything not declared a 'default export'. - var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; - var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; - var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; - if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { - // declaration spaces for exported and non-exported declarations intersect - 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); - } - } - } - function getDeclarationSpaces(d) { - switch (d.kind) { - case 230 /* InterfaceDeclaration */: - return 2097152 /* ExportType */; - case 233 /* ModuleDeclaration */: - return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ - ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ - : 4194304 /* ExportNamespace */; - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 237 /* ImportEqualsDeclaration */: - var result_3 = 0; - var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - default: - return 1048576 /* ExportValue */; - } - } - } - function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { - var promisedType = getPromisedTypeOfPromise(type, errorNode); - return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); - } - /** - * Gets the "promised type" of a promise. - * @param type The type of the promise. - * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. - */ - function getPromisedTypeOfPromise(promise, errorNode) { - // - // { // promise - // then( // thenFunction - // onfulfilled: ( // onfulfilledParameterType - // value: T // valueParameterType - // ) => any - // ): any; - // } - // - if (isTypeAny(promise)) { - return undefined; - } - var typeAsPromise = promise; - if (typeAsPromise.promisedTypeOfPromise) { - return typeAsPromise.promisedTypeOfPromise; - } - if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { - return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; - } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (isTypeAny(thenFunction)) { - return undefined; - } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; - if (thenSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); - } - return undefined; - } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); - if (isTypeAny(onfulfilledParameterType)) { - return undefined; - } - var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); - if (onfulfilledParameterSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); - } - return undefined; - } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); - } - /** - * Gets the "awaited type" of a type. - * @param type The type to await. - * @remarks The "awaited type" of an expression is its "promised type" if the expression is a - * Promise-like type; otherwise, it is the type of the expression. This is used to reflect - * The runtime behavior of the `await` keyword. - */ - function checkAwaitedType(type, errorNode, diagnosticMessage) { - return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; - } - function getAwaitedType(type, errorNode, diagnosticMessage) { - var typeAsAwaitable = type; - if (typeAsAwaitable.awaitedTypeOfType) { - return typeAsAwaitable.awaitedTypeOfType; - } - if (isTypeAny(type)) { - return typeAsAwaitable.awaitedTypeOfType = type; - } - if (type.flags & 65536 /* Union */) { - var types = void 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituentType = _a[_i]; - types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); - } - if (!types) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true); - } - var promisedType = getPromisedTypeOfPromise(type); - if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { - // Verify that we don't have a bad actor in the form of a promise whose - // promised type is the same as the promise type, or a mutually recursive - // promise. If so, we return undefined as we cannot guess the shape. If this - // were the actual case in the JavaScript, this Promise would never resolve. - // - // An example of a bad actor with a singly-recursive promise type might - // be: - // - // interface BadPromise { - // then( - // onfulfilled: (value: BadPromise) => any, - // onrejected: (error: any) => any): BadPromise; - // } - // The above interface will pass the PromiseLike check, and return a - // promised type of `BadPromise`. Since this is a self reference, we - // don't want to keep recursing ad infinitum. - // - // An example of a bad actor in the form of a mutually-recursive - // promise type might be: - // - // interface BadPromiseA { - // then( - // onfulfilled: (value: BadPromiseB) => any, - // onrejected: (error: any) => any): BadPromiseB; - // } - // - // interface BadPromiseB { - // then( - // onfulfilled: (value: BadPromiseA) => any, - // onrejected: (error: any) => any): BadPromiseA; - // } - // - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); - } - return undefined; - } - // Keep track of the type we're about to unwrap to avoid bad recursive promise types. - // See the comments above for more information. - awaitedTypeStack.push(type.id); - var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); - awaitedTypeStack.pop(); - if (!awaitedType) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = awaitedType; - } - // The type was not a promise, so it could not be unwrapped any further. - // As long as the type does not have a callable "then" property, it is - // safe to return the type; otherwise, an error will be reported in - // the call to getNonThenableType and we will return undefined. - // - // An example of a non-promise "thenable" might be: - // - // await { then(): void {} } - // - // The "thenable" does not match the minimal definition for a promise. When - // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise - // will never settle. We treat this as an error to help flag an early indicator - // of a runtime problem. If the user wants to return this value from an async - // function, they would need to wrap it in some other value. If they want it to - // be treated as a promise, they can cast to . - var thenFunction = getTypeOfPropertyOfType(type, "then"); - if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { - if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); - error(errorNode, diagnosticMessage); - } - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = type; - } - /** - * Checks the return type of an async function to ensure it is a compatible - * Promise implementation. - * - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. - * - * @param node The signature to check - */ - function checkAsyncFunctionReturnType(node) { - // As part of our emit for an async function, we will need to emit the entity name of - // the return type annotation as an expression. To meet the necessary runtime semantics - // for __awaiter, we must also check that the type of the declaration (e.g. the static - // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. - // - // An example might be (from lib.es6.d.ts): - // - // interface Promise { ... } - // interface PromiseConstructor { - // new (...): Promise; - // } - // declare var Promise: PromiseConstructor; - // - // When an async function declares a return type annotation of `Promise`, we - // need to get the type of the `Promise` variable declaration above, which would - // be `PromiseConstructor`. - // - // The same case applies to a class: - // - // declare class Promise { - // constructor(...); - // then(...): Promise; - // } - // - var returnType = getTypeFromTypeNode(node.type); - if (languageVersion >= 2 /* ES2015 */) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); - if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { - // The promise type was not a valid type reference to the global promise type, so we - // report an error and return the unknown type. - error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return unknownType; - } - } - else { - // Always mark the type node as referenced if it points to a value - markTypeNodeAsReferenced(node.type); - if (returnType === unknownType) { - return unknownType; - } - var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); - if (promiseConstructorName === undefined) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return unknownType; - } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true); - var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; - if (promiseConstructorType === unknownType) { - if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.text === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { - error(node.type, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - else { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - } - return unknownType; - } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); - if (globalPromiseConstructorLikeType === emptyObjectType) { - // If we couldn't resolve the global PromiseConstructorLike type we cannot verify - // compatibility with __awaiter. - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return unknownType; - } - // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.text, 107455 /* Value */); - if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - } - // Get and return the awaited type of the return type. - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - /** Check a decorator */ - function checkDecorator(node) { - var signature = getResolvedSignature(node); - var returnType = getReturnTypeOfSignature(signature); - if (returnType.flags & 1 /* Any */) { - return; - } - var expectedReturnType; - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - var errorInfo; - switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - var classSymbol = getSymbolOfNode(node.parent); - var classConstructorType = getTypeOfSymbol(classSymbol); - expectedReturnType = getUnionType([classConstructorType, voidType]); - break; - case 146 /* Parameter */: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); - break; - case 149 /* PropertyDeclaration */: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); - break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); - var descriptorType = createTypedPropertyDescriptorType(methodType); - expectedReturnType = getUnionType([descriptorType, voidType]); - break; - } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); - } - /** - * If a TypeNode can be resolved to a value symbol imported from an external module, it is - * marked as referenced to prevent import elision. - */ - function markTypeNodeAsReferenced(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 - && rootSymbol.flags & 8388608 /* Alias */ - && symbolIsValue(rootSymbol) - && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - 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; - } - /** Check the decorators of a node */ - function checkDecorators(node) { - if (!node.decorators) { - return; - } - // skip this check for nodes that cannot have decorators. These should have already had an error reported by - // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node)) { - return; - } - if (!compilerOptions.experimentalDecorators) { - error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); - } - var firstDecorator = node.decorators[0]; - checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 146 /* Parameter */) { - checkExternalEmitHelpers(firstDecorator, 32 /* Param */); - } - if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); - // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. - switch (node.kind) { - case 229 /* ClassDeclaration */: - var constructor = ts.getFirstConstructorWithBody(node); - if (constructor) { - for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - } - break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - case 149 /* PropertyDeclaration */: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); - break; - case 146 /* Parameter */: - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - } - } - ts.forEach(node.decorators, checkDecorator); - } - function checkFunctionDeclaration(node) { - if (produceDiagnostics) { - checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function checkFunctionOrMethodDeclaration(node) { - checkDecorators(node); - checkSignatureDeclaration(node); - var functionFlags = ts.getFunctionFlags(node); - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name && node.name.kind === 144 /* ComputedPropertyName */) { - // This check will account for methods in class/interface declarations, - // as well as accessors in classes/object literals - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - // first we want to check the local symbol that contain this declaration - // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol - // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode - var symbol = getSymbolOfNode(node); - var localSymbol = node.localSymbol || symbol; - // Since the javascript won't do semantic analysis like typescript, - // if the javascript file comes before the typescript file and both contain same name functions, - // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - var firstDeclaration = ts.forEach(localSymbol.declarations, - // Get first non javascript function declaration - function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? - declaration : undefined; }); - // Only type check the symbol once - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(localSymbol); - } - if (symbol.parent) { - // run check once for the first declaration - if (ts.getDeclarationOfKind(symbol, node.kind) === node) { - // run check on export symbol to check that modifiers agree across all exported declarations - checkFunctionOrConstructorSymbol(symbol); - } - } - } - checkSourceElement(node.body); - if ((functionFlags & 1 /* Generator */) === 0) { - var returnOrPromisedType = node.type && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(node.type)); // normal function - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (produceDiagnostics && !node.type) { - // Report an implicit any error if there is no body, no explicit return type, and node is not a private method - // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); - } - if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(node.body)) { - // A generator with a body and no type annotation can still cause errors. It can error if the - // yielded values have no common supertype, or it can give an implicit any error if it has no - // yielded values. The only way to trigger these errors is to try checking its return type. - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - } - registerForUnusedIdentifiersCheck(node); - } - function registerForUnusedIdentifiersCheck(node) { - if (deferredUnusedIdentifierNodes) { - deferredUnusedIdentifierNodes.push(node); - } - } - function checkUnusedIdentifiers() { - if (deferredUnusedIdentifierNodes) { - for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { - var node = deferredUnusedIdentifierNodes_1[_i]; - switch (node.kind) { - case 265 /* SourceFile */: - case 233 /* ModuleDeclaration */: - checkUnusedModuleMembers(node); - break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - checkUnusedClassMembers(node); - checkUnusedTypeParameters(node); - break; - case 230 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node); - break; - case 207 /* Block */: - case 235 /* CaseBlock */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - checkUnusedLocalsAndParameters(node); - break; - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - if (node.body) { - checkUnusedLocalsAndParameters(node); - } - checkUnusedTypeParameters(node); - break; - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - checkUnusedTypeParameters(node); - break; - } - } - } - } - function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - 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(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(ts.getNameOfDeclaration(d) || d, local.name); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } - function errorUnusedLocal(node, name) { - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 /* VariableDeclaration */ && - (declaration.parent.parent.kind === 215 /* ForInStatement */ || - declaration.parent.parent.kind === 216 /* ForOfStatement */)) { - return; - } - } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); - } - } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 /* Identifier */ && node.text.charCodeAt(0) === 95 /* _ */; - } - function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); - } - } - else if (member.kind === 152 /* Constructor */) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); - } - } - } - } - } - } - } - function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.typeParameters) { - // Only report errors on the last declaration for the type parameter container; - // this ensures that all uses have been accounted for. - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } - for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { - var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); - } - } - } - } - } - function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); - } - } - } - }); - } - } - function checkBlock(node) { - // Grammar checking for SyntaxKind.Block - if (node.kind === 207 /* Block */) { - checkGrammarStatementInAmbientContext(node); - } - ts.forEach(node.statements, checkSourceElement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkCollisionWithArgumentsInGeneratedCode(node) { - // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { - return; - } - ts.forEach(node.parameters, function (p) { - if (p.name && !ts.isBindingPattern(p.name) && p.name.text === argumentsSymbol.name) { - error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); - } - }); - } - function needCollisionCheckForIdentifier(node, identifier, name) { - if (!(identifier && identifier.text === name)) { - return false; - } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 148 /* PropertySignature */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 150 /* MethodSignature */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // it is ok to have member named '_super' or '_this' - member access is always qualified - return false; - } - if (ts.isInAmbientContext(node)) { - // ambient context - no codegen impact - return false; - } - var root = ts.getRootDeclaration(node); - if (root.kind === 146 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { - // just an overload - no codegen impact - return false; - } - return true; - } - function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { - potentialThisCollisions.push(node); - } - } - function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { - potentialNewTargetCollisions.push(node); - } - } - // this function will run after checking the source file so 'CaptureThis' is correct for all nodes - function checkIfThisIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 71 /* Identifier */; - if (isDeclaration_1) { - 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); - } - return true; - } - }); - } - function checkIfNewTargetIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { - var isDeclaration_2 = node.kind !== 71 /* Identifier */; - if (isDeclaration_2) { - 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); - } - return true; - } - }); - } - function checkCollisionWithCapturedSuperVariable(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "_super")) { - return; - } - // bubble up and find containing type - var enclosingClass = ts.getContainingClass(node); - // if containing type was not found or it is ambient - exit (no codegen) - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { - return; - } - if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71 /* Identifier */; - if (isDeclaration_3) { - error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); - } - else { - error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); - } - } - } - function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - // No need to check for require or exports for ES6 modules and later - if (modulekind >= ts.ModuleKind.ES2015) { - return; - } - if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { - return; - } - // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { - return; - } - // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent - var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { - // If the declaration happens to be in external module, report error that require and exports are reserved keywords - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { - return; - } - // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { - return; - } - // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent - var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { - // If the declaration happens to be in external module, report error that Promise is a reserved identifier. - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkVarDeclaredNamesNotShadowed(node) { - // - ScriptBody : StatementList - // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList - // also occurs in the VarDeclaredNames of StatementList. - // - Block : { StatementList } - // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList - // also occurs in the VarDeclaredNames of StatementList. - // Variable declarations are hoisted to the top of their function scope. They can shadow - // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition - // by the binder as the declaration scope is different. - // A non-initialized declaration is a no-op as the block declaration will resolve before the var - // declaration. the problem is if the declaration has an initializer. this will act as a write to the - // block declared value. this is fine for let, but not const. - // Only consider declarations with initializers, uninitialized const declarations will not - // step on a let/const variable. - // Do not consider const and const declarations, as duplicate block-scoped declarations - // are handled by the binder. - // We are only looking for const declarations that step on let\const declarations from a - // different scope. e.g.: - // { - // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration - // const x = 0; // symbol for this declaration will be 'symbol' - // } - // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { - return; - } - // skip variable declarations that don't have initializers - // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern - // so we'll always treat binding elements as initialized - if (node.kind === 226 /* VariableDeclaration */ && !node.initializer) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol.flags & 1 /* FunctionScopedVariable */) { - var localDeclarationSymbol = resolveName(node, node.name.text, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); - if (localDeclarationSymbol && - localDeclarationSymbol !== symbol && - localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 208 /* VariableStatement */ && varDeclList.parent.parent - ? varDeclList.parent.parent - : undefined; - // names of block-scoped and function scoped variables can collide only - // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) - var namesShareScope = container && - (container.kind === 207 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 234 /* ModuleBlock */ || - container.kind === 233 /* ModuleDeclaration */ || - container.kind === 265 /* SourceFile */); - // here we know that function scoped variable is shadowed by block scoped one - // if they are defined in the same scope - binder has already reported redeclaration error - // otherwise if variable has an initializer - show error that initialization will fail - // since LHS will be block scoped name instead of function scoped - if (!namesShareScope) { - var name = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); - } - } - } - } - } - // Check that a parameter initializer contains no references to parameters declared to the right of itself - function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146 /* Parameter */) { - return; - } - var func = ts.getContainingFunction(node); - visit(node.initializer); - function visit(n) { - if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { - // do not dive in types - // skip declaration names (i.e. in object literal expressions) - return; - } - if (n.kind === 179 /* PropertyAccessExpression */) { - // skip property names in property access expression - return visit(n.expression); - } - else if (n.kind === 71 /* Identifier */) { - // check FunctionLikeDeclaration.locals (stores parameters\function local variable) - // if it contains entry with a specified name - var symbol = resolveName(n, n.text, 107455 /* Value */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { - return; - } - if (symbol.valueDeclaration === node) { - error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); - return; - } - // locals map for function contain both parameters and function locals - // so we need to do a bit of extra work to check if reference is legal - var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 /* Parameter */ || - symbol.valueDeclaration.kind === 176 /* BindingElement */) { - // it is ok to reference parameter in initializer if either - // - parameter is located strictly on the left of current parameter declaration - if (symbol.valueDeclaration.pos < node.pos) { - return; - } - // - parameter is wrapped in function-like entity - if (ts.findAncestor(n, function (current) { - if (current === node.initializer) { - return "quit"; - } - return ts.isFunctionLike(current.parent) || - // computed property names/initializers in instance property declaration of class like entities - // are executed in constructor and thus deferred - (current.parent.kind === 149 /* PropertyDeclaration */ && - !(ts.hasModifier(current.parent, 32 /* Static */)) && - ts.isClassLike(current.parent.parent)); - })) { - return; - } - // fall through to report error - } - error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); - } - } - else { - return ts.forEachChild(n, visit); - } - } - } - function convertAutoToAny(type) { - return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; - } - // Check variable, parameter, or property declaration - function checkVariableLikeDeclaration(node) { - checkDecorators(node); - checkSourceElement(node.type); - // For a computed property, just check the initializer and exit - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - if (node.initializer) { - checkExpressionCached(node.initializer); - } - } - if (node.kind === 176 /* BindingElement */) { - if (node.parent.kind === 174 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { - checkExternalEmitHelpers(node, 4 /* Rest */); - } - // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.propertyName); - } - // check private/protected variable access - var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); - var name = node.propertyName || node.name; - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); - } - } - // For a binding pattern, check contained binding elements - if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512 /* Read */); - } - ts.forEach(node.name.elements, checkSourceElement); - } - // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 146 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { - error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); - return; - } - // For a binding pattern, validate the initializer and exit - if (ts.isBindingPattern(node.name)) { - // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); - checkParameterInitializer(node); - } - return; - } - var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); - if (node === symbol.valueDeclaration) { - // Node is the primary declaration of the symbol, just validate the initializer - // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); - checkParameterInitializer(node); - } - } - else { - // Node is a secondary declaration, check that type is identical to primary declaration and check that - // initializer is consistent with type associated with the node - var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.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(node.name), typeToString(type), typeToString(declarationType)); - } - if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); - } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - 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)); - } - } - if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */) { - // We know we don't have a binding pattern or computed name here - checkExportsOnMergedDeclarations(node); - if (node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */) { - checkVarDeclaredNamesNotShadowed(node); - } - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 /* Parameter */ && right.kind === 226 /* VariableDeclaration */) || - (left.kind === 226 /* VariableDeclaration */ && right.kind === 146 /* Parameter */)) { - // Differences in optionality between parameters and variables are allowed. - return true; - } - if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { - return false; - } - var interestingFlags = 8 /* Private */ | - 16 /* Protected */ | - 256 /* Async */ | - 128 /* Abstract */ | - 64 /* Readonly */ | - 32 /* Static */; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); - } - function checkVariableDeclaration(node) { - checkGrammarVariableDeclaration(node); - return checkVariableLikeDeclaration(node); - } - function checkBindingElement(node) { - checkGrammarBindingElement(node); - return checkVariableLikeDeclaration(node); - } - function checkVariableStatement(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); - ts.forEach(node.declarationList.declarations, checkSourceElement); - } - function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 178 /* ObjectLiteralExpression */) { - if (ts.getFunctionFlags(node) & 2 /* Async */) { - if (node.modifiers.length > 1) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - } - function checkExpressionStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - } - function checkIfStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209 /* EmptyStatement */) { - error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); - } - checkSourceElement(node.elseStatement); - } - function checkDoStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkSourceElement(node.statement); - checkExpression(node.expression); - } - function checkWhileStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.statement); - } - function checkForStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227 /* VariableDeclarationList */) { - checkGrammarVariableDeclarationList(node.initializer); - } - } - if (node.initializer) { - if (node.initializer.kind === 227 /* VariableDeclarationList */) { - ts.forEach(node.initializer.declarations, checkVariableDeclaration); - } - else { - checkExpression(node.initializer); - } - } - if (node.condition) - checkExpression(node.condition); - if (node.incrementor) - checkExpression(node.incrementor); - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForOfStatement(node) { - checkGrammarForInOrForOfStatement(node); - if (node.kind === 216 /* ForOfStatement */) { - if (node.awaitModifier) { - 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 (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { - // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled - checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); - } - } - // Check the LHS and RHS - // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS - // via checkRightHandSideOfForOf. - // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. - // Then check that the RHS is assignable to it. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - // There may be a destructuring assignment on the left side - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { - // iteratedType may be undefined. In this case, we still want to check the structure of - // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like - // to short circuit the type relation checking as much as possible, so we pass the unknownType. - checkDestructuringAssignment(varExpr, iteratedType || unknownType); - } - else { - var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); - // iteratedType will be undefined if the rightType was missing properties/signatures - // required to get its iteratedType (like [Symbol.iterator] or next). This may be - // because we accessed properties from anyType, or it may have led to an error inside - // getElementTypeOfIterable. - if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); - } - } - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInStatement(node) { - // Grammar checking - checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 - // In a 'for-in' statement of the form - // for (let VarDecl in Expr) Statement - // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, - // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { - var variable = node.initializer.declarations[0]; - if (variable && ts.isBindingPattern(variable.name)) { - error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - checkForInOrForOfVariableDeclaration(node); - } - else { - // In a 'for-in' statement of the form - // for (Var in Expr) Statement - // Var must be an expression classified as a reference of type Any or the String primitive type, - // and Expr must be an expression of type Any, an object type, or a type parameter type. - var varExpr = node.initializer; - var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); - } - else { - // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); - } - } - // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved - // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { - error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInOrForOfVariableDeclaration(iterationStatement) { - var variableDeclarationList = iterationStatement.initializer; - // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. - if (variableDeclarationList.declarations.length >= 1) { - var decl = variableDeclarationList.declarations[0]; - checkVariableDeclaration(decl); - } - } - function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { - var expressionType = checkNonNullExpression(rhsExpression); - return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); - } - function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable) { - if (isTypeAny(inputType)) { - return inputType; - } - return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, /*checkAssignability*/ true) || anyType; - } - /** - * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment - * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type - * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. - */ - function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, checkAssignability) { - var uplevelIteration = languageVersion >= 2 /* ES2015 */; - var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; - // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 - // or higher, when inside of an async generator or for-await-if, or when - // downlevelIteration is requested. - if (uplevelIteration || downlevelIteration || allowAsyncIterable) { - // We only report errors for an invalid iterable type in ES2015 or higher. - var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterable, allowAsyncIterable, checkAssignability); - if (iteratedType || uplevelIteration) { - return iteratedType; - } - } - var arrayType = inputType; - var reportedError = false; - var hasStringConstituent = false; - // If strings are permitted, remove any string-like constituents from the array type. - // This allows us to find other non-string element types from an array unioned with - // a string. - if (allowStringInput) { - if (arrayType.flags & 65536 /* Union */) { - // After we remove all types that are StringLike, we will know if there was a string constituent - // based on whether the result of filter is a new array. - var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); - if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); - } - } - else if (arrayType.flags & 262178 /* StringLike */) { - arrayType = neverType; - } - hasStringConstituent = arrayType !== inputType; - if (hasStringConstituent) { - if (languageVersion < 1 /* ES5 */) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); - reportedError = true; - } - } - // Now that we've removed all the StringLike types, if no constituents remain, then the entire - // arrayOrStringType was a string. - if (arrayType.flags & 8192 /* Never */) { - return stringType; - } - } - } - if (!isArrayLikeType(arrayType)) { - if (errorNode && !reportedError) { - // Which error we report depends on whether we allow strings or if there was a - // string constituent. For example, if the input type is number | string, we - // want to say that number is not an array type. But if the input was just - // number and string input is allowed, we want to say that number is not an - // array type or a string type. - var diagnostic = !allowStringInput || hasStringConstituent - ? downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type - : downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; - error(errorNode, diagnostic, typeToString(arrayType)); - } - return hasStringConstituent ? stringType : undefined; - } - var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); - if (hasStringConstituent && arrayElementType) { - // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 262178 /* StringLike */) { - return stringType; - } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); - } - return arrayElementType; - } - /** - * We want to treat type as an iterable, and get the type it is an iterable of. The iterable - * must have the following structure (annotated with the names of the variables below): - * - * { // iterable - * [Symbol.iterator]: { // iteratorMethod - * (): Iterator - * } - * } - * - * For an async iterable, we expect the following structure: - * - * { // iterable - * [Symbol.asyncIterator]: { // iteratorMethod - * (): AsyncIterator - * } - * } - * - * T is the type we are after. At every level that involves analyzing return types - * of signatures, we union the return types of all the signatures. - * - * Another thing to note is that at any step of this process, we could run into a dead end, - * meaning either the property is missing, or we run into the anyType. If either of these things - * happens, we return undefined to signal that we could not find the iterated type. If a property - * is missing, and the previous step did not result in 'any', then we also give an error if the - * caller requested it. Then the caller can decide what to do in the case where there is no iterated - * type. This is different from returning anyType, because that would signify that we have matched the - * whole pattern and that T (above) is 'any'. - * - * For a **for-of** statement, `yield*` (in a normal generator), spread, array - * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` - * method. - * - * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. - * - * For a **for-await-of** statement or a `yield*` in an async generator we will look for - * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. - */ - function getIteratedTypeOfIterable(type, errorNode, isAsyncIterable, allowNonAsyncIterables, checkAssignability) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterable = type; - if (isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable) { - return isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable; - } - if (isAsyncIterable) { - // As an optimization, if the type is an instantiation of the global `AsyncIterable` - // or the global `AsyncIterableIterator` then just grab its type argument. - if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || - isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; - } - } - if (!isAsyncIterable || allowNonAsyncIterables) { - // As an optimization, if the type is an instantiation of the global `Iterable` or - // `IterableIterator` then just grab its type argument. - if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || - isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0] - : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; - } - } - var iteratorMethodSignatures; - var isNonAsyncIterable = false; - if (isAsyncIterable) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0 /* Call */); - } - if (!isAsyncIterable || (allowNonAsyncIterables && !ts.some(iteratorMethodSignatures))) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0 /* Call */); - isNonAsyncIterable = true; - } - if (ts.some(iteratorMethodSignatures)) { - var iteratorMethodReturnType = getUnionType(ts.map(iteratorMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); - var iteratedType = getIteratedTypeOfIterator(iteratorMethodReturnType, errorNode, /*isAsyncIterator*/ !isNonAsyncIterable); - if (checkAssignability && errorNode && iteratedType) { - // If `checkAssignability` was specified, we were called from - // `checkIteratedTypeOrElementType`. As such, we need to validate that - // the type passed in is actually an Iterable. - checkTypeAssignableTo(type, isNonAsyncIterable - ? createIterableType(iteratedType) - : createAsyncIterableType(iteratedType), errorNode); - } - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; - } - if (errorNode) { - error(errorNode, isAsyncIterable - ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); - } - return undefined; - } - /** - * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on - * Iterators instead of Iterables. Here is the structure: - * - * { // iterator - * next: { // nextMethod - * (): { // nextResult - * value: T // nextValue - * } - * } - * } - * - * For an async iterator, we expect the following structure: - * - * { // iterator - * next: { // nextMethod - * (): PromiseLike<{ // nextResult - * value: T // nextValue - * }> - * } - * } - */ - function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterator = type; - if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { - return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; - } - // As an optimization, if the type is an instantiation of the global `Iterator` (for - // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then - // just grab its type argument. - var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; - if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] - : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; - } - // Both async and non-async iterators must have a `next` method. - var nextMethod = getTypeOfPropertyOfType(type, "next"); - if (isTypeAny(nextMethod)) { - return undefined; - } - var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : emptyArray; - if (nextMethodSignatures.length === 0) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.An_async_iterator_must_have_a_next_method - : ts.Diagnostics.An_iterator_must_have_a_next_method); - } - return undefined; - } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); - if (isTypeAny(nextResult)) { - return undefined; - } - // For an async iterator, we must get the awaited type of the return type. - if (isAsyncIterator) { - nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); - if (isTypeAny(nextResult)) { - return undefined; - } - } - var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); - if (!nextValue) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property - : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue - : typeAsIterator.iteratedTypeOfIterator = nextValue; - } - /** - * A generator may have a return type of `Iterator`, `Iterable`, or - * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, - * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract - * the iterated type from this return type for contextual typing and verifying signatures. - */ - function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { - if (isTypeAny(returnType)) { - return undefined; - } - return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, isAsyncGenerator, /*allowNonAsyncIterables*/ false, /*checkAssignability*/ false) - || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); - } - function checkBreakOrContinueStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); - // TODO: Check that target label is valid - } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); - } - function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - 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 */); - } - function checkReturnStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } - } - var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { - // A generator does not need its return expressions checked against its return type. - // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added - // for generators. - return; - } - if (func.kind === 154 /* SetAccessor */) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } - } - else if (func.kind === 152 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - // If the function has a return type, but promisedType is - // undefined, an error will be reported in checkAsyncFunctionReturnType - // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); - } - } - } - else if (func.kind !== 152 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - // The function has a return type, but the return statement doesn't have an expression. - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - } - function checkWithStatement(node) { - // Grammar checking for withStatement - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 16384 /* AwaitContext */) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); - } - } - checkExpression(node.expression); - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; - var end = node.statement.pos; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); - } - } - function checkSwitchStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - var firstDefaultClause; - var hasDuplicateDefaultClause = false; - var expressionType = checkExpression(node.expression); - var expressionIsLiteral = isLiteralType(expressionType); - ts.forEach(node.caseBlock.clauses, function (clause) { - // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 258 /* DefaultClause */ && !hasDuplicateDefaultClause) { - if (firstDefaultClause === undefined) { - firstDefaultClause = clause; - } - else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); - hasDuplicateDefaultClause = true; - } - } - if (produceDiagnostics && clause.kind === 257 /* CaseClause */) { - var caseClause = clause; - // TypeScript 1.0 spec (April 2014): 5.9 - // In a 'switch' statement, each 'case' expression must be of a type that is comparable - // to or from the type of the 'switch' expression. - var caseType = checkExpression(caseClause.expression); - var caseIsLiteral = isLiteralType(caseType); - var comparedExpressionType = expressionType; - if (!caseIsLiteral || !expressionIsLiteral) { - caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; - comparedExpressionType = getBaseTypeOfLiteralType(expressionType); - } - if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { - // expressionType is not comparable to caseType, try the reversed check and report errors if it fails - checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); - } - } - ts.forEach(clause.statements, checkSourceElement); - }); - if (node.caseBlock.locals) { - registerForUnusedIdentifiersCheck(node.caseBlock); - } - } - function checkLabeledStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - ts.findAncestor(node.parent, function (current) { - if (ts.isFunctionLike(current)) { - return "quit"; - } - if (current.kind === 222 /* LabeledStatement */ && current.label.text === node.label.text) { - var sourceFile = ts.getSourceFileOfNode(node); - grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); - return true; - } - }); - } - // ensure that label is unique - checkSourceElement(node.statement); - } - function checkThrowStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.expression === undefined) { - grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); - } - } - if (node.expression) { - checkExpression(node.expression); - } - } - function checkTryStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkBlock(node.tryBlock); - var catchClause = node.catchClause; - if (catchClause) { - // Grammar checking - if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.type) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); - } - else if (catchClause.variableDeclaration.initializer) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); - } - else { - var blockLocals_1 = catchClause.block.locals; - if (blockLocals_1) { - ts.forEachKey(catchClause.locals, function (caughtName) { - var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { - grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); - } - }); - } - } - } - checkBlock(catchClause.block); - } - if (node.finallyBlock) { - checkBlock(node.finallyBlock); - } - } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); - var stringIndexType = getIndexTypeOfType(type, 0 /* String */); - var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); - if (stringIndexType || numberIndexType) { - ts.forEach(getPropertiesOfObjectType(type), function (prop) { - var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); - }); - if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; - // Only process instance properties with computed names here. - // Static properties cannot be in conflict with indexers, - // and properties with literal names were already checked. - if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); - } - } - } - } - var errorNode; - if (stringIndexType && numberIndexType) { - errorNode = declaredNumberIndexer || declaredStringIndexer; - // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { - var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; - } - } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { - error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); - } - function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { - return; - } - var propDeclaration = prop.valueDeclaration; - // index is numeric and property name is not valid numeric literal - 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 us to rule out cases when both property and indexer are inherited from the base class - var errorNode; - if (propDeclaration && - (propDeclaration.kind === 194 /* BinaryExpression */ || - ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || - prop.parent === containingType.symbol)) { - errorNode = propDeclaration; - } - else if (indexDeclaration) { - errorNode = indexDeclaration; - } - else if (getObjectFlags(containingType) & 2 /* Interface */) { - // for interfaces property and indexer might be inherited from different bases - // check if any base class already has both property and indexer. - // check should be performed only if 'type' is the first type that brings property\indexer together - var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; - } - if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 /* String */ - ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 - : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; - error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); - } - } - } - function checkTypeNameIsReserved(name, message) { - // TS 1.0 spec (April 2014): 3.6.1 - // The predefined type keywords are reserved and cannot be used as names of user defined types. - switch (name.text) { - case "any": - case "number": - case "boolean": - case "string": - case "symbol": - case "void": - case "object": - error(name, message, name.text); - } - } - /** - * Check each type parameter and check that type parameters have no duplicate type parameter declarations - */ - function checkTypeParameters(typeParameterDeclarations) { - if (typeParameterDeclarations) { - var seenDefault = false; - for (var i = 0; i < typeParameterDeclarations.length; i++) { - var node = typeParameterDeclarations[i]; - checkTypeParameter(node); - if (produceDiagnostics) { - if (node.default) { - seenDefault = true; - } - else if (seenDefault) { - error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); - } - for (var j = 0; j < i; j++) { - if (typeParameterDeclarations[j].symbol === node.symbol) { - error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); - } - } - } - } - } - } - /** Check that type parameter lists are identical across multiple declarations */ - function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { - return; - } - var links = getSymbolLinks(symbol); - if (!links.typeParametersChecked) { - links.typeParametersChecked = true; - var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { - return; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { - // Report an error on every conflicting declaration. - var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); - } - } - } - } - function areTypeParametersIdentical(declarations, typeParameters) { - var maxTypeArgumentCount = ts.length(typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - // If this declaration has too few or too many type parameters, we report an error - var numTypeParameters = ts.length(declaration.typeParameters); - if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { - return false; - } - for (var i = 0; i < numTypeParameters; i++) { - var source = declaration.typeParameters[i]; - var target = typeParameters[i]; - // If the type parameter node does not have the same as the resolved type - // parameter at this position, we report an error. - if (source.name.text !== target.symbol.name) { - return false; - } - // If the type parameter node does not have an identical constraint as the resolved - // type parameter at this position, we report an error. - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; - } - // If the type parameter node has a default and it is not identical to the default - // for the type parameter at this position, we report an error. - var sourceDefault = source.default && getTypeFromTypeNode(source.default); - var targetDefault = getDefaultFromTypeParameter(target); - if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { - return false; - } - } - } - return true; - } - function checkClassExpression(node) { - checkClassLikeDeclaration(node); - checkNodeDeferred(node); - return getTypeOfSymbol(getSymbolOfNode(node)); - } - function checkClassExpressionDeferred(node) { - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); - } - checkClassLikeDeclaration(node); - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassLikeDeclaration(node) { - checkGrammarClassLikeDeclaration(node); - checkDecorators(node); - if (node.name) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkTypeParameters(node.typeParameters); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - var staticType = getTypeOfSymbol(symbol); - checkTypeParameterListsIdentical(symbol); - checkClassForDuplicateDeclarations(node); - // Only check for reserved static identifiers on non-ambient context. - if (!ts.isInAmbientContext(node)) { - checkClassForStaticPropertyNameConflicts(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length && produceDiagnostics) { - var baseType_1 = baseTypes[0]; - var baseConstructorType = getBaseConstructorTypeOfClass(type); - var staticBaseType = getApparentType(baseConstructorType); - checkBaseTypeAccessibility(staticBaseType, baseTypeNode); - checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { - ts.forEach(baseTypeNode.typeArguments, checkSourceElement); - for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { - var constructor = _a[_i]; - if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { - break; - } - } - } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 /* TypeVariable */ && !isMixinConstructorType(staticType)) { - error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); - } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 540672 /* TypeVariable */)) { - // When the static base type is a "class-like" constructor function (but not actually a class), we verify - // that all instantiated base constructor signatures return the same type. We can simply compare the type - // references (as opposed to checking the structure of the types) because elsewhere we have already checked - // that the base type is a class or interface type (and not, for example, an anonymous object type). - var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); - } - } - checkKindsOfPropertyMemberOverrides(type, baseType_1); - } - } - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); - if (implementedTypeNodes) { - for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { - var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { - error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(typeRefNode); - if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); - if (t !== unknownType) { - if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); - } - else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); - } - } - } - } - } - if (produceDiagnostics) { - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - } - } - function checkBaseTypeAccessibility(type, node) { - var signatures = getSignaturesOfType(type, 1 /* Construct */); - if (signatures.length) { - var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); - } - } - } - } - 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 ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; - } - function getClassLikeDeclarationOfSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); - } - function getClassOrInterfaceDeclarationsOfSymbol(symbol) { - return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 /* ClassDeclaration */ || d.kind === 230 /* InterfaceDeclaration */; - }); - } - function checkKindsOfPropertyMemberOverrides(type, baseType) { - // TypeScript 1.0 spec (April 2014): 8.2.3 - // A derived class inherits all members from its base class it doesn't override. - // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. - // Both public and private property members are inherited, but only public property members can be overridden. - // A property member in a derived class is said to override a property member in a base class - // when the derived class property member has the same name and kind(instance or static) - // as the base class property member. - // The type of an overriding property member must be assignable(section 3.8.4) - // to the type of the overridden property member, or otherwise a compile - time error occurs. - // Base class instance member functions can be overridden by derived class instance member functions, - // but not by other kinds of members. - // Base class instance member variables and accessors can be overridden by - // derived class instance member variables and accessors, but not by other kinds of members. - // NOTE: assignability is checked in checkClassDeclaration - var baseProperties = getPropertiesOfType(baseType); - for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; - var base = getTargetSymbol(baseProperty); - if (base.flags & 16777216 /* Prototype */) { - continue; - } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - 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, - // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* - // type declaration, derived and base resolve to the same symbol even in the case of generic classes. - if (derived === base) { - // derived class inherits base without override/redeclaration - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - // It is an error to inherit an abstract member without implementing it or being declared abstract. - // If there is no declaration for the derived class (as in the case of class expressions), - // then the class cannot be declared abstract. - if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 199 /* ClassExpression */) { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); - } - else { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); - } - } - } - else { - // derived overrides base. - 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 (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; - } - var errorMessage = void 0; - if (isMethodLike(base)) { - if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; - } - } - else if (base.flags & 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; - } - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); - } - } - } - } - function isAccessor(kind) { - return kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */; - } - function checkInheritedPropertiesAreIdentical(type, typeNode) { - var baseTypes = getBaseTypes(type); - if (baseTypes.length < 2) { - return true; - } - var seen = ts.createMap(); - ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.name, { prop: p, containingType: type }); }); - var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; - var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; - var existing = seen.get(prop.name); - if (!existing) { - seen.set(prop.name, { prop: prop, containingType: base }); - } - else { - var isInheritedProperty = existing.containingType !== type; - if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { - ok = false; - var typeName1 = typeToString(existing.containingType); - var typeName2 = typeToString(base); - var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); - } - } - } - } - return ok; - } - function checkInterfaceDeclaration(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); - checkTypeParameters(node.typeParameters); - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - checkTypeParameterListsIdentical(symbol); - // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); - if (node === firstInterfaceDecl) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - // run subsequent checks only if first set succeeded - if (checkInheritedPropertiesAreIdentical(type, node.name)) { - for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { - var baseType = _a[_i]; - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); - } - checkIndexConstraints(type); - } - } - checkObjectTypeForDuplicateDeclarations(node); - } - ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { - error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(heritageElement); - }); - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); - } - } - function checkTypeAliasDeclaration(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); - checkTypeParameters(node.typeParameters); - checkSourceElement(node.type); - } - function computeEnumMemberValues(node) { - var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - nodeLinks.flags |= 16384 /* EnumValuesComputed */; - var autoValue = 0; - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var value = computeMemberValue(member, autoValue); - getNodeLinks(member).enumMemberValue = value; - autoValue = typeof value === "number" ? value + 1 : undefined; - } - } - } - 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); - } - } - 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; - } - } - 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; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 45 /* LessThanLessThanToken */: return left << right; - case 50 /* CaretToken */: return left ^ right; - case 39 /* AsteriskToken */: return left * right; - case 41 /* SlashToken */: return left / right; - case 37 /* PlusToken */: return left + right; - case 38 /* MinusToken */: return left - right; - case 42 /* PercentToken */: return left % right; - } - } - 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); - } - } - 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; - } - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkExportsOnMergedDeclarations(node); - computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); - } - // Spec 2014 - Section 9.3: - // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, - // and when an enum type has multiple declarations, only one declaration is permitted to omit a value - // for the first member. - // - // Only perform this check once per symbol - var enumSymbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); - if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { - // check that const is placed\omitted on all enum declarations - ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); - } - }); - } - var seenEnumMissingInitialInitializer_1 = false; - ts.forEach(enumSymbol.declarations, function (declaration) { - // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 232 /* EnumDeclaration */) { - return false; - } - var enumDeclaration = declaration; - if (!enumDeclaration.members.length) { - return false; - } - var firstEnumMember = enumDeclaration.members[0]; - if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer_1) { - error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); - } - else { - seenEnumMissingInitialInitializer_1 = true; - } - } - }); - } - } - function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 229 /* ClassDeclaration */ || - (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { - return declaration; - } - } - return undefined; - } - function inSameLexicalScope(node1, node2) { - var container1 = ts.getEnclosingBlockScopeContainer(node1); - var container2 = ts.getEnclosingBlockScopeContainer(node2); - if (isGlobalSourceFile(container1)) { - return isGlobalSourceFile(container2); - } - else if (isGlobalSourceFile(container2)) { - return false; - } - else { - return container1 === container2; - } - } - function checkModuleDeclaration(node) { - if (produceDiagnostics) { - // Grammar checking - var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); - if (isGlobalAugmentation && !inAmbientContext) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); - } - var isAmbientExternalModule = ts.isAmbientModule(node); - var contextErrorMessage = isAmbientExternalModule - ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file - : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; - if (checkGrammarModuleElementContext(node, contextErrorMessage)) { - // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { - grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - } - if (ts.isIdentifier(node.name)) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - // The following checks only apply on a non-ambient instantiated module declaration. - if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 - && !inAmbientContext - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { - var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); - if (firstNonAmbientClassOrFunc) { - if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); - } - else if (node.pos < firstNonAmbientClassOrFunc.pos) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); - } - } - // if the module merges with a class declaration in the same lexical scope, - // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 229 /* ClassDeclaration */); - if (mergedClass && - inSameLexicalScope(node, mergedClass)) { - getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; - } - } - if (isAmbientExternalModule) { - if (ts.isExternalModuleAugmentation(node)) { - // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) - // otherwise we'll be swamped in cascading errors. - // We can detect if augmentation was applied using following rules: - // - augmentation for a global scope is always applied - // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728 /* Transient */); - if (checkBody && node.body) { - // body of ambient external module is always a module block - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - checkModuleAugmentationElement(statement, isGlobalAugmentation); - } - } - } - else if (isGlobalSourceFile(node.parent)) { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); - } - } - else { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else { - // Node is not an augmentation and is not located on the script level. - // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); - } - } - } - } - if (node.body) { - checkSourceElement(node.body); - if (!ts.isGlobalScopeAugmentation(node)) { - registerForUnusedIdentifiersCheck(node); - } - } - } - function checkModuleAugmentationElement(node, isGlobalAugmentation) { - switch (node.kind) { - case 208 /* VariableStatement */: - // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - checkModuleAugmentationElement(decl, isGlobalAugmentation); - } - break; - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: - grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); - break; - case 237 /* ImportEqualsDeclaration */: - case 238 /* ImportDeclaration */: - grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); - break; - case 176 /* BindingElement */: - case 226 /* VariableDeclaration */: - var name = node.name; - if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; - // mark individual names in binding pattern - checkModuleAugmentationElement(el, isGlobalAugmentation); - } - break; - } - // falls through - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 228 /* FunctionDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - if (isGlobalAugmentation) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 134217728 /* Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } - break; - } - } - function getFirstIdentifier(node) { - switch (node.kind) { - case 71 /* Identifier */: - return node; - case 143 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 71 /* Identifier */); - return node; - case 179 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 71 /* Identifier */); - return node; - } - } - function checkExternalImportOrExportDeclaration(node) { - var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { - error(moduleName, ts.Diagnostics.String_literal_expected); - return false; - } - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 /* ExportDeclaration */ ? - ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : - ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); - return false; - } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration - // no need to do this again. - if (!isTopLevelInExternalModuleAugmentation(node)) { - // TypeScript 1.0 spec (April 2013): 12.1.6 - // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference - // other external modules only through top - level external module names. - // Relative external module names are not permitted. - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; - } - } - return true; - } - function checkAliasSymbol(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target !== unknownSymbol) { - // For external modules symbol represent local symbol for an alias. - // This local symbol will merge any other local declarations (excluding other aliases) - // and symbol.flags will contains combined representation for all merged declaration. - // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, - // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* - // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | - (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | - (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); - if (target.flags & excludedMeanings) { - var message = node.kind === 246 /* ExportSpecifier */ ? - ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : - 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) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkAliasSymbol(node); - } - function checkImportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); - } - if (checkExternalImportOrExportDeclaration(node)) { - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - checkImportBinding(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { - checkImportBinding(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, checkImportBinding); - } - } - } - } - } - function checkImportEqualsDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. - return; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { - checkImportBinding(node); - if (ts.getModifierFlags(node) & 1 /* Export */) { - markExportAsReferenced(node); - } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveAlias(getSymbolOfNode(node)); - if (target !== unknownSymbol) { - if (target.flags & 107455 /* Value */) { - // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { - error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); - } - } - if (target.flags & 793064 /* Type */) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); - } - } - } - else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - // Import equals declaration is deprecated in es6 or above - grammarErrorOnNode(node, ts.Diagnostics.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); - } - } - } - } - function checkExportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { - // If we hit an export in an illegal context, just bail out to avoid cascading errors. - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); - } - if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { - // export { x, y } - // export { x, y } from "foo" - ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 /* ModuleBlock */ && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { - error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); - } - } - else { - // export * from "foo" - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); - } - } - } - } - function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 /* SourceFile */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 233 /* ModuleDeclaration */; - if (!isInAppropriateContext) { - grammarErrorOnFirstToken(node, errorMessage); - } - return !isInAppropriateContext; - } - function checkExportSpecifier(node) { - checkAliasSymbol(node); - if (!node.parent.parent.moduleSpecifier) { - var exportedName = node.propertyName || node.name; - // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, - /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); - } - else { - markExportAsReferenced(node); - } - } - } - function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { - // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. - return; - } - var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { - if (node.isExportEquals) { - error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); - } - else { - error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); - } - return; - } - // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); - } - if (node.expression.kind === 71 /* Identifier */) { - markExportAsReferenced(node); - } - else { - checkExpressionCached(node.expression); - } - checkExternalModuleExports(container); - if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - // export assignment is not supported in es6 modules - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); - } - else if (modulekind === ts.ModuleKind.System) { - // system modules does not support export assignment - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); - } - } - } - function hasExportedMembers(moduleSymbol) { - return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); - } - function checkExternalModuleExports(node) { - var moduleSymbol = getSymbolOfNode(node); - var links = getSymbolLinks(moduleSymbol); - if (!links.exportsChecked) { - var exportEqualsSymbol = moduleSymbol.exports.get("export="); - if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { - var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration)) { - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); - } - } - // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. - // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); - if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { - // it is legal to merge type alias with other values - // so count should be either 1 (just type alias) or 2 (type alias + merged value) - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); - } - } - } - }); - links.exportsChecked = true; - } - function isNotOverload(declaration) { - return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || - !!declaration.body; - } - } - function checkSourceElement(node) { - if (!node) { - return; - } - var kind = node.kind; - if (cancellationToken) { - // Only bother checking on a few construct kinds. We don't want to be excessively - // hitting the cancellation token on every node we check. - switch (kind) { - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: - cancellationToken.throwIfCancellationRequested(); - } - } - switch (kind) { - case 145 /* TypeParameter */: - return checkTypeParameter(node); - case 146 /* Parameter */: - return checkParameter(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return checkPropertyDeclaration(node); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - return checkSignatureDeclaration(node); - case 157 /* IndexSignature */: - return checkSignatureDeclaration(node); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - return checkMethodDeclaration(node); - case 152 /* Constructor */: - return checkConstructorDeclaration(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return checkAccessorDeclaration(node); - case 159 /* TypeReference */: - return checkTypeReferenceNode(node); - case 158 /* TypePredicate */: - return checkTypePredicate(node); - case 162 /* TypeQuery */: - return checkTypeQuery(node); - case 163 /* TypeLiteral */: - return checkTypeLiteral(node); - case 164 /* ArrayType */: - return checkArrayType(node); - case 165 /* TupleType */: - return checkTupleType(node); - case 166 /* UnionType */: - case 167 /* IntersectionType */: - return checkUnionOrIntersectionType(node); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: - return checkSourceElement(node.type); - case 171 /* IndexedAccessType */: - return checkIndexedAccessType(node); - case 172 /* MappedType */: - return checkMappedType(node); - case 228 /* FunctionDeclaration */: - return checkFunctionDeclaration(node); - case 207 /* Block */: - case 234 /* ModuleBlock */: - return checkBlock(node); - case 208 /* VariableStatement */: - return checkVariableStatement(node); - case 210 /* ExpressionStatement */: - return checkExpressionStatement(node); - case 211 /* IfStatement */: - return checkIfStatement(node); - case 212 /* DoStatement */: - return checkDoStatement(node); - case 213 /* WhileStatement */: - return checkWhileStatement(node); - case 214 /* ForStatement */: - return checkForStatement(node); - case 215 /* ForInStatement */: - return checkForInStatement(node); - case 216 /* ForOfStatement */: - return checkForOfStatement(node); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: - return checkBreakOrContinueStatement(node); - case 219 /* ReturnStatement */: - return checkReturnStatement(node); - case 220 /* WithStatement */: - return checkWithStatement(node); - case 221 /* SwitchStatement */: - return checkSwitchStatement(node); - case 222 /* LabeledStatement */: - return checkLabeledStatement(node); - case 223 /* ThrowStatement */: - return checkThrowStatement(node); - case 224 /* TryStatement */: - return checkTryStatement(node); - case 226 /* VariableDeclaration */: - return checkVariableDeclaration(node); - case 176 /* BindingElement */: - return checkBindingElement(node); - case 229 /* ClassDeclaration */: - return checkClassDeclaration(node); - case 230 /* InterfaceDeclaration */: - return checkInterfaceDeclaration(node); - case 231 /* TypeAliasDeclaration */: - return checkTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: - return checkEnumDeclaration(node); - case 233 /* ModuleDeclaration */: - return checkModuleDeclaration(node); - case 238 /* ImportDeclaration */: - return checkImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: - return checkImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: - return checkExportDeclaration(node); - case 243 /* ExportAssignment */: - return checkExportAssignment(node); - case 209 /* EmptyStatement */: - checkGrammarStatementInAmbientContext(node); - return; - case 225 /* DebuggerStatement */: - checkGrammarStatementInAmbientContext(node); - return; - case 247 /* MissingDeclaration */: - return checkMissingDeclaration(node); - } - } - // Function and class expression bodies are checked after all statements in the enclosing body. This is - // to ensure constructs like the following are permitted: - // const foo = function () { - // const s = foo(); - // return "hello"; - // } - // Here, performing a full type check of the body of the function expression whilst in the process of - // determining the type of foo would cause foo to be given type any because of the recursive reference. - // Delaying the type check of the body ensures foo has been assigned a type. - function checkNodeDeferred(node) { - if (deferredNodes) { - deferredNodes.push(node); - } - } - function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; - switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - checkFunctionExpressionOrObjectLiteralMethodDeferred(node); - break; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - checkAccessorDeclaration(node); - break; - case 199 /* ClassExpression */: - checkClassExpressionDeferred(node); - break; - } - } - } - function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); - checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); - } - // Fully type check a source file and collect the relevant diagnostics. - function checkSourceFileWorker(node) { - var links = getNodeLinks(node); - if (!(links.flags & 1 /* TypeChecked */)) { - // If skipLibCheck is enabled, skip type checking if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip type checking if file contains a - // '/// ' directive. - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { - return; - } - // Grammar checking - checkGrammarSourceFile(node); - potentialThisCollisions.length = 0; - potentialNewTargetCollisions.length = 0; - deferredNodes = []; - deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; - ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); - if (ts.isExternalModule(node)) { - registerForUnusedIdentifiersCheck(node); - } - if (!node.isDeclarationFile) { - checkUnusedIdentifiers(); - } - deferredNodes = undefined; - deferredUnusedIdentifierNodes = undefined; - if (ts.isExternalOrCommonJsModule(node)) { - checkExternalModuleExports(node); - } - if (potentialThisCollisions.length) { - ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); - potentialThisCollisions.length = 0; - } - if (potentialNewTargetCollisions.length) { - ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); - potentialNewTargetCollisions.length = 0; - } - links.flags |= 1 /* TypeChecked */; - } - } - function getDiagnostics(sourceFile, ct) { - try { - // Record the cancellation token so it can be checked later on during checkSourceElement. - // Do this in a finally block so we can ensure that it gets reset back to nothing after - // this call is done. - cancellationToken = ct; - return getDiagnosticsWorker(sourceFile); - } - finally { - cancellationToken = undefined; - } - } - function getDiagnosticsWorker(sourceFile) { - throwIfNonDiagnosticsProducing(); - if (sourceFile) { - // Some global diagnostics are deferred until they are needed and - // may not be reported in the firt call to getGlobalDiagnostics. - // We should catch these changes and report them. - var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; - checkSourceFile(sourceFile); - var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); - var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { - // If the arrays are not the same reference, new diagnostics were added. - var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); - return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); - } - else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { - // If the arrays are the same reference, but the length has changed, a single - // new diagnostic was added as DiagnosticCollection attempts to reuse the - // same array. - return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); - } - return semanticDiagnostics; - } - // Global diagnostics are always added when a file is not provided to - // getDiagnostics - ts.forEach(host.getSourceFiles(), checkSourceFile); - return diagnostics.getDiagnostics(); - } - function getGlobalDiagnostics() { - throwIfNonDiagnosticsProducing(); - return diagnostics.getGlobalDiagnostics(); - } - function throwIfNonDiagnosticsProducing() { - if (!produceDiagnostics) { - throw new Error("Trying to get diagnostics from a type checker that does not produce them."); - } - } - // Language service support - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 /* WithStatement */ && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } - function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return []; - } - var symbols = ts.createMap(); - var memberFlags = 0 /* None */; - populateSymbols(); - return symbolsToArray(symbols); - function populateSymbols() { - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 265 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - // falls through - case 233 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); - break; - case 232 /* EnumDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); - break; - case 199 /* ClassExpression */: - var className = location.name; - if (className) { - copySymbol(location.symbol, meaning); - } - // falls through - // this fall-through is necessary because we would like to handle - // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - // If we didn't come from static member of class or interface, - // add the type parameters into the symbol table - // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. - // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 32 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); - } - break; - case 186 /* FunctionExpression */: - var funcName = location.name; - if (funcName) { - copySymbol(location.symbol, meaning); - } - break; - } - if (ts.introducesArgumentsExoticObject(location)) { - copySymbol(argumentsSymbol, meaning); - } - memberFlags = ts.getModifierFlags(location); - location = location.parent; - } - copySymbols(globals, meaning); - } - /** - * Copy the given symbol into symbol tables if the symbol has the given meaning - * and it doesn't already existed in the symbol table - * @param key a key for storing in symbol table; if undefined, use symbol.name - * @param symbol the symbol to be added into symbol table - * @param meaning meaning of symbol to filter by before adding to symbol table - */ - function copySymbol(symbol, meaning) { - if (symbol.flags & meaning) { - var id = symbol.name; - // We will copy all symbol regardless of its reserved name because - // symbolsToArray will check whether the key is a reserved name and - // it will not copy symbol with reserved name to the array - if (!symbols.has(id)) { - symbols.set(id, symbol); - } - } - } - function copySymbols(source, meaning) { - if (meaning) { - source.forEach(function (symbol) { - copySymbol(symbol, meaning); - }); - } - } - } - function isTypeDeclarationName(name) { - return name.kind === 71 /* Identifier */ && - isTypeDeclaration(name.parent) && - name.parent.name === name; - } - function isTypeDeclaration(node) { - switch (node.kind) { - case 145 /* TypeParameter */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: - return true; - } - } - // True if the given identifier is part of a type reference - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 143 /* QualifiedName */) { - node = node.parent; - } - return node.parent && (node.parent.kind === 159 /* TypeReference */ || node.parent.kind === 277 /* JSDocTypeReference */); - } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 179 /* PropertyAccessExpression */) { - node = node.parent; - } - return node.parent && node.parent.kind === 201 /* ExpressionWithTypeArguments */; - } - function forEachEnclosingClass(node, callback) { - var result; - while (true) { - node = ts.getContainingClass(node); - if (!node) - break; - if (result = callback(node)) - break; - } - return result; - } - function isNodeWithinClass(node, classDeclaration) { - return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); - } - function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143 /* QualifiedName */) { - nodeOnRightSide = nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 237 /* ImportEqualsDeclaration */) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 243 /* ExportAssignment */) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; - } - return undefined; - } - function isInRightSideOfImportOrExportAssignment(node) { - return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; - } - function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); - switch (specialPropertyAssignmentKind) { - case 1 /* ExportsProperty */: - case 3 /* PrototypeProperty */: - return getSymbolOfNode(entityName.parent); - case 4 /* ThisProperty */: - case 2 /* ModuleExports */: - case 5 /* Property */: - return getSymbolOfNode(entityName.parent.parent); - } - } - function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { - if (ts.isDeclarationName(entityName)) { - return getSymbolOfNode(entityName.parent); - } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 /* PropertyAccessExpression */ && - entityName.parent === entityName.parent.parent.left) { - // Check if this is a special property assignment - var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); - if (specialPropertyAssignmentSymbol) { - return specialPropertyAssignmentSymbol; - } - } - if (entityName.parent.kind === 243 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); - } - if (entityName.kind !== 179 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { - // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 237 /* ImportEqualsDeclaration */); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); - } - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = 0 /* None */; - // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 201 /* ExpressionWithTypeArguments */) { - meaning = 793064 /* Type */; - // In a class 'extends' clause we are also looking for a value. - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455 /* Value */; - } - } - else { - meaning = 1920 /* Namespace */; - } - meaning |= 8388608 /* Alias */; - var entityNameSymbol = resolveEntityName(entityName, meaning); - if (entityNameSymbol) { - return entityNameSymbol; - } - } - if (ts.isPartOfExpression(entityName)) { - if (ts.nodeIsMissing(entityName)) { - // Missing entity name. - return undefined; - } - if (entityName.kind === 71 /* Identifier */) { - if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { - return getIntrinsicTagSymbol(entityName.parent); - } - return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); - } - else if (entityName.kind === 179 /* PropertyAccessExpression */) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkPropertyAccessExpression(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - else if (entityName.kind === 143 /* QualifiedName */) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkQualifiedName(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - } - else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 159 /* TypeReference */ || entityName.parent.kind === 277 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; - return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); - } - else if (entityName.parent.kind === 253 /* JsxAttribute */) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 158 /* TypePredicate */) { - return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); - } - // Do we want to return undefined here? - return undefined; - } - function getSymbolAtLocation(node) { - if (node.kind === 265 /* SourceFile */) { - return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; - } - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return undefined; - } - if (isDeclarationNameOrImportPropertyName(node)) { - // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(node.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); - } - if (node.kind === 71 /* Identifier */) { - if (isInRightSideOfImportOrExportAssignment(node)) { - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - } - else if (node.parent.kind === 176 /* BindingElement */ && - node.parent.parent.kind === 174 /* ObjectBindingPattern */ && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); - if (propertyDeclaration) { - return propertyDeclaration; - } - } - } - switch (node.kind) { - case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99 /* ThisKeyword */: - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - if (ts.isFunctionLike(container)) { - var sig = getSignatureFromDeclaration(container); - if (sig.thisParameter) { - return sig.thisParameter; - } - } - // falls through - case 97 /* SuperKeyword */: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; - case 169 /* ThisType */: - return getTypeFromTypeNode(node).symbol; - case 123 /* ConstructorKeyword */: - // constructor keyword for an overload, should take us to the definition if it exist - var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152 /* Constructor */) { - return constructorDeclaration.parent.symbol; - } - return undefined; - case 9 /* StringLiteral */: - // External module name in an import declaration - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { - return resolveExternalModuleName(node, node); - } - // falls through - case 8 /* NumericLiteral */: - // index access - if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); - } - break; - } - return undefined; - } - function getShorthandAssignmentValueSymbol(location) { - // The function returns a value symbol of an identifier in the short-hand property assignment. - // This is necessary as an identifier in short-hand property assignment can contains two meaning: - // property name and property value. - if (location && location.kind === 262 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */); - } - return undefined; - } - /** Returns the target of an export specifier without following aliases */ - function getExportSpecifierLocalTargetSymbol(node) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); - } - function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return unknownType; - } - if (ts.isPartOfTypeNode(node)) { - var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; - } - if (ts.isPartOfExpression(node)) { - return getRegularTypeOfExpression(node); - } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the - // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); - } - if (isTypeDeclaration(node)) { - // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - var symbol = getSymbolOfNode(node); - return getDeclaredTypeOfSymbol(symbol); - } - if (isTypeDeclarationName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - } - if (ts.isDeclaration(node)) { - // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - var symbol = getSymbolOfNode(node); - return getTypeOfSymbol(symbol); - } - if (isDeclarationNameOrImportPropertyName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); - } - if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); - } - if (isInRightSideOfImportOrExportAssignment(node)) { - var symbol = getSymbolAtLocation(node); - var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); - return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); - } - return unknownType; - } - // Gets the type of object literal or array literal of destructuring assignment. - // { a } from - // for ( { a } of elems) { - // } - // [ a ] from - // [a] = [ some array ...] - function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 /* ObjectLiteralExpression */ || expr.kind === 177 /* ArrayLiteralExpression */); - // If this is from "for of" - // for ( { a } of elems) { - // } - if (expr.parent.kind === 216 /* ForOfStatement */) { - var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - // If this is from "for" initializer - // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 194 /* BinaryExpression */) { - var iteratedType = getTypeOfExpression(expr.parent.right); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - // If this is from nested object binding pattern - // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 261 /* PropertyAssignment */) { - var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); - } - // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 177 /* ArrayLiteralExpression */); - // [{ property1: p1, property2 }] = elems; - var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); - } - // Gets the property symbol corresponding to the property in destructuring assignment - // 'property1' from - // for ( { property1: a } of elems) { - // } - // 'property1' at location 'a' from: - // [a] = [ property1, property2 ] - function getPropertySymbolOfDestructuringAssignment(location) { - // Get the type of the object or array literal and then look for property of given name in the type - var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); - return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); - } - function getRegularTypeOfExpression(expr) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { - expr = expr.parent; - } - return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); - } - /** - * Gets either the static or instance type of a class element, based on - * whether the element is declared as "static". - */ - function getParentTypeOfClassElement(node) { - var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 /* Static */ - ? getTypeOfSymbol(classSymbol) - : getDeclaredTypeOfSymbol(classSymbol); - } - // Return the list of properties of the given type, augmented with properties from Function - // if the type has call or construct signatures - function getAugmentedPropertiesOfType(type) { - type = getApparentType(type); - var propsByName = createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName.has(p.name)) { - propsByName.set(p.name, p); - } - }); - } - return getNamedMembers(propsByName); - } - function getRootSymbols(symbol) { - 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_4.push(symbol); - } - }); - return symbols_4; - } - else if (symbol.flags & 134217728 /* Transient */) { - if (symbol.leftSpread) { - var links = symbol; - return getRootSymbols(links.leftSpread).concat(getRootSymbols(links.rightSpread)); - } - if (symbol.syntheticOrigin) { - return getRootSymbols(symbol.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } - } - return [symbol]; - } - // Emitter support - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var isPropertyName_1 = node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; - return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; - } - } - return false; - } - function moduleExportsSomeValue(moduleReferenceExpression) { - var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - // If the module is not found or is shorthand, assume that it may export a value. - return true; - } - var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); - // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment - // otherwise it will return moduleSymbol itself - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - var symbolLinks = getSymbolLinks(moduleSymbol); - if (symbolLinks.exportsSomeValue === undefined) { - // for export assignments - check if resolved symbol for RHS is itself a value - // otherwise - check if at least one export is value - symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455 /* Value */) - : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); - } - return symbolLinks.exportsSomeValue; - function isValue(s) { - s = resolveSymbol(s); - return s && !!(s.flags & 107455 /* Value */); - } - } - function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; - } - // When resolved as an expression identifier, if the given node references an exported entity, return the declaration - // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - // When resolving the export container for the name of a module or enum - // declaration, we need to start resolution at the declaration's container. - // Otherwise, we could incorrectly resolve the export container as the - // declaration if it contains an exported member with the same name. - var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); - if (symbol) { - if (symbol.flags & 1048576 /* ExportValue */) { - // If we reference an exported entity within the same module declaration, then whether - // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the - // kinds that we do NOT prefix. - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol_1 = getParentOfSymbol(symbol); - if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 265 /* SourceFile */) { - var symbolFile = parentSymbol_1.valueDeclaration; - var referenceFile = ts.getSourceFileOfNode(node); - // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. - var symbolIsUmdExport = symbolFile !== referenceFile; - return symbolIsUmdExport ? undefined : symbolFile; - } - return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); - } - } - } - } - // When resolved as an expression identifier, if the given node references an import, return the declaration of - // that import. Otherwise, return undefined. - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && symbol.flags & 8388608 /* Alias */) { - return getDeclarationOfAliasSymbol(symbol); - } - } - return undefined; - } - function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */) { - var links = getSymbolLinks(symbol); - if (links.isDeclarationWithCollidingName === undefined) { - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (ts.isStatementWithLocals(container)) { - var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { - // redeclaration - always should be renamed - links.isDeclarationWithCollidingName = true; - } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { - // binding is captured in the function - // should be renamed if: - // - binding is not top level - top level bindings never collide with anything - // AND - // - binding is not declared in loop, should be renamed to avoid name reuse across siblings - // let a, b - // { let x = 1; a = () => x; } - // { let x = 100; b = () => x; } - // console.log(a()); // should print '1' - // console.log(b()); // should print '100' - // OR - // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body - // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly - // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus - // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; - var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 207 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); - links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); - } - else { - links.isDeclarationWithCollidingName = false; - } - } - } - return links.isDeclarationWithCollidingName; - } - return false; - } - // When resolved as an expression identifier, if the given node references a nested block scoped entity with - // a name that either hides an existing name or might hide it when compiled downlevel, - // return the declaration of that entity. Otherwise, return undefined. - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { - return symbol.valueDeclaration; - } - } - } - return undefined; - } - // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an - // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); - if (node) { - var symbol = getSymbolOfNode(node); - if (symbol) { - return isSymbolOfDeclarationWithCollidingName(symbol); - } - } - return false; - } - function isValueAliasDeclaration(node) { - switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244 /* ExportDeclaration */: - var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243 /* ExportAssignment */: - return node.expression - && node.expression.kind === 71 /* Identifier */ - ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) - : true; - } - return false; - } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { - // parent is not source file or it is not reference to internal module - return false; - } - var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); - return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); - } - function isAliasResolvedToValue(symbol) { - var target = resolveAlias(symbol); - if (target === unknownSymbol) { - return true; - } - // const enums and modules that contain only const enums are not considered values from the emit perspective - // unless 'preserveConstEnums' option is set to true - return target.flags & 107455 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); - } - function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; - } - function isReferencedAliasDeclaration(node, checkChildren) { - if (ts.isAliasSymbolDeclaration(node)) { - var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { - return true; - } - } - if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); - } - return false; - } - function isImplementationOfOverload(node) { - if (ts.nodeIsPresent(node.body)) { - var symbol = getSymbolOfNode(node); - var signaturesOfSymbol = getSignaturesOfSymbol(symbol); - // If this function body corresponds to function with multiple signature, it is implementation of overload - // e.g.: function foo(a: string): string; - // function foo(a: number): number; - // function foo(a: any) { // This is implementation of the overloads - // return a; - // } - return signaturesOfSymbol.length > 1 || - // If there is single signature for the symbol, it is overload if that signature isn't coming from the node - // e.g.: function foo(a: string): string; - // function foo(a: any) { // This is implementation of the overloads - // return a; - // } - (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); - } - return false; - } - function isRequiredInitializedParameter(parameter) { - return strictNullChecks && - !isOptionalParameter(parameter) && - parameter.initializer && - !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); - } - function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; - } - function getEnumMemberValue(node) { - computeEnumMemberValues(node.parent); - return getNodeLinks(node).enumMemberValue; - } - function canHaveConstantValue(node) { - switch (node.kind) { - case 264 /* EnumMember */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - return true; - } - return false; - } - function getConstantValue(node) { - if (node.kind === 264 /* EnumMember */) { - return getEnumMemberValue(node); - } - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol && (symbol.flags & 8 /* EnumMember */)) { - // inline property\index accesses only for const enums - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); - } - } - return undefined; - } - function isFunctionType(type) { - return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; - } - function getTypeReferenceSerializationKind(typeName, location) { - // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); - // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); - if (valueSymbol && valueSymbol === typeSymbol) { - var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); - if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { - return ts.TypeReferenceSerializationKind.Promise; - } - var constructorType = getTypeOfSymbol(valueSymbol); - if (constructorType && isConstructorType(constructorType)) { - return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; - } - } - // We might not be able to resolve type symbol so use unknown type in that case (eg error case) - if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - var type = getDeclaredTypeOfSymbol(typeSymbol); - if (type === unknownType) { - return ts.TypeReferenceSerializationKind.Unknown; - } - else if (type.flags & 1 /* Any */) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { - return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; - } - else if (isTypeOfKind(type, 136 /* BooleanLike */)) { - return ts.TypeReferenceSerializationKind.BooleanType; - } - else if (isTypeOfKind(type, 84 /* NumberLike */)) { - return ts.TypeReferenceSerializationKind.NumberLikeType; - } - else if (isTypeOfKind(type, 262178 /* StringLike */)) { - return ts.TypeReferenceSerializationKind.StringLikeType; - } - else if (isTupleType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else if (isTypeOfKind(type, 512 /* ESSymbol */)) { - return ts.TypeReferenceSerializationKind.ESSymbolType; - } - else if (isFunctionType(type)) { - return ts.TypeReferenceSerializationKind.TypeWithCallSignature; - } - else if (isArrayType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else { - return ts.TypeReferenceSerializationKind.ObjectType; - } - } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { - // Get type of the symbol if this is the valid symbol otherwise get type at location - var symbol = getSymbolOfNode(declaration); - var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) - ? getWidenedLiteralType(getTypeOfSymbol(symbol)) - : unknownType; - if (flags & 4096 /* AddUndefined */) { - type = getNullableType(type, 2048 /* Undefined */); - } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { - var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); - } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name) { - return globals.has(name); - } - function getReferencedValueSymbol(reference, startInDeclarationContainer) { - var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; - if (resolvedSymbol) { - return resolvedSymbol; - } - var location = reference; - if (startInDeclarationContainer) { - // When resolving the name of a declaration as a value, we need to start resolution - // at a point outside of the declaration. - var parent = reference.parent; - if (ts.isDeclaration(parent) && reference === parent.name) { - location = getDeclarationContainer(parent); - } - } - return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); - } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); - if (reference) { - var symbol = getReferencedValueSymbol(reference); - if (symbol) { - return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; - } - } - } - return undefined; - } - function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); - } - return false; - } - function writeLiteralConstValue(node, writer) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); - } - function createResolver() { - // this variable and functions that use it are deliberately moved here from the outer scope - // to avoid scope pollution - var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); - var fileToDirective; - if (resolvedTypeReferenceDirectives) { - // populate reverse mapping: file path -> type reference directive that was resolved to this file - fileToDirective = ts.createFileMap(); - resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { - if (!resolvedDirective) { - return; - } - var file = host.getSourceFile(resolvedDirective.resolvedFileName); - fileToDirective.set(file.path, key); - }); - } - return { - getReferencedExportContainer: getReferencedExportContainer, - getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, - isDeclarationWithCollidingName: isDeclarationWithCollidingName, - isValueAliasDeclaration: function (node) { - node = ts.getParseTreeNode(node); - // Synthesized nodes are always treated like values. - return node ? isValueAliasDeclaration(node) : true; - }, - hasGlobalName: hasGlobalName, - isReferencedAliasDeclaration: function (node, checkChildren) { - node = ts.getParseTreeNode(node); - // Synthesized nodes are always treated as referenced. - return node ? isReferencedAliasDeclaration(node, checkChildren) : true; - }, - getNodeCheckFlags: function (node) { - node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; - }, - isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, - isDeclarationVisible: isDeclarationVisible, - isImplementationOfOverload: isImplementationOfOverload, - isRequiredInitializedParameter: isRequiredInitializedParameter, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, - isSymbolAccessible: isSymbolAccessible, - isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - collectLinkedAliases: collectLinkedAliases, - getReferencedValueDeclaration: getReferencedValueDeclaration, - getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, - isOptionalParameter: isOptionalParameter, - moduleExportsSomeValue: moduleExportsSomeValue, - isArgumentsLocalBinding: isArgumentsLocalBinding, - getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, - getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, - isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } - }; - // defined here to avoid outer scope pollution - function getTypeReferenceDirectivesForEntityName(node) { - // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - // property access can only be used as values - // qualified names can only be used as types\namespaces - // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 179 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) - ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793064 /* Type */ | 1920 /* Namespace */; - var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); - return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; - } - // defined here to avoid outer scope pollution - function getTypeReferenceDirectivesForSymbol(symbol, meaning) { - // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { - return undefined; - } - // check what declarations in the symbol can contribute to the target meaning - var typeReferenceDirectives; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - // check meaning of the local symbol to see if declaration needs to be analyzed further - if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); - if (typeReferenceDirective) { - (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); - } - else { - // found at least one entry that does not originate from type reference directive - return undefined; - } - } - } - return typeReferenceDirectives; - } - function isSymbolFromTypeDeclarationFile(symbol) { - // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) - if (!symbol.declarations) { - return false; - } - // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope - // external modules cannot define or contribute to type declaration files - var current = symbol; - while (true) { - var parent = getParentOfSymbol(current); - if (parent) { - current = parent; - } - else { - break; - } - } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 /* SourceFile */ && current.flags & 512 /* ValueModule */) { - return false; - } - // check that at least one declaration of top level symbol originates from type declaration file - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.contains(file.path)) { - return true; - } - } - return false; - } - } - function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); - if (!moduleSymbol) { - return undefined; - } - return ts.getDeclarationOfKind(moduleSymbol, 265 /* SourceFile */); - } - function initializeTypeChecker() { - // Bind all source files and propagate errors - for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); - } - // Initialize global symbol table - var augmentations; - for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); - } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); - } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); - } - if (file.symbol && file.symbol.globalExports) { - // Merge in UMD exports with first-in-wins semantics (see #9771) - var source = file.symbol.globalExports; - source.forEach(function (sourceSymbol, id) { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); - } - }); - } - } - if (augmentations) { - // merge module augmentations. - // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed - for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { - var list = augmentations_1[_d]; - for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { - var augmentation = list_1[_e]; - mergeModuleAugmentation(augmentation); - } - } - } - // Setup global builtins - addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); - getSymbolLinks(undefinedSymbol).type = undefinedWideningType; - getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); - getSymbolLinks(unknownSymbol).type = unknownType; - // Initialize special types - globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); - globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); - globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); - globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); - globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); - globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); - globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); - anyArrayType = createArrayType(anyType); - autoArrayType = createArrayType(autoType); - globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); - anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); - } - function checkExternalEmitHelpers(location, helpers) { - if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { - var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { - var helpersModule = resolveHelpersModule(sourceFile, location); - if (helpersModule !== unknownSymbol) { - var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - 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 */); - if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); - } - } - } - } - requestedExternalEmitHelpers |= helpers; - } - } - } - function getHelperName(helper) { - switch (helper) { - case 1 /* Extends */: return "__extends"; - case 2 /* Assign */: return "__assign"; - case 4 /* Rest */: return "__rest"; - case 8 /* Decorate */: return "__decorate"; - case 16 /* Metadata */: return "__metadata"; - case 32 /* Param */: return "__param"; - case 64 /* Awaiter */: return "__awaiter"; - case 128 /* Generator */: return "__generator"; - case 256 /* Values */: return "__values"; - case 512 /* Read */: return "__read"; - case 1024 /* Spread */: return "__spread"; - 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."); - } - } - function resolveHelpersModule(node, errorNode) { - if (!externalHelpersModule) { - externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; - } - return externalHelpersModule; - } - // GRAMMAR CHECKING - function checkGrammarDecorators(node) { - if (!node.decorators) { - return false; - } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); - } - } - else if (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); - } - } - return false; - } - function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; - } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; - var flags = 0 /* None */; - for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { - var modifier = _a[_i]; - if (modifier.kind !== 131 /* ReadonlyKeyword */) { - if (node.kind === 148 /* PropertySignature */ || node.kind === 150 /* MethodSignature */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); - } - if (node.kind === 157 /* IndexSignature */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); - } - } - switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (node.kind !== 232 /* EnumDeclaration */ && node.parent.kind === 229 /* ClassDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); - } - break; - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: - var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113 /* ProtectedKeyword */) { - lastProtected = modifier; - } - else if (modifier.kind === 112 /* PrivateKeyword */) { - lastPrivate = modifier; - } - if (flags & 28 /* AccessibilityModifier */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); - } - else if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); - } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); - } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); - } - else if (flags & 128 /* Abstract */) { - if (modifier.kind === 112 /* PrivateKeyword */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); - } - else { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); - } - } - flags |= ts.modifierToFlag(modifier.kind); - break; - case 115 /* StaticKeyword */: - if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); - } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); - } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); - } - else if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - flags |= 32 /* Static */; - lastStatic = modifier; - break; - case 131 /* ReadonlyKeyword */: - if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); - } - else if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */ && node.kind !== 157 /* IndexSignature */ && node.kind !== 146 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. - return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); - } - flags |= 64 /* Readonly */; - lastReadonly = modifier; - break; - case 84 /* ExportKeyword */: - if (flags & 1 /* Export */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); - } - else if (flags & 2 /* Ambient */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); - } - else if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); - } - else if (node.parent.kind === 229 /* ClassDeclaration */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); - } - flags |= 1 /* Export */; - break; - case 124 /* DeclareKeyword */: - if (flags & 2 /* Ambient */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.parent.kind === 229 /* ClassDeclaration */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); - } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234 /* ModuleBlock */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); - } - flags |= 2 /* Ambient */; - lastDeclare = modifier; - break; - case 117 /* AbstractKeyword */: - if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); - } - if (node.kind !== 229 /* ClassDeclaration */) { - if (node.kind !== 151 /* MethodDeclaration */ && - node.kind !== 149 /* PropertyDeclaration */ && - node.kind !== 153 /* GetAccessor */ && - node.kind !== 154 /* SetAccessor */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); - } - if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); - } - if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - if (flags & 8 /* Private */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); - } - } - flags |= 128 /* Abstract */; - break; - case 120 /* AsyncKeyword */: - if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); - } - else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); - } - flags |= 256 /* Async */; - lastAsync = modifier; - break; - } - } - if (node.kind === 152 /* Constructor */) { - if (flags & 32 /* Static */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); - } - if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); - } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); - } - return; - } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); - } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); - } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); - } - if (flags & 256 /* Async */) { - return checkGrammarAsyncModifier(node, lastAsync); - } - } - /** - * true | false: Early return this value from checkGrammarModifiers. - * undefined: Need to do full checking on the modifiers. - */ - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 233 /* ModuleDeclaration */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 146 /* Parameter */: - return false; - default: - if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - return false; - } - switch (node.kind) { - case 228 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 229 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 230 /* InterfaceDeclaration */: - case 208 /* VariableStatement */: - case 231 /* TypeAliasDeclaration */: - return true; - case 232 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } - function checkGrammarAsyncModifier(node, asyncModifier) { - switch (node.kind) { - case 151 /* MethodDeclaration */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return false; - } - return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); - } - function checkGrammarForDisallowedTrailingComma(list) { - if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } - if (typeParameters && typeParameters.length === 0) { - var start = typeParameters.pos - "<".length; - var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; - return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); - } - } - function checkGrammarParameterList(parameters) { - var seenOptionalParameter = false; - var parameterCount = parameters.length; - for (var i = 0; i < parameterCount; i++) { - var parameter = parameters[i]; - if (parameter.dotDotDotToken) { - if (i !== (parameterCount - 1)) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); - } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); - } - } - else if (parameter.questionToken) { - seenOptionalParameter = true; - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); - } - } - else if (seenOptionalParameter && !parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); - } - } - } - function checkGrammarFunctionLikeDeclaration(node) { - // Prevent cascading error by short-circuit - var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); - } - function checkGrammarClassLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); - } - function checkGrammarArrowFunction(node, file) { - if (node.kind === 187 /* ArrowFunction */) { - var arrowFunction = node; - var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; - var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; - if (startLine !== endLine) { - return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); - } - } - return false; - } - function checkGrammarIndexSignatureParameters(node) { - var parameter = node.parameters[0]; - if (node.parameters.length !== 1) { - if (parameter) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - else { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - } - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); - } - if (ts.getModifierFlags(parameter) !== 0) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); - } - if (!parameter.type) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); - } - if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); - } - if (!node.type) { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); - } - } - function checkGrammarIndexSignature(node) { - // Prevent cascading error by short-circuit - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); - } - function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { - if (typeArguments && typeArguments.length === 0) { - var sourceFile = ts.getSourceFileOfNode(node); - var start = typeArguments.pos - "<".length; - var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function checkGrammarTypeArguments(node, typeArguments) { - return checkGrammarForDisallowedTrailingComma(typeArguments) || - checkGrammarForAtLeastOneTypeArgument(node, typeArguments); - } - function checkGrammarForOmittedArgument(node, args) { - if (args) { - var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { - var arg = args_4[_i]; - if (arg.kind === 200 /* OmittedExpression */) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); - } - } - } - } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); - } - function checkGrammarHeritageClause(node) { - var types = node.types; - if (checkGrammarForDisallowedTrailingComma(types)) { - return true; - } - if (types && types.length === 0) { - var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); - } - } - function checkGrammarClassDeclarationHeritageClauses(node) { - var seenExtendsClause = false; - var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); - } - if (heritageClause.types.length > 1) { - return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); - } - seenImplementsClause = true; - } - // Grammar checking heritageClause inside class declaration - checkGrammarHeritageClause(heritageClause); - } - } - } - function checkGrammarInterfaceDeclaration(node) { - var seenExtendsClause = false; - if (node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); - } - // Grammar checking heritageClause inside class declaration - checkGrammarHeritageClause(heritageClause); - } - } - return false; - } - function checkGrammarComputedPropertyName(node) { - // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 144 /* ComputedPropertyName */) { - return false; - } - var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { - return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); - } - } - function checkGrammarForGenerator(node) { - if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 /* FunctionDeclaration */ || - node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */); - if (ts.isInAmbientContext(node)) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); - } - if (!node.body) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); - } - } - } - function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } - } - function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */) { - continue; - } - var name = prop.name; - if (name.kind === 144 /* ComputedPropertyName */) { - // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name); - } - if (prop.kind === 262 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { - // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern - // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); - } - // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { - var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 151 /* MethodDeclaration */) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); - } - } - } - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = void 0; - if (prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */) { - // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151 /* MethodDeclaration */) { - currentKind = Property; - } - else if (prop.kind === 153 /* GetAccessor */) { - currentKind = GetAccessor; - } - else if (prop.kind === 154 /* SetAccessor */) { - currentKind = SetAccessor; - } - else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); - } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name); - if (effectiveName === undefined) { - continue; - } - var existingKind = seen.get(effectiveName); - if (!existingKind) { - seen.set(effectiveName, currentKind); - } - else { - if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); - } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen.set(effectiveName, currentKind | existingKind); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); - } - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); - } - } - } - } - function checkGrammarJsxElement(node) { - var seen = ts.createMap(); - for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { - var attr = _a[_i]; - if (attr.kind === 255 /* JsxSpreadAttribute */) { - continue; - } - var jsxAttr = attr; - var name = jsxAttr.name; - if (!seen.get(name.text)) { - seen.set(name.text, true); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); - } - var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 /* JsxExpression */ && !initializer.expression) { - return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); - } - } - } - function checkGrammarForInOrForOfStatement(forInOrOfStatement) { - if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { - return true; - } - if (forInOrOfStatement.kind === 216 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { - return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - } - } - if (forInOrOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var variableList = forInOrOfStatement.initializer; - if (!checkGrammarVariableDeclarationList(variableList)) { - var declarations = variableList.declarations; - // declarations.length can be zero if there is an error in variable declaration in for-of or for-in - // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details - // For example: - // var let = 10; - // for (let of [1,2,3]) {} // this is invalid ES6 syntax - // for (let in [1,2,3]) {} // this is invalid ES6 syntax - // We will then want to skip on grammar checking on variableList declaration - if (!declarations.length) { - return false; - } - if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ - ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement - : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; - return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); - } - var firstDeclaration = declarations[0]; - if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ - ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer - : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; - return grammarErrorOnNode(firstDeclaration.name, diagnostic); - } - if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ - ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation - : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; - return grammarErrorOnNode(firstDeclaration, diagnostic); - } - } - } - return false; - } - function checkGrammarAccessor(accessor) { - var kind = accessor.kind; - if (languageVersion < 1 /* ES5 */) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); - } - else if (ts.isInAmbientContext(accessor)) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); - } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); - } - else if (accessor.typeParameters) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); - } - else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 /* GetAccessor */ ? - ts.Diagnostics.A_get_accessor_cannot_have_parameters : - ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); - } - else if (kind === 154 /* SetAccessor */) { - if (accessor.type) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); - } - else { - var parameter = accessor.parameters[0]; - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); - } - else if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); - } - else if (parameter.initializer) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); - } - } - } - } - /** Does the accessor have the right number of parameters? - * A get accessor has no parameters or a single `this` parameter. - * A set accessor has one parameter or a `this` parameter and one more parameter. - */ - function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 0 : 1); - } - function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 1 : 2)) { - return ts.getThisParameter(accessor); - } - } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { - return grammarErrorOnNode(node, message); - } - } - function checkGrammarMethod(node) { - if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || - checkGrammarFunctionLikeDeclaration(node) || - checkGrammarForGenerator(node)) { - return true; - } - if (node.parent.kind === 178 /* ObjectLiteralExpression */) { - if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { - return true; - } - else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - } - if (ts.isClassLike(node.parent)) { - // Technically, computed properties in ambient contexts is disallowed - // for property declarations and accessors too, not just methods. - // However, property declarations disallow computed names in general, - // and accessors are not allowed in ambient contexts in general, - // so this error only really matters for methods. - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); - } - else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); - } - } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); - } - else if (node.parent.kind === 163 /* TypeLiteral */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); - } - } - function checkGrammarBreakOrContinueStatement(node) { - var current = node; - while (current) { - if (ts.isFunctionLike(current)) { - return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); - } - switch (current.kind) { - case 222 /* LabeledStatement */: - if (node.label && current.label.text === node.label.text) { - // found matching label - verify that label usage is correct - // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 217 /* ContinueStatement */ - && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); - if (isMisplacedContinueLabel) { - return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); - } - return false; - } - break; - case 221 /* SwitchStatement */: - if (node.kind === 218 /* BreakStatement */ && !node.label) { - // unlabeled break within switch statement - ok - return false; - } - break; - default: - if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { - // unlabeled break or continue within iteration statement - ok - return false; - } - break; - } - current = current.parent; - } - if (node.label) { - var message = node.kind === 218 /* BreakStatement */ - ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement - : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - else { - var message = node.kind === 218 /* BreakStatement */ - ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement - : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - } - function checkGrammarBindingElement(node) { - if (node.dotDotDotToken) { - var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - if (node.name.kind === 175 /* ArrayBindingPattern */ || node.name.kind === 174 /* ObjectBindingPattern */) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (node.initializer) { - // Error on equals token which immediately precedes the initializer - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - } - } - function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && - expr.operand.kind === 8 /* NumericLiteral */; - } - function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 /* ForInStatement */ && node.parent.parent.kind !== 216 /* ForOfStatement */) { - if (ts.isInAmbientContext(node)) { - if (node.initializer) { - if (ts.isConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - else if (!node.initializer) { - if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); - } - if (ts.isConst(node)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); - } - } - } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { - checkESModuleMarker(node.name); - } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); - // 1. LexicalDeclaration : LetOrConst BindingList ; - // It is a Syntax Error if the BoundNames of BindingList contains "let". - // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding - // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". - // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code - // and its Identifier is eval or arguments - return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); - } - function checkESModuleMarker(name) { - if (name.kind === 71 /* Identifier */) { - if (ts.unescapeIdentifier(name.text) === "__esModule") { - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; - if (!ts.isOmittedExpression(element)) { - return checkESModuleMarker(element.name); - } - } - } - } - function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71 /* Identifier */) { - if (name.originalKeywordKind === 110 /* LetKeyword */) { - return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; - if (!ts.isOmittedExpression(element)) { - checkGrammarNameInLetOrConstDeclarations(element.name); - } - } - } - } - function checkGrammarVariableDeclarationList(declarationList) { - var declarations = declarationList.declarations; - if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { - return true; - } - if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); - } - } - function allowLetAndConstDeclarations(parent) { - switch (parent.kind) { - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - return false; - case 222 /* LabeledStatement */: - return allowLetAndConstDeclarations(parent.parent); - } - return true; - } - function checkGrammarForDisallowedLetOrConstStatement(node) { - if (!allowLetAndConstDeclarations(node.parent)) { - if (ts.isLet(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); - } - else if (ts.isConst(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); - } - } - } - function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */) { - if (node.name.text !== "target") { - return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.text, ts.tokenToString(node.keywordToken), "target"); - } - } - } - function hasParseDiagnostics(sourceFile) { - return sourceFile.parseDiagnostics.length > 0; - } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorOnNode(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); - return true; - } - } - function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarProperty(node) { - if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); - } - } - else if (node.parent.kind === 163 /* TypeLiteral */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); - } - } - if (ts.isInAmbientContext(node) && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace - // interfaces and imports categories: - // - // DeclarationElement: - // ExportAssignment - // export_opt InterfaceDeclaration - // export_opt TypeAliasDeclaration - // export_opt ImportDeclaration - // export_opt ExternalImportDeclaration - // export_opt AmbientDeclaration - // - // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 230 /* InterfaceDeclaration */ || - node.kind === 231 /* TypeAliasDeclaration */ || - node.kind === 238 /* ImportDeclaration */ || - node.kind === 237 /* ImportEqualsDeclaration */ || - node.kind === 244 /* ExportDeclaration */ || - node.kind === 243 /* ExportAssignment */ || - node.kind === 236 /* NamespaceExportDeclaration */ || - ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { - return false; - } - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); - } - function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { - for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208 /* VariableStatement */) { - if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { - return true; - } - } - } - } - function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); - } - function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { - // An accessors is already reported about the ambient context - if (isAccessor(node.parent.kind)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = true; - } - // Find containing block which is either Block, ModuleBlock, SourceFile - var links = getNodeLinks(node); - if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); - } - // We are either parented by another statement, or some sort of block. - // If we're in a block, we only want to really report an error once - // to prevent noisiness. So use a bit on the block to indicate if - // this has already been reported, and don't report if it has. - // - if (node.parent.kind === 207 /* Block */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - var links_1 = getNodeLinks(node.parent); - // Check if the containing block ever report this error - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); - } - } - else { - // We must be parented by a statement. If so, there's no need - // to report the error as our parent will have already done it. - // Debug.assert(isStatement(node.parent)); - } - } - } - function checkGrammarNumericLiteral(node) { - // Grammar checking - if (node.numericLiteralFlags & 4 /* Octal */) { - var diagnosticMessage = void 0; - if (languageVersion >= 1 /* ES5 */) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 173 /* LiteralType */)) { - diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 264 /* EnumMember */)) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; - } - if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; - var literal = (withMinus ? "-" : "") + "0o" + node.text; - return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); - } - } - } - function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); - return true; - } - } - function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(global); - } - }); - return result; - } - } - 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 = {})); /// /// @@ -48304,11 +49373,11 @@ var ts; 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)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), 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 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)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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 */: @@ -48316,9 +49385,9 @@ var ts; 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)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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 @@ -48327,9 +49396,9 @@ var ts; 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)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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 */: @@ -48349,7 +49418,7 @@ var ts; case 171 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); case 172 /* MappedType */: - 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)); + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), 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)); // Binding patterns @@ -48379,9 +49448,9 @@ var ts; case 185 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 186 /* FunctionExpression */: - return ts.updateFunctionExpression(node, 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)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187 /* ArrowFunction */: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 188 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189 /* TypeOfExpression */: @@ -48405,7 +49474,7 @@ var ts; case 198 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); case 199 /* ClassExpression */: - return ts.updateClassExpression(node, 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)); + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 201 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 202 /* AsExpression */: @@ -48457,13 +49526,13 @@ var ts; case 227 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 228 /* FunctionDeclaration */: - 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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 */: @@ -48537,9 +49606,9 @@ var ts; case 265 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -48595,7 +49664,7 @@ var ts; case 209 /* EmptyStatement */: case 200 /* OmittedExpression */: case 225 /* DebuggerStatement */: - case 295 /* NotEmittedStatement */: + case 287 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -48761,9 +49830,6 @@ var ts; result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 203 /* NonNullExpression */: - result = reduceNode(node.expression, cbNode, result); - break; // Misc case 205 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); @@ -48972,10 +50038,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -49066,38 +50132,228 @@ var ts; } var Debug; (function (Debug) { + var isDebugInfoEnabled = false; Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } : ts.noop; Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) - ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; Debug.assertNode = Debug.shouldAssert(1 /* Normal */) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } : ts.noop; Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) - ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } : ts.noop; Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) - ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } : ts.noop; Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) - ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; - function getFunctionName(func) { - if (typeof func !== "function") { - return ""; + /** + * Injects debug information into frequently used types. + */ + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + // Add additional properties in debug mode to assist with debugging. + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, + "__debugObjectFlags": { get: function () { return this.flags & 32768 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, + "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + "__debugGetText": { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } } - else if (func.hasOwnProperty("name")) { - return func.name; - } - else { - var text = Function.prototype.toString.call(func); - var match = /^function\s+([\w\$]+)\s*\(/.exec(text); - return match ? match[1] : ""; + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 238 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + break; + case 237 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 244 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 243 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 208 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 228 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 229 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; } } - })(Debug = ts.Debug || (ts.Debug = {})); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { + uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + /** Use a sparse array as a multi-map. */ + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } })(ts || (ts = {})); /// /// @@ -49450,11 +50706,11 @@ var ts; } else if (ts.isStringOrNumericLiteral(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); - argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); return ts.createPropertyAccess(value, name); } } @@ -49557,6 +50813,22 @@ var ts; /* Enables substitutions for unqualified enum members */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -49834,7 +51106,9 @@ var ts; case 231 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. case 149 /* PropertyDeclaration */: - // TypeScript property declarations are elided. + // TypeScript property declarations are elided. + case 236 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. return undefined; case 152 /* Constructor */: return visitConstructor(node); @@ -49960,6 +51234,26 @@ var ts; function shouldEmitDecorateCallForParameter(parameter) { return parameter.decorators !== undefined && parameter.decorators.length > 0; } + function getClassFacts(node, staticProperties) { + var facts = 0 /* None */; + if (ts.some(staticProperties)) + facts |= 1 /* HasStaticInitializedProperties */; + if (ts.getClassExtendsHeritageClauseElement(node)) + facts |= 64 /* HasExtendsClause */; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2 /* HasConstructorDecorators */; + if (ts.childIsDecorated(node)) + facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) + facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) + facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; + return facts; + } /** * Transforms a class declaration with TypeScript syntax into compatible ES6. * @@ -49973,44 +51267,73 @@ var ts; */ function visitClassDeclaration(node) { var staticProperties = getInitializedProperties(node, /*isStatic*/ true); - var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; - var isDecoratedClass = shouldEmitDecorateCallForClass(node); - // emit name if - // - node has a name - // - node has static initializers - // - node has a member that is decorated - // - var name = node.name; - if (!name && (staticProperties.length > 0 || ts.childIsDecorated(node))) { - name = ts.getGeneratedNameForNode(node); + var facts = getClassFacts(node, staticProperties); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + context.startLexicalEnvironment(); } - var classStatement = isDecoratedClass - ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) - : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - if (staticProperties.length) { - addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); } // Write any decorators of the node. addClassElementDecorationStatements(statements, node, /*isStatic*/ false); addClassElementDecorationStatements(statements, node, /*isStatic*/ true); addConstructorDecorationStatement(statements, node); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addRange(statements, context.endLexicalEnvironment()); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } // If the class is exported as part of a TypeScript namespace, emit the namespace export. // Otherwise, if the class was exported at the top level and was decorated, emit an export // declaration or export default for the class. - if (isNamespaceExport(node)) { + if (facts & 8 /* IsExportOfNamespace */) { addExportMemberAssignment(statements, node); } - else if (isDecoratedClass) { - if (isDefaultExternalModuleExport(node)) { + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } - else if (isNamedExternalModuleExport(node)) { + else if (facts & 16 /* IsNamedExternalExport */) { statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } } @@ -50026,20 +51349,23 @@ var ts; * * @param node A ClassDeclaration node. * @param name The name of the class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. - * @param hasStaticProperties A value indicating whether the class has static properties. + * @param facts Precomputed facts about the class. */ - function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { // ${modifiers} class ${name} ${heritageClauses} { // ${members} // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; var classDeclaration = ts.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause)); + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0)); // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); - if (hasStaticProperties) { + if (facts & 1 /* HasStaticInitializedProperties */) { emitFlags |= 32 /* NoTrailingSourceMap */; } ts.setTextRange(classDeclaration, node); @@ -50050,13 +51376,8 @@ var ts; /** * Transforms a decorated class declaration and appends the resulting statements. If * the class requires an alias to avoid issues with double-binding, the alias is returned. - * - * @param statements A statement list to which to add the declaration. - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. */ - function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { + function createClassDeclarationHeadWithDecorators(node, name, facts) { // When we emit an ES6 class that has a class decorator, we must tailor the // emit to certain specific cases. // @@ -50149,7 +51470,7 @@ var ts; // ${members} // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, hasExtendsClause); + var members = transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0); var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -50650,8 +51971,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -50900,7 +52221,7 @@ var ts; var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { continue; } if (parameter.dotDotDotToken) { @@ -51025,7 +52346,7 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } @@ -51033,7 +52354,7 @@ var ts; // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || - serializedUnion.text !== serializedIndividual.text) { + serializedUnion.escapedText !== serializedIndividual.escapedText) { return ts.createIdentifier("Object"); } } @@ -51148,7 +52469,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeIdentifier(name.text)); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.getSynthesizedClone(name); @@ -51320,7 +52641,7 @@ var ts; /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var statements = [updated]; addExportMemberAssignment(statements, node); return statements; @@ -51390,7 +52711,7 @@ var ts; * - The node is exported from a TypeScript namespace. */ function visitVariableStatement(node) { - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); if (variables.length === 0) { // elide statement if there are no initialized variables. @@ -51599,7 +52920,7 @@ var ts; * or `exports.x`). */ function hasNamespaceQualifiedExportName(node) { - return isNamespaceExport(node) + return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System); @@ -51612,10 +52933,10 @@ var ts; * on symbol names. */ function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createMap(); + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); } if (!currentScopeFirstDeclarationsOfName.has(name)) { currentScopeFirstDeclarationsOfName.set(name, node); @@ -51628,7 +52949,7 @@ var ts; */ function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { return currentScopeFirstDeclarationsOfName.get(name) === node; } @@ -51965,7 +53286,7 @@ var ts; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); - if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ @@ -51983,7 +53304,7 @@ var ts; * * @param node The node to test. */ - function isNamespaceExport(node) { + function isExportOfNamespace(node) { return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); } /** @@ -52020,7 +53341,7 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); - ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); var statement = ts.createStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); @@ -52057,7 +53378,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeIdentifier(node.name.text) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -52187,10 +53508,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_2 = ts.getSynthesizedClone(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; } } } @@ -52564,7 +53885,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -52893,8 +54214,10 @@ 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 createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); @@ -52915,9 +54238,9 @@ var ts; ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), + /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52928,7 +54251,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - 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 */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -53155,7 +54478,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -53470,8 +54793,8 @@ var ts; } else { var name = node.tagName; - if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.text)) { - return ts.createLiteral(name.text); + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.createExpressionFromEntityName(name); @@ -53485,11 +54808,11 @@ var ts; */ function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(name.text)) { + if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { return name; } else { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } } function visitJsxExpression(node) { @@ -54006,11 +55329,58 @@ var ts; && node.kind === 219 /* ReturnStatement */ && !node.expression; } + function isClassLikeVariableStatement(node) { + if (!ts.isVariableStatement(node)) + return false; + var variable = ts.singleOrUndefined(node.declarationList.declarations); + return variable + && variable.initializer + && ts.isIdentifier(variable.name) + && (ts.isClassLike(variable.initializer) + || (ts.isAssignmentExpression(variable.initializer) + && ts.isIdentifier(variable.initializer.left) + && ts.isClassLike(variable.initializer.right))); + } + function isTypeScriptClassWrapper(node) { + var call = ts.tryCast(node, ts.isCallExpression); + if (!call || ts.isParseTreeNode(call) || + ts.some(call.typeArguments) || + ts.some(call.arguments)) { + return false; + } + var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + if (!func || ts.isParseTreeNode(func) || + ts.some(func.typeParameters) || + ts.some(func.parameters) || + func.type || + !func.body) { + return false; + } + var statements = func.body.statements; + if (statements.length < 2) { + return false; + } + var firstStatement = statements[0]; + if (ts.isParseTreeNode(firstStatement) || + !ts.isClassLike(firstStatement) && + !isClassLikeVariableStatement(firstStatement)) { + return false; + } + var lastStatement = ts.elementAt(statements, -1); + var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); + if (!returnStatement || + !returnStatement.expression || + !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { + return false; + } + return true; + } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && ts.isStatement(node)) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || isTypeScriptClassWrapper(node); } function visitor(node) { if (shouldVisitNode(node)) { @@ -54197,7 +55567,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return node; } - if (node.text !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { return node; } return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); @@ -54209,7 +55579,7 @@ var ts; // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement var jump = node.kind === 218 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(node.label.text)) || + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; @@ -54226,12 +55596,12 @@ var ts; } else { if (node.kind === 218 /* BreakStatement */) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); + labelMarker = "break-" + node.label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); + labelMarker = "continue-" + node.label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -55276,9 +56646,9 @@ var ts; if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); + : visitVariableDeclaration); var declarationList = ts.createVariableDeclarationList(declarations); ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); @@ -55371,9 +56741,9 @@ var ts; return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_3 = ts.getMutableClone(node); - clone_3.initializer = ts.createVoidZero(); - return clone_3; + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; } return ts.visitEachChild(node, visitor, context); } @@ -55396,10 +56766,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(node.label.text, node.label.text); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); } function resetLabel(node) { - convertedLoopState.labels.set(node.label.text, undefined); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -55824,17 +57194,17 @@ var ts; loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); } else { - var clone_4 = ts.getMutableClone(node); + var clone_3 = ts.getMutableClone(node); // clean statement part - clone_4.statement = undefined; + clone_3.statement = undefined; // visit childnodes to transform initializer/condition/incrementor parts - clone_4 = ts.visitEachChild(clone_4, visitor, context); + clone_3 = ts.visitEachChild(clone_3, visitor, context); // set loop statement - clone_4.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); + clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); // reset and re-aggregate the transform flags - clone_4.transformFlags = 0; - ts.aggregateTransformFlags(clone_4); - loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + clone_3.transformFlags = 0; + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -55943,7 +57313,7 @@ var ts; else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeIdentifier(name.text)); + var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -56141,12 +57511,122 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { + if (isTypeScriptClassWrapper(node)) { + return visitTypeScriptClassWrapper(node); + } if (node.transformFlags & 64 /* ES2015 */) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } + function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. + var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + // The class statements are the statements generated by visiting the first statement of the + // body (1), while all other statements are added to remainingStatements (2) + var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); + var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // var C_1; + // }()) + // + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + // Find the trailing 'return' statement (4) + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + // Add the remaining statements of the outer wrapper. + ts.addRange(statements, remainingStatements); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); + } function visitImmediateSuperCallInBody(node) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); } @@ -56241,7 +57721,7 @@ var ts; if (ts.isCallExpression(firstSegment) && ts.isIdentifier(firstSegment.expression) && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) - && firstSegment.expression.text === "___spread") { + && firstSegment.expression.escapedText === "___spread") { return segments[0]; } } @@ -56250,7 +57730,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 177 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -56259,7 +57739,7 @@ var ts; } } function partitionSpread(node) { - return ts.isSpreadExpression(node) + return ts.isSpreadElement(node) ? visitSpanOfSpreads : visitSpanOfNonSpreads; } @@ -56460,7 +57940,7 @@ var ts; : ts.createIdentifier("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */ && node.name.text === "target") { + if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { if (hierarchyFacts & 8192 /* ComputedPropertyName */) { hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } @@ -56610,9 +58090,7 @@ var ts; return false; } if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { - // we are in the class body, but we treat static fields as outside of the class body - return currentNode.kind !== 149 /* PropertyDeclaration */ - || (ts.getModifierFlags(currentNode) & 32 /* Static */) === 0; + return true; } currentNode = currentNode.parent; } @@ -56659,7 +58137,7 @@ var ts; return false; } var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression.text === "arguments"; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; } } ts.transformES2015 = transformES2015; @@ -56781,7 +58259,7 @@ var ts; * @param name An Identifier */ function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -57324,7 +58802,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } /** @@ -57430,10 +58908,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -57694,10 +59172,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -57836,7 +59314,7 @@ var ts; return undefined; } function transformInitializedVariable(node) { - return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); } function transformAndEmitIfStatement(node) { if (containsYield(node)) { @@ -58114,13 +59592,13 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? node.label.text : undefined); + var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); emitBreak(label, /*location*/ node); } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && node.label.text); + var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -58128,13 +59606,13 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? node.label.text : undefined); + var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); emitBreak(label, /*location*/ node); } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && node.label.text); + var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -58285,7 +59763,7 @@ var ts; // /*body*/ // .endlabeled // .mark endLabel - beginLabeledBlock(node.label.text); + beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -58295,7 +59773,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(node.label.text); + beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -58380,17 +59858,17 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(node.text)) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_7 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_7, node); - ts.setCommentRange(clone_7, node); - return clone_7; + var clone_6 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -58534,7 +60012,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = variable.name.text; + var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -58618,7 +60096,7 @@ var ts; kind: 3 /* Loop */, isScript: false, breakLabel: breakLabel, - continueLabel: continueLabel + continueLabel: continueLabel, }); return breakLabel; } @@ -58656,7 +60134,7 @@ var ts; beginBlock({ kind: 2 /* Switch */, isScript: false, - breakLabel: breakLabel + breakLabel: breakLabel, }); return breakLabel; } @@ -59468,6 +60946,7 @@ var ts; var currentSourceFile; // The current file. var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. + var needUMDDynamicImportHelper; return transformSourceFile; /** * Transforms the module aspects of a SourceFile. @@ -59475,7 +60954,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } currentSourceFile = node; @@ -59486,6 +60965,7 @@ var ts; var updated = transformModule(node); currentSourceFile = undefined; currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; return ts.aggregateTransformFlags(updated); } function shouldEmitUnderscoreUnderscoreESModule() { @@ -59512,11 +60992,12 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); ts.addRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. ts.addEmitHelper(updated, exportStarHelper); } + ts.addEmitHelpers(updated, context.readEmitHelpers()); return updated; } /** @@ -59715,11 +61196,14 @@ var ts; // and merge any new lexical declarations. ts.addRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. ts.addEmitHelper(body, exportStarHelper); } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } return body; } /** @@ -59770,16 +61254,92 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 298 /* MergeDeclarationMarker */: + case 290 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 291 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - // This visitor does not descend into the tree, as export/import statements - // are only transformed at the top level of a file. - return node; + return ts.visitEachChild(node, importCallExpressionVisitor, context); } } + function importCallExpressionVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else { + return ts.visitEachChild(node, importCallExpressionVisitor, context); + } + } + function visitImportCallExpression(node) { + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return transformImportCallExpressionAMD(node); + case ts.ModuleKind.UMD: + return transformImportCallExpressionUMD(node); + case ts.ModuleKind.CommonJS: + default: + return transformImportCallExpressionCommonJS(node); + } + } + function transformImportCallExpressionUMD(node) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + needUMDDynamicImportHelper = true; + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ transformImportCallExpressionCommonJS(node), + /*whenFalse*/ transformImportCallExpressionAMD(node)); + } + function transformImportCallExpressionAMD(node) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + return ts.createNew(ts.createIdentifier("Promise"), + /*typeArguments*/ undefined, [ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)], + /*type*/ undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + } + function transformImportCallExpressionCommonJS(node) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []), "then"), + /*typeArguments*/ undefined, [ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))]))]); + } /** * Visits an ImportDeclaration node. * @@ -59917,12 +61477,7 @@ var ts; } else { // export * from "mod"; - return ts.setTextRange(ts.createStatement(ts.createCall(ts.createIdentifier("__export"), - /*typeArguments*/ undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ])), node); + return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } /** @@ -59956,13 +61511,13 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, node.parameters, - /*type*/ undefined, node.body), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), /*location*/ node), /*original*/ node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -59984,10 +61539,10 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, node.heritageClauses, node.members), node), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -60032,7 +61587,7 @@ var ts; } } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -60051,13 +61606,13 @@ var ts; */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(node, + return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), /*visitor*/ undefined, context, 0 /* All */, /*needsValue*/ false, createExportExpression); } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), node.initializer); + /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); } } /** @@ -60234,7 +61789,7 @@ var ts; */ function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -60530,7 +62085,19 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + } + // emit helper for dynamic import + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; })(ts || (ts = {})); /// @@ -60571,7 +62138,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60789,7 +62356,7 @@ var ts; if (moduleInfo.exportedNames) { for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { var exportedLocalName = _c[_b]; - if (exportedLocalName.text === "default") { + if (exportedLocalName.escapedText === "default") { continue; } // write name of exported declaration, i.e 'export var x...' @@ -60809,7 +62376,7 @@ var ts; for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; // write name of indirectly exported entry, i.e. 'export {x} from ...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -60903,7 +62470,7 @@ var ts; var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); @@ -61002,7 +62569,7 @@ var ts; // Elide `export=` as it is illegal in a SystemJS module. return undefined; } - var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -61021,11 +62588,11 @@ var ts; function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1 /* Export */)) { hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), - /*type*/ undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); } else { - hoistedStatements = ts.append(hoistedStatements, node); + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -61050,7 +62617,7 @@ var ts; // Rewrite the class declaration into an assignment of a class expression. statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement)), node))), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); @@ -61069,7 +62636,7 @@ var ts; */ function visitVariableStatement(node) { if (!shouldHoistVariableDeclarationList(node.declarationList)) { - return ts.visitNode(node, destructuringVisitor, ts.isStatement); + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); } var expressions; var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); @@ -61135,9 +62702,9 @@ var ts; function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) - ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, /*needsValue*/ false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Creates an assignment expression for an exported variable declaration. @@ -61320,7 +62887,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = decl.name.text; + excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -61343,7 +62910,7 @@ var ts; if (ts.hasModifier(decl, 1 /* Export */)) { var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); - excludeName = exportName.text; + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); } if (decl.name) { statements = appendExportsOfDeclaration(statements, decl, excludeName); @@ -61364,11 +62931,11 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; - if (exportSpecifier.name.text !== excludeName) { + if (exportSpecifier.name.escapedText !== excludeName) { statements = appendExportStatement(statements, exportSpecifier.name, name); } } @@ -61459,12 +63026,12 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 298 /* MergeDeclarationMarker */: + case 290 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 291 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - return destructuringVisitor(node); + return destructuringAndImportCallVisitor(node); } } /** @@ -61475,7 +63042,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -61487,7 +63054,7 @@ var ts; function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -61499,7 +63066,7 @@ var ts; function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -61540,7 +63107,7 @@ var ts; * @param node The node to visit. */ function visitDoStatement(node) { - return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Visits the body of a WhileStatement to hoist declarations. @@ -61548,7 +63115,7 @@ var ts; * @param node The node to visit. */ function visitWhileStatement(node) { - return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } /** * Visits the body of a LabeledStatement to hoist declarations. @@ -61564,7 +63131,7 @@ var ts; * @param node The node to visit. */ function visitWithStatement(node) { - return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } /** * Visits the body of a SwitchStatement to hoist declarations. @@ -61572,7 +63139,7 @@ var ts; * @param node The node to visit. */ function visitSwitchStatement(node) { - return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); } /** * Visits the body of a CaseBlock to hoist declarations. @@ -61592,7 +63159,7 @@ var ts; * @param node The node to visit. */ function visitCaseClause(node) { - return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); } /** * Visits the body of a DefaultClause to hoist declarations. @@ -61642,18 +63209,35 @@ var ts; * * @param node The node to visit. */ - function destructuringVisitor(node) { + function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ && node.kind === 194 /* BinaryExpression */) { return visitDestructuringAssignment(node); } - else if (node.transformFlags & 2048 /* ContainsDestructuringAssignment */) { - return ts.visitEachChild(node, destructuringVisitor, context); + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { return node; } } + function visitImportCallExpression(node) { + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, node.arguments); + } /** * Visits a DestructuringAssignment to flatten destructuring to exported symbols. * @@ -61661,10 +63245,10 @@ var ts; */ function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { - return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, /*needsValue*/ true); } - return ts.visitEachChild(node, destructuringVisitor, context); + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** * Determines whether the target of a destructuring assigment refers to an exported symbol. @@ -61675,7 +63259,7 @@ var ts; if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { return hasExportedReferenceInDestructuringTarget(node.left); } - else if (ts.isSpreadExpression(node)) { + else if (ts.isSpreadElement(node)) { return hasExportedReferenceInDestructuringTarget(node.expression); } else if (ts.isObjectLiteralExpression(node)) { @@ -62026,6 +63610,7 @@ var ts; ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); /// +/// /// /// /// @@ -62042,6 +63627,7 @@ var ts; (function (ts) { function getModuleTransformer(moduleKind) { switch (moduleKind) { + case ts.ModuleKind.ESNext: case ts.ModuleKind.ES2015: return ts.transformES2015Module; case ts.ModuleKind.System: @@ -62106,7 +63692,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(300 /* Count */); + var enabledSyntaxKindFeatures = new Array(292 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -62237,7 +63823,7 @@ var ts; function hoistVariableDeclaration(name) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); - var decl = ts.createVariableDeclaration(name); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); if (!lexicalEnvironmentVariableDeclarations) { lexicalEnvironmentVariableDeclarations = [decl]; } @@ -62374,7 +63960,7 @@ var ts; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSourceFile; + var currentSource; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be // Current source map file and its index in the sources list @@ -62397,6 +63983,12 @@ var ts; getText: getText, getSourceMappingURL: getSourceMappingURL, }; + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(pos) { + return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); + } /** * Initialize the SourceMapWriter for a new output file. * @@ -62411,7 +64003,7 @@ var ts; if (sourceMapData) { reset(); } - currentSourceFile = undefined; + currentSource = undefined; currentSourceText = undefined; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; @@ -62468,7 +64060,7 @@ var ts; if (disabled) { return; } - currentSourceFile = undefined; + currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; lastRecordedSourceMapSpan = undefined; @@ -62528,7 +64120,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("beforeSourcemap"); } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); // Convert the location to be one-based. sourceLinePos.line++; sourceLinePos.character++; @@ -62577,12 +64169,21 @@ var ts; if (node) { var emitNode = node.emitNode; var emitFlags = emitNode && emitNode.flags; - var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; - if (node.kind !== 295 /* NotEmittedStatement */ + var range = emitNode && emitNode.sourceMapRange; + var _a = range || node, pos = _a.pos, end = _a.end; + var source = range && range.source; + var oldSource = currentSource; + if (source === oldSource) + source = undefined; + if (source) + setSourceFile(source); + if (node.kind !== 287 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { - emitPos(ts.skipTrivia(currentSourceText, pos)); + emitPos(skipSourceTrivia(pos)); } + if (source) + setSourceFile(oldSource); if (emitFlags & 64 /* NoNestedSourceMaps */) { disabled = true; emitCallback(hint, node); @@ -62591,11 +64192,15 @@ var ts; else { emitCallback(hint, node); } - if (node.kind !== 295 /* NotEmittedStatement */ + if (source) + setSourceFile(source); + if (node.kind !== 287 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); } + if (source) + setSourceFile(oldSource); } } /** @@ -62613,7 +64218,7 @@ var ts; var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } @@ -62634,22 +64239,22 @@ var ts; if (disabled) { return; } - currentSourceFile = sourceFile; - currentSourceText = currentSourceFile.text; + currentSource = sourceFile; + currentSourceText = currentSource.text; // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSource.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSource.text); } } } @@ -62766,9 +64371,11 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */; - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; + // 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. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { @@ -63227,7 +64834,7 @@ var ts; var writer = ts.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; @@ -63335,10 +64942,10 @@ var ts; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } - function reportIllegalExtends() { + function reportPrivateInBaseOfClassExpression(propertyName) { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleThisError() { @@ -63351,17 +64958,22 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); // use the checker's type, not the declared type, - // for non-optional initialized parameters that aren't a parameter property + // for optional parameter properties + // and also for non-optional initialized parameters that aren't a parameter property + // these types may need to add `undefined`. var shouldUseResolverType = declaration.kind === 146 /* Parameter */ && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { // Write the type emitType(type); } else { errorNameNode = declaration.name; - var format = 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */ | - (shouldUseResolverType ? 4096 /* AddUndefined */ : 0); + var format = 4 /* UseTypeOfFunction */ | + 16384 /* WriteClassExpressionAsTypeLiteral */ | + 2048 /* UseTypeAliasValue */ | + (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -63375,7 +64987,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -63584,7 +65196,7 @@ var ts; currentIdentifiers = node.identifiers; isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; - ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComments*/ true); emitLines(node.statements); } // Return a temp variable name to be used in `export default`/`export class ... extends` statements. @@ -63613,7 +65225,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; @@ -64097,7 +65709,7 @@ var ts; if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? "null" : - emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name @@ -64800,6 +66412,64 @@ var ts; var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + function getOutputExtension(sourceFile, options) { + if (options.jsx === 1 /* Preserve */) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; + } + } + return ".js" /* Js */; + } + function getOriginalSourceFileOrBundle(sourceFileOrBundle) { + if (sourceFileOrBundle.kind === 266 /* Bundle */) { + return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); + } + return ts.getOriginalSourceFile(sourceFileOrBundle); + } + /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); @@ -64834,7 +66504,7 @@ var ts; }); // Emit each output file ts.performance.mark("beforePrint"); - ts.forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); // Clean up emit nodes on parse tree transform.dispose(); @@ -64856,7 +66526,7 @@ var ts; emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -65278,6 +66948,8 @@ var ts; return emitModuleBlock(node); case 235 /* CaseBlock */: return emitCaseBlock(node); + case 236 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); case 237 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); case 238 /* ImportDeclaration */: @@ -65367,6 +67039,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: writeTokenNode(node); return; // Expressions @@ -65430,9 +67103,9 @@ var ts; case 250 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: return emitCommaList(node); } } @@ -65531,6 +67204,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -65550,6 +67224,7 @@ var ts; emitModifiers(node, node.modifiers); writeIfPresent(node.asteriskToken, "*"); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -65612,7 +67287,7 @@ var ts; function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); - emitParametersForArrow(node, node.parameters); + emitParameters(node, node.parameters); write(" => "); emit(node.type); } @@ -65704,7 +67379,7 @@ var ts; } else { write("{"); - emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); + emitList(node, elements, 432 /* ObjectBindingPatternElements */); write("}"); } } @@ -66413,6 +68088,11 @@ var ts; } write(";"); } + function emitNamespaceExportDeclaration(node) { + write("export as namespace "); + emit(node.name); + write(";"); + } function emitNamedExports(node) { emitNamedImportsOrExports(node); } @@ -66525,6 +68205,21 @@ var ts; ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || 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]); @@ -66637,7 +68332,7 @@ var ts; } emit(statement); if (seenPrologueDirectives) { - seenPrologueDirectives.set(statement.expression.text, statement.expression.text); + seenPrologueDirectives.set(statement.expression.text, true); } } } @@ -66686,7 +68381,7 @@ var ts; // function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 256 /* Modifiers */); + emitList(node, modifiers, 131328 /* Modifiers */); write(" "); } } @@ -66732,11 +68427,24 @@ var ts; function emitParameters(parentNode, parameters) { emitList(parentNode, parameters, 1360 /* Parameters */); } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier + } function emitParametersForArrow(parentNode, parameters) { - if (parameters && - parameters.length === 1 && - parameters[0].type === undefined && - parameters[0].pos === parentNode.pos) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { emit(parameters[0]); } else { @@ -67080,7 +68788,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeIdentifier(node.text); + return ts.unescapeLeadingUnderscores(node.escapedText); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -67131,12 +68839,12 @@ var ts; // Auto, Loop, and Unique names are cached based on their unique // autoGenerateId. var autoGenerateId = name.autoGenerateId; - return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(makeName(name))); + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } function generateNameCached(node) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); } /** * Returns a value indicating whether a name is unique globally, within the current file, @@ -67153,9 +68861,9 @@ var ts; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { - var local = node.locals.get(name); + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { + if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -67204,7 +68912,7 @@ var ts; while (true) { var generatedName = baseName + i; if (isUniqueName(generatedName)) { - generatedNames.set(generatedName, generatedName); + generatedNames.set(generatedName, true); return generatedName; } i++; @@ -67223,8 +68931,8 @@ var ts; */ function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 /* StringLiteral */ ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); } /** @@ -67282,7 +68990,7 @@ var ts; case 2 /* Loop */: return makeTempVariableName(268435456 /* _i */); case 3 /* Unique */: - return makeUniqueName(ts.unescapeIdentifier(name.text)); + return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -67374,15 +69082,14 @@ var ts; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 131328] = "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["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; @@ -67418,7 +69125,6 @@ var ts; /// var ts; (function (ts) { - var emptyArray = []; var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -67641,9 +69347,9 @@ var ts; 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 start = diagnostic.start, length_6 = 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 _b = ts.getLineAndCharacterOfPosition(file, start + length_6), 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; @@ -67693,6 +69399,7 @@ var ts; 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); + output += ts.sys.newLine; } return output; } @@ -67739,6 +69446,19 @@ var ts; } return resolutions; } + /** + * 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. + */ function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -67772,11 +69492,12 @@ var ts; var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); // Map storing if there is emit blocking diagnostics for given input - var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -67789,20 +69510,20 @@ var ts; else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); }; } else { var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } - var filesByName = ts.createFileMap(); + var filesByName = ts.createMap(); // 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; + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); @@ -67835,6 +69556,7 @@ var ts; } } } + var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks moduleResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure @@ -67844,6 +69566,7 @@ var ts; getSourceFile: getSourceFile, getSourceFileByPath: getSourceFileByPath, getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, getOptionsDiagnostics: getOptionsDiagnostics, @@ -67870,6 +69593,9 @@ var ts; ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function getCommonSourceDirectory() { if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); @@ -67893,7 +69619,7 @@ var ts; if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); @@ -67981,7 +69707,7 @@ var ts; } var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) - : emptyArray; + : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { // There were no unresolved/ambient resolutions. @@ -68086,6 +69812,10 @@ var ts; // moduleAugmentations has changed oldProgram.structureIsReused = 1 /* SafeModules */; } + if ((oldSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */) !== (newSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed oldProgram.structureIsReused = 1 /* SafeModules */; @@ -68135,14 +69865,28 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } + // If a file has ceased to be missing, then we need to discard some of the old + // structure in order to pick it up. + // Caution: if the file has created and then deleted between since it was discovered to + // be missing, then the corresponding file watcher will have been closed and no new one + // will be created until we encounter a change that prevents complete structure reuse. + // During this interval, creation of the file will go unnoticed. We expect this to be + // both rare and low-impact. + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { + var p = _e[_d]; + filesByName.set(p, undefined); + } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { - var modifiedFile = modifiedSourceFiles_2[_d]; + for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { + var modifiedFile = modifiedSourceFiles_2[_f]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -68179,7 +69923,7 @@ var ts; return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); } function isEmitBlocked(emitFileName) { - return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; @@ -68220,7 +69964,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return getSourceFileByPath(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { return filesByName.get(path); @@ -68229,14 +69973,12 @@ var ts; if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } - var allDiagnostics = []; - ts.forEach(program.getSourceFiles(), function (sourceFile) { + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } - ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); - }); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return getDiagnostics(sourceFile, cancellationToken); + })); } function getSyntacticDiagnostics(sourceFile, cancellationToken) { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); @@ -68260,6 +70002,9 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + if (ts.isCheckJsEnabledForFile(sourceFile, options)) { + sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); + } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -68295,14 +70040,14 @@ var ts; // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a // '/// ' directive. if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { - return emptyArray; + return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var bindDiagnostics = sourceFile.bindDiagnostics; // For JavaScript files, we don't want to report semantic errors unless explicitly requested. - var includeCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); - var checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : []; + var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); @@ -68360,7 +70105,6 @@ var ts; case 186 /* FunctionExpression */: case 228 /* FunctionDeclaration */: case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: case 226 /* VariableDeclaration */: // type annotation if (parent.type === node) { @@ -68397,10 +70141,14 @@ var ts; case 232 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 184 /* TypeAssertionExpression */: - var typeAssertionExpression = node; - diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + case 203 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; + case 202 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 184 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; parent = node; @@ -68421,7 +70169,6 @@ var ts; case 186 /* FunctionExpression */: case 228 /* FunctionDeclaration */: case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); @@ -68521,10 +70268,10 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; if (sourceFile) { if (!cache.perFile) { - cache.perFile = ts.createFileMap(); + cache.perFile = ts.createMap(); } cache.perFile.set(sourceFile.path, result); } @@ -68537,15 +70284,10 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); - ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); } function getGlobalDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { processSourceFile(ts.normalizePath(fileName), isDefaultLib); @@ -68565,6 +70307,7 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import var imports; var moduleAugmentations; var ambientModules; @@ -68583,13 +70326,13 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); - if (isJavaScriptFile) { - collectRequireCalls(node); + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(node); } } - file.imports = imports || emptyArray; - file.moduleAugmentations = moduleAugmentations || emptyArray; - file.ambientModuleNames = ambientModules || emptyArray; + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { @@ -68597,7 +70340,7 @@ var ts; case 237 /* ImportEqualsDeclaration */: case 244 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { + if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; } if (!moduleNameExpr.text) { @@ -68612,19 +70355,20 @@ var ts; break; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { - var moduleName = node.name; + var moduleName = node.name; // TODO: GH#17347 + var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name // immediately nested in top level ambient module declaration . - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module - (ambientModules || (ambientModules = [])).push(moduleName.text); + (ambientModules || (ambientModules = [])).push(nameText); } // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. @@ -68642,18 +70386,21 @@ var ts; } } } - function collectRequireCalls(node) { + function collectDynamicImportOrRequireCalls(node) { if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { (imports || (imports = [])).push(node.arguments[0]); } + else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { + (imports || (imports = [])).push(node.arguments[0]); + } else { - ts.forEachChild(node, collectRequireCalls); + ts.forEachChild(node, collectDynamicImportOrRequireCalls); } } } /** 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)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -68683,13 +70430,13 @@ var ts; } var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); if (fail && !sourceFileWithAddedExtension) - fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); return sourceFileWithAddedExtension; } } /** 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) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -68708,7 +70455,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(path)) { + if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems @@ -68748,13 +70495,14 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(path); + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(path, file); + filesByNameIgnoreCase.set(pathLowerCase, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -68880,7 +70628,7 @@ var ts; modulesWithElidedImports.set(file.path, true); } else if (shouldAddFile) { - var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end); } @@ -68924,28 +70672,28 @@ var ts; function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); } if (options.noEmitOnError) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); } if (options.out) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); } if (options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); } } if (options.inlineSourceMap) { if (options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); } if (options.mapRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); } } if (options.paths && options.baseUrl === undefined) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } if (options.paths) { for (var key in options.paths) { @@ -68953,65 +70701,66 @@ var ts; continue; } if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); } - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var subst = _a[_i]; + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); } } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); } } } if (!options.sourceMap && !options.inlineSourceMap) { if (options.inlineSources) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); } if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); } } if (options.out && options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } if (options.mapRoot && !options.sourceMap) { // Error to specify --mapRoot without --sourcemap - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); } if (options.declarationDir) { if (!options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); } if (options.out || options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.lib && options.noLib) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; 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)); + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { @@ -69027,7 +70776,7 @@ var ts; // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); @@ -69043,34 +70792,34 @@ var ts; var dir = getCommonSourceDirectory(); // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } if (!options.noEmit && options.allowJs && options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } if (options.jsxFactory) { if (options.reactNamespace) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); } if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); } } else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); @@ -69079,9 +70828,9 @@ var ts; // Verify that all the emit files are unique and don't overwrite input files function verifyEmitFilePath(emitFileName, emitFilesSeen) { if (emitFileName) { - var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + var emitFilePath = toPath(emitFileName); // Report error if the output overwrites input file - if (filesByName.contains(emitFilePath)) { + if (filesByName.has(emitFilePath)) { var chain_1; if (!options.configFilePath) { // The program is from either an inferred project or an external project @@ -69090,19 +70839,98 @@ var ts; chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; // Report error if multiple files write into same file - if (emitFilesSeen.contains(emitFilePath)) { + if (emitFilesSeen.has(emitFileKey)) { // Already seen the same emit file - report error blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { - emitFilesSeen.set(emitFilePath, true); + emitFilesSeen.set(emitFileKey, true); } } } } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + if (ts.isArrayLiteralExpression(keyProps.initializer) && + keyProps.initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionPathsSyntax() { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + } + return ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile && options.configFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + } + return !!props.length; + } function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } } @@ -69116,15 +70944,15 @@ var ts; function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { - case ts.Extension.Ts: - case ts.Extension.Dts: + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: // These are always allowed. return undefined; - case ts.Extension.Tsx: + case ".tsx" /* Tsx */: return needJsx(); - case ts.Extension.Jsx: + case ".jsx" /* Jsx */: return needJsx() || needAllowJs(); - case ts.Extension.Js: + case ".js" /* Js */: return needAllowJs(); } function needJsx() { @@ -69135,12 +70963,16 @@ var ts; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; + function checkAllDefined(names) { + ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); + return names; + } })(ts || (ts = {})); /// /// /// /// -/// +/// var ts; (function (ts) { /* @internal */ @@ -69237,11 +71069,12 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES2015, "es2015": ts.ModuleKind.ES2015, + "esnext": ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, }, { name: "lib", @@ -69748,6 +71581,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, { // A list of plugins to load in the language service name: "plugins", @@ -69811,7 +71650,6 @@ var ts; return typeAcquisition; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; - /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -69827,13 +71665,15 @@ var ts; optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; return optionNameMapCache; } - ts.getOptionNameMap = getOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } /* @internal */ function parseCustomTypeOption(opt, value, errors) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); @@ -69864,7 +71704,6 @@ var ts; var options = {}; var fileNames = []; var errors = []; - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; parseStrings(commandLine); return { options: options, @@ -69880,13 +71719,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); - // Try to translate short option names to their full equivalents. - var short = shortOptionNames.get(s); - if (short !== undefined) { - s = short; - } - var opt = optionNameMap.get(s); + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -69974,19 +71807,26 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } /** * Read tsconfig.json file * @param fileName The path to the config file */ function readConfigFile(fileName, readFile) { - var text = ""; - try { - text = readFile(fileName); - } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; - } - return parseConfigFileTextToJson(fileName, text); + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; /** @@ -69994,17 +71834,239 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } - try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; - } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; - } + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]); + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value + */ + function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.jsonObject) { + return {}; + } + return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, + /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 261 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined" && typeof value !== "undefined") { + result[keyText] = value; + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || knownOptions === knownRootOptions)) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (knownOptions === knownRootOptions) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 86 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95 /* NullKeyword */: + reportInvalidOptionValue(!!option); + return null; // tslint:disable-line:no-null-keyword + case 9 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + var text = valueExpression.text; + if (option && typeof option.type !== "string") { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text)) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 178 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 177 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return node.kind === 9 /* StringLiteral */ && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34 /* doubleQuote */; + } + } + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + typeof option.type === "string" ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = typeof option.type === "string" ? option.type : "string"; + return typeof value === expectedType; + } + } /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -70013,13 +72075,7 @@ var ts; /* @internal */ function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - // only set the files property if we have at least one file - configurations.files = fileNames; - } + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition) { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { @@ -70042,40 +72098,38 @@ var ts; }); } function serializeCompilerOptions(options) { - var result = {}; + var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name in options) { + var _loop_5 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - continue; + return "continue"; } var value = options[name]; var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { // There is no map associated with this compiler option then use the value as-is // This is the case if the value is expect to be string, number, boolean or list of string - result[name] = value; + result.set(name, value); } else { if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name] = convertedValue; + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { // There is a typeMap associated with this command-line option so use it to map value back to its name - result[name] = getNameOfCompilerOptionValue(value, customTypeMap); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } + }; + for (var name in options) { + _loop_5(name); } return result; } @@ -70092,7 +72146,7 @@ var ts; case "object": return {}; default: - return ts.arrayFrom(option.type.keys())[0]; + return option.type.keys().next().value; } } function makePadding(paddingLength) { @@ -70100,31 +72154,31 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.reduceLeft(ts.filter(ts.optionDeclarations, function (o) { return o.category !== ts.Diagnostics.Command_line_Options && o.category !== ts.Diagnostics.Advanced_Options; }), function (memo, value) { - if (value.category) { - var name = ts.getLocaleSpecificMessage(value.category); - (memo[name] || (memo[name] = [])).push(value); + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); } - return memo; - }, {}); - // Serialize all options and thier descriptions + } + // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; var nameColumn = []; var descriptionColumn = []; - var knownKeysCount = ts.getOwnKeys(configurations.compilerOptions).length; - for (var category in categorizedOptions) { + categorizedOptions.forEach(function (options, category) { if (nameColumn.length !== 0) { nameColumn.push(""); descriptionColumn.push(""); } nameColumn.push("/* " + category + " */"); descriptionColumn.push(""); - for (var _i = 0, _a = categorizedOptions[category]; _i < _a.length; _i++) { - var option = _a[_i]; + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; var optionName = void 0; - if (ts.hasProperty(configurations.compilerOptions, option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(configurations.compilerOptions[option.name]) + ((seenKnownKeys += 1) === knownKeysCount ? "" : ","); + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); } else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; @@ -70133,7 +72187,7 @@ var ts; descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); marginLength = Math.max(optionName.length, marginLength); } - } + }); // Write the output var tab = makePadding(2); var result = []; @@ -70143,13 +72197,13 @@ var ts; for (var i = 0; i < nameColumn.length; i++) { var optionName = nameColumn[i]; var description = descriptionColumn[i]; - result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description); + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); } - if (configurations.files && configurations.files.length) { + if (fileNames.length) { result.push(tab + "},"); result.push(tab + "\"files\": ["); - for (var i = 0; i < configurations.files.length; i++) { - result.push("" + tab + tab + JSON.stringify(configurations.files[i]) + (i === configurations.files.length - 1 ? "" : ",")); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); } result.push(tab + "]"); } @@ -70161,194 +72215,285 @@ var ts; } } ts.generateTSConfig = generateTSConfig; - /** - * Remove the comments from a json like text. - * Comments can be single line comments (starting with # or //) or multiline comments using / * * / - * - * This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate. - */ - function removeComments(jsonText) { - var output = ""; - var scanner = ts.createScanner(1 /* ES5 */, /* skipTrivia */ false, 0 /* Standard */, jsonText); - var token; - while ((token = scanner.scan()) !== 1 /* EndOfFileToken */) { - switch (token) { - case 2 /* SingleLineCommentTrivia */: - case 3 /* MultiLineCommentTrivia */: - // replace comments with whitespace to preserve original character positions - output += scanner.getTokenText().replace(/\S/g, " "); - break; - default: - output += scanner.getTokenText(); - break; - } - } - return output; - } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse * @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) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @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 + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @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 parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - 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); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.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); + setConfigFileInOptions(options, sourceFile); var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typeAcquisition: typeAcquisition, - raw: json, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + compileOnSave: !!raw.compileOnSave }; function getFileNames() { var fileNames; - if (ts.hasProperty(json, "files")) { - if (ts.isArray(json["files"])) { - fileNames = json["files"]; + if (ts.hasProperty(raw, "files")) { + if (ts.isArray(raw["files"])) { + fileNames = raw["files"]; if (fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); } } var includeSpecs; - if (ts.hasProperty(json, "include")) { - if (ts.isArray(json["include"])) { - includeSpecs = json["include"]; + if (ts.hasProperty(raw, "include")) { + if (ts.isArray(raw["include"])) { + includeSpecs = raw["include"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(json, "exclude")) { - if (ts.isArray(json["exclude"])) { - excludeSpecs = json["exclude"]; + if (ts.hasProperty(raw, "exclude")) { + if (ts.isArray(raw["exclude"])) { + excludeSpecs = raw["exclude"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { // If no includes were specified, exclude common package folders and the outDir - excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; + var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - excludeSpecs.push(outDir); + specs.push(outDir); } + excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); - if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } return result; } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isSuccessfulParsedTsconfig(value) { + return !!value.options; } - 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) { + function parseConfig(json, sourceFile, 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 }; + return { raw: json || convertToObject(sourceFile, errors) }; } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { 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; + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; 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); + if (typeof json.extends !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } - return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - 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; + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } } - extended = ts.normalizeSlashes(extended); + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(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)); + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + 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, extended)); + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return undefined; } } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); 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 }; + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; + return undefined; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); if (typeof result === "boolean" && result) { @@ -70356,7 +72501,6 @@ var ts; } return false; } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -70369,15 +72513,23 @@ var ts; return { options: options, errors: errors }; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultCompilerOptions(configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultTypeAcquisition(configFileName) { var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return options; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; @@ -70386,7 +72538,7 @@ var ts; if (!jsonOptions) { return; } - var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); + var optionNameMap = commandLineOptionsToMap(optionDeclarations); for (var id in jsonOptions) { var opt = optionNameMap.get(id); if (opt) { @@ -70398,28 +72550,41 @@ var ts; } } function convertJsonOption(opt, value, basePath, errors) { - var optType = opt.type; - var expectedType = typeof optType === "string" ? optType : "string"; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); - } - else if (typeof value === expectedType) { - if (typeof optType !== "string") { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (typeof optType !== "string") { return convertJsonOptionOfCustomType(opt, value, errors); } - else { - if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; - } - } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType)); + else if (typeof option.type !== "string") { + return option.type.get(value); } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); @@ -70515,7 +72680,7 @@ var ts; * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the @@ -70530,10 +72695,10 @@ var ts; // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); if (include) { - include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); + include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); } if (exclude) { - exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true); + exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); } // Wildcard directories (provided as part of a wildcard path) are stored in a // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), @@ -70553,7 +72718,7 @@ var ts; } } if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, /*depth*/ undefined); _a < _b.length; _a++) { var file = _b[_a]; // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. @@ -70582,24 +72747,40 @@ var ts; wildcardDirectories: wildcardDirectories }; } - function validateSpecs(specs, errors, allowTrailingRecursion) { + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { var validSpecs = []; for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { var spec = specs_1[_i]; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else { validSpecs.push(spec); } } return validSpecs; + function createDiagnostic(message, spec) { + if (jsonSourceFile && jsonSourceFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isArrayLiteralExpression(property.initializer)) { + for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (ts.isStringLiteral(element) && element.text === spec) { + return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); + } + } + } + } + } + return ts.createCompilerDiagnostic(message, spec); + } } /** * Gets directories in a set of include patterns that should be watched for changes. @@ -70641,7 +72822,7 @@ var ts; } } // Remove any subpaths under an existing recursively watched directory. - for (var key in wildcardDirectories) + for (var key in wildcardDirectories) { if (ts.hasProperty(wildcardDirectories, key)) { for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { var recursiveKey = recursiveKeys_1[_a]; @@ -70650,6 +72831,7 @@ var ts; } } } + } } return wildcardDirectories; } @@ -70719,6 +72901,45 @@ var ts; function caseInsensitiveKeyMapper(key) { return key.toLowerCase(); } + /** + * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string":// Could be any arbitrary string -- use empty string instead. + return ""; + case "number":// Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -70756,10 +72977,10 @@ var ts; ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); var IndentStyle; (function (IndentStyle) { @@ -70820,115 +73041,111 @@ var ts; TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); - // TODO: move these to enums var ScriptElementKind; (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; /** predefined type (void) or keyword (class) */ - ScriptElementKind.keyword = "keyword"; + ScriptElementKind["keyword"] = "keyword"; /** top level script node */ - ScriptElementKind.scriptElement = "script"; + ScriptElementKind["scriptElement"] = "script"; /** module foo {} */ - ScriptElementKind.moduleElement = "module"; + ScriptElementKind["moduleElement"] = "module"; /** class X {} */ - ScriptElementKind.classElement = "class"; + ScriptElementKind["classElement"] = "class"; /** var x = class X {} */ - ScriptElementKind.localClassElement = "local class"; + ScriptElementKind["localClassElement"] = "local class"; /** interface Y {} */ - ScriptElementKind.interfaceElement = "interface"; + ScriptElementKind["interfaceElement"] = "interface"; /** type T = ... */ - ScriptElementKind.typeElement = "type"; + ScriptElementKind["typeElement"] = "type"; /** enum E */ - ScriptElementKind.enumElement = "enum"; - ScriptElementKind.enumMemberElement = "enum member"; + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; /** * Inside module and script only * const v = .. */ - ScriptElementKind.variableElement = "var"; + ScriptElementKind["variableElement"] = "var"; /** Inside function */ - ScriptElementKind.localVariableElement = "local var"; + ScriptElementKind["localVariableElement"] = "local var"; /** * Inside module and script only * function f() { } */ - ScriptElementKind.functionElement = "function"; + ScriptElementKind["functionElement"] = "function"; /** Inside function */ - ScriptElementKind.localFunctionElement = "local function"; + ScriptElementKind["localFunctionElement"] = "local function"; /** class X { [public|private]* foo() {} } */ - ScriptElementKind.memberFunctionElement = "method"; + ScriptElementKind["memberFunctionElement"] = "method"; /** class X { [public|private]* [get|set] foo:number; } */ - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; /** * class X { [public|private]* foo:number; } * interface Y { foo:number; } */ - ScriptElementKind.memberVariableElement = "property"; + ScriptElementKind["memberVariableElement"] = "property"; /** class X { constructor() { } } */ - ScriptElementKind.constructorImplementationElement = "constructor"; + ScriptElementKind["constructorImplementationElement"] = "constructor"; /** interface Y { ():number; } */ - ScriptElementKind.callSignatureElement = "call"; + ScriptElementKind["callSignatureElement"] = "call"; /** interface Y { []:number; } */ - ScriptElementKind.indexSignatureElement = "index"; + ScriptElementKind["indexSignatureElement"] = "index"; /** interface Y { new():Y; } */ - ScriptElementKind.constructSignatureElement = "construct"; + ScriptElementKind["constructSignatureElement"] = "construct"; /** function foo(*Y*: string) */ - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; /** * */ - ScriptElementKind.jsxAttribute = "JSX attribute"; + ScriptElementKind["jsxAttribute"] = "JSX attribute"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - return ClassificationTypeNames; - }()); - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - ts.ClassificationTypeNames = ClassificationTypeNames; + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); var ClassificationType; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -70962,7 +73179,6 @@ var ts; var ts; (function (ts) { ts.scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); - ts.emptyArray = []; var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -70996,11 +73212,12 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 283 /* JSDocTypedefTag */: + // If it has no name node, it shares the name with the value declaration below it. + return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 264 /* EnumMember */: case 229 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 232 /* EnumDeclaration */: - return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -71011,6 +73228,7 @@ var ts; else { return 4 /* Namespace */; } + case 232 /* EnumDeclaration */: case 241 /* NamedImports */: case 242 /* ImportSpecifier */: case 237 /* ImportEqualsDeclaration */: @@ -71022,7 +73240,7 @@ var ts; case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { @@ -71030,9 +73248,9 @@ var ts; return 1 /* Value */; } else if (node.parent.kind === 243 /* ExportAssignment */) { - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -71044,6 +73262,10 @@ var ts; else if (isNamespaceReference(node)) { return 4 /* Namespace */; } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName + return 2 /* Type */; + } else { return 1 /* Value */; } @@ -71061,12 +73283,13 @@ var ts; } return 4 /* Namespace */; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -71101,10 +73324,19 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 159 /* TypeReference */ || - (node.parent.kind === 201 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 99 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || - node.kind === 169 /* ThisType */; + switch (node.kind) { + case 99 /* ThisKeyword */: + return !ts.isPartOfExpression(node); + case 169 /* ThisType */: + return true; + } + switch (node.parent.kind) { + case 159 /* TypeReference */: + return true; + case 201 /* ExpressionWithTypeArguments */: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; } function isCallExpressionTarget(node) { return isCallOrNewExpressionTarget(node, 181 /* CallExpression */); @@ -71124,7 +73356,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 222 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -71192,6 +73424,12 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { + if (node.kind === 283 /* JSDocTypedefTag */) { + // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. + // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. + // Then we get parent again in the loop. + node = node.parent.parent; + } while (true) { node = node.parent; if (!node) { @@ -71217,15 +73455,15 @@ var ts; function getNodeKind(node) { switch (node.kind) { case 265 /* SourceFile */: - return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; case 233 /* ModuleDeclaration */: - return ts.ScriptElementKind.moduleElement; + return "module" /* moduleElement */; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: - return ts.ScriptElementKind.classElement; - case 230 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; - case 231 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; - case 232 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; + return "class" /* classElement */; + case 230 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 231 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 232 /* EnumDeclaration */: return "enum" /* enumElement */; case 226 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); case 176 /* BindingElement */: @@ -71233,39 +73471,39 @@ var ts; case 187 /* ArrowFunction */: case 228 /* FunctionDeclaration */: case 186 /* FunctionExpression */: - return ts.ScriptElementKind.functionElement; - case 153 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; - case 154 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; + return "function" /* functionElement */; + case 153 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 154 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: - return ts.ScriptElementKind.memberFunctionElement; + return "method" /* memberFunctionElement */; case 149 /* PropertyDeclaration */: case 148 /* PropertySignature */: - return ts.ScriptElementKind.memberVariableElement; - case 157 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; - case 156 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; - case 155 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; - case 152 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; - case 145 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; - case 264 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; - case 146 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + return "property" /* memberVariableElement */; + case 157 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 156 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 155 /* CallSignature */: return "call" /* callSignatureElement */; + case 152 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 145 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 264 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 146 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; case 237 /* ImportEqualsDeclaration */: case 242 /* ImportSpecifier */: case 239 /* ImportClause */: case 246 /* ExportSpecifier */: case 240 /* NamespaceImport */: - return ts.ScriptElementKind.alias; - case 290 /* JSDocTypedefTag */: - return ts.ScriptElementKind.typeElement; + return "alias" /* alias */; + case 283 /* JSDocTypedefTag */: + return "type" /* typeElement */; default: - return ts.ScriptElementKind.unknown; + return "" /* unknown */; } function getKindOfVariableDeclaration(v) { return ts.isConst(v) - ? ts.ScriptElementKind.constElement + ? "const" /* constElement */ : ts.isLet(v) - ? ts.ScriptElementKind.letElement - : ts.ScriptElementKind.variableElement; + ? "let" /* letElement */ + : "var" /* variableElement */; } } ts.getNodeKind = getNodeKind; @@ -71482,7 +73720,7 @@ var ts; // for the position of the relevant node (or comma). var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { // find syntax list that covers the span of the node - if (c.kind === 294 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -71495,33 +73733,31 @@ var ts; * position >= start and (position < end or (position === end && token is keyword or identifier)) */ function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; /* 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)) */ function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; - /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); + /** + * Returns the token if position is in [start, end). + * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true + */ + function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); + function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { @@ -71531,21 +73767,22 @@ var ts; // find the child that contains 'position' for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; - if (ts.isJSDocNode(child) && !includeJsDocComment) { + if (!includeJsDocComment && ts.isJSDocNode(child)) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); if (start > position) { - continue; + // If this child begins after position, then all subsequent children will as well. + break; } var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { current = child; continue outer; } - else if (includeItemAtEndPosition && end === position) { + else if (includePrecedingTokenAtEndPosition && end === position) { var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { return previousToken; } } @@ -71564,7 +73801,7 @@ var ts; function findTokenOnLeftOfPosition(file, position) { // 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. - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -71594,7 +73831,7 @@ var ts; } } ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { + function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { return find(startNode || sourceFile); function findRightmostToken(n) { if (ts.isToken(n)) { @@ -71620,7 +73857,7 @@ var ts; // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { - var start = child.getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { @@ -71634,7 +73871,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265 /* SourceFile */); + ts.Debug.assert(startNode !== undefined || n.kind === 265 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -71656,7 +73893,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9 /* StringLiteral */) { + if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); // To be "in" one of these literals, the position has to be: @@ -71677,7 +73914,7 @@ var ts; * returns true if the position is in between the open and close elements of an JSX expression. */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return false; } @@ -71706,7 +73943,7 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; @@ -71717,7 +73954,7 @@ var ts; * @param predicate Additional predicate to test on the comment range. */ function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } return position <= tokenAtPosition.getStart(sourceFile) && (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); @@ -71751,7 +73988,7 @@ var ts; } } function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); @@ -71761,42 +73998,6 @@ var ts; } } ts.hasDocComment = hasDocComment; - /** - * Get the corresponding JSDocTag node if the position is in a jsDoc comment - */ - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (ts.isToken(node)) { - switch (node.kind) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - // if the current token is var, let or const, skip the VariableDeclarationList - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (jsDoc.tags) { - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } - } - } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; function nodeHasTokens(n) { // If we have a token or node that has a non-zero width, it must have tokens. // Note, that getWidth() does not take trivia into account. @@ -71806,20 +74007,20 @@ var ts; var flags = ts.getCombinedModifierFlags(node); var result = []; if (flags & 8 /* Private */) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); + result.push("private" /* privateMemberModifier */); if (flags & 16 /* Protected */) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + result.push("protected" /* protectedMemberModifier */); if (flags & 4 /* Public */) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); + result.push("public" /* publicMemberModifier */); if (flags & 32 /* Static */) - result.push(ts.ScriptElementKindModifier.staticModifier); + result.push("static" /* staticModifier */); if (flags & 128 /* Abstract */) - result.push(ts.ScriptElementKindModifier.abstractModifier); + result.push("abstract" /* abstractModifier */); if (flags & 1 /* Export */) - result.push(ts.ScriptElementKindModifier.exportedModifier); + result.push("export" /* exportedModifier */); if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + result.push("declare" /* ambientModifier */); + return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { @@ -71871,6 +74072,12 @@ var ts; return false; } ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; function compareDataObjects(dst, src) { if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { return false; @@ -72005,7 +74212,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop + reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { if (lineStart) { @@ -72077,7 +74284,7 @@ var ts; else if (flags & 524288 /* TypeAlias */) { return ts.SymbolDisplayPartKind.aliasName; } - else if (flags & 8388608 /* Alias */) { + else if (flags & 2097152 /* Alias */) { return ts.SymbolDisplayPartKind.aliasName; } return ts.SymbolDisplayPartKind.text; @@ -72085,10 +74292,7 @@ var ts; } ts.symbolPart = symbolPart; function displayPart(text, kind) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] - }; + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; } ts.displayPart = displayPart; function spacePart() { @@ -72131,10 +74335,13 @@ var ts; } ts.lineBreakPart = lineBreakPart; function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { @@ -72159,7 +74366,7 @@ var ts; // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever is under the cursor. if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144 /* ComputedPropertyName */) { - return location.text; + return ts.getTextOfIdentifierOrLiteral(location); } // Try to get the local symbol if we're dealing with an 'export default' // since that symbol has the "true" name. @@ -72200,41 +74407,9 @@ var ts; function getScriptKind(fileName, host) { // First check to see if the script kind was specified by the host. Chances are the host // may override the default script kind for the file extension. - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2 /* ES2015 */, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - // Becasue the content was wrapped in "()", the start position of diagnostics needs to be subtract by 1 - // 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_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; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -72248,7 +74423,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -72320,7 +74495,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_7 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -72329,8 +74504,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_7, classification: convertClassification(type) }); + lastEnd = start + length_7; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72759,7 +74934,7 @@ var ts; // Only bother calling into the typechecker if this is an identifier that // could possibly resolve to a type name. This makes classification run // in a third of the time it would normally take. - if (classifiableNames.get(identifier.text)) { + if (classifiableNames.has(identifier.escapedText)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); @@ -72776,29 +74951,29 @@ var ts; ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; function getClassificationTypeName(type) { switch (type) { - case 1 /* comment */: return ts.ClassificationTypeNames.comment; - case 2 /* identifier */: return ts.ClassificationTypeNames.identifier; - case 3 /* keyword */: return ts.ClassificationTypeNames.keyword; - case 4 /* numericLiteral */: return ts.ClassificationTypeNames.numericLiteral; - case 5 /* operator */: return ts.ClassificationTypeNames.operator; - case 6 /* stringLiteral */: return ts.ClassificationTypeNames.stringLiteral; - case 8 /* whiteSpace */: return ts.ClassificationTypeNames.whiteSpace; - case 9 /* text */: return ts.ClassificationTypeNames.text; - case 10 /* punctuation */: return ts.ClassificationTypeNames.punctuation; - case 11 /* className */: return ts.ClassificationTypeNames.className; - case 12 /* enumName */: return ts.ClassificationTypeNames.enumName; - case 13 /* interfaceName */: return ts.ClassificationTypeNames.interfaceName; - case 14 /* moduleName */: return ts.ClassificationTypeNames.moduleName; - case 15 /* typeParameterName */: return ts.ClassificationTypeNames.typeParameterName; - case 16 /* typeAliasName */: return ts.ClassificationTypeNames.typeAliasName; - case 17 /* parameterName */: return ts.ClassificationTypeNames.parameterName; - case 18 /* docCommentTagName */: return ts.ClassificationTypeNames.docCommentTagName; - case 19 /* jsxOpenTagName */: return ts.ClassificationTypeNames.jsxOpenTagName; - case 20 /* jsxCloseTagName */: return ts.ClassificationTypeNames.jsxCloseTagName; - case 21 /* jsxSelfClosingTagName */: return ts.ClassificationTypeNames.jsxSelfClosingTagName; - case 22 /* jsxAttribute */: return ts.ClassificationTypeNames.jsxAttribute; - case 23 /* jsxText */: return ts.ClassificationTypeNames.jsxText; - case 24 /* jsxAttributeStringLiteralValue */: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + case 1 /* comment */: return "comment" /* comment */; + case 2 /* identifier */: return "identifier" /* identifier */; + case 3 /* keyword */: return "keyword" /* keyword */; + case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 5 /* operator */: return "operator" /* operator */; + case 6 /* stringLiteral */: return "string" /* stringLiteral */; + case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; + case 9 /* text */: return "text" /* text */; + case 10 /* punctuation */: return "punctuation" /* punctuation */; + case 11 /* className */: return "class name" /* className */; + case 12 /* enumName */: return "enum name" /* enumName */; + case 13 /* interfaceName */: return "interface name" /* interfaceName */; + case 14 /* moduleName */: return "module name" /* moduleName */; + case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */; + case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */; + case 17 /* parameterName */: return "parameter name" /* parameterName */; + case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */; + case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */; + case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */; + case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */; + case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; + case 23 /* jsxText */: return "jsx text" /* jsxText */; + case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; } } function convertClassifications(classifications) { @@ -72870,9 +75045,9 @@ var ts; pushClassification(start, width, 1 /* comment */); continue; } - // for the ======== add a comment for the first line, and then lex all - // subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 61 /* equals */); + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); classifyDisabledMergeCode(text, start, end); } } @@ -72904,20 +75079,20 @@ var ts; if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); - pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@" + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 286 /* JSDocParameterTag */: + case 279 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 289 /* JSDocTemplateTag */: + case 282 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 288 /* JSDocTypeTag */: + case 281 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 287 /* JSDocReturnTag */: + case 280 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -72929,20 +75104,20 @@ var ts; } return; function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); - pos = tag.preParameterName.end; + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; } if (tag.typeExpression) { pushCommentRange(pos, tag.typeExpression.pos - pos); processElement(tag.typeExpression); pos = tag.typeExpression.end; } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); - pos = tag.postParameterName.end; + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; } } } @@ -72953,8 +75128,8 @@ var ts; } } function classifyDisabledMergeCode(text, start, end) { - // Classify the line that the ======= marker is on as a comment. Then just lex - // all further tokens and add them to the result. + // Classify the line that the ||||||| or ======= marker is on as a comment. + // Then just lex all further tokens and add them to the result. var i; for (i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { @@ -72981,7 +75156,7 @@ var ts; * False will mean that node is not classified and traverse routine should recurse into node contents. */ function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { + if (ts.isJSDoc(node)) { return true; } if (ts.nodeIsMissing(node)) { @@ -73179,14 +75354,9 @@ var ts; // Make all paths absolute/normalized if they are not already rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within - var relativeDirectory; - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDirectory = rootDirs_1[_i]; - if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { - relativeDirectory = scriptPath.substr(rootDirectory.length); - break; - } - } + var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + }); // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); } @@ -73245,7 +75415,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + result.push(createCompletionEntryForModule(foundFile, "script" /* scriptElement */, span)); }); } // If possible, get folder completion as well @@ -73254,7 +75424,7 @@ var ts; for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { var directory = directories_2[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + result.push(createCompletionEntryForModule(directoryName, "directory" /* directory */, span)); } } } @@ -73284,7 +75454,7 @@ var ts; var pattern = _a[_i]; for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { var match = _c[_b]; - result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); } } } @@ -73292,7 +75462,7 @@ var ts; else if (ts.startsWith(path, fragment)) { var entry = paths[path] && paths[path].length === 1 && paths[path][0]; if (entry) { - result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); } } } @@ -73305,7 +75475,7 @@ var ts; getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { var moduleName = _e[_d]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } @@ -73339,8 +75509,8 @@ var ts; continue; } var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); + var length_8 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); } return result; } @@ -73354,24 +75524,21 @@ var ts; var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); - var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.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) { var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { - if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { - return moduleName.substr(moduleNameWithSeperator_1.length); - } - return moduleName; + nonRelativeModuleNames = ts.map(nonRelativeModuleNames, function (nonRelativeModuleName) { + return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); } if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { var visibleModule = _a[_i]; if (!isNestedModule) { - nonRelativeModules.push(visibleModule.moduleName); + nonRelativeModuleNames.push(visibleModule.moduleName); } else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); @@ -73380,16 +75547,16 @@ var ts; var f = nestedFiles_1[_b]; f = ts.normalizePath(f); var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); - nonRelativeModules.push(nestedModule); + nonRelativeModuleNames.push(nestedModule); } } } } } - return ts.deduplicate(nonRelativeModules); + return ts.deduplicate(nonRelativeModuleNames); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return undefined; } @@ -73441,7 +75608,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } } else if (host.getDirectories) { @@ -73475,7 +75642,7 @@ var ts; for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { var typeDirectory = directories_3[_i]; typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); } } } @@ -73547,7 +75714,7 @@ var ts; } } function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + return { name: name, kind: kind, kindModifiers: "" /* none */, sortText: name, replacementSpan: replacementSpan }; } // Replace everything after the last directory seperator that appears function getDirectoryFragmentTextSpan(text, textStart) { @@ -73620,6 +75787,12 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var KeywordCompletionFilters; + (function (KeywordCompletionFilters) { + KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); @@ -73631,80 +75804,78 @@ 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, 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() }; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + if (sourceFile.languageVariant === 1 /* JSX */ && + location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any + var tagName = location.parent.parent.openingElement.tagName; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, + entries: [{ + name: tagName.getFullText(), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }] }; } - if (requestJsDocTag) { - // If the current position is a jsDoc tag, only tags should be provided for completion - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagCompletions() }; + if (request) { + var entries_2 = request.kind === "JsDocTagName" + ? ts.JsDoc.getJSDocTagNameCompletions() + : request.kind === "JsDocTag" + ? ts.JsDoc.getJSDocTagCompletions() + : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target)); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 /* JSX */ && - location.parent && location.parent.kind === 252 /* JsxClosingElement */) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
completion list at "1" will contain "div" with type any - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0", - }); - } - else if (!hasFilteredClassMemberKeywords) { - return undefined; - } + if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - if (hasFilteredClassMemberKeywords) { - ts.addRange(entries, classMemberKeywordCompletions); - } - else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { - ts.addRange(entries, keywordCompletions); + // TODO add filter for keyword based on type/value/namespace and also location + // Add all keywords if + // - this is not a member completion list (all the keywords) + // - other filters are enabled in required scenario so add those keywords + if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { + ts.addRange(entries, getKeywordCompletions(keywordFilters)); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target) { - var entries = []; - var nameTable = ts.getNameTable(sourceFile); - nameTable.forEach(function (pos, name) { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } - if (!uniqueNames.get(name)) { - uniqueNames.set(name, name); - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name), target, /*performCharacterChecks*/ true); - if (displayName) { - var entry = { - name: displayName, - kind: ts.ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } + var realName = ts.unescapeLeadingUnderscores(name); + if (uniqueNames.has(realName)) { + return; + } + uniqueNames.set(realName, true); + var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true); + if (displayName) { + entries.push({ + name: displayName, + kind: "warning" /* warning */, + kindModifiers: "", + sortText: "1" + }); } }); - return entries; } function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); if (!displayName) { return undefined; } @@ -73730,10 +75901,10 @@ var ts; var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!uniqueNames.get(id)) { + var id = entry.name; + if (!uniqueNames.has(id)) { entries.push(entry); - uniqueNames.set(id, id); + uniqueNames.set(id, true); } } } @@ -73818,9 +75989,9 @@ var ts; 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]; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { @@ -73869,8 +76040,8 @@ var ts; uniques.set(name, true); result.push({ name: name, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, + kindModifiers: "" /* none */, + kind: "var" /* variableElement */, sortText: "0" }); } @@ -73880,14 +76051,14 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_1 = completionData.location; + var symbols = completionData.symbols, location = completionData.location; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_1) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_1, location_1, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -73899,12 +76070,12 @@ var ts; } } // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === entryName; }); if (keywordCompletion) { return { name: entryName, - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, tags: undefined @@ -73916,36 +76087,31 @@ var ts; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - // Find the symbol with the matching entry name. - // We don't need to perform character checks here because we're only comparing the - // name against 'entryName' (which is known to be good), not building a new - // completion entry. - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); - } - return undefined; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - // JsDoc tag-name is just the name of the JSDoc tagname (exclude "@") - var requestJsDocTagName = false; - // JsDoc tag includes both "@" and tag-name - var requestJsDocTag = false; + var request; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) 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.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { - // The current position is next to the '@' sign, when no tag name being provided yet. - // Provide a full list of tag names if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { - requestJsDocTagName = true; + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + request = { kind: "JsDocTagName" }; } else { // When completion is requested without "@", we will have check to make sure that @@ -73965,33 +76131,37 @@ var ts; // * |c| // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); - requestJsDocTag = !(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/)); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + request = { kind: "JsDocTag" }; + } } } // Completion should work inside certain JsDoc tags. For example: // /** @type {number | string} */ // Completion should work in the brackets - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); + var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - requestJsDocTagName = true; + request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 288 /* JSDocTypeTag */: - case 286 /* JSDocParameterTag */: - case 287 /* JSDocReturnTag */: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 284 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } - if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; + if (request) { + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -73999,7 +76169,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -74007,9 +76177,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + var start_4 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -74018,7 +76188,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -74077,7 +76247,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; - var hasFilteredClassMemberKeywords = false; + var keywordFilters = 0 /* None */; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -74085,7 +76255,7 @@ var ts; else if (isRightOfOpenTag) { var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 8388608 /* Alias */)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); })); } else { symbols = tagSymbols; @@ -74111,51 +76281,75 @@ 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, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 277 /* JSDocAugmentsTag */: + case 279 /* JSDocParameterTag */: + case 284 /* JSDocPropertyTag */: + case 280 /* JSDocReturnTag */: + case 281 /* JSDocTypeTag */: + case 283 /* JSDocTypedefTag */: + return true; + } + } function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */ || node.kind === 179 /* PropertyAccessExpression */) { + // Since this is qualified name check its a type node location + var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); - // This is an alias, follow what it aliases - if (symbol && symbol.flags & 8388608 /* Alias */) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952 /* HasExports */) { - // Extract module or enum members - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { + // Extract module or enum members + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isRhsOfImportDeclaration ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var symbol_2 = exportedSymbols_1[_i]; + if (isValidAccess(symbol_2)) { + symbols.push(symbol_2); + } } - }); + // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 /* SourceFile */ && d.kind !== 233 /* ModuleDeclaration */ && d.kind !== 232 /* EnumDeclaration */; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } } function addTypeProperties(type) { - if (type) { - // Filter private properties - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); } - if (isJavaScriptFile && type.flags & 65536 /* Union */) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } + } + if (isJavaScriptFile && type.flags & 65536 /* Union */) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); } } } @@ -74172,6 +76366,15 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (tryGetConstructorLikeCompletionContainer(contextToken)) { + // no members, only keywords + isMemberCompletion = false; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 2 /* ConstructorParameterKeywords */; + return true; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -74232,11 +76435,72 @@ var ts; scopeNode.kind === 256 /* JsxExpression */ || ts.isStatement(scopeNode); } - /// TODO filter meaning based on the current context - var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 2097152 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + // Its a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol); + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455 /* Value */); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 /* TypeOfKeyword */ && + contextToken.parent.kind === 162 /* TypeQuery */; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56 /* ColonToken */: + return parentKind === 149 /* PropertyDeclaration */ || + parentKind === 148 /* PropertySignature */ || + parentKind === 146 /* Parameter */ || + parentKind === 226 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 58 /* EqualsToken */: + return parentKind === 231 /* TypeAliasDeclaration */; + case 118 /* AsKeyword */: + return parentKind === 202 /* AsExpression */; + } + } + } + function symbolCanBeReferencedAtTypeLocation(symbol) { + symbol = symbol.exportSymbol || symbol; + // This is an alias, follow what it aliases + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & 793064 /* Type */) { + return true; + } + if (symbol.flags & 1536 /* Module */) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + // If the exported symbols contains type, + // symbol can be referenced at locations where type is allowed + return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); + } + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -74293,7 +76557,7 @@ var ts; || containingNodeKind === 157 /* IndexSignature */ // [ | : string ] || containingNodeKind === 144 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 128 /* ModuleKeyword */: // module | - case 129 /* NamespaceKeyword */: + case 129 /* NamespaceKeyword */:// namespace | return true; case 23 /* DotToken */: return containingNodeKind === 233 /* ModuleDeclaration */; // module A.| @@ -74325,13 +76589,13 @@ var ts; if (contextToken.kind === 9 /* StringLiteral */ || contextToken.kind === 12 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_3 = contextToken.getStart(); + var start_5 = contextToken.getStart(); var end = contextToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. // 2. at the end position of an unterminated token. // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_3 < position && position < end) { + if (start_5 < position && position < end) { return true; } if (position === end) { @@ -74362,41 +76626,36 @@ var ts; typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { + else { + ts.Debug.assert(objectLikeContainer.kind === 174 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - // We don't want to complete using the type acquired by the shape - // of the binding pattern; we are only interested in types acquired - // through type declaration or inference. - // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - - // type of parameter will flow in from the contextual type of the function - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 146 /* Parameter */) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 151 /* MethodDeclaration */ || rootDeclaration.parent.kind === 154 /* SetAccessor */) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } + if (!ts.isVariableLike(rootDeclaration)) + throw ts.Debug.fail("Root declaration is not variable-like."); + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 146 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - if (canGetType) { - 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; + else if (rootDeclaration.parent.kind === 151 /* MethodDeclaration */ || rootDeclaration.parent.kind === 154 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } - else { - ts.Debug.fail("Root declaration is not variable-like."); + if (canGetType) { + 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; } } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -74448,7 +76707,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements - hasFilteredClassMemberKeywords = true; + keywordFilters = 1 /* ClassElementKeywords */; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); if (baseTypeNode || implementsTypeNodes) { @@ -74476,12 +76735,12 @@ var ts; } } var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? - undefined : - ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + ts.emptyArray : + ts.flatMap(implementsTypeNodes || ts.emptyArray, 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); + ts.emptyArray, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); } } } @@ -74493,9 +76752,9 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */: + case 26 /* CommaToken */:// const x = { a: 0, | var parent = contextToken.parent; - if (parent && (parent.kind === 178 /* ObjectLiteralExpression */ || parent.kind === 174 /* ObjectBindingPattern */)) { + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; @@ -74511,7 +76770,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // import { | - case 26 /* CommaToken */: + case 26 /* CommaToken */:// import { a as 0, | switch (contextToken.parent.kind) { case 241 /* NamedImports */: case 245 /* NamedExports */: @@ -74524,6 +76783,14 @@ var ts; function isFromClassElementDeclaration(node) { return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); } + function isParameterOfConstructorDeclaration(node) { + return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); + } + function isConstructorParameterCompletion(node) { + return node.parent && + isParameterOfConstructorDeclaration(node.parent) && + (isConstructorParameterCompletionKeyword(node.kind) || ts.isDeclarationName(node)); + } /** * 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. @@ -74531,13 +76798,18 @@ var ts; function tryGetClassLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 17 /* OpenBraceToken */: + case 17 /* OpenBraceToken */:// class c { | + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number, | } + case 26 /* CommaToken */: 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 */: @@ -74554,11 +76826,29 @@ var ts; } } // class c { method() { } | method2() { } } - if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + if (location && location.kind === 286 /* SyntaxList */ && ts.isClassLike(location.parent)) { return location.parent; } return undefined; } + /** + * 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 tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 19 /* OpenParenToken */: + case 26 /* CommaToken */: + return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + default: + if (isConstructorParameterCompletion(contextToken)) { + return contextToken.parent.parent; + } + } + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -74616,19 +76906,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152 /* Constructor */: - case 161 /* ConstructorType */: - case 160 /* FunctionType */: - return false; - default: - return true; - } - } /** * @returns true if we are certain that the currently edited location must define a new location; false otherwise. */ @@ -74640,12 +76917,15 @@ var ts; containingNodeKind === 227 /* VariableDeclarationList */ || containingNodeKind === 208 /* VariableStatement */ || containingNodeKind === 232 /* EnumDeclaration */ || - isFunction(containingNodeKind) || - containingNodeKind === 229 /* ClassDeclaration */ || - containingNodeKind === 199 /* ClassExpression */ || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 230 /* InterfaceDeclaration */ || containingNodeKind === 175 /* ArrayBindingPattern */ || - containingNodeKind === 231 /* TypeAliasDeclaration */; // type Map, K, | + containingNodeKind === 231 /* TypeAliasDeclaration */ || + // class A= contextToken.pos); case 23 /* DotToken */: return containingNodeKind === 175 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: @@ -74654,7 +76934,7 @@ var ts; return containingNodeKind === 175 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: return containingNodeKind === 260 /* CatchClause */ || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: return containingNodeKind === 232 /* EnumDeclaration */ || containingNodeKind === 230 /* InterfaceDeclaration */ || @@ -74669,7 +76949,7 @@ var ts; containingNodeKind === 199 /* ClassExpression */ || containingNodeKind === 230 /* InterfaceDeclaration */ || containingNodeKind === 231 /* TypeAliasDeclaration */ || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: @@ -74679,7 +76959,7 @@ var ts; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 146 /* Parameter */; + return containingNodeKind === 146 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); case 118 /* AsKeyword */: return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || @@ -74699,7 +76979,7 @@ var ts; case 110 /* LetKeyword */: case 76 /* ConstKeyword */: case 116 /* YieldKeyword */: - case 138 /* TypeKeyword */: + case 138 /* TypeKeyword */:// type htm| return true; } // If the previous token is keyword correspoding to class member completion keyword @@ -74708,6 +76988,17 @@ var ts; isFromClassElementDeclaration(contextToken)) { return false; } + if (isConstructorParameterCompletion(contextToken)) { + // constructor parameter completion is available only if + // - its modifier of the constructor parameter or + // - its name of the parameter and not being edited + // eg. constructor(a |<- this shouldnt show completion + if (!ts.isIdentifier(contextToken) || + isConstructorParameterCompletionKeywordText(contextToken.getText()) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -74727,7 +77018,10 @@ var ts; case "yield": return true; } - return false; + return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -74746,7 +77040,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = ts.createMap(); + var existingImportsOrExports = ts.createUnderscoreEscapedMap(); 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 @@ -74754,12 +77048,12 @@ var ts; continue; } var name = element.propertyName || element.name; - existingImportsOrExports.set(name.text, true); + existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports.get(e.name); }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); } /** * Filters out completion suggestions for named imports or exports. @@ -74771,7 +77065,7 @@ var ts; if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; } - var existingMemberNames = ts.createMap(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members @@ -74791,18 +77085,19 @@ var ts; if (m.kind === 176 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { - existingName = m.propertyName.text; + existingName = m.propertyName.escapedText; } } else { - // TODO(jfreeman): Account for computed property name + // TODO: 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 = ts.getNameOfDeclaration(m).text; + var name = ts.getNameOfDeclaration(m); + existingName = ts.getEscapedTextOfIdentifierOrLiteral(name); } existingMemberNames.set(existingName, true); } - return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.escapedName); }); } /** * Filters out completion suggestions for class elements. @@ -74810,7 +77105,7 @@ var ts; * @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(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members @@ -74840,9 +77135,20 @@ var ts; 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 */); })); + var result = []; + addPropertySymbols(baseSymbols, 8 /* Private */); + addPropertySymbols(implementingTypeSymbols, 24 /* NonPublicAccessibilityModifier */); + return result; + function addPropertySymbols(properties, inValidModifierFlags) { + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; + if (isValidProperty(property, inValidModifierFlags)) { + result.push(property); + } + } + } function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.name) && + return !existingMemberNames.get(propertySymbol.escapedName) && propertySymbol.getDeclarations() && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); } @@ -74854,7 +77160,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterJsxAttributes(symbols, attributes) { - var seenNames = ts.createMap(); + var seenNames = ts.createUnderscoreEscapedMap(); 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 @@ -74862,10 +77168,10 @@ var ts; continue; } if (attr.kind === 253 /* JsxAttribute */) { - seenNames.set(attr.name.text, true); + seenNames.set(attr.name.escapedText, true); } } - return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); + return ts.filter(symbols, function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { return node.getStart() <= position && position <= node.getEnd(); @@ -74874,53 +77180,70 @@ var ts; /** * Get the name to be display in completion from a given symbol. * - * @return undefined if the name is of external module otherwise a name with striped of any quote + * @return undefined if the name is of external module */ - function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(typeChecker, symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + var name = symbol.name; + if (!name) + return undefined; + // First check of the displayName is not external module; if it is an external module, it is not valid entry + if (symbol.flags & 1920 /* Namespace */) { + var firstCharCode = name.charCodeAt(0); + if (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks); } /** * Get a displayName from a given for completion list, performing any necessary quotes stripping * and checking whether the name is valid identifier name. */ function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { - return undefined; - } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks) { - if (!ts.isIdentifierText(name, target)) { - return undefined; - } + if (performCharacterChecks && !ts.isIdentifierText(name, target)) { + return undefined; } return name; } // A cache of completion entries for keywords, these do not change between sessions - var keywordCompletions = []; - for (var i = 72 /* FirstKeyword */; i <= 142 /* LastKeyword */; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, - sortText: "0" - }); + var _keywordCompletions = []; + function getKeywordCompletions(keywordFilter) { + var completions = _keywordCompletions[keywordFilter]; + if (completions) { + return completions; + } + return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); + function generateKeywordCompletions(keywordFilter) { + switch (keywordFilter) { + case 0 /* None */: + return getAllKeywordCompletions(); + case 1 /* ClassElementKeywords */: + return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + case 2 /* ConstructorParameterKeywords */: + return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + } + } + function getAllKeywordCompletions() { + var allKeywordsCompletions = []; + for (var i = 72 /* FirstKeyword */; i <= 142 /* LastKeyword */; i++) { + allKeywordsCompletions.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); + } + return allKeywordsCompletions; + } + function getFilteredKeywordCompletions(filterFn) { + return ts.filter(getKeywordCompletions(0 /* None */), function (entry) { return filterFn(entry.name); }); + } } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -74940,9 +77263,18 @@ var ts; function isClassMemberCompletionKeywordText(text) { return isClassMemberCompletionKeyword(ts.stringToToken(text)); } - var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { - return isClassMemberCompletionKeywordText(entry.name); - }); + function isConstructorParameterCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + return true; + } + } + function isConstructorParameterCompletionKeywordText(text) { + return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); + } function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -74952,6 +77284,36 @@ var ts; kind === 34 /* EqualsEqualsEqualsToken */ || kind === 35 /* ExclamationEqualsEqualsToken */; } + /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ + function getJsDocTagAtPosition(node, position) { + var jsDoc = getJsDocHavingNode(node).jsDoc; + if (!jsDoc) + return undefined; + for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) { + var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags; + if (!tags || position < pos || position > end) + continue; + for (var i = tags.length - 1; i >= 0; i--) { + var tag = tags[i]; + if (position >= tag.pos) { + return tag; + } + } + } + } + function getJsDocHavingNode(node) { + if (!ts.isToken(node)) + return node; + switch (node.kind) { + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + // if the current token is var, let or const, skip the VariableDeclarationList + return node.parent.parent; + default: + return node.parent; + } + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -74960,17 +77322,28 @@ var ts; var DocumentHighlights; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + // Note that getTouchingWord indicates failure by returning the sourceFile node. + if (node === sourceFile) + return undefined; + ts.Debug.assert(node.parent !== undefined); + if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + // For a JSX element, just highlight the matching tag, not all references. + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var end = node.getEnd(); return { fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: ts.HighlightSpanKind.none + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" /* none */ }; } function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { @@ -75224,7 +77597,7 @@ var ts; case 265 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { - nodes = declaration.members.concat(declaration); + nodes = declaration.members.concat([declaration]); } else { nodes = container.statements; @@ -75247,7 +77620,7 @@ var ts; } } else if (modifierFlag & 128 /* Abstract */) { - nodes = nodes.concat(container); + nodes = nodes.concat([container]); } break; default: @@ -75451,7 +77824,7 @@ var ts; result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: ts.HighlightSpanKind.reference + kind: "reference" /* reference */ }); i++; // skip the next keyword continue; @@ -75468,7 +77841,7 @@ var ts; */ function isLabeledBy(node, labelName) { for (var owner = node.parent; owner.kind === 222 /* LabeledStatement */; owner = owner.parent) { - if (owner.label.text === labelName) { + if (owner.label.escapedText === labelName) { return true; } } @@ -75490,7 +77863,7 @@ var ts; function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createFileMap()); + buckets.set(key, bucket = ts.createMap()); } return bucket; } @@ -75498,9 +77871,9 @@ var ts; var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); var sourceFiles = []; - entries.forEachValue(function (key, entry) { + entries.forEach(function (entry, name) { sourceFiles.push({ - name: key, + name: name, refCount: entry.languageServiceRefCount, references: entry.owners.slice(0) }); @@ -75573,7 +77946,7 @@ var ts; entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(path); + bucket.delete(path); } } return { @@ -75642,7 +78015,7 @@ var ts; } function handleDirectImports(exportingModuleSymbol) { var theseDirectImports = getDirectImports(exportingModuleSymbol); - if (theseDirectImports) + if (theseDirectImports) { for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { var direct = theseDirectImports_1[_i]; if (!markSeenDirectImport(direct)) { @@ -75688,6 +78061,7 @@ var ts; break; } } + } } function handleNamespaceImport(importDeclaration, name, isReExport) { if (exportKind === 2 /* ExportEquals */) { @@ -75721,11 +78095,12 @@ var ts; var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); var directImports = getDirectImports(moduleSymbol); - if (directImports) + if (directImports) { for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { var directImport = directImports_1[_i]; addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); } + } } function getDirectImports(moduleSymbol) { return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); @@ -75737,17 +78112,18 @@ var ts; * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. */ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.name; + var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { importSearches.push([location, symbol]); } - if (directImports) + if (directImports) { for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { var decl = directImports_2[_i]; handleImport(decl); } + } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { if (decl.kind === 237 /* ImportEqualsDeclaration */) { @@ -75785,7 +78161,7 @@ var ts; var name = importClause.name; // If a default import has the same name as the default export, allow to rename it. // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.text === symbolName(exportSymbol))) { + if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { var defaultImportAlias = checker.getSymbolAtLocation(name); addSearch(name, defaultImportAlias); } @@ -75803,16 +78179,16 @@ var ts; */ function handleNamespaceImportLike(importName) { // Don't rename an import that already has a different name than the export. - if (exportKind === 2 /* ExportEquals */ && (!isForRename || importName.text === exportName)) { + if (exportKind === 2 /* ExportEquals */ && (!isForRename || importName.escapedText === exportName)) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) + if (namedBindings) { for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var element = _a[_i]; var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).text !== exportName) { + if ((propertyName || name).escapedText !== exportName) { continue; } if (propertyName) { @@ -75830,6 +78206,7 @@ var ts; addSearch(name, localSymbol); } } + } } } /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ @@ -75962,24 +78339,22 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; - if (symbol.flags & 7340032 /* Export */) { + if (symbol.exportSymbol) { if (parent.kind === 179 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && parent.parent.kind === 194 /* BinaryExpression */ + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) : undefined; } else { - var exportSymbol = symbol.exportSymbol; - ts.Debug.assert(!!exportSymbol); - return exportInfo(exportSymbol, getExportKindForDeclaration(parent)); + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); } } else { - var exportNode = getExportNode(parent); + var exportNode = getExportNode(parent, node); if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) { - if (exportNode.kind === 237 /* ImportEqualsDeclaration */ && exportNode.moduleReference === node) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. if (comingFromExport) { return undefined; @@ -75991,19 +78366,25 @@ var ts; return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } } - else if (parent.kind === 243 /* ExportAssignment */) { - // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = parent.symbol.parent; - ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 /* ExportEquals */ } }; + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); } - else if (parent.kind === 194 /* BinaryExpression */) { + else if (ts.isExportAssignment(parent.parent)) { + return getExportAssignmentExport(parent.parent); + } + else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (parent.parent.kind === 194 /* BinaryExpression */) { + else if (ts.isBinaryExpression(parent.parent)) { return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); } } + function getExportAssignmentExport(ex) { + // Get the symbol for the `export =` node; its parent is the module it's the export of. + var exportingModuleSymbol = ex.symbol.parent; + ts.Debug.assert(!!exportingModuleSymbol); + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 /* ExportEquals */ } }; + } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; switch (ts.getSpecialPropertyAssignmentKind(node)) { @@ -76023,19 +78404,19 @@ var ts; function getImport() { var isImport = isNodeImport(node); if (!isImport) - return; + return undefined; // A symbol being imported is always an alias. So get what that aliases to find the local symbol. var importedSymbol = checker.getImmediateAliasedSymbol(symbol); - if (importedSymbol) { - // Search on the local symbol in the exporting module, not the exported symbol. - importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); - // Similarly, skip past the symbol for 'export =' - if (importedSymbol.name === "export=") { - importedSymbol = checker.getImmediateAliasedSymbol(importedSymbol); - } - if (symbolName(importedSymbol) === symbol.name) { - return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); - } + if (!importedSymbol) + return undefined; + // Search on the local symbol in the exporting module, not the exported symbol. + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + // Similarly, skip past the symbol for 'export =' + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + if (symbolName(importedSymbol) === symbol.escapedName) { + return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } function exportInfo(symbol, kind) { @@ -76048,11 +78429,26 @@ var ts; } } FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152 /* Alias */) { + return checker.getImmediateAliasedSymbol(importedSymbol); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { + return decl.expression.symbol; + } + else if (ts.isBinaryExpression(decl)) { + return decl.right.symbol; + } + ts.Debug.fail(); + } + // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. - function getExportNode(parent) { + function getExportNode(parent, node) { if (parent.kind === 226 /* VariableDeclaration */) { var p = parent; - return p.parent.kind === 260 /* CatchClause */ ? undefined : p.parent.parent.kind === 208 /* VariableStatement */ ? p.parent.parent : undefined; + return p.name !== node ? undefined : + p.parent.kind === 260 /* CatchClause */ ? undefined : p.parent.parent.kind === 208 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -76083,27 +78479,28 @@ var ts; } FindAllReferences.getExportInfo = getExportInfo; function symbolName(symbol) { - if (symbol.name !== "default") { - return symbol.name; + if (symbol.escapedName !== "default") { + return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; } var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ && name.text; + return name && name.kind === 71 /* Identifier */ && name.escapedText; }); } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. - if (symbol.declarations) + if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { return checker.getExportSpecifierLocalTargetSymbol(declaration); } } + } return symbol; } function getContainingModuleSymbol(importer, checker) { @@ -76157,13 +78554,17 @@ var ts; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + // A node in a JSDoc comment can't have an implementation anyway. + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); 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(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265 /* SourceFile */) { + return undefined; + } 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). @@ -76211,22 +78612,22 @@ var ts; } case "label": { var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: ts.ScriptElementKind.label, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: ts.ScriptElementKind.keyword, displayParts: [{ text: name_4, kind: ts.ScriptElementKind.keyword }] }; + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: ts.ScriptElementKind.variableElement, displayParts: displayParts_2 }; + return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: ts.ScriptElementKind.variableElement, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -76236,7 +78637,7 @@ var ts; var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); return { - containerKind: "", + containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, @@ -76258,7 +78659,7 @@ var ts; fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -76269,7 +78670,7 @@ var ts; } else { var textSpan = entry.textSpan, fileName = entry.fileName; - return { textSpan: textSpan, fileName: fileName, kind: ts.ScriptElementKind.unknown, displayParts: [] }; + return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] }; } } function implementationKindDisplayParts(node, checker) { @@ -76279,13 +78680,13 @@ var ts; } else if (node.kind === 178 /* ObjectLiteralExpression */) { return { - kind: ts.ScriptElementKind.interfaceElement, + kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } else if (node.kind === 199 /* ClassExpression */) { return { - kind: ts.ScriptElementKind.localClassElement, + kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] }; } @@ -76296,14 +78697,14 @@ var ts; function toHighlightSpan(entry) { if (entry.type === "span") { var fileName_1 = entry.fileName, textSpan = entry.textSpan; - return { fileName: fileName_1, span: { textSpan: textSpan, kind: ts.HighlightSpanKind.reference } }; + return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; var writeAccess = isWriteAccess(node); var span = { textSpan: getTextSpan(node), - kind: writeAccess ? ts.HighlightSpanKind.writtenReference : ts.HighlightSpanKind.reference, + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: isInString }; return { fileName: fileName, span: span }; @@ -76320,20 +78721,19 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccess(node) { - if (node.kind === 71 /* Identifier */ && ts.isDeclarationName(node)) { + if (ts.isAnyDeclarationName(node)) { return true; } var parent = node.parent; - if (parent) { - if (parent.kind === 193 /* PostfixUnaryExpression */ || parent.kind === 192 /* PrefixUnaryExpression */) { + switch (parent && parent.kind) { + case 193 /* PostfixUnaryExpression */: + case 192 /* PrefixUnaryExpression */: return true; - } - else if (parent.kind === 194 /* BinaryExpression */ && parent.left === node) { - var operator = parent.operatorToken.kind; - return 58 /* FirstAssignment */ <= operator && operator <= 70 /* LastAssignment */; - } + case 194 /* BinaryExpression */: + return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); + default: + return false; } - return false; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -76384,7 +78784,7 @@ var ts; case 244 /* ExportDeclaration */: return true; case 181 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -76453,7 +78853,7 @@ var ts; // Compute the meaning from the location and the symbol it references var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; - var state = createState(sourceFiles, node, checker, cancellationToken, searchMeaning, options, result); + var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). @@ -76483,53 +78883,94 @@ var ts; } return symbol; } - function createState(sourceFiles, originalLocation, checker, cancellationToken, searchMeaning, options, result) { - var symbolIdToReferences = []; - var inheritsFromCache = ts.createMap(); - // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. - var sourceFileToSeenSymbols = []; - var isForConstructor = originalLocation.kind === 123 /* ConstructorKeyword */; - var importTracker; - return __assign({}, options, { sourceFiles: sourceFiles, isForConstructor: isForConstructor, checker: checker, cancellationToken: cancellationToken, searchMeaning: searchMeaning, inheritsFromCache: inheritsFromCache, getImportSearches: getImportSearches, createSearch: createSearch, referenceAdder: referenceAdder, addStringOrCommentReference: addStringOrCommentReference, - markSearchedSymbol: markSearchedSymbol, markSeenContainingTypeReference: ts.nodeSeenTracker(), markSeenReExportRHS: ts.nodeSeenTracker() }); - function getImportSearches(exportSymbol, exportInfo) { - if (!importTracker) - importTracker = FindAllReferences.createImportTracker(sourceFiles, checker, cancellationToken); - return importTracker(exportSymbol, exportInfo, options.isForRename); + /** + * Holds all state needed for the finding references. + * Unlike `Search`, there is only one `State`. + */ + var State = (function () { + function State(sourceFiles, + /** True if we're searching for constructor references. */ + isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.isForConstructor = isForConstructor; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ + this.inheritsFromCache = ts.createMap(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. + this.sourceFileToSeenSymbols = []; } - function createSearch(location, symbol, comingFrom, searchOptions) { + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + }; + /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; - var escapedText = ts.escapeIdentifier(text); - var parents = options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, checker); - return { location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: includes }; - function includes(referenceSymbol) { - return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; - } - } - function referenceAdder(referenceSymbol, searchLocation) { - var symbolId = ts.getSymbolId(referenceSymbol); - var references = symbolIdToReferences[symbolId]; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + return { + location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, + }; + }; + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ + State.prototype.referenceAdder = function (searchSymbol, searchLocation) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; if (!references) { - references = symbolIdToReferences[symbolId] = []; - result.push({ definition: { type: "symbol", symbol: referenceSymbol, node: searchLocation }, references: references }); + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; - } - function addStringOrCommentReference(fileName, textSpan) { - result.push({ + }; + /** Add a reference with no associated definition. */ + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ definition: undefined, references: [{ type: "span", fileName: fileName, textSpan: textSpan }] }); - } - function markSearchedSymbol(sourceFile, symbol) { + }; + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ + State.prototype.markSearchedSymbol = function (sourceFile, symbol) { var sourceId = ts.getNodeId(sourceFile); var symbolId = ts.getSymbolId(symbol); - var seenSymbols = sourceFileToSeenSymbols[sourceId] || (sourceFileToSeenSymbols[sourceId] = []); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []); return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true); - } - } + }; + return State; + }()); /** Search for all imports of a given exported symbol using `State.getImportSearches`. */ function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; @@ -76554,7 +78995,7 @@ var ts; break; case 1 /* Default */: // Search for a property access to '.default'. This can't be renamed. - indirectSearch = state.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); break; case 2 /* ExportEquals */: break; @@ -76584,15 +79025,17 @@ var ts; return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && checker.getPropertySymbolOfDestructuringAssignment(location); } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { + function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 176 /* BindingElement */); - return bindingElement && + if (bindingElement && bindingElement.parent.kind === 174 /* ObjectBindingPattern */ && - !bindingElement.propertyName; + !bindingElement.propertyName) { + return bindingElement; + } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176 /* BindingElement */); + var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); + if (bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } @@ -76618,14 +79061,16 @@ var ts; } // If this is private property or method, the scope is the containing class if (flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.find(declarations, function (d) { return !!(ts.getModifierFlags(d) & 8 /* Private */); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 229 /* ClassDeclaration */); } + // Else this is a public property and could be accessed from anywhere. + return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + if (getObjectBindingElementWithoutPropertyName(symbol)) { return undefined; } // If the symbol has a parent, it's globally visible. @@ -76634,10 +79079,6 @@ var ts; if (parent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } - // If this is a synthetic property, it's a property and must be searched for globally. - if ((flags & 134217728 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */)) { - return undefined; - } var scope; for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var declaration = declarations_10[_i]; @@ -76661,11 +79102,8 @@ 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, container, fullStart) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { 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. @@ -76676,10 +79114,10 @@ var ts; var text = sourceFile.text; var sourceLength = text.length; var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); + var position = text.indexOf(symbolName, container.pos); while (position >= 0) { // If we are past the end, stop looking - if (position > end) + if (position > container.end) break; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). @@ -76700,7 +79138,7 @@ var ts; 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); + var node = ts.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 && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); @@ -76712,7 +79150,7 @@ 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 ts.unescapeIdentifier(node.text).length === searchSymbolName.length; + return node.text.length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && node.text.length === searchSymbolName.length; @@ -76732,10 +79170,10 @@ var ts; return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -76754,18 +79192,18 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments); _i < _a.length; _i++) { + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.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 // match in a comment or string if that's what the caller is asking // for. - if (!state.implementations && (state.findInStrings && ts.isInString(sourceFile, position) || state.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { // In the case where we're looking inside comments/strings, we don't have // an actual definition. So just use 'undefined' here. Features like // 'Rename' won't care (as they ignore the definitions), and features like @@ -76820,7 +79258,7 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.isForRename && state.markSeenReExportRHS(name)) { + if (!state.options.isForRename && state.markSeenReExportRHS(name)) { addReference(name, referenceSymbol, name, state); } } @@ -76830,7 +79268,7 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.isForRename)) { + if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); ts.Debug.assert(!!exportInfo); @@ -76866,7 +79304,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename || importOrExport.isNamedImport) { searchForImportedSymbol(symbol, state); } } @@ -76885,13 +79323,13 @@ var ts; * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the * position of property accessing, the referenceEntry of such position will be handled in the first case. */ - if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { + if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) { addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { var addRef = state.referenceAdder(relatedSymbol, searchLocation); - if (state.implementations) { + if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { @@ -76925,7 +79363,7 @@ var ts; * Reference the constructor and all calls to `new this()`. */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor").declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); ts.Debug.assert(decl.kind === 152 /* Constructor */ && !!ctrKeyword); @@ -76948,7 +79386,7 @@ var ts; /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor"); + var ctr = symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } @@ -76992,15 +79430,16 @@ var ts; addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { - if (parent.body.kind === 207 /* Block */) { - ts.forEachReturnStatement(parent.body, function (returnStatement) { + var body = parent.body; + if (body.kind === 207 /* Block */) { + ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); } }); } - else if (isImplementationExpression(parent.body)) { - addReference(parent.body); + else if (isImplementationExpression(body)) { + addReference(body); } } else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { @@ -77155,7 +79594,7 @@ var ts; 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); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; } @@ -77221,7 +79660,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || !ts.isThis(node)) { return; } @@ -77271,7 +79710,7 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + var node_7 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); } @@ -77339,7 +79778,7 @@ var ts; } // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap(), checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); } } return result; @@ -77367,7 +79806,7 @@ var ts; // the function will add any found symbol of the property-name, then its sub-routine will call // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. - if (previousIterationSymbolsCache.has(symbol.name)) { + if (previousIterationSymbolsCache.has(symbol.escapedName)) { return; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -77391,7 +79830,7 @@ var ts; result.push.apply(result, checker.getRootSymbols(propertySymbol)); } // Visit the typeReference as well to see if it directly or indirectly use that property - previousIterationSymbolsCache.set(symbol.name, symbol); + previousIterationSymbolsCache.set(symbol.escapedName, symbol); getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); } } @@ -77444,7 +79883,7 @@ var ts; return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); return ts.find(result, search.includes); } return undefined; @@ -77459,7 +79898,7 @@ var ts; } return undefined; } - return node.name.text; + return ts.getTextOfIdentifierOrLiteral(node.name); } /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { @@ -77615,7 +80054,7 @@ var ts; if (referenceFile) { return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; } - return undefined; + // Might still be on jsdoc, so keep looking. } // Type reference directives var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); @@ -77624,15 +80063,15 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } // Labels if (ts.isJumpStatementTarget(node)) { var labelName = node.text; - var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, ts.ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, labelName); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -77649,7 +80088,7 @@ 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 */ && shouldSkipAlias(node, symbol.declarations[0])) { + if (symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = typeChecker.getAliasedSymbol(symbol); if (aliased.declarations) { symbol = aliased; @@ -77691,7 +80130,7 @@ var ts; GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -77761,8 +80200,7 @@ var ts; for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { var declaration = _a[_i]; if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, - /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); + return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); } } ts.Debug.fail("Expected declaration to have at least one class-like declaration"); @@ -77848,7 +80286,7 @@ var ts; return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ts.ScriptElementKind.scriptElement, + kind: "script" /* scriptElement */, name: name, containerName: undefined, containerKind: undefined @@ -77934,19 +80372,14 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getCommentsFromJSDoc(declaration); - if (!comments) { - return; - } - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var comment = comments_3[_i]; - if (comment) { + ts.forEach(ts.getAllJSDocs(declaration), function (doc) { + if (doc.comment) { if (documentationComment.length) { documentationComment.push(ts.lineBreakPart()); } - documentationComment.push(ts.textPart(comment)); + documentationComment.push(ts.textPart(doc.comment)); } - } + }); }); return documentationComment; } @@ -77955,20 +80388,10 @@ var ts; // Only collect doc comments from duplicate declarations once. var tags = []; forEachUnique(declarations, function (declaration) { - var jsDocs = ts.getJSDocs(declaration); - if (!jsDocs) { - return; - } - for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { - var doc = jsDocs_1[_i]; - var tagsForDoc = doc.tags; - if (tagsForDoc) { - tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 284 /* JSDocTag */; }).map(function (jsDocTag) { - return { - name: jsDocTag.tagName.text, - text: jsDocTag.comment - }; - })); + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 276 /* JSDocTag */) { + tags.push({ name: tag.tagName.text, text: tag.comment }); } } }); @@ -77997,7 +80420,7 @@ var ts; return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword" /* keyword */, kindModifiers: "", sortText: "0", }; @@ -78008,13 +80431,34 @@ var ts; return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: "@" + tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword" /* keyword */, kindModifiers: "", sortText: "0" }; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. @@ -78040,7 +80484,7 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -78084,7 +80528,7 @@ var ts; for (var i = 0; i < parameters.length; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 71 /* Identifier */ ? - currentName.text : + currentName.escapedText : "param" + i; if (isJavaScriptFile) { docParams += indentationStr + " * @param {any} " + paramName + newLine; @@ -78161,10 +80605,6 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - // A map of loose file names to library names - // that we are confident require typings - var safeList; - var EmptySafeList = ts.createMap(); /* @internal */ JsTyping.nodeCoreModuleList = [ "buffer", "querystring", "events", "http", "cluster", @@ -78175,6 +80615,11 @@ var ts; "constants", "process", "v8", "timers", "console" ]; var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -78184,53 +80629,41 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { - // A typing name to typing file path mapping - var inferredTypings = ts.createMap(); + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 /* JS */ || kind === 2 /* JSX */; + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMapFromTemplate(result.config) : EmptySafeList; - } var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var searchDirs = []; - var exclude = []; - mergeTypings(typeAcquisition.include); - exclude = typeAcquisition.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { var packageJsonPath = ts.combinePaths(searchDir, "package.json"); getTypingNamesFromJson(packageJsonPath, filesToWatch); var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); getTypingNamesFromJson(bowerJsonPath, filesToWatch); var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath); - } + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); getTypingNamesFromSourceFileNames(fileNames); // add typings for unresolved imports if (unresolvedImports) { - for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { - var moduleId = unresolvedImports_1[_a]; - var typingName = nodeCoreModules.has(moduleId) ? "node" : moduleId; - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } + var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + addInferredTypings(module, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typingLocation, name) { @@ -78239,9 +80672,11 @@ var ts; } }); // Remove typings that the user has added to the exclude list - for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { - var excludeTypingName = exclude_1[_b]; - inferredTypings.delete(excludeTypingName); + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); } var newTypingNames = []; var cachedTypingPaths = []; @@ -78253,44 +80688,31 @@ var ts; newTypingNames.push(typing); } }); - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - /** - * Merge a given list of typingNames to the inferredTypings map - */ - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!inferredTypings.has(typing)) { - inferredTypings.set(typing, undefined); - } + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); } } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } /** * Get the typing info from common package manager json files like package.json or bower.json */ function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (host.fileExists(jsonPath)) { - filesToWatch.push(jsonPath); - } - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } + if (!host.fileExists(jsonPath)) { + return; } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); } /** * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" @@ -78299,29 +80721,38 @@ var ts; * @param fileNames are the names for source files in the project */ function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return safeList.has(f); })); + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); if (hasJsxFile) { - mergeTypings(["react"]); + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); } } /** * Infer typing names from packages folder (ex: node_module, bower_components) * @param packagesFolderPath is the path to the packages folder */ - function getTypingNamesFromPackagesFolder(packagesFolderPath) { + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { filesToWatch.push(packagesFolderPath); // Todo: add support for ModuleResolutionHost too if (!host.directoryExists(packagesFolderPath)) { return; } - var typingNames = []; + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` var fileNames = host.readDirectory(packagesFolderPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -78329,11 +80760,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; + var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_8.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -78346,15 +80774,18 @@ var ts; if (!packageJson.name) { continue; } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); inferredTypings.set(packageJson.name, absolutePath); } else { - typingNames.push(packageJson.name); + packageNames.push(packageJson.name); } } - mergeTypings(typingNames); + addInferredTypings(packageNames, " Found package names"); } } JsTyping.discoverTypings = discoverTypings; @@ -78368,9 +80799,9 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; } ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { @@ -78405,7 +80836,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_6(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. rawItems = ts.filter(rawItems, function (item) { @@ -78413,7 +80844,7 @@ var ts; if (decl.kind === 239 /* ImportClause */ || decl.kind === 242 /* ImportSpecifier */ || decl.kind === 237 /* ImportEqualsDeclaration */) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); - return importer.name !== imported.name; + return importer.escapedName !== imported.escapedName; } else { return true; @@ -78436,21 +80867,11 @@ var ts; } return true; } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - node.kind === 8 /* NumericLiteral */) { - return node.text; - } - } - return undefined; - } function tryAddSingleDeclarationName(declaration, containers) { if (declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var text = getTextOfIdentifierOrLiteral(name); + var text = ts.getTextOfIdentifierOrLiteral(name); if (text !== undefined) { containers.unshift(text); } @@ -78469,7 +80890,7 @@ var ts; // // [X.Y.Z]() { } function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = getTextOfIdentifierOrLiteral(expression); + var text = ts.getTextOfIdentifierOrLiteral(expression); if (text !== undefined) { if (includeLastPortion) { containers.unshift(text); @@ -78540,7 +80961,7 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ }; } } @@ -78780,7 +81201,7 @@ var ts; default: ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 290 /* JSDocTypedefTag */) { + if (tag.kind === 283 /* JSDocTypedefTag */) { addLeafNode(tag); } }); @@ -78884,14 +81305,14 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.getPropertyNameForPropertyNameNode(declName); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { case 186 /* FunctionExpression */: case 187 /* ArrowFunction */: case 199 /* ClassExpression */: return getFunctionOrClassName(node); - case 290 /* JSDocTypedefTag */: + case 283 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return undefined; @@ -78934,7 +81355,7 @@ var ts; return "()"; case 157 /* IndexSignature */: return "[]"; - case 290 /* JSDocTypedefTag */: + case 283 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return ""; @@ -78982,7 +81403,7 @@ var ts; case 233 /* ModuleDeclaration */: case 265 /* SourceFile */: case 231 /* TypeAliasDeclaration */: - case 290 /* JSDocTypedefTag */: + case 283 /* JSDocTypedefTag */: return true; case 152 /* Constructor */: case 151 /* MethodDeclaration */: @@ -79069,10 +81490,10 @@ var ts; } // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); while (moduleDeclaration.body && moduleDeclaration.body.kind === 233 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } return result.join("."); } @@ -79137,7 +81558,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_13); } @@ -79148,7 +81569,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_14); } @@ -79160,8 +81581,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { - var currentComment = comments_4[_i]; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var currentComment = comments_3[_i]; cancellationToken.throwIfCancellationRequested(); // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last @@ -79891,13 +82312,9 @@ var ts; }); } function getFileReference() { - var file = ts.scanner.getTokenValue(); + var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; + return { fileName: fileName, pos: pos, end: pos + fileName.length }; } function recordAmbientExternalModule() { if (!ambientExternalModules) { @@ -79939,7 +82356,15 @@ var ts; var token = ts.scanner.getToken(); if (token === 91 /* ImportKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 19 /* OpenParenToken */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import("mod"); + recordModuleName(); + return true; + } + } + else if (token === 9 /* StringLiteral */) { // import "mod"; recordModuleName(); return true; @@ -80123,7 +82548,7 @@ var ts; // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); - // + // import("mod"); // export * from "mod" // export {a as b} from "mod" // export import i = require("mod") @@ -80230,7 +82655,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } var displayName = ts.stripQuotes(node.text); - return getRenameInfoSuccess(displayName, displayName, ts.ScriptElementKind.variableElement, ts.ScriptElementKindModifier.none, node, sourceFile); + return getRenameInfoSuccess(displayName, displayName, "var" /* variableElement */, "" /* none */, node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -80279,7 +82704,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var emptyArray = []; var ArgumentListKind; (function (ArgumentListKind) { ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; @@ -80296,14 +82720,13 @@ var ts; return undefined; } var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); + if (!argumentInfo) + return undefined; cancellationToken.throwIfCancellationRequested(); // Semantic filtering of signature help - if (!argumentInfo) { - return undefined; - } var call = argumentInfo.invocation; var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates); + var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { // We didn't have any sig help items produced by the TS compiler. If this is a JS @@ -80328,7 +82751,7 @@ var ts; : expression.kind === 179 /* PropertyAccessExpression */ ? expression.name : undefined; - if (!name || !name.text) { + if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -80359,7 +82782,9 @@ var ts; */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { if (ts.isCallOrNewExpression(node.parent)) { - var callExpression = node.parent; + var invocation = node.parent; + var list = void 0; + var argumentIndex = void 0; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -80374,43 +82799,30 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 27 /* LessThanToken */ || - node.kind === 19 /* OpenParenToken */) { + if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); ts.Debug.assert(list !== undefined); - return { - kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: 0, - argumentCount: getArgumentCount(list) - }; + argumentIndex = 0; } - // findListItemInfo can return undefined if we are not in parent's argument list - // or type argument list. This includes cases where the cursor is: - // - To the right of the closing parenthesis, non-substitution template, or template tail. - // - Between the type arguments and the arguments (greater than token) - // - On the target of the call (parent.func) - // - On the 'new' keyword in a 'new' expression - var listItemInfo = ts.findListItemInfo(node); - if (listItemInfo) { - var list = listItemInfo.list; - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; - var argumentIndex = getArgumentIndex(list, node); - var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + list = ts.findContainingList(node); + if (!list) + return undefined; + argumentIndex = getArgumentIndex(list, node); } - return undefined; + var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; + var argumentCount = getArgumentCount(list); + ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 183 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; @@ -80598,33 +83010,9 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } - /** - * The selectedItemIndex could be negative for several reasons. - * 1. There are too many arguments for all of the overloads - * 2. None of the overloads were type compatible - * The solution here is to try to pick the best overload by picking - * either the first one that has an appropriate number of parameters, - * or the one with the most parameters. - */ - function selectBestInvalidOverloadIndex(candidates, argumentCount) { - var maxParamsSignatureIndex = -1; - var maxParams = -1; - for (var i = 0; i < candidates.length; i++) { - var candidate = candidates[i]; - if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { - return i; - } - if (candidate.parameters.length > maxParams) { - maxParams = candidate.parameters.length; - maxParamsSignatureIndex = i; - } - } - return maxParamsSignatureIndex; - } - function createSignatureHelpItems(candidates, bestSignature, argumentListInfo, typeChecker) { - var applicableSpan = argumentListInfo.argumentsSpan; + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var invocation = argumentListInfo.invocation; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); @@ -80639,8 +83027,9 @@ var ts; if (isTypeParameterList) { isVariadic = false; // type parameter lists are not variadic prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - var typeParameters = candidateSignature.typeParameters; - signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; + // Use `.mapper` to ensure we get the generic type arguments even if this is an instantiated version of the signature. + var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); @@ -80654,8 +83043,7 @@ var ts; }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - var parameters = candidateSignature.parameters; - signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; + signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { @@ -80672,21 +83060,10 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - var argumentIndex = argumentListInfo.argumentIndex; - // argumentCount is the *apparent* number of arguments. - var argumentCount = argumentListInfo.argumentCount; - var selectedItemIndex = candidates.indexOf(bestSignature); - if (selectedItemIndex < 0) { - selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount); - } ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - items: items, - applicableSpan: applicableSpan, - selectedItemIndex: selectedItemIndex, - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); @@ -80704,7 +83081,7 @@ var ts; }); return { name: typeParameter.symbol.name, - documentation: emptyArray, + documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; @@ -80719,72 +83096,73 @@ var ts; (function (SymbolDisplay) { // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { - var flags = symbol.flags; - if (flags & 32 /* Class */) + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32 /* Class */) { return ts.getDeclarationOfKind(symbol, 199 /* ClassExpression */) ? - ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + "local class" /* localClassElement */ : "class" /* classElement */; + } if (flags & 384 /* Enum */) - return ts.ScriptElementKind.enumElement; + return "enum" /* enumElement */; if (flags & 524288 /* TypeAlias */) - return ts.ScriptElementKind.typeElement; + return "type" /* typeElement */; if (flags & 64 /* Interface */) - return ts.ScriptElementKind.interfaceElement; + return "interface" /* interfaceElement */; if (flags & 262144 /* TypeParameter */) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter" /* typeParameterElement */; var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - if (result === ts.ScriptElementKind.unknown) { + if (result === "" /* unknown */) { if (flags & 262144 /* TypeParameter */) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter" /* typeParameterElement */; if (flags & 8 /* EnumMember */) - return ts.ScriptElementKind.enumMemberElement; - if (flags & 8388608 /* Alias */) - return ts.ScriptElementKind.alias; + return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) + return "alias" /* alias */; if (flags & 1536 /* Module */) - return ts.ScriptElementKind.moduleElement; + return "module" /* moduleElement */; } return result; } SymbolDisplay.getSymbolKind = getSymbolKind; function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { if (typeChecker.isUndefinedSymbol(symbol)) { - return ts.ScriptElementKind.variableElement; + return "var" /* variableElement */; } if (typeChecker.isArgumentsSymbol(symbol)) { - return ts.ScriptElementKind.localVariableElement; + return "local var" /* localVariableElement */; } if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) { - return ts.ScriptElementKind.parameterElement; + return "parameter" /* parameterElement */; } - var flags = symbol.flags; + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 3 /* Variable */) { if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ts.ScriptElementKind.parameterElement; + return "parameter" /* parameterElement */; } else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ts.ScriptElementKind.constElement; + return "const" /* constElement */; } else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ts.ScriptElementKind.letElement; + return "let" /* letElement */; } - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; } if (flags & 16 /* Function */) - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; if (flags & 32768 /* GetAccessor */) - return ts.ScriptElementKind.memberGetAccessorElement; + return "getter" /* memberGetAccessorElement */; if (flags & 65536 /* SetAccessor */) - return ts.ScriptElementKind.memberSetAccessorElement; + return "setter" /* memberSetAccessorElement */; if (flags & 8192 /* Method */) - return ts.ScriptElementKind.memberFunctionElement; + return "method" /* memberFunctionElement */; if (flags & 16384 /* Constructor */) - return ts.ScriptElementKind.constructorImplementationElement; + return "constructor" /* constructorImplementationElement */; if (flags & 4 /* Property */) { - if (flags & 134217728 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { + if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { // If union property is result of union of non method (property/accessors/variables), it is labeled as property var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { - return ts.ScriptElementKind.memberVariableElement; + return "property" /* memberVariableElement */; } ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); }); @@ -80793,23 +83171,23 @@ var ts; // make sure it has call signatures before we can label it as method var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { - return ts.ScriptElementKind.memberFunctionElement; + return "method" /* memberFunctionElement */; } - return ts.ScriptElementKind.memberVariableElement; + return "property" /* memberVariableElement */; } return unionPropertyKind; } if (location.parent && ts.isJsxAttribute(location.parent)) { - return ts.ScriptElementKind.jsxAttribute; + return "JSX attribute" /* jsxAttribute */; } - return ts.ScriptElementKind.memberVariableElement; + return "property" /* memberVariableElement */; } - return ts.ScriptElementKind.unknown; + return "" /* unknown */; } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) - : ts.ScriptElementKindModifier.none; + : "" /* none */; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location @@ -80818,19 +83196,19 @@ var ts; var displayParts = []; var documentation; var tags; - var symbolFlags = symbol.flags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; // Class at constructor site need to be shown as constructor apart from property,method, vars - if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { + if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor - if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { - symbolKind = ts.ScriptElementKind.memberVariableElement; + if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { + symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); if (type) { if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { var right = location.parent.name; @@ -80867,11 +83245,11 @@ var ts; if (signature) { if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { // Constructor - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - else if (symbolFlags & 8388608 /* Alias */) { - symbolKind = ts.ScriptElementKind.alias; + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { @@ -80884,13 +83262,13 @@ var ts; addPrefixForAnyFunctionOrVar(symbol, symbolKind); } switch (symbolKind) { - case ts.ScriptElementKind.jsxAttribute: - case ts.ScriptElementKind.memberVariableElement: - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.parameterElement: - case ts.ScriptElementKind.localVariableElement: + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: // If it is call or construct signature of lambda's write type name displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); @@ -80901,7 +83279,7 @@ var ts; if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } - addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -80910,7 +83288,7 @@ var ts; hasAddedSymbolInfo = true; } } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; @@ -80928,7 +83306,7 @@ var ts; } if (functionDeclaration_1.kind === 152 /* Constructor */) { // show (constructor) Type(...) signature - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { @@ -80947,7 +83325,7 @@ var ts; // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class - pushTypePart(ts.ScriptElementKind.localClassElement); + pushTypePart("local class" /* localClassElement */); } else { // Class declaration has name which is not local. @@ -80973,7 +83351,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); @@ -81022,7 +83400,7 @@ var ts; else if (declaration.kind !== 155 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 231 /* TypeAliasDeclaration */) { // Type alias type parameter @@ -81038,7 +83416,7 @@ var ts; } } if (symbolFlags & 8 /* EnumMember */) { - symbolKind = ts.ScriptElementKind.enumMemberElement; + symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; if (declaration.kind === 264 /* EnumMember */) { @@ -81051,7 +83429,7 @@ var ts; } } } - if (symbolFlags & 8388608 /* Alias */) { + if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); if (symbol.declarations[0].kind === 236 /* NamespaceExportDeclaration */) { displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -81089,7 +83467,7 @@ var ts; }); } if (!hasAddedSymbolInfo) { - if (symbolKind !== ts.ScriptElementKind.unknown) { + if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); @@ -81099,10 +83477,10 @@ var ts; addPrefixForAnyFunctionOrVar(symbol, symbolKind); } // For properties, variables and local vars: show the type - if (symbolKind === ts.ScriptElementKind.memberVariableElement || - symbolKind === ts.ScriptElementKind.jsxAttribute || + if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || - symbolKind === ts.ScriptElementKind.localVariableElement || + symbolKind === "local var" /* localVariableElement */ || isThisExpression) { displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); @@ -81122,7 +83500,7 @@ var ts; symbolFlags & 16384 /* Constructor */ || symbolFlags & 131072 /* Signature */ || symbolFlags & 98304 /* Accessor */ || - symbolKind === ts.ScriptElementKind.memberFunctionElement) { + symbolKind === "method" /* memberFunctionElement */) { var allSignatures = type.getNonNullableType().getCallSignatures(); addSignatureDisplayParts(allSignatures[0], allSignatures); } @@ -81135,7 +83513,7 @@ var ts; if (!documentation) { documentation = symbol.getDocumentationComment(); tags = symbol.getJsDocTags(); - if (documentation.length === 0 && symbol.flags & 4 /* Property */) { + if (documentation.length === 0 && symbolFlags & 4 /* Property */) { // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. @@ -81183,11 +83561,11 @@ var ts; } function pushTypePart(symbolKind) { switch (symbolKind) { - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.functionElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.constructorImplementationElement: + case "var" /* variableElement */: + case "function" /* functionElement */: + case "let" /* letElement */: + case "const" /* constElement */: + case "constructor" /* constructorImplementationElement */: displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: @@ -81198,7 +83576,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -81345,8 +83723,8 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); - options = ts.clone(options); - var _loop_5 = function (opt) { + options = ts.cloneCompilerOptions(options); + var _loop_7 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -81365,7 +83743,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_7(opt); } return options; } @@ -81589,11 +83967,7 @@ var ts; break; } } - lastTokenInfo = { - leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia, - token: token - }; + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } function isOnToken() { @@ -81719,7 +84093,8 @@ var ts; FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81861,9 +84236,9 @@ var ts; } return true; }; + RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); - RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81903,13 +84278,13 @@ var ts; this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); // Place a space before open brace in a function declaration this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a control flow construct this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); @@ -82155,6 +84530,9 @@ var ts; Rules.IsOptionDisabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; }; + Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + }; Rules.IsOptionEnabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; }; @@ -82206,24 +84584,8 @@ var ts; Rules.IsConditionalOperatorContext = function (context) { return context.contextNode.kind === 195 /* ConditionalExpression */; }; - Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { - //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. - //// - //// Ex: - //// if (1) { .... - //// * ) and { are on the same line so apply the rule. Here we don't care whether it's same or multi block context - //// - //// Ex: - //// if (1) - //// { ... } - //// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we don't format. - //// - //// Ex: - //// if (1) - //// { ... - //// } - //// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we format. - return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); + Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { + return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); }; Rules.IsBraceWrappedContext = function (context) { return context.contextNode.kind === 174 /* ObjectBindingPattern */ || Rules.IsSingleLineBlockContext(context); @@ -82275,7 +84637,7 @@ var ts; // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 230 /* InterfaceDeclaration */: + case 230 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -82828,11 +85190,39 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 25 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + /** + * We limit the span to end at the opening curly to handle the case where + * the brace matched to that just typed will be incorrect after further edits. + * For example, we could type the opening curly for the following method + * body without brace-matching activated: + * ``` + * class C { + * foo() + * } + * ``` + * and we wouldn't want to move the closing brace. + */ + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, options, rulesProvider, 4 /* FormatOnOpeningCurlyBrace */); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 18 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -82847,46 +85237,39 @@ var ts; // format from the beginning of the line var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), - end: end + end: end, }; return formatSpan(span, sourceFile, options, rulesProvider, 1 /* FormatSelection */); } formatting.formatSelection = formatSelection; - function formatOutermostParent(position, expectedLastToken, sourceFile, options, rulesProvider, requestKind) { - var parent = findOutermostParent(position, expectedLastToken, sourceFile); - if (!parent) { - return []; - } - var span = { - pos: ts.getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile), - end: parent.end - }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + /** + * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment). + * @param expectedTokenKind The kind of the last token constituting the desired parent node. + */ + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; } - function findOutermostParent(position, expectedTokenKind, sourceFile) { - var precedingToken = ts.findPrecedingToken(position, sourceFile); - // when it is claimed that trigger character was typed at given position - // we verify that there is a token with a matching kind whose end is equal to position (because the character was just typed). - // If this condition is not hold - then trigger character was typed in some other context, - // i.e.in comment and thus should not trigger autoformatting - if (!precedingToken || - precedingToken.kind !== expectedTokenKind || - position !== precedingToken.getEnd()) { - return undefined; - } - // walk up and search for the parent node that ends at the same position with precedingToken. - // for cases like this - // - // let x = 1; - // while (true) { - // } - // after typing close curly in while statement we want to reformat just the while statement. - // However if we just walk upwards searching for the parent that has the same end value - - // we'll end up with the whole source file. isListElement allows to stop on the list element level - var current = precedingToken; + /** + * Finds the highest node enclosing `node` at the same list level as `node` + * and whose end does not exceed `node.end`. + * + * Consider typing the following + * ``` + * let x = 1; + * while (true) { + * } + * ``` + * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding + * variable declaration. + */ + function findOutermostNodeWithinListLevel(node) { + var current = node; while (current && current.parent && - current.parent.end === precedingToken.end && + current.parent.end === node.end && !isListElement(current.parent, current)) { current = current.parent; } @@ -83020,12 +85403,22 @@ var ts; return 0; } /* @internal */ - function formatNode(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors sourceFileLike); } - formatting.formatNode = formatNode; + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + } function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); @@ -83626,7 +86019,7 @@ var ts; if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } - // edit should not be applied only if we have one line feed between elements + // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); @@ -84342,7 +86735,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { // find first non-whitespace position in the leading trivia of the node var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -84354,7 +86747,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -84431,7 +86824,7 @@ var ts; if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -84550,7 +86943,7 @@ var ts; }; ChangeTracker.prototype.getChanges = function () { var _this = this; - var changesPerFile = ts.createFileMap(); + var changesPerFile = ts.createMap(); // group changes per file for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { var c = _a[_i]; @@ -84562,8 +86955,7 @@ var ts; } // convert changes var fileChangesList = []; - changesPerFile.forEachValue(function (path) { - var changesInFile = changesPerFile.get(path); + changesPerFile.forEach(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; var fileTextChanges = { fileName: sourceFile.fileName, textChanges: [] }; for (var _i = 0, _a = ChangeTracker.normalize(changesInFile); _i < _a.length; _i++) { @@ -84636,7 +87028,7 @@ var ts; lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNode(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } textChanges.applyFormatting = applyFormatting; @@ -84817,40 +87209,48 @@ var ts; } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - var results; - var refactorList = []; - refactors.forEach(function (refactor) { - refactorList.push(refactor); + return ts.flatMapIter(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); }); - 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; + function getEditsForRefactor(context, refactorName, actionName) { var refactor = refactors.get(refactorName); - if (!refactor) { - return undefined; - } - var codeActions = refactor.getCodeActions(context); - if (codeActions) { - ts.addRange((result || (result = [])), codeActions); - } - return result; + return refactor && refactor.getEditsForAction(context, actionName); } - refactor_1.getRefactorCodeActions = getRefactorCodeActions; + refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var qualifiedName = ts.getAncestor(token, 143 /* QualifiedName */); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + if (!ts.isIdentifier(qualifiedName.left)) { + return undefined; + } + var leftText = qualifiedName.left.getText(sourceFile); + var rightText = qualifiedName.right.getText(sourceFile); + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84861,7 +87261,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -84902,11 +87302,7 @@ var ts; newNodes.push(newIndexSignatureDeclaration); } function pushAction(result, newNodes, description) { - var newAction = { - description: description, - changes: codefix.newNodesToChanges(newNodes, openBrace, context) - }; - result.push(newAction); + result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -84922,85 +87318,118 @@ var ts; getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { - var sourceFile = context.sourceFile; + var tokenSourceFile = context.sourceFile; var start = context.span.start; - // This is the identifier of the missing property. eg: + // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(tokenSourceFile, start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent) || token.parent.expression.kind !== 99 /* ThisKeyword */) { + if (!ts.isPropertyAccessExpression(token.parent)) { return undefined; } - var classMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); - if (!ts.isClassElement(classMemberDeclaration)) { - return undefined; + var tokenName = token.getText(tokenSourceFile); + var makeStatic = false; + var classDeclaration; + if (token.parent.expression.kind === 99 /* ThisKeyword */) { + var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); + if (!ts.isClassElement(containingClassMemberDeclaration)) { + return undefined; + } + classDeclaration = containingClassMemberDeclaration.parent; + // Property accesses on `this` in a static method are accesses of a static member. + makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */); + } + else { + var checker = context.program.getTypeChecker(); + var leftExpression = token.parent.expression; + var leftExpressionType = checker.getTypeAtLocation(leftExpression); + if (leftExpressionType.flags & 32768 /* Object */) { + var symbol = leftExpressionType.symbol; + if (symbol.flags & 32 /* Class */) { + classDeclaration = symbol.declarations && symbol.declarations[0]; + if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { + // The expression is a class symbol but the type is not the instance-side. + makeStatic = true; + } + } + } } - var classDeclaration = classMemberDeclaration.parent; if (!classDeclaration || !ts.isClassLike(classDeclaration)) { return undefined; } - var isStatic = ts.hasModifier(classMemberDeclaration, 32 /* Static */); - return ts.isInJavaScriptFile(sourceFile) ? getActionsForAddMissingMemberInJavaScriptFile() : getActionsForAddMissingMemberInTypeScriptFile(); - function getActionsForAddMissingMemberInJavaScriptFile() { - var memberName = token.getText(); - if (isStatic) { + var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); + var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); + return ts.isInJavaScriptFile(classDeclarationSourceFile) ? + getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : + getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); + function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ false); + if (methodCodeAction) { + actions = [methodCodeAction]; + } + if (makeStatic) { if (classDeclaration.kind === 199 /* ClassExpression */) { - return undefined; + return actions; } var className = classDeclaration.name.getText(); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classDeclaration.getEnd(), length: 0 }, - newText: "" + context.newLineCharacter + className + "." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + var initializeStaticAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), + changes: staticInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeStaticAction); + return actions; } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); if (!classConstructor) { - return undefined; + return actions; } - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classConstructor.body.getEnd() - 1, length: 0 }, - newText: "this." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var initializeAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), + changes: propertyInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeAction); + return actions; } } - function getActionsForAddMissingMemberInTypeScriptFile() { + function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ true); + if (methodCodeAction) { + actions = [methodCodeAction]; + } var typeNode; if (token.parent.parent.kind === 194 /* BinaryExpression */) { var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(binaryExpression.right))); + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } typeNode = typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); var property = ts.createProperty( /*decorators*/ undefined, - /*modifiers*/ isStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, token.getText(sourceFile), + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - propertyChangeTracker.insertNodeAfter(sourceFile, openBrace, property, { suffix: context.newLineCharacter }); - var actions = [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_declaration_for_missing_property_0), [token.getText()]), - changes: propertyChangeTracker.getChanges() - }]; - if (!isStatic) { + propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); + (actions || (actions = [])).push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + changes: propertyChangeTracker.getChanges() + }); + if (!makeStatic) { + // Index signatures cannot have the static modifier. var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, @@ -85012,14 +87441,28 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); + indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_missing_property_0), [token.getText()]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: indexSignatureChangeTracker.getChanges() }); } return actions; } + function getActionForMethodDeclaration(includeTypeScriptSyntax) { + if (token.parent.parent.kind === 181 /* CallExpression */) { + var callExpression = token.parent.parent; + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? + ts.Diagnostics.Declare_method_0 : + ts.Diagnostics.Declare_static_method_0), [tokenName]), + changes: methodDeclarationChangeTracker.getChanges() + }; + } + } } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -85038,10 +87481,11 @@ var ts; // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 var checker = context.program.getTypeChecker(); var suggestion; - if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71 /* Identifier */); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } @@ -85095,7 +87539,7 @@ var ts; var 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. - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -85133,7 +87577,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 99 /* ThisKeyword */) { return undefined; } @@ -85145,9 +87589,9 @@ var ts; // figure out if the `this` access is actually inside the supercall // i.e. super(this.a), since in that case we won't suggest a fix if (superCall.expression && superCall.expression.kind === 181 /* CallExpression */) { - var arguments_1 = superCall.expression.arguments; - for (var i = 0; i < arguments_1.length; i++) { - if (arguments_1[i].expression === token) { + var expressionArguments = superCall.expression.arguments; + for (var i = 0; i < expressionArguments.length; i++) { + if (expressionArguments[i].expression === token) { return undefined; } } @@ -85181,7 +87625,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 123 /* ConstructorKeyword */) { return undefined; } @@ -85206,7 +87650,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { return undefined; @@ -85246,7 +87690,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } @@ -85273,140 +87717,147 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); // this handles var ["computed"] = 12; if (token.kind === 21 /* OpenBracketToken */) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); } switch (token.kind) { case 71 /* Identifier */: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: return deleteDefault(); } function deleteDefault() { if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + return [deleteNode(token.parent)]; } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + return [deleteNode(token.parent.parent)]; } else { return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226 /* VariableDeclaration */: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = 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); + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; // handle case where 'import a = A;' case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237 /* ImportEqualsDeclaration */); + return [deleteNode(importEquals)]; case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; + var namedImports = 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); + return deleteNamedImportBinding(namedImports); } else { // delete import specifier - return deleteNodeInList(token.parent); + return [deleteNodeInList(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; + case 239 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); + 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); + var start_6 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); 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) }); + return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; } else { - return deleteNode(importClause.name); + 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); - } + return deleteNamedImportBinding(parent); default: return deleteDefault(); } } + function deleteNamedImportBinding(namedBindings) { + if (namedBindings.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; + } + return undefined; + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(namedBindings, 238 /* ImportDeclaration */); + return [deleteNode(importDecl)]; + } + } // token.parent is a variableDeclaration - function deleteVariableDeclaration(varDecl) { + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, 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); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : 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()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215 /* ForInStatement */: // There is no valid fix in the case of: // for .. in - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -85426,10 +87877,10 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); @@ -85437,6 +87888,48 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], + getCodeActions: getActionsForJSDocTypes + }); + function getActionsForJSDocTypes(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, function (n) { return n.kind === 226 /* VariableDeclaration */; }); + if (!decl) + return; + var checker = context.program.getTypeChecker(); + var jsdocType = decl.type; + var original = ts.getTextOfNode(jsdocType); + var type = checker.getTypeFromTypeNode(jsdocType); + var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; + if (jsdocType.kind === 270 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); + actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); + } + return actions; + } + function createAction(declaration, fileName, original, replacement) { + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), + changes: [{ + fileName: fileName, + textChanges: [{ + span: { start: declaration.getStart(), length: declaration.getWidth() }, + newText: replacement + }] + }], + }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -85551,7 +88044,7 @@ var ts; 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 token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); var name = token.getText(); var symbolIdActionMap = new ImportCodeActionMap(); // this is a module id -> module import declaration map @@ -85559,8 +88052,22 @@ var ts; 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 umdSymbol = checker.getSymbolAtLocation(token); + var symbol = void 0; + var symbolName = void 0; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = name; + } + else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455 /* Value */)); + symbolName = symbol.name; + } + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, symbolName, /*isDefault*/ false, /*isNamespaceImport*/ true); } var candidateModules = checker.getAmbientModules(); for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { @@ -85576,17 +88083,19 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { // check if this symbol is already used var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isDefault*/ true)); } } + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(name !== "default"); // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); } } return symbolIdActionMap.getAllActions(); @@ -85621,16 +88130,13 @@ var ts; } } function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + return ts.getSymbolId(ts.skipAlias(symbol, checker)); } 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) { + function getCodeActionForImport(moduleSymbol, symbolName, 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. @@ -85763,10 +88269,10 @@ var ts; var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); var changeTracker = createChangeTracker(); var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + ? ts.createImportClause(ts.createIdentifier(symbolName), /*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))])); + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); 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 }); @@ -85777,7 +88283,7 @@ var ts; // 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); + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -85790,8 +88296,9 @@ var ts; tryGetModuleNameFromRootDirs() || ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; } } function tryGetModuleNameFromBaseUrl() { @@ -85859,44 +88366,101 @@ var ts; // nothing to do here return undefined; } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { 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"))); + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (context.host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); 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 mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } } - catch (e) { } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory); + } } - return relativeFileName; } } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[otherpackage/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["PackageContent"] = 2] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + packageRootIndex = partEnd; + state = 2 /* PackageContent */; + break; + case 2 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 2 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDir = rootDirs_1[_i]; var relativeName = getRelativePathIfInDirectory(path, rootDir); if (relativeName !== undefined) { return relativeName; @@ -85917,7 +88481,7 @@ var ts; } function getRelativePath(path, directoryPath) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; } } } @@ -85959,7 +88523,7 @@ var ts; // 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 (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -85968,7 +88532,7 @@ var ts; }; } } - // If all fails, add an extra new line immediatlly before the error span. + // If all fails, add an extra new line immediately before the error span. return { span: { start: position, length: 0 }, newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter @@ -86037,7 +88601,7 @@ var ts; */ function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.getName()); }); + var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); var newNodes = []; for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { var symbol = missingMembers_1[_i]; @@ -86068,7 +88632,7 @@ var ts; var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); - var optional = !!(symbol.flags & 67108864 /* Optional */); + var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { case 153 /* GetAccessor */: case 154 /* SetAccessor */: @@ -86133,6 +88697,41 @@ var ts; return signatureDeclaration; } } + function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { + var parameters = createDummyParameters(callExpression.arguments.length, /*names*/ undefined, /*minArgumentCount*/ undefined, includeTypeScriptSyntax); + var typeParameters; + if (includeTypeScriptSyntax) { + var typeArgCount = ts.length(callExpression.typeArguments); + for (var i = 0; i < typeArgCount; i++) { + var name = typeArgCount < 8 ? String.fromCharCode(84 /* T */ + i) : "T" + i; + var typeParameter = ts.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined); + (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); + } + } + var newMethod = ts.createMethod( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ undefined, methodName, + /*questionToken*/ undefined, typeParameters, parameters, + /*type*/ includeTypeScriptSyntax ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, createStubbedMethodBody()); + return newMethod; + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ names && names[i] || "arg" + i, + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, + /*type*/ addAnyType ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, + /*initializer*/ undefined); + parameters.push(newParameter); + } + return parameters; + } function createMethodImplementingSignatures(signatures, name, optional, modifiers) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, @@ -86152,18 +88751,8 @@ var ts; } } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); - var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.getName(); }); - var parameters = []; - for (var i = 0; i < maxNonRestArgs; i++) { - var anyType = ts.createKeywordTypeNode(119 /* AnyKeyword */); - var newParameter = ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, maxArgsParameterSymbolNames[i], - /*questionToken*/ i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyType, - /*initializer*/ undefined); - parameters.push(newParameter); - } + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -86199,6 +88788,7 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/// /// /// /// @@ -86207,7 +88797,8 @@ var ts; /// /// /// -/// +/// +/// /// /// /// @@ -86216,34 +88807,55 @@ var ts; (function (ts) { var refactor; (function (refactor) { + var actionName = "convert"; var convertFunctionToES6Class = { name: "Convert to ES2015 class", description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getCodeActions: getCodeActions, - isApplicable: isApplicable + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions }; refactor.registerRefactor(convertFunctionToES6Class); - function isApplicable(context) { + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start); + var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); 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; + if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - function getCodeActions(context) { + function getEditsForAction(context, action) { + // Somehow wrong action got invoked? + if (actionName !== action) { + return undefined; + } var start = context.startPosition; var sourceFile = context.file; var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var ctorSymbol = checker.getSymbolAtLocation(token); var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { - return []; + return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -86267,7 +88879,7 @@ var ts; break; } if (!newClassDeclaration) { - return []; + return undefined; } // Because the preceding node could be touched, we need to insert nodes before delete nodes. changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); @@ -86275,10 +88887,9 @@ var ts; var deleteCallback = deletes_1[_i]; deleteCallback(); } - return [{ - description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), - changes: changeTracker.getChanges() - }]; + return { + edits: changeTracker.getChanges() + }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { @@ -86338,11 +88949,14 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186 /* FunctionExpression */: + case 186 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - case 187 /* ArrowFunction */: + copyComments(assignmentBinaryExpression, method); + return method; + } + case 187 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; @@ -86354,18 +88968,39 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - default: + copyComments(assignmentBinaryExpression, method); + return method; + } + 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, + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } } } } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { @@ -86378,16 +89013,20 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; } 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, + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; } } })(refactor = ts.refactor || (ts.refactor = {})); @@ -86429,7 +89068,7 @@ var ts; /* @internal */ var ruleProvider; function createNode(kind, pos, end, parent) { - var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; @@ -86474,10 +89113,11 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { + NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var token = ts.scanner.scan(); + ts.Debug.assert(token !== 1 /* EndOfFileToken */); // Else it would infinitely loop var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -86487,7 +89127,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -86505,47 +89145,49 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143 /* FirstNode */) { - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; - var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 283 /* FirstJSDocTagNode */ && this.kind <= 293 /* LastJSDocTagNode */; - var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); - } - children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } - }; - var processNodes = function (nodes) { - if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); - } - children.push(_this.createSyntaxList(nodes)); - pos_3 = nodes.end; - }; - // jsDocComments need to be the first children - if (this.jsDoc) { - for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - processNode(jsDocComment); - } - } - // For syntactic classifications, all trivia are classcified together, including jsdoc comments. - // For that to work, the jsdoc comments should still be the leading trivia of the first child. - // Restoring the scanner position ensures that. - pos_3 = this.pos; - ts.forEachChild(this, processNode, processNodes); - if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); - } - ts.scanner.setText(undefined); + if (!ts.isNodeKind(this.kind)) { + this._children = ts.emptyArray; + return; } - this._children = children || ts.emptyArray; + if (ts.isJSDocCommentContainingNode(this)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + return; + } + var children = []; + ts.scanner.setText((sourceFile || this.getSourceFile()).text); + var pos = this.pos; + var processNode = function (node) { + pos = _this.addSyntheticNodes(children, pos, node.pos); + children.push(node); + pos = node.end; + }; + var processNodes = function (nodes) { + if (pos < nodes.pos) { + pos = _this.addSyntheticNodes(children, pos, nodes.pos); + } + children.push(_this.createSyntaxList(nodes)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + processNode(jsDocComment); + } + } + // For syntactic classifications, all trivia are classcified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = this.pos; + ts.forEachChild(this, processNode, processNodes); + if (pos < this.end) { + this.addSyntheticNodes(children, pos, this.end); + } + ts.scanner.setText(undefined); + this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -86567,7 +89209,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 267 /* FirstJSDocNode */ || kid.kind > 285 /* LastJSDocNode */; }); return child.kind < 143 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -86643,11 +89285,21 @@ var ts; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; } SymbolObject.prototype.getFlags = function () { return this.flags; }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedName); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; SymbolObject.prototype.getName = function () { return this.name; }; @@ -86682,6 +89334,13 @@ var ts; function IdentifierObject(_kind, pos, end) { return _super.call(this, pos, end) || this; } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedText); + }, + enumerable: true, + configurable: true + }); return IdentifierObject; }(TokenOrIdentifierObject)); IdentifierObject.prototype.kind = 71 /* Identifier */; @@ -86814,26 +89473,16 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_9 = ts.getTextOfIdentifierOrLiteral(name); + if (result_9 !== undefined) { + return result_9; } if (name.kind === 144 /* ComputedPropertyName */) { var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } - return getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; - } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - node.kind === 8 /* NumericLiteral */) { - return node.text; + return ts.getTextOfIdentifierOrLiteral(expr); } } return undefined; @@ -86872,7 +89521,6 @@ var ts; case 237 /* ImportEqualsDeclaration */: case 246 /* ExportSpecifier */: case 242 /* ImportSpecifier */: - case 237 /* ImportEqualsDeclaration */: case 239 /* ImportClause */: case 240 /* NamespaceImport */: case 153 /* GetAccessor */: @@ -86894,8 +89542,9 @@ var ts; ts.forEachChild(decl.name, visit); break; } - if (decl.initializer) + if (decl.initializer) { visit(decl.initializer); + } } // falls through case 264 /* EnumMember */: @@ -86938,6 +89587,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); + var SourceMapSourceObject = (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); function getServicesObjectAllocator() { return { getNodeConstructor: function () { return NodeObject; }, @@ -86947,6 +89607,7 @@ var ts; getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, }; } function toEditorSettings(optionsAsMap) { @@ -86998,10 +89659,9 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = ts.createFileMap(); + this.fileNameToEntry = ts.createMap(); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { @@ -87028,24 +89688,20 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { - return this.fileNameToEntry.contains(path); - }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); + HostCache.prototype.containsEntryByPath = function (path) { + return this.fileNameToEntry.has(path); }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (_path, value) { + this.fileNameToEntry.forEach(function (value) { if (value) { fileNames.push(value.hostFileName); } @@ -87053,11 +89709,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -87285,12 +89941,19 @@ var ts; getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { // stub missing host functionality - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -87407,8 +90070,18 @@ var ts; return false; } } + var currentOptions = program.getCompilerOptions(); + var newOptions = hostCache.compilationSettings(); // If the compilation settings do no match, then the program is not up-to-date - return ts.compareDataObjects(program.getCompilerOptions(), hostCache.compilationSettings()); + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; } } function getProgram() { @@ -87423,7 +90096,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } /// Diagnostics function getSyntacticDiagnostics(fileName) { @@ -87466,7 +90141,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -87488,8 +90163,8 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ts.ScriptElementKind.unknown, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "" /* unknown */, + kindModifiers: "" /* none */, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, @@ -87554,7 +90229,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, isDefinition: false, isInString: highlightSpan.isInString, }); @@ -87587,12 +90262,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; - function writeFile(fileName, data, writeByteOrderMark) { - outputFiles.push({ - name: fileName, - writeByteOrderMark: writeByteOrderMark, - text: data - }); + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); @@ -87620,7 +90291,7 @@ var ts; function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { return; } @@ -87714,7 +90385,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); // Ensure that there is a corresponding token to match ours. @@ -87776,7 +90447,10 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "}") { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { @@ -87790,27 +90464,13 @@ var ts; function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var span = { start: start, length: end - start }; - var newLineChar = ts.getNewLineOrDefaultFromHost(host); - var allFixes = []; - ts.forEach(ts.deduplicate(errorCodes), function (error) { + var span = ts.createTextSpanFromBounds(start, end); + var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); + var rulesProvider = getRuleProvider(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - var context = { - errorCode: error, - sourceFile: sourceFile, - span: span, - program: program, - newLineCharacter: newLineChar, - host: host, - cancellationToken: cancellationToken, - rulesProvider: getRuleProvider(formatOptions) - }; - var fixes = ts.codefix.getFixes(context); - if (fixes) { - allFixes = allFixes.concat(fixes); - } + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); - return allFixes; } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); @@ -87836,6 +90496,12 @@ var ts; if (ts.isInTemplateString(sourceFile, position)) { return false; } + switch (openingBrace) { + case 39 /* singleQuote */: + case 34 /* doubleQuote */: + case 96 /* backtick */: + return !ts.isInComment(sourceFile, position); + } return true; } function getTodoComments(fileName, descriptors) { @@ -87850,7 +90516,8 @@ var ts; cancellationToken.throwIfCancellationRequested(); var fileContents = sourceFile.text; var result = []; - if (descriptors.length > 0) { + // Exclude node_modules files as we don't want to show the todos of external libraries. + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { var regExp = getTodoCommentsRegExp(); var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { @@ -87894,11 +90561,7 @@ var ts; continue; } var message = matchArray[2]; - result.push({ - descriptor: descriptor, - message: message, - position: matchPosition - }); + result.push({ descriptor: descriptor, message: message, position: matchPosition }); } } return result; @@ -87960,6 +90623,10 @@ var ts; (char >= 65 /* A */ && char <= 90 /* Z */) || (char >= 48 /* _0 */ && char <= 57 /* _9 */); } + function isNodeModulesFile(path) { + var node_modulesFolderName = "/node_modules/"; + return path.indexOf(node_modulesFolderName) !== -1; + } } function getRenameInfo(fileName, position) { synchronizeHostData(); @@ -87983,18 +90650,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); } - function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, - getApplicableRefactors: getApplicableRefactors, - getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -88032,7 +90697,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, - getProgram: getProgram + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, }; } ts.createLanguageService = createLanguageService; @@ -88046,40 +90713,32 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); - walk(sourceFile); - sourceFile.nameTable = nameTable; - function walk(node) { - switch (node.kind) { - case 71 /* Identifier */: - setNameTable(node.text, node); - break; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - // We want to store any numbers/strings if they were a name that could be - // related to a declaration. So, if we have 'import x = require("something")' - // then we want 'something' to be in the name table. Similarly, if we have - // "a['propname']" then we want to store "propname" in the name table. - if (ts.isDeclarationName(node) || - node.parent.kind === 248 /* ExternalModuleReference */ || - isArgumentOfElementAccessExpression(node) || - ts.isLiteralComputedPropertyDeclarationName(node)) { - setNameTable(node.text, node); - } - break; - default: - ts.forEachChild(node, walk); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - ts.forEachChild(jsDoc, walk); - } - } + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } - } - function setNameTable(text, node) { - nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); - } + ts.forEachChild(node, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + /** + * We want to store any numbers/strings if they were a name that could be + * related to a declaration. So, if we have 'import x = require("something")' + * then we want 'something' to be in the name table. Similarly, if we have + * "a['propname']" then we want to store "propname" in the name table. + */ + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 248 /* ExternalModuleReference */ || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { @@ -88118,22 +90777,22 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.getTextOfPropertyName(node.name); + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); if (name && contextualType) { - var result_9 = []; + var result_10 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_10.push(symbol); } }); - return result_9; + return result_10; } if (symbol) { - result_9.push(symbol); - return result_9; + result_10.push(symbol); + return result_10; } } return undefined; @@ -88176,7 +90835,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var 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 @@ -88977,25 +91636,8 @@ var ts; } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - // Wrap the API changes for 2.0 release. This try/catch - // should be removed once TypeScript 2.0 has shipped. - try { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - } - catch (e) { - var results = []; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { - var file = _b[_a]; - if (!ts.contains(results, file)) { - results.push(file); - } - } - } - return results; - } + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -89003,9 +91645,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; - CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { - return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); - }; CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { return JSON.parse(this.shimHost.getDirectories(path)); }; @@ -89391,7 +92030,7 @@ 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) { + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { resolvedFileName = undefined; } return { @@ -89452,24 +92091,15 @@ var ts; var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseConfigFileTextToJson(fileName, text); - if (result.error) { - return { - options: {}, - typeAcquisition: {}, - files: [], - raw: {}, - errors: [realizeDiagnostic(result.error, "\r\n")] - }; - } + var result = ts.parseJsonText(fileName, text); var normalizedFileName = ts.normalizeSlashes(fileName); - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, - errors: realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") }; }); }; @@ -89481,7 +92111,10 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -89531,7 +92164,7 @@ var ts; }; TypeScriptServicesFactory.prototype.close = function () { // Forget all the registered shims - this._shims = []; + ts.clear(this._shims); this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { @@ -89567,6 +92200,4 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.4"; - -//# sourceMappingURL=typescriptServices.js.map +var toolsVersion = "2.5"; diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index df00c45de24..392b7e36a07 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -22,19 +22,22 @@ declare namespace ts { interface MapLike { [index: string]: T; } - /** ES6 Map interface. */ - interface Map { + /** ES6 Map interface, only read methods included. */ + interface ReadonlyMap { get(key: string): T | undefined; has(key: string): boolean; - set(key: string, value: T): this; - delete(key: string): boolean; - clear(): void; forEach(action: (value: T, key: string) => void): void; readonly size: number; keys(): Iterator; values(): Iterator; entries(): Iterator<[string, T]>; } + /** ES6 Map interface. */ + interface Map extends ReadonlyMap { + set(key: string, value: T): this; + delete(key: string): boolean; + clear(): void; + } /** ES6 Iterator type. */ interface Iterator { next(): { @@ -45,18 +48,13 @@ declare namespace ts { done: true; }; } + /** Array that is only intended to be pushed to, never read. */ + interface Push { + push(...values: T[]): void; + } type Path = string & { __pathBrand: any; }; - interface FileMap { - get(fileName: Path): T; - set(fileName: Path, value: T): void; - contains(fileName: Path): boolean; - remove(fileName: Path): void; - forEachValue(f: (key: Path, v: T) => void): void; - getKeys(): Path[]; - clear(): void; - } interface TextRange { pos: number; end: number; @@ -332,37 +330,29 @@ declare namespace ts { JSDocTypeExpression = 267, JSDocAllType = 268, JSDocUnknownType = 269, - JSDocArrayType = 270, - JSDocUnionType = 271, - JSDocTupleType = 272, - JSDocNullableType = 273, - JSDocNonNullableType = 274, - JSDocRecordType = 275, - JSDocRecordMember = 276, - JSDocTypeReference = 277, - JSDocOptionalType = 278, - JSDocFunctionType = 279, - JSDocVariadicType = 280, - JSDocConstructorType = 281, - JSDocThisType = 282, - JSDocComment = 283, - JSDocTag = 284, - JSDocAugmentsTag = 285, - JSDocParameterTag = 286, - JSDocReturnTag = 287, - JSDocTypeTag = 288, - JSDocTemplateTag = 289, - JSDocTypedefTag = 290, - JSDocPropertyTag = 291, - JSDocTypeLiteral = 292, - JSDocLiteralType = 293, - SyntaxList = 294, - NotEmittedStatement = 295, - PartiallyEmittedExpression = 296, - CommaListExpression = 297, - MergeDeclarationMarker = 298, - EndOfDeclarationMarker = 299, - Count = 300, + JSDocNullableType = 270, + JSDocNonNullableType = 271, + JSDocOptionalType = 272, + JSDocFunctionType = 273, + JSDocVariadicType = 274, + JSDocComment = 275, + JSDocTag = 276, + JSDocAugmentsTag = 277, + JSDocClassTag = 278, + JSDocParameterTag = 279, + JSDocReturnTag = 280, + JSDocTypeTag = 281, + JSDocTemplateTag = 282, + JSDocTypedefTag = 283, + JSDocPropertyTag = 284, + JSDocTypeLiteral = 285, + SyntaxList = 286, + NotEmittedStatement = 287, + PartiallyEmittedExpression = 288, + CommaListExpression = 289, + MergeDeclarationMarker = 290, + EndOfDeclarationMarker = 291, + Count = 292, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -389,9 +379,9 @@ declare namespace ts { LastBinaryOperator = 70, FirstNode = 143, FirstJSDocNode = 267, - LastJSDocNode = 293, - FirstJSDocTagNode = 283, - LastJSDocTagNode = 293, + LastJSDocNode = 285, + FirstJSDocTagNode = 276, + LastJSDocTagNode = 285, } enum NodeFlags { None = 0, @@ -414,6 +404,7 @@ declare namespace ts { JavaScriptFile = 65536, ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, + JSDoc = 1048576, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, @@ -455,7 +446,7 @@ declare namespace ts { modifiers?: ModifiersArray; parent?: Node; } - interface NodeArray extends Array, TextRange { + interface NodeArray extends ReadonlyArray, TextRange { hasTrailingComma?: boolean; } interface Token extends Node { @@ -476,10 +467,10 @@ declare namespace ts { 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. + * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) + * Text of identifier, but if the identifier begins with two underscores, this will begin with three. */ - text: string; + escapedText: __String; originalKeywordKind?: SyntaxKind; isInJSDocNamespace?: boolean; } @@ -562,7 +553,7 @@ declare namespace ts { initializer?: Expression; } interface PropertySignature extends TypeElement { - kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; + kind: SyntaxKind.PropertySignature; name: PropertyName; questionToken?: QuestionToken; type?: TypeNode; @@ -600,7 +591,7 @@ declare namespace ts { interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; - name: DeclarationName; + name?: DeclarationName; questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; @@ -622,19 +613,21 @@ declare namespace ts { type ArrayBindingElement = BindingElement | OmittedExpression; /** * Several node kinds share function-like features such as a signature, - * a name, and a body. These nodes should extend FunctionLikeDeclaration. + * a name, and a body. These nodes should extend FunctionLikeDeclarationBase. * Examples: * - FunctionDeclaration * - MethodDeclaration * - AccessorDeclaration */ - interface FunctionLikeDeclaration extends SignatureDeclaration { + interface FunctionLikeDeclarationBase extends SignatureDeclaration { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; body?: Block | Expression; } - interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; @@ -643,12 +636,12 @@ declare namespace ts { kind: SyntaxKind.MethodSignature; name: PropertyName; } - interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } - interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement { kind: SyntaxKind.Constructor; parent?: ClassDeclaration | ClassExpression; body?: FunctionBody; @@ -658,13 +651,13 @@ declare namespace ts { kind: SyntaxKind.SemicolonClassElement; parent?: ClassDeclaration | ClassExpression; } - interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.GetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; body: FunctionBody; } - interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement { kind: SyntaxKind.SetAccessor; parent?: ClassDeclaration | ClassExpression | ObjectLiteralExpression; name: PropertyName; @@ -691,6 +684,7 @@ declare namespace ts { interface ConstructorTypeNode extends TypeNode, SignatureDeclaration { kind: SyntaxKind.ConstructorType; } + type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; interface TypeReferenceNode extends TypeNode { kind: SyntaxKind.TypeReference; typeName: EntityName; @@ -768,22 +762,24 @@ declare namespace ts { interface UnaryExpression extends Expression { _unaryExpressionBrand: any; } - interface IncrementExpression extends UnaryExpression { - _incrementExpressionBrand: any; + /** Deprecated, please use UpdateExpression */ + type IncrementExpression = UpdateExpression; + interface UpdateExpression extends UnaryExpression { + _updateExpressionBrand: any; } type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; - interface PrefixUnaryExpression extends IncrementExpression { + interface PrefixUnaryExpression extends UpdateExpression { kind: SyntaxKind.PrefixUnaryExpression; operator: PrefixUnaryOperator; operand: UnaryExpression; } type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; - interface PostfixUnaryExpression extends IncrementExpression { + interface PostfixUnaryExpression extends UpdateExpression { kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; operator: PostfixUnaryOperator; } - interface LeftHandSideExpression extends IncrementExpression { + interface LeftHandSideExpression extends UpdateExpression { _leftHandSideExpressionBrand: any; } interface MemberExpression extends LeftHandSideExpression { @@ -804,6 +800,9 @@ declare namespace ts { interface SuperExpression extends PrimaryExpression { kind: SyntaxKind.SuperKeyword; } + interface ImportExpression extends PrimaryExpression { + kind: SyntaxKind.ImportKeyword; + } interface DeleteExpression extends UnaryExpression { kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; @@ -880,12 +879,12 @@ declare namespace ts { } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; - interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase { kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } - interface ArrowFunction extends Expression, FunctionLikeDeclaration { + interface ArrowFunction extends Expression, FunctionLikeDeclarationBase { kind: SyntaxKind.ArrowFunction; equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; @@ -988,6 +987,9 @@ declare namespace ts { interface SuperCall extends CallExpression { expression: SuperExpression; } + interface ImportCall extends CallExpression { + expression: ImportExpression; + } interface ExpressionWithTypeArguments extends TypeNode { kind: SyntaxKind.ExpressionWithTypeArguments; parent?: HeritageClause; @@ -1137,6 +1139,7 @@ declare namespace ts { condition?: Expression; incrementor?: Expression; } + type ForInOrOfStatement = ForInStatement | ForOfStatement; interface ForInStatement extends IterationStatement { kind: SyntaxKind.ForInStatement; initializer: ForInitializer; @@ -1210,7 +1213,7 @@ declare namespace ts { variableDeclaration: VariableDeclaration; block: Block; } - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; + type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; @@ -1379,9 +1382,9 @@ declare namespace ts { pos: -1; end: -1; } - interface JSDocTypeExpression extends Node { + interface JSDocTypeExpression extends TypeNode { kind: SyntaxKind.JSDocTypeExpression; - type: JSDocType; + type: TypeNode; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; @@ -1392,72 +1395,33 @@ declare namespace ts { interface JSDocUnknownType extends JSDocType { kind: SyntaxKind.JSDocUnknownType; } - interface JSDocArrayType extends JSDocType { - kind: SyntaxKind.JSDocArrayType; - elementType: JSDocType; - } - interface JSDocUnionType extends JSDocType { - kind: SyntaxKind.JSDocUnionType; - types: NodeArray; - } - interface JSDocTupleType extends JSDocType { - kind: SyntaxKind.JSDocTupleType; - types: NodeArray; - } interface JSDocNonNullableType extends JSDocType { kind: SyntaxKind.JSDocNonNullableType; - type: JSDocType; + type: TypeNode; } interface JSDocNullableType extends JSDocType { kind: SyntaxKind.JSDocNullableType; - type: JSDocType; - } - interface JSDocRecordType extends JSDocType { - kind: SyntaxKind.JSDocRecordType; - literal: TypeLiteralNode; - } - interface JSDocTypeReference extends JSDocType { - kind: SyntaxKind.JSDocTypeReference; - name: EntityName; - typeArguments: NodeArray; + type: TypeNode; } interface JSDocOptionalType extends JSDocType { kind: SyntaxKind.JSDocOptionalType; - type: JSDocType; + type: TypeNode; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { kind: SyntaxKind.JSDocFunctionType; - parameters: NodeArray; - type: JSDocType; } interface JSDocVariadicType extends JSDocType { kind: SyntaxKind.JSDocVariadicType; - type: JSDocType; - } - interface JSDocConstructorType extends JSDocType { - kind: SyntaxKind.JSDocConstructorType; - type: JSDocType; - } - interface JSDocThisType extends JSDocType { - kind: SyntaxKind.JSDocThisType; - type: JSDocType; - } - interface JSDocLiteralType extends JSDocType { - kind: SyntaxKind.JSDocLiteralType; - literal: LiteralTypeNode; - } - type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; - interface JSDocRecordMember extends PropertySignature { - kind: SyntaxKind.JSDocRecordMember; - name: Identifier | StringLiteral | NumericLiteral; - type?: JSDocType; + type: TypeNode; } + type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { + parent: JSDoc; atToken: AtToken; tagName: Identifier; comment: string | undefined; @@ -1469,6 +1433,9 @@ declare namespace ts { kind: SyntaxKind.JSDocAugmentsTag; typeExpression: JSDocTypeExpression; } + interface JSDocClassTag extends JSDocTag { + kind: SyntaxKind.JSDocClassTag; + } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; @@ -1482,32 +1449,32 @@ declare namespace ts { typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; - typeExpression?: JSDocTypeExpression; - jsDocTypeLiteral?: JSDocTypeLiteral; + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } - interface JSDocPropertyTag extends JSDocTag, TypeElement { - kind: SyntaxKind.JSDocPropertyTag; - name: Identifier; + interface JSDocPropertyLikeTag extends JSDocTag, Declaration { + parent: JSDoc; + name: EntityName; typeExpression: JSDocTypeExpression; + /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ + isNameFirst: boolean; + isBracketed: boolean; + } + interface JSDocPropertyTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocPropertyTag; + } + interface JSDocParameterTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocParameterTag; } interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; - jsDocPropertyTags?: NodeArray; + jsDocPropertyTags?: ReadonlyArray; jsDocTypeTag?: JSDocTypeTag; - } - interface JSDocParameterTag extends JSDocTag { - kind: SyntaxKind.JSDocParameterTag; - /** the parameter name, if provided *before* the type (TypeScript-style) */ - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - /** the parameter name, if provided *after* the type (JSDoc-standard) */ - postParameterName?: Identifier; - /** the parameter name, regardless of the location it was provided */ - parameterName: Identifier; - isBracketed: boolean; + /** If true, then this type literal represents an *array* of its type. */ + isArrayType?: boolean; } enum FlowFlags { Unreachable = 1, @@ -1600,6 +1567,10 @@ declare namespace ts { kind: SyntaxKind.Bundle; sourceFiles: SourceFile[]; } + interface JsonSourceFile extends SourceFile { + jsonObject?: ObjectLiteralExpression; + extendedSourceFiles?: string[]; + } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; getSourceFile(fileName: string): SourceFile; @@ -1608,16 +1579,16 @@ declare namespace ts { } interface ParseConfigHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[]; + readDirectory(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray, includes: ReadonlyArray, depth: number): string[]; /** * Gets a value indicating whether the specified path exists and is a file. * @param path The path to test. */ fileExists(path: string): boolean; - readFile(path: string): string; + readFile(path: string): string | undefined; } interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray): void; } class OperationCanceledException { } @@ -1704,14 +1675,15 @@ declare 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; getReturnTypeOfSignature(signature: Signature): Type; + getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** Note that the resulting nodes cannot be checked. */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; @@ -1735,9 +1707,13 @@ declare namespace ts { getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature | undefined; + /** + * returns unknownSignature in the case of an error. Don't know when it returns undefined. + * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. + */ + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; + isImplementationOfOverload(node: FunctionLike): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; @@ -1800,23 +1776,25 @@ declare namespace ts { clear(): void; trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; - reportIllegalExtends(): void; + reportPrivateInBaseOfClassExpression(propertyName: string): void; } enum TypeFormatFlags { None = 0, WriteArrayAsGenericType = 1, - UseTypeOfFunction = 2, - NoTruncation = 4, - WriteArrowStyleSignature = 8, - WriteOwnNameForAnyLike = 16, - WriteTypeArgumentsOfSignature = 32, - InElementType = 64, - UseFullyQualifiedType = 128, - InFirstTypeArgument = 256, - InTypeAlias = 512, - UseTypeAliasValue = 1024, - SuppressAnyReturnType = 2048, - AddUndefined = 4096, + UseTypeOfFunction = 4, + NoTruncation = 8, + WriteArrowStyleSignature = 16, + WriteOwnNameForAnyLike = 32, + WriteTypeArgumentsOfSignature = 64, + InElementType = 128, + UseFullyQualifiedType = 256, + InFirstTypeArgument = 512, + InTypeAlias = 1024, + UseTypeAliasValue = 2048, + SuppressAnyReturnType = 4096, + AddUndefined = 8192, + WriteClassExpressionAsTypeLiteral = 16384, + InArrayType = 32768, } enum SymbolFormatFlags { None = 0, @@ -1863,13 +1841,11 @@ declare namespace ts { TypeParameter = 262144, TypeAlias = 524288, ExportValue = 1048576, - ExportType = 2097152, - ExportNamespace = 4194304, - Alias = 8388608, - Prototype = 16777216, - ExportStar = 33554432, - Optional = 67108864, - Transient = 134217728, + Alias = 2097152, + Prototype = 4194304, + ExportStar = 8388608, + Optional = 16777216, + Transient = 33554432, Enum = 384, Variable = 3, Value = 107455, @@ -1894,26 +1870,73 @@ declare namespace ts { SetAccessorExcludes = 74687, TypeParameterExcludes = 530920, TypeAliasExcludes = 793064, - AliasExcludes = 8388608, - ModuleMember = 8914931, + AliasExcludes = 2097152, + ModuleMember = 2623475, ExportHasLocal = 944, HasExports = 1952, HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - Export = 7340032, ClassMember = 106500, } interface Symbol { flags: SymbolFlags; - name: string; + escapedName: __String; declarations?: Declaration[]; valueDeclaration?: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; } - type SymbolTable = Map; + enum InternalSymbolName { + Call = "__call", + Constructor = "__constructor", + New = "__new", + Index = "__index", + ExportStar = "__export", + Global = "__global", + Missing = "__missing", + Type = "__type", + Object = "__object", + JSXAttributes = "__jsxAttributes", + Class = "__class", + Function = "__function", + Computed = "__computed", + Resolving = "__resolving__", + ExportEquals = "export=", + Default = "default", + } + /** + * This represents a string whose leading underscore have been escaped by adding extra leading underscores. + * The shape of this brand is rather unique compared to others we've used. + * Instead of just an intersection of a string and an object, it is that union-ed + * with an intersection of void and an object. This makes it wholly incompatible + * with a normal string (which is good, it cannot be misused on assignment or on usage), + * while still being comparable with a normal string via === (also good) and castable from a string. + */ + type __String = (string & { + __escapedIdentifier: void; + }) | (void & { + __escapedIdentifier: void; + }) | InternalSymbolName; + /** ReadonlyMap where keys are `__String`s. */ + interface ReadonlyUnderscoreEscapedMap { + get(key: __String): T | undefined; + has(key: __String): boolean; + forEach(action: (value: T, key: __String) => void): void; + readonly size: number; + keys(): Iterator<__String>; + values(): Iterator; + entries(): Iterator<[__String, T]>; + } + /** Map where keys are `__String`s. */ + interface UnderscoreEscapedMap extends ReadonlyUnderscoreEscapedMap { + set(key: __String, value: T): this; + delete(key: __String): boolean; + clear(): void; + } + /** SymbolTable based on ES6 Map interface. */ + type SymbolTable = UnderscoreEscapedMap; enum TypeFlags { Any = 1, String = 2, @@ -1987,7 +2010,7 @@ declare namespace ts { interface ObjectType extends Type { objectFlags: ObjectFlags; } - /** Class and interface types (TypeFlags.Class and TypeFlags.Interface). */ + /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; outerTypeParameters: TypeParameter[]; @@ -2003,7 +2026,7 @@ declare namespace ts { declaredNumberIndexInfo: IndexInfo; } /** - * Type references (TypeFlags.Reference). When a class or interface has type parameters or + * Type references (ObjectFlags.Reference). When a class or interface has type parameters or * a "this" type, references to the class or interface are made using type references. The * typeArguments property specifies the types to substitute for the type parameters of the * class or interface and optionally includes an extra element that specifies the type to @@ -2062,6 +2085,24 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } + enum InferencePriority { + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, + } + interface InferenceInfo { + typeParameter: TypeParameter; + candidates: Type[]; + inferredType: Type; + priority: InferencePriority; + topLevel: boolean; + isFixed: boolean; + } + enum InferenceFlags { + InferUnionTypes = 1, + NoDefault = 2, + AnyDefault = 4, + } interface JsFileExtensionInfo { extension: string; isMixedContent: boolean; @@ -2143,6 +2184,7 @@ declare namespace ts { noImplicitAny?: boolean; noImplicitReturns?: boolean; noImplicitThis?: boolean; + noStrictGenericChecks?: boolean; noUnusedLocals?: boolean; noUnusedParameters?: boolean; noImplicitUseStrict?: boolean; @@ -2172,7 +2214,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; - [option: string]: CompilerOptionsValue | undefined; + [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { enableAutoDiscovery?: boolean; @@ -2197,6 +2239,7 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, + ESNext = 6, } enum JsxEmit { None = 0, @@ -2219,6 +2262,7 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, + JSON = 6, } enum ScriptTarget { ES3 = 0, @@ -2253,7 +2297,7 @@ declare namespace ts { } interface ModuleResolutionHost { fileExists(fileName: string): boolean; - readFile(fileName: string): string; + readFile(fileName: string): string | undefined; trace?(s: string): void; directoryExists?(directoryName: string): boolean; realpath?(path: string): string; @@ -2290,12 +2334,11 @@ declare namespace ts { extension: Extension; } enum Extension { - Ts = 0, - Tsx = 1, - Dts = 2, - Js = 3, - Jsx = 4, - LastTypeScriptExtension = 2, + Ts = ".ts", + Tsx = ".tsx", + Dts = ".d.ts", + Js = ".js", + Jsx = ".jsx", } interface ResolvedModuleWithFailedLookupLocations { resolvedModule: ResolvedModuleFull | undefined; @@ -2327,6 +2370,14 @@ declare namespace ts { resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getEnvironmentVariable?(name: string): string; } + interface SourceMapRange extends TextRange { + source?: SourceMapSource; + } + interface SourceMapSource { + fileName: string; + text: string; + skipTrivia?: (pos: number) => number; + } enum EmitFlags { SingleLine = 1, AdviseOnEmitNode = 2, @@ -2457,7 +2508,7 @@ declare namespace ts { * A function that accepts and possibly transforms a node. */ type Visitor = (node: Node) => VisitResult; - type VisitResult = T | T[]; + type VisitResult = T | T[] | undefined; interface Printer { /** * Print a node and its subtree as-is, without any emit transformations. @@ -2542,13 +2593,19 @@ declare namespace ts { } } declare namespace ts { + const versionMajorMinor = "2.5"; /** The version of the TypeScript compiler release */ - const version = "2.4.0"; + const version: string; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { - type FileWatcherCallback = (fileName: string, removed?: boolean) => void; + enum FileWatcherEventKind { + Created = 0, + Changed = 1, + Deleted = 2, + } + type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; interface WatchedFile { fileName: string; @@ -2560,7 +2617,7 @@ declare namespace ts { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; - readFile(path: string, encoding?: string): string; + readFile(path: string, encoding?: string): string | undefined; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** @@ -2576,8 +2633,12 @@ declare namespace ts { getExecutingFilePath(): string; getCurrentDirectory(): string; getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; + /** + * This should be cryptographically secure. + * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) + */ createHash?(data: string): string; getMemoryUsage?(): number; exit(exitCode?: number): void; @@ -2630,9 +2691,9 @@ declare namespace ts { scanRange(start: number, length: number, callback: () => T): T; tryScan(callback: () => T): T; } - function tokenToString(t: SyntaxKind): string; + function tokenToString(t: SyntaxKind): string | undefined; function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; - function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; + function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; function isWhiteSpaceLike(ch: number): boolean; /** Does not include line breaks. For that, see isWhiteSpaceLike. */ function isWhiteSpaceSingleLine(ch: number): boolean; @@ -2677,7 +2738,7 @@ declare namespace ts { * This function will then merge those changes into a single change range valid between V1 and * Vn. */ - function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; + function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; function getTypeParameterOwner(d: Declaration): Declaration; function isParameterPropertyDeclaration(node: Node): boolean; function getCombinedModifierFlags(node: Node): ModifierFlags; @@ -2690,8 +2751,8 @@ declare namespace ts { getExecutingFilePath(): string; resolvePath(path: string): string; fileExists(fileName: string): boolean; - readFile(fileName: string): string; - }, errors?: Diagnostic[]): void; + readFile(fileName: string): string | undefined; + }, errors?: Push): void; function getOriginalNode(node: Node): Node; function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; /** @@ -2721,13 +2782,280 @@ declare namespace ts { * @param identifier The escaped identifier text. * @returns The unescaped identifier text. */ - function unescapeIdentifier(identifier: string): string; + function unescapeLeadingUnderscores(identifier: __String): string; + /** + * Remove extra underscore from escaped identifier text content. + * @deprecated Use `id.text` for the unescaped text. + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeIdentifier(id: string): string; + function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined; +} +declare namespace ts { + function isNumericLiteral(node: Node): node is NumericLiteral; + function isStringLiteral(node: Node): node is StringLiteral; + function isJsxText(node: Node): node is JsxText; + function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node: Node): node is LiteralExpression; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddle(node: Node): node is TemplateMiddle; + function isTemplateTail(node: Node): node is TemplateTail; + function isIdentifier(node: Node): node is Identifier; + function isQualifiedName(node: Node): node is QualifiedName; + function isComputedPropertyName(node: Node): node is ComputedPropertyName; + function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration; + function isParameter(node: Node): node is ParameterDeclaration; + function isDecorator(node: Node): node is Decorator; + function isPropertySignature(node: Node): node is PropertySignature; + function isPropertyDeclaration(node: Node): node is PropertyDeclaration; + function isMethodSignature(node: Node): node is MethodSignature; + function isMethodDeclaration(node: Node): node is MethodDeclaration; + function isConstructorDeclaration(node: Node): node is ConstructorDeclaration; + function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration; + function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration; + function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration; + function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration; + function isTypePredicateNode(node: Node): node is TypePredicateNode; + function isTypeReferenceNode(node: Node): node is TypeReferenceNode; + function isFunctionTypeNode(node: Node): node is FunctionTypeNode; + function isConstructorTypeNode(node: Node): node is ConstructorTypeNode; + function isTypeQueryNode(node: Node): node is TypeQueryNode; + function isTypeLiteralNode(node: Node): node is TypeLiteralNode; + function isArrayTypeNode(node: Node): node is ArrayTypeNode; + function isTupleTypeNode(node: Node): node is TupleTypeNode; + function isUnionTypeNode(node: Node): node is UnionTypeNode; + function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode; + function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode; + function isThisTypeNode(node: Node): node is ThisTypeNode; + function isTypeOperatorNode(node: Node): node is TypeOperatorNode; + function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; + function isMappedTypeNode(node: Node): node is MappedTypeNode; + function isLiteralTypeNode(node: Node): node is LiteralTypeNode; + function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; + function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; + function isBindingElement(node: Node): node is BindingElement; + function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression; + function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression; + function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression; + function isElementAccessExpression(node: Node): node is ElementAccessExpression; + function isCallExpression(node: Node): node is CallExpression; + function isNewExpression(node: Node): node is NewExpression; + function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression; + function isTypeAssertion(node: Node): node is TypeAssertion; + function isParenthesizedExpression(node: Node): node is ParenthesizedExpression; + function skipPartiallyEmittedExpressions(node: Expression): Expression; + function skipPartiallyEmittedExpressions(node: Node): Node; + function isFunctionExpression(node: Node): node is FunctionExpression; + function isArrowFunction(node: Node): node is ArrowFunction; + function isDeleteExpression(node: Node): node is DeleteExpression; + function isTypeOfExpression(node: Node): node is TypeOfExpression; + function isVoidExpression(node: Node): node is VoidExpression; + function isAwaitExpression(node: Node): node is AwaitExpression; + function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression; + function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression; + function isBinaryExpression(node: Node): node is BinaryExpression; + function isConditionalExpression(node: Node): node is ConditionalExpression; + function isTemplateExpression(node: Node): node is TemplateExpression; + function isYieldExpression(node: Node): node is YieldExpression; + function isSpreadElement(node: Node): node is SpreadElement; + function isClassExpression(node: Node): node is ClassExpression; + function isOmittedExpression(node: Node): node is OmittedExpression; + function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; + function isAsExpression(node: Node): node is AsExpression; + function isNonNullExpression(node: Node): node is NonNullExpression; + function isMetaProperty(node: Node): node is MetaProperty; + function isTemplateSpan(node: Node): node is TemplateSpan; + function isSemicolonClassElement(node: Node): node is SemicolonClassElement; + function isBlock(node: Node): node is Block; + function isVariableStatement(node: Node): node is VariableStatement; + function isEmptyStatement(node: Node): node is EmptyStatement; + function isExpressionStatement(node: Node): node is ExpressionStatement; + function isIfStatement(node: Node): node is IfStatement; + function isDoStatement(node: Node): node is DoStatement; + function isWhileStatement(node: Node): node is WhileStatement; + function isForStatement(node: Node): node is ForStatement; + function isForInStatement(node: Node): node is ForInStatement; + function isForOfStatement(node: Node): node is ForOfStatement; + function isContinueStatement(node: Node): node is ContinueStatement; + function isBreakStatement(node: Node): node is BreakStatement; + function isReturnStatement(node: Node): node is ReturnStatement; + function isWithStatement(node: Node): node is WithStatement; + function isSwitchStatement(node: Node): node is SwitchStatement; + function isLabeledStatement(node: Node): node is LabeledStatement; + function isThrowStatement(node: Node): node is ThrowStatement; + function isTryStatement(node: Node): node is TryStatement; + function isDebuggerStatement(node: Node): node is DebuggerStatement; + function isVariableDeclaration(node: Node): node is VariableDeclaration; + function isVariableDeclarationList(node: Node): node is VariableDeclarationList; + function isFunctionDeclaration(node: Node): node is FunctionDeclaration; + function isClassDeclaration(node: Node): node is ClassDeclaration; + function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration; + function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration; + function isEnumDeclaration(node: Node): node is EnumDeclaration; + function isModuleDeclaration(node: Node): node is ModuleDeclaration; + function isModuleBlock(node: Node): node is ModuleBlock; + function isCaseBlock(node: Node): node is CaseBlock; + function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration; + function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration; + function isImportDeclaration(node: Node): node is ImportDeclaration; + function isImportClause(node: Node): node is ImportClause; + function isNamespaceImport(node: Node): node is NamespaceImport; + function isNamedImports(node: Node): node is NamedImports; + function isImportSpecifier(node: Node): node is ImportSpecifier; + function isExportAssignment(node: Node): node is ExportAssignment; + function isExportDeclaration(node: Node): node is ExportDeclaration; + function isNamedExports(node: Node): node is NamedExports; + function isExportSpecifier(node: Node): node is ExportSpecifier; + function isMissingDeclaration(node: Node): node is MissingDeclaration; + function isExternalModuleReference(node: Node): node is ExternalModuleReference; + function isJsxElement(node: Node): node is JsxElement; + function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement; + function isJsxOpeningElement(node: Node): node is JsxOpeningElement; + function isJsxClosingElement(node: Node): node is JsxClosingElement; + function isJsxAttribute(node: Node): node is JsxAttribute; + function isJsxAttributes(node: Node): node is JsxAttributes; + function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute; + function isJsxExpression(node: Node): node is JsxExpression; + function isCaseClause(node: Node): node is CaseClause; + function isDefaultClause(node: Node): node is DefaultClause; + function isHeritageClause(node: Node): node is HeritageClause; + function isCatchClause(node: Node): node is CatchClause; + function isPropertyAssignment(node: Node): node is PropertyAssignment; + function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment; + function isSpreadAssignment(node: Node): node is SpreadAssignment; + function isEnumMember(node: Node): node is EnumMember; + function isSourceFile(node: Node): node is SourceFile; + function isBundle(node: Node): node is Bundle; + function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; + function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; + function isJSDocUnknownType(node: Node): node is JSDocUnknownType; + function isJSDocNullableType(node: Node): node is JSDocNullableType; + function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType; + function isJSDocOptionalType(node: Node): node is JSDocOptionalType; + function isJSDocFunctionType(node: Node): node is JSDocFunctionType; + function isJSDocVariadicType(node: Node): node is JSDocVariadicType; + function isJSDoc(node: Node): node is JSDoc; + function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocParameterTag(node: Node): node is JSDocParameterTag; + function isJSDocReturnTag(node: Node): node is JSDocReturnTag; + function isJSDocTypeTag(node: Node): node is JSDocTypeTag; + function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag; + function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag; + function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; + function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; + function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; } declare namespace ts { /** - * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. */ - function createNodeArray(elements?: T[], hasTrailingComma?: boolean): NodeArray; + function isToken(n: Node): boolean; + function isLiteralExpression(node: Node): node is LiteralExpression; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; + function isStringTextContainingNode(node: Node): boolean; + function isModifier(node: Node): node is Modifier; + function isEntityName(node: Node): node is EntityName; + function isPropertyName(node: Node): node is PropertyName; + function isBindingName(node: Node): node is BindingName; + function isFunctionLike(node: Node): node is FunctionLike; + function isClassElement(node: Node): node is ClassElement; + function isClassLike(node: Node): node is ClassLikeDeclaration; + function isAccessor(node: Node): node is AccessorDeclaration; + function isTypeElement(node: Node): node is TypeElement; + function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node: Node): node is TypeNode; + function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode; + function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName; + function isCallLikeExpression(node: Node): node is CallLikeExpression; + function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression; + function isTemplateLiteral(node: Node): node is TemplateLiteral; + function isAssertionExpression(node: Node): node is AssertionExpression; + function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; + function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; + function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node: Node): boolean; +} +declare namespace ts { + function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; + function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName: string, sourceText: string): JsonSourceFile; + function isExternalModule(file: SourceFile): boolean; + function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; +} +declare namespace ts { + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + /** + * Cached module resolutions per containing directory. + * This assumes that any module id will have the same resolution for sibling files located in the same folder. + */ + interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { + getOrCreateCacheForDirectory(directoryName: string): Map; + } + /** + * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory + * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. + */ + interface NonRelativeModuleNameResolutionCache { + getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; + } + interface PerModuleNameCache { + get(directory: string): ResolvedModuleWithFailedLookupLocations; + set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; + } + function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + function createNodeArray(elements?: ReadonlyArray, hasTrailingComma?: boolean): NodeArray; function createLiteral(value: string): StringLiteral; function createLiteral(value: number): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; @@ -2755,36 +3083,36 @@ 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 createTypeParameterDeclaration(name: string | Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; + function createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; function updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - 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 createParameter(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; + function updateParameter(node: ParameterDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | 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 createMethodSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined): MethodSignature; + function createPropertySignature(modifiers: ReadonlyArray | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function updatePropertySignature(node: PropertySignature, modifiers: ReadonlyArray | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertySignature; + function createProperty(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function updateProperty(node: PropertyDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; + function createMethodSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, 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; - function createGetAccessor(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: string | PropertyName, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - 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 createMethod(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function updateMethod(node: MethodDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; + function createConstructor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function updateConstructor(node: ConstructorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, body: Block | undefined): ConstructorDeclaration; + function createGetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function updateGetAccessor(node: GetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; + function createSetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; + function updateSetAccessor(node: SetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, 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 createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; + function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, 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 createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | 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; @@ -2792,17 +3120,17 @@ declare namespace ts { 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 createTypeLiteralNode(members: ReadonlyArray): 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 createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode; + function updateTypleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): 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 createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray): UnionOrIntersectionTypeNode; function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; @@ -2814,34 +3142,34 @@ declare namespace ts { 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; - function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ArrayBindingElement[]): ArrayBindingPattern; + function createObjectBindingPattern(elements: ReadonlyArray): ObjectBindingPattern; + function updateObjectBindingPattern(node: ObjectBindingPattern, elements: ReadonlyArray): ObjectBindingPattern; + function createArrayBindingPattern(elements: ReadonlyArray): ArrayBindingPattern; + function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ReadonlyArray): ArrayBindingPattern; function createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; - function createArrayLiteral(elements?: Expression[], multiLine?: boolean): ArrayLiteralExpression; - function updateArrayLiteral(node: ArrayLiteralExpression, elements: Expression[]): ArrayLiteralExpression; - function createObjectLiteral(properties?: ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; - function updateObjectLiteral(node: ObjectLiteralExpression, properties: ObjectLiteralElementLike[]): ObjectLiteralExpression; + function createArrayLiteral(elements?: ReadonlyArray, multiLine?: boolean): ArrayLiteralExpression; + function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; + function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; + function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; function createPropertyAccess(expression: Expression, name: string | Identifier): PropertyAccessExpression; function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - function createCall(expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]): CallExpression; - function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[]): CallExpression; - function createNew(expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[] | undefined): NewExpression; - function updateNew(node: NewExpression, expression: Expression, typeArguments: TypeNode[] | undefined, argumentsArray: Expression[] | undefined): NewExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; + function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; function createParen(expression: Expression): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - function createArrowFunction(modifiers: Modifier[] | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; - function updateArrowFunction(node: ArrowFunction, modifiers: Modifier[] | undefined, typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined, body: ConciseBody): ArrowFunction; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; + function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; function createTypeOf(expression: Expression): TypeOfExpression; @@ -2859,18 +3187,18 @@ declare namespace ts { 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; - function createTemplateExpression(head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; - function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; function createYield(expression?: Expression): YieldExpression; function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function createSpread(expression: Expression): SpreadElement; function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; - function createClassExpression(modifiers: Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; - function updateClassExpression(node: ClassExpression, modifiers: Modifier[] | undefined, name: Identifier | undefined, typeParameters: TypeParameterDeclaration[] | undefined, heritageClauses: HeritageClause[], members: ClassElement[]): ClassExpression; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; function createOmittedExpression(): OmittedExpression; - function createExpressionWithTypeArguments(typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; function createAsExpression(expression: Expression, type: TypeNode): AsExpression; function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; @@ -2880,10 +3208,10 @@ declare namespace ts { 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 createBlock(statements: ReadonlyArray, multiLine?: boolean): Block; + function updateBlock(node: Block, statements: ReadonlyArray): Block; + function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement; + function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement; function createEmptyStatement(): EmptyStatement; function createStatement(expression: Expression): ExpressionStatement; function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; @@ -2918,50 +3246,50 @@ declare namespace ts { 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; - function updateModuleDeclaration(node: ModuleDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; - function createModuleBlock(statements: Statement[]): ModuleBlock; - function updateModuleBlock(node: ModuleBlock, statements: Statement[]): ModuleBlock; - function createCaseBlock(clauses: CaseOrDefaultClause[]): CaseBlock; - function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; + function createVariableDeclarationList(declarations: ReadonlyArray, flags?: NodeFlags): VariableDeclarationList; + function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; + function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; + function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; + function createEnumDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, members: ReadonlyArray): EnumDeclaration; + function updateEnumDeclaration(node: EnumDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, members: ReadonlyArray): EnumDeclaration; + function createModuleDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; + function updateModuleDeclaration(node: ModuleDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + function createModuleBlock(statements: ReadonlyArray): ModuleBlock; + function updateModuleBlock(node: ModuleBlock, statements: ReadonlyArray): ModuleBlock; + function createCaseBlock(clauses: ReadonlyArray): CaseBlock; + function updateCaseBlock(node: CaseBlock, clauses: ReadonlyArray): 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; - function updateImportDeclaration(node: ImportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; - function createImportClause(name: Identifier, namedBindings: NamedImportBindings): ImportClause; - function updateImportClause(node: ImportClause, name: Identifier, namedBindings: NamedImportBindings): ImportClause; + function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; + function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; + function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function createNamespaceImport(name: Identifier): NamespaceImport; function updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; - function createNamedImports(elements: ImportSpecifier[]): NamedImports; - function updateNamedImports(node: NamedImports, elements: ImportSpecifier[]): NamedImports; + function createNamedImports(elements: ReadonlyArray): NamedImports; + function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - function createExportAssignment(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; - function updateExportAssignment(node: ExportAssignment, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, expression: Expression): ExportAssignment; - function createExportDeclaration(decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; - function updateExportDeclaration(node: ExportDeclaration, decorators: Decorator[] | undefined, modifiers: Modifier[] | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; - function createNamedExports(elements: ExportSpecifier[]): NamedExports; - function updateNamedExports(node: NamedExports, elements: ExportSpecifier[]): NamedExports; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; + function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; + function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; + function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; + function createNamedExports(elements: ReadonlyArray): NamedExports; + function updateNamedExports(node: NamedExports, elements: ReadonlyArray): NamedExports; function createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; function createExternalModuleReference(expression: Expression): ExternalModuleReference; function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; - function createJsxElement(openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement): JsxElement; - function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: JsxChild[], closingElement: JsxClosingElement): JsxElement; + function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; + function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; @@ -2970,18 +3298,18 @@ declare namespace ts { function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; 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 createJsxAttributes(properties: ReadonlyArray): JsxAttributes; + function updateJsxAttributes(node: JsxAttributes, properties: ReadonlyArray): 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 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 createCaseClause(expression: Expression, statements: ReadonlyArray): CaseClause; + function updateCaseClause(node: CaseClause, expression: Expression, statements: ReadonlyArray): CaseClause; + function createDefaultClause(statements: ReadonlyArray): DefaultClause; + function updateDefaultClause(node: DefaultClause, statements: ReadonlyArray): DefaultClause; + function createHeritageClause(token: HeritageClause["token"], types: ReadonlyArray): HeritageClause; + function updateHeritageClause(node: HeritageClause, types: ReadonlyArray): 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; @@ -2992,7 +3320,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: Statement[]): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -3014,10 +3342,12 @@ 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 createCommaList(elements: ReadonlyArray): CommaListExpression; + function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; function createBundle(sourceFiles: SourceFile[]): Bundle; function updateBundle(node: Bundle, sourceFiles: SourceFile[]): Bundle; + function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression; + function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression): Expression; function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; @@ -3039,10 +3369,6 @@ declare namespace ts { */ function disposeEmitNodes(sourceFile: SourceFile): void; function setTextRange(range: T, location: TextRange | undefined): T; - /** - * Gets flags that control emit behavior of a node. - */ - function getEmitFlags(node: Node): EmitFlags | undefined; /** * Sets flags that control emit behavior of a node. */ @@ -3050,19 +3376,23 @@ declare namespace ts { /** * Gets a custom text range to use when emitting source maps. */ - function getSourceMapRange(node: Node): TextRange; + function getSourceMapRange(node: Node): SourceMapRange; /** * Sets a custom text range to use when emitting source maps. */ - function setSourceMapRange(node: T, range: TextRange | undefined): T; + function setSourceMapRange(node: T, range: SourceMapRange | undefined): T; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource; /** * Gets the TextRange to use for source maps for a token of a node. */ - function getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange | undefined; + function getTokenSourceMapRange(node: Node, token: SyntaxKind): SourceMapRange | undefined; /** * Sets the TextRange to use for source maps for a token of a node. */ - function setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange | undefined): T; + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: SourceMapRange | undefined): T; /** * Gets a custom text range to use when emitting comments. */ @@ -3107,58 +3437,6 @@ declare namespace ts { function moveEmitHelpers(source: Node, target: Node, predicate: (helper: EmitHelper) => boolean): void; function setOriginalNode(node: T, original: Node | undefined): T; } -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 | 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 { - function moduleHasNonRelativeName(moduleName: string): boolean; - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; - /** - * Cached module resolutions per containing directory. - * This assumes that any module id will have the same resolution for sibling files located in the same folder. - */ - interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache { - getOrCreateCacheForDirectory(directoryName: string): Map; - } - /** - * Stored map from non-relative module name to a table: directory -> result of module lookup in this directory - * We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive. - */ - interface NonRelativeModuleNameResolutionCache { - getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; - } - interface PerModuleNameCache { - get(directory: string): ResolvedModuleWithFailedLookupLocations; - set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; - } - function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; -} declare namespace ts { /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. @@ -3256,15 +3534,28 @@ declare namespace ts { function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + /** + * 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. + */ function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { - function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; + function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; /** * Read tsconfig.json file * @param fileName The path to the config file */ - function readConfigFile(fileName: string, readFile: (path: string) => string): { + function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { config?: any; error?: Diagnostic; }; @@ -3273,20 +3564,35 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { + function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic; }; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse * @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; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @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 + */ + function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; @@ -3312,31 +3618,36 @@ declare namespace ts { getText(sourceFile?: SourceFile): string; getFirstToken(sourceFile?: SourceFile): Node; getLastToken(sourceFile?: SourceFile): Node; - forEachChild(cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; + forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; + } + interface Identifier { + readonly text: string; } interface Symbol { + readonly name: string; getFlags(): SymbolFlags; + getEscapedName(): __String; getName(): string; - getDeclarations(): Declaration[]; + getDeclarations(): Declaration[] | undefined; getDocumentationComment(): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; } 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; } interface Signature { getDeclaration(): SignatureDeclaration; - getTypeParameters(): TypeParameter[]; + getTypeParameters(): TypeParameter[] | undefined; getParameters(): Symbol[]; getReturnType(): Type; getDocumentationComment(): SymbolDisplayPart[]; @@ -3352,6 +3663,9 @@ declare namespace ts { interface SourceFileLike { getLineAndCharacterOfPosition(pos: number): LineAndCharacter; } + interface SourceMapSource { + getLineAndCharacterOfPosition(pos: number): LineAndCharacter; + } /** * Represents an immutable snapshot of a script at a specified time.Once acquired, the * snapshot is observably immutable. i.e. the same calls with the same parameters will return @@ -3402,8 +3716,8 @@ declare namespace ts { trace?(s: string): void; error?(s: string): void; useCaseSensitiveFileNames?(): boolean; - readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; - readFile?(path: string, encoding?: string): string; + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + readFile?(path: string, encoding?: string): string | undefined; fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; @@ -3461,7 +3775,7 @@ declare 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; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; @@ -3472,7 +3786,7 @@ declare namespace ts { } interface ClassifiedSpan { textSpan: TextSpan; - classificationType: string; + classificationType: ClassificationTypeNames; } /** * Navigation bar interface designed for visual studio's dual-column layout. @@ -3482,7 +3796,7 @@ declare namespace ts { */ interface NavigationBarItem { text: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; spans: TextSpan[]; childItems: NavigationBarItem[]; @@ -3497,8 +3811,7 @@ declare namespace ts { 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; /** @@ -3532,10 +3845,54 @@ declare namespace ts { /** Text changes to apply to each file as part of the code action */ changes: FileTextChanges[]; } + /** + * A set of one or more available refactoring actions, grouped under a parent refactoring. + */ interface ApplicableRefactorInfo { + /** + * The programmatic name of the refactoring + */ name: string; + /** + * A description of this refactoring category to show to the user. + * If the refactoring gets inlined (see below), this text will not be visible. + */ description: string; + /** + * Inlineable refactorings can have their actions hoisted out to the top level + * of a context menu. Non-inlineanable refactorings should always be shown inside + * their parent grouping. + * + * If not specified, this value is assumed to be 'true' + */ + inlineable?: boolean; + actions: RefactorActionInfo[]; } + /** + * Represents a single refactoring action - for example, the "Extract Method..." refactor might + * offer several actions, each corresponding to a surround class or closure to extract into. + */ + type RefactorActionInfo = { + /** + * The programmatic name of the refactoring action + */ + name: string; + /** + * A description of this refactoring action to show to the user. + * If the parent refactoring is inlined away, this will be the only text shown, + * so this description should make sense by itself if the parent is inlineable=true + */ + description: string; + }; + /** + * A set of edits to make in response to a refactor action, plus an optional + * location where renaming should be invoked from + */ + type RefactorEditInfo = { + edits: FileTextChanges[]; + renameFilename?: string; + renameLocation?: number; + }; interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -3553,35 +3910,35 @@ declare namespace ts { isInString?: true; } interface ImplementationLocation extends DocumentSpan { - kind: string; + kind: ScriptElementKind; displayParts: SymbolDisplayPart[]; } interface DocumentHighlights { fileName: string; highlightSpans: HighlightSpan[]; } - namespace HighlightSpanKind { - const none = "none"; - const definition = "definition"; - const reference = "reference"; - const writtenReference = "writtenReference"; + enum HighlightSpanKind { + none = "none", + definition = "definition", + reference = "reference", + writtenReference = "writtenReference", } interface HighlightSpan { fileName?: string; isInString?: true; textSpan: TextSpan; - kind: string; + kind: HighlightSpanKind; } interface NavigateToItem { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; matchKind: string; isCaseSensitive: boolean; fileName: string; textSpan: TextSpan; containerName: string; - containerKind: string; + containerKind: ScriptElementKind; } enum IndentStyle { None = 0, @@ -3641,9 +3998,9 @@ declare namespace ts { interface DefinitionInfo { fileName: string; textSpan: TextSpan; - kind: string; + kind: ScriptElementKind; name: string; - containerKind: string; + containerKind: ScriptElementKind; containerName: string; } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { @@ -3686,7 +4043,7 @@ declare namespace ts { text?: string; } interface QuickInfo { - kind: string; + kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; displayParts: SymbolDisplayPart[]; @@ -3698,7 +4055,7 @@ declare namespace ts { localizedErrorMessage: string; displayName: string; fullDisplayName: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } @@ -3745,7 +4102,7 @@ declare namespace ts { } interface CompletionEntry { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; sortText: string; /** @@ -3757,7 +4114,7 @@ declare namespace ts { } interface CompletionEntryDetails { name: string; - kind: string; + kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; documentation: SymbolDisplayPart[]; @@ -3842,107 +4199,107 @@ declare namespace ts { getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; } - namespace ScriptElementKind { - const unknown = ""; - const warning = "warning"; + enum ScriptElementKind { + unknown = "", + warning = "warning", /** predefined type (void) or keyword (class) */ - const keyword = "keyword"; + keyword = "keyword", /** top level script node */ - const scriptElement = "script"; + scriptElement = "script", /** module foo {} */ - const moduleElement = "module"; + moduleElement = "module", /** class X {} */ - const classElement = "class"; + classElement = "class", /** var x = class X {} */ - const localClassElement = "local class"; + localClassElement = "local class", /** interface Y {} */ - const interfaceElement = "interface"; + interfaceElement = "interface", /** type T = ... */ - const typeElement = "type"; + typeElement = "type", /** enum E */ - const enumElement = "enum"; - const enumMemberElement = "enum member"; + enumElement = "enum", + enumMemberElement = "enum member", /** * Inside module and script only * const v = .. */ - const variableElement = "var"; + variableElement = "var", /** Inside function */ - const localVariableElement = "local var"; + localVariableElement = "local var", /** * Inside module and script only * function f() { } */ - const functionElement = "function"; + functionElement = "function", /** Inside function */ - const localFunctionElement = "local function"; + localFunctionElement = "local function", /** class X { [public|private]* foo() {} } */ - const memberFunctionElement = "method"; + memberFunctionElement = "method", /** class X { [public|private]* [get|set] foo:number; } */ - const memberGetAccessorElement = "getter"; - const memberSetAccessorElement = "setter"; + memberGetAccessorElement = "getter", + memberSetAccessorElement = "setter", /** * class X { [public|private]* foo:number; } * interface Y { foo:number; } */ - const memberVariableElement = "property"; + memberVariableElement = "property", /** class X { constructor() { } } */ - const constructorImplementationElement = "constructor"; + constructorImplementationElement = "constructor", /** interface Y { ():number; } */ - const callSignatureElement = "call"; + callSignatureElement = "call", /** interface Y { []:number; } */ - const indexSignatureElement = "index"; + indexSignatureElement = "index", /** interface Y { new():Y; } */ - const constructSignatureElement = "construct"; + constructSignatureElement = "construct", /** function foo(*Y*: string) */ - const parameterElement = "parameter"; - const typeParameterElement = "type parameter"; - const primitiveType = "primitive type"; - const label = "label"; - const alias = "alias"; - const constElement = "const"; - const letElement = "let"; - const directory = "directory"; - const externalModuleName = "external module name"; + parameterElement = "parameter", + typeParameterElement = "type parameter", + primitiveType = "primitive type", + label = "label", + alias = "alias", + constElement = "const", + letElement = "let", + directory = "directory", + externalModuleName = "external module name", /** * */ - const jsxAttribute = "JSX attribute"; + jsxAttribute = "JSX attribute", } - namespace ScriptElementKindModifier { - const none = ""; - const publicMemberModifier = "public"; - const privateMemberModifier = "private"; - const protectedMemberModifier = "protected"; - const exportedModifier = "export"; - const ambientModifier = "declare"; - const staticModifier = "static"; - const abstractModifier = "abstract"; + enum ScriptElementKindModifier { + none = "", + publicMemberModifier = "public", + privateMemberModifier = "private", + protectedMemberModifier = "protected", + exportedModifier = "export", + ambientModifier = "declare", + staticModifier = "static", + abstractModifier = "abstract", } - class ClassificationTypeNames { - static comment: string; - static identifier: string; - static keyword: string; - static numericLiteral: string; - static operator: string; - static stringLiteral: string; - static whiteSpace: string; - static text: string; - static punctuation: string; - static className: string; - static enumName: string; - static interfaceName: string; - static moduleName: string; - static typeParameterName: string; - static typeAliasName: string; - static parameterName: string; - static docCommentTagName: string; - static jsxOpenTagName: string; - static jsxCloseTagName: string; - static jsxSelfClosingTagName: string; - static jsxAttribute: string; - static jsxText: string; - static jsxAttributeStringLiteralValue: string; + enum ClassificationTypeNames { + comment = "comment", + identifier = "identifier", + keyword = "keyword", + numericLiteral = "number", + operator = "operator", + stringLiteral = "string", + whiteSpace = "whitespace", + text = "text", + punctuation = "punctuation", + 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", } enum ClassificationType { comment = 1, diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 9f28644b4e5..eb71a73ba46 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -13,6 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +"use strict"; var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; @@ -336,40 +337,32 @@ var ts; SyntaxKind[SyntaxKind["JSDocAllType"] = 268] = "JSDocAllType"; // The ? type 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["JSDocNullableType"] = 270] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 271] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 272] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 273] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 274] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 275] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTag"] = 276] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 277] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 278] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 279] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 280] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 281] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 282] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 283] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 284] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 285] = "JSDocTypeLiteral"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 294] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 286] = "SyntaxList"; // Transformation nodes - 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["NotEmittedStatement"] = 287] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 288] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 289] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 290] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 291] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 300] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 292] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -397,9 +390,9 @@ var ts; 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[SyntaxKind["LastJSDocNode"] = 285] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 276] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 285] = "LastJSDocTagNode"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -423,6 +416,17 @@ var ts; NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; + // This flag will be set when the parser encounters a dynamic import expression so that module resolution + // will not have to walk the tree if the flag is not set. However, this flag is just a approximation because + // once it is set, the flag never gets cleared (hence why it's named "PossiblyContainsDynamicImport"). + // During editing, if dynamic import is removed, incremental parsing will *NOT* update this flag. This means that the tree will always be traversed + // during module resolution. However, the removal operation should not occur often and in the case of the + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. + /* @internal */ + NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; @@ -557,18 +561,20 @@ var ts; (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[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 2048] = "UseTypeAliasValue"; + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -646,13 +652,11 @@ var ts; 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["Alias"] = 2097152] = "Alias"; + SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -681,14 +685,13 @@ var ts; 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["AliasExcludes"] = 2097152] = "AliasExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "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"; /* @internal */ // The set of things we consider semantically classifiable. Used to speed up the LS during @@ -716,6 +719,25 @@ var ts; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + var InternalSymbolName; + (function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["Resolving"] = "__resolving__"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {})); /* @internal */ var NodeCheckFlags; (function (NodeCheckFlags) { @@ -826,6 +848,18 @@ var ts; IndexKind[IndexKind["String"] = 0] = "String"; IndexKind[IndexKind["Number"] = 1] = "Number"; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); + var InferencePriority; + (function (InferencePriority) { + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; + })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); + var InferenceFlags; + (function (InferenceFlags) { + InferenceFlags[InferenceFlags["InferUnionTypes"] = 1] = "InferUnionTypes"; + InferenceFlags[InferenceFlags["NoDefault"] = 2] = "NoDefault"; + InferenceFlags[InferenceFlags["AnyDefault"] = 4] = "AnyDefault"; + })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {})); /* @internal */ var SpecialPropertyAssignmentKind; (function (SpecialPropertyAssignmentKind) { @@ -860,6 +894,7 @@ var ts; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {})); var JsxEmit; (function (JsxEmit) { @@ -881,6 +916,7 @@ var ts; ScriptKind[ScriptKind["TS"] = 3] = "TS"; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; + ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -1039,12 +1075,11 @@ var ts; })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {})); var Extension; (function (Extension) { - Extension[Extension["Ts"] = 0] = "Ts"; - Extension[Extension["Tsx"] = 1] = "Tsx"; - Extension[Extension["Dts"] = 2] = "Dts"; - Extension[Extension["Js"] = 3] = "Js"; - Extension[Extension["Jsx"] = 4] = "Jsx"; - Extension[Extension["LastTypeScriptExtension"] = 2] = "LastTypeScriptExtension"; + Extension["Ts"] = ".ts"; + Extension["Tsx"] = ".tsx"; + Extension["Dts"] = ".d.ts"; + Extension["Js"] = ".js"; + Extension["Jsx"] = ".jsx"; })(Extension = ts.Extension || (ts.Extension = {})); /* @internal */ var TransformFlags; @@ -1082,6 +1117,10 @@ var ts; TransformFlags[TransformFlags["ContainsBindingPattern"] = 8388608] = "ContainsBindingPattern"; TransformFlags[TransformFlags["ContainsYield"] = 16777216] = "ContainsYield"; TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 33554432] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 67108864] = "ContainsDynamicImport"; + // Please leave this as 1 << 29. + // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. + // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. @@ -1168,6 +1207,7 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of @@ -1179,7 +1219,7 @@ var ts; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 32768] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1287,8 +1327,11 @@ var ts; /// var ts; (function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "2.5"; /** The version of the TypeScript compiler release */ - ts.version = "2.4.0"; + ts.version = ts.versionMajorMinor + ".0"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -1326,14 +1369,32 @@ var ts; return new MapCtr(); } ts.createMap = createMap; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + /* @internal */ + function createSymbolTable(symbols) { + var result = createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; function createMapFromTemplate(template) { var map = new MapCtr(); // Copies keys/values from template. Note that for..in will not throw if // template is undefined, and instead will just exit the loop. - for (var key in template) + for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); } + } return map; } ts.createMapFromTemplate = createMapFromTemplate; @@ -1407,46 +1468,6 @@ var ts; return class_1; }()); } - function createFileMap(keyMapper) { - var files = createMap(); - return { - get: get, - set: set, - contains: contains, - remove: remove, - forEachValue: forEachValueInMap, - getKeys: getKeys, - clear: clear, - }; - function forEachValueInMap(f) { - files.forEach(function (file, key) { - f(key, file); - }); - } - function getKeys() { - return arrayFrom(files.keys()); - } - // path should already be well-formed so it does not need to be normalized - function get(path) { - return files.get(toKey(path)); - } - function set(path, value) { - files.set(toKey(path), value); - } - function contains(path) { - return files.has(toKey(path)); - } - function remove(path) { - files.delete(toKey(path)); - } - function clear() { - files.clear(); - } - function toKey(path) { - return keyMapper ? keyMapper(path) : path; - } - } - ts.createFileMap = createFileMap; function toPath(fileName, basePath, getCanonicalFileName) { var nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) @@ -1657,6 +1678,10 @@ var ts; array.length = outIndex; } ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; function map(array, f) { var result; if (array) { @@ -1668,7 +1693,6 @@ var ts; return result; } ts.map = map; - // Maps from T to T and avoids allocation if all elements map to themselves function sameMap(array, f) { var result; if (array) { @@ -1738,13 +1762,19 @@ 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 flatMapIter(iter, mapfn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapfn(value); + if (res) + result.push.apply(result, res); + } + return result; + } + ts.flatMapIter = flatMapIter; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1767,6 +1797,18 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapDefined(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } + } + return result; + } + ts.mapDefined = mapDefined; /** * Computes the first matching span of elements and returns a tuple of the first span * and the remaining elements. @@ -1916,9 +1958,6 @@ var ts; !equalOwnProperties(oldOptions.paths, newOptions.paths); } ts.changesAffectModuleResolution = changesAffectModuleResolution; - /** - * Compacts an array, removing any falsey elements. - */ function compact(array) { var result; if (array) { @@ -1966,6 +2005,7 @@ var ts; var result = 0; for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { var v = array_7[_i]; + // Note: we need the following type assertion because of GH #17069 result += v[prop]; } return result; @@ -1988,6 +2028,13 @@ var ts; return to; } ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } /** * Appends a range of value to an array, returning the array. * @@ -1995,13 +2042,21 @@ var ts; * is created if `value` was appended. * @param from The values to append to the array. If `from` is `undefined`, nothing is * appended. If an element of `from` is `undefined`, that element is not appended. + * @param start The offset in `from` at which to start copying values. + * @param end The offset in `from` at which to stop copying values (non-inclusive). */ - function addRange(to, from) { + function addRange(to, from, start, end) { if (from === undefined) return to; - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - to = append(to, v); + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + var v = from[i]; + if (v !== undefined) { + to.push(from[i]); + } } return to; } @@ -2027,22 +2082,32 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; /** * Returns the first element of an array if non-empty, `undefined` otherwise. */ function firstOrUndefined(array) { - return array && array.length > 0 - ? array[0] - : undefined; + return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; /** * Returns the last element of an array if non-empty, `undefined` otherwise. */ function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; /** @@ -2054,10 +2119,6 @@ var ts; : undefined; } ts.singleOrUndefined = singleOrUndefined; - /** - * Returns the only element of an array if it contains only one element; otheriwse, returns the - * array. - */ function singleOrMany(array) { return array && array.length === 1 ? array[0] @@ -2181,10 +2242,11 @@ var ts; */ function getOwnKeys(map) { var keys = []; - for (var key in map) + for (var key in map) { if (hasOwnProperty.call(map, key)) { keys.push(key); } + } return keys; } ts.getOwnKeys = getOwnKeys; @@ -2197,19 +2259,6 @@ var ts; var _b; } ts.arrayFrom = arrayFrom; - function convertToArray(iterator, f) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(f(value)); - } - return result; - var _b; - } - ts.convertToArray = convertToArray; - /** - * Calls `callback` for each entry in the map, returning the first truthy result. - * Use `map.forEach` instead for normal iteration. - */ function forEachEntry(map, callback) { var iterator = map.entries(); for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { @@ -2223,7 +2272,6 @@ var ts; var _b; } ts.forEachEntry = forEachEntry; - /** `forEachEntry` for just keys. */ function forEachKey(map, callback) { var iterator = map.keys(); for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { @@ -2236,7 +2284,6 @@ var ts; var _b; } ts.forEachKey = forEachKey; - /** Copy entries from `source` to `target`. */ function copyEntries(source, target) { source.forEach(function (value, key) { target.set(key, value); @@ -2250,10 +2297,11 @@ var ts; } for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var arg = args_1[_a]; - for (var p in arg) + for (var p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; } + } } return t; } @@ -2269,18 +2317,20 @@ var ts; return true; if (!left || !right) return false; - for (var key in left) + for (var key in left) { if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } - for (var key in right) + } + for (var key in right) { if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } + } return true; } ts.equalOwnProperties = equalOwnProperties; @@ -2293,6 +2343,10 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToSet(array, makeKey) { + return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -2311,14 +2365,16 @@ var ts; ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) + for (var id in second) { if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - for (var id in first) + } + for (var id in first) { if (hasOwnProperty.call(first, id)) { result[id] = first[id]; } + } return result; } ts.extend = extend; @@ -2355,6 +2411,16 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; /** Does nothing. */ function noop() { } ts.noop = noop; @@ -2696,12 +2762,23 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + /* @internal */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isExternalModuleNameRelative(moduleName) { // TypeScript 1.0 spec (April 2014): 11.2.1 // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + /** @deprecated Use `!isExternalModuleNameRelative(moduleName)` instead. */ + function moduleHasNonRelativeName(moduleName) { + return !isExternalModuleNameRelative(moduleName); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0 /* ES3 */; } @@ -2824,7 +2901,7 @@ var ts; if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] - directoryComponents.length--; + directoryComponents.pop(); } // Find the component that differs var joinStartIndex; @@ -2962,7 +3039,8 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsAny(path, extensions) { + /* @internal */ + function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; if (fileExtensionIs(path, extension)) { @@ -2971,7 +3049,7 @@ var ts; } return false; } - ts.fileExtensionIsAny = fileExtensionIsAny; + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. @@ -3097,7 +3175,7 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -3111,17 +3189,16 @@ var ts; var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } return flatten(results); - function visitDirectory(path, absolutePath) { + function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; files = files.slice().sort(comparer); - directories = directories.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; @@ -3139,13 +3216,20 @@ var ts; var current = files_1[_i]; _loop_1(current); } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + directories = directories.slice().sort(comparer); for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { var current = directories_1[_b]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName); + visitDirectory(name, absoluteName, depth); } } } @@ -3201,20 +3285,22 @@ var ts; // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt // to get the ScriptKind from the file name. If it cannot be resolved // from the file name then the default 'TS' script kind is returned. - return (scriptKind || getScriptKindFromFileName(fileName)) || 3 /* TS */; + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; } ts.ensureScriptKind = ensureScriptKind; function getScriptKindFromFileName(fileName) { var ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { - case ".js": + case ".js" /* Js */: return 1 /* JS */; - case ".jsx": + case ".jsx" /* Jsx */: return 2 /* JSX */; - case ".ts": + case ".ts" /* Ts */: return 3 /* TS */; - case ".tsx": + case ".tsx" /* Tsx */: return 4 /* TSX */; + case ".json": + return 6 /* JSON */; default: return 0 /* Unknown */; } @@ -3223,10 +3309,10 @@ var ts; /** * List of supported extensions in order of file resolution precedence. */ - ts.supportedTypeScriptExtensions = [".ts", ".tsx", ".d.ts"]; + ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"]; - ts.supportedJavascriptExtensions = [".js", ".jsx"]; + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; @@ -3314,7 +3400,7 @@ var ts; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; function removeFileExtension(path) { for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { var ext = extensionsToRemove_1[_i]; @@ -3340,11 +3426,14 @@ var ts; ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; this.declarations = undefined; } - function Type(_checker, flags) { + function Type(checker, flags) { this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } } function Signature() { } @@ -3359,6 +3448,11 @@ var ts; this.parent = undefined; this.original = undefined; } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, getTokenConstructor: function () { return Node; }, @@ -3366,7 +3460,8 @@ var ts; getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, - getSignatureConstructor: function () { return Signature; } + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; var AssertionLevel; (function (AssertionLevel) { @@ -3378,25 +3473,43 @@ var ts; var Debug; (function (Debug) { Debug.currentAssertionLevel = 0 /* None */; + Debug.isDebugging = false; function shouldAssert(level) { return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo) { + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { - var verboseDebugString = ""; if (verboseDebugInfo) { - verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); } - debugger; - throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; - function fail(message) { - Debug.assert(/*expression*/ false, message); + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; } Debug.fail = fail; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; })(Debug = ts.Debug || (ts.Debug = {})); /** Remove an item from an array, moving everything to its right one space left. */ function orderedRemoveItem(array, item) { @@ -3524,7 +3637,7 @@ var ts; ts.positionIsSynthesized = positionIsSynthesized; /** True if an extension is one of the supported TypeScript extensions. */ function extensionIsTypeScript(ext) { - return ext <= ts.Extension.LastTypeScriptExtension; + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; } ts.extensionIsTypeScript = extensionIsTypeScript; /** @@ -3540,21 +3653,7 @@ var ts; } ts.extensionFromPath = extensionFromPath; function tryGetExtensionFromPath(path) { - if (fileExtensionIs(path, ".d.ts")) { - return ts.Extension.Dts; - } - if (fileExtensionIs(path, ".ts")) { - return ts.Extension.Ts; - } - if (fileExtensionIs(path, ".tsx")) { - return ts.Extension.Tsx; - } - if (fileExtensionIs(path, ".js")) { - return ts.Extension.Js; - } - if (fileExtensionIs(path, ".jsx")) { - return ts.Extension.Jsx; - } + return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3565,6 +3664,12 @@ var ts; /// var ts; (function (ts) { + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -3640,7 +3745,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName); + fileCallback(fileName, FileWatcherEventKind.Changed); } } } @@ -3654,9 +3759,15 @@ var ts; if (platform === "win32" || platform === "win64") { return false; } - // convert current file name to upper case / lower case and check if file exists - // (guards against cases when name is already all uppercase or lowercase) - return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); @@ -3737,8 +3848,8 @@ var ts; return { files: [], directories: [] }; } } - function readDirectory(path, extensions, excludes, includes) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries); } var FileSystemEntryKind; (function (FileSystemEntryKind) { @@ -3790,10 +3901,19 @@ var ts; }; } function fileChanged(curr, prev) { - if (+curr.mtime <= +prev.mtime) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { return; } - callback(fileName); + callback(fileName, eventKind); } }, watchDirectory: function (directoryName, callback, recursive) { @@ -3820,9 +3940,7 @@ var ts; } }); }, - resolvePath: function (path) { - return _path.resolve(path); - }, + resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { @@ -3876,6 +3994,7 @@ var ts; realpath: function (path) { return _fs.realpathSync(path); }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { try { require("source-map-support").install(); @@ -3915,7 +4034,7 @@ var ts; getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), - readDirectory: function (path, extensions, excludes, includes) { + readDirectory: function (path, extensions, excludes, includes, _depth) { var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, @@ -3960,913 +4079,936 @@ var ts; ? 1 /* Normal */ : 0 /* None */; } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } })(ts || (ts = {})); // /// /* @internal */ var ts; (function (ts) { + function diag(code, category, key, message) { + return { code: code, category: category, key: key, message: message }; + } ts.Diagnostics = { - Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated_string_literal_1002", message: "Unterminated string literal." }, - Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_1003", message: "Identifier expected." }, - _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "_0_expected_1005", message: "'{0}' expected." }, - A_file_cannot_have_a_reference_to_itself: { code: 1006, category: ts.DiagnosticCategory.Error, key: "A_file_cannot_have_a_reference_to_itself_1006", message: "A file cannot have a reference to itself." }, - Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing_comma_not_allowed_1009", message: "Trailing comma not allowed." }, - Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "Asterisk_Slash_expected_1010", message: "'*/' expected." }, - Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_1012", message: "Unexpected token." }, - A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_last_in_a_parameter_list_1014", message: "A rest parameter must be last in a parameter list." }, - Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: ts.DiagnosticCategory.Error, key: "Parameter_cannot_have_question_mark_and_initializer_1015", message: "Parameter cannot have question mark and initializer." }, - A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: ts.DiagnosticCategory.Error, key: "A_required_parameter_cannot_follow_an_optional_parameter_1016", message: "A required parameter cannot follow an optional parameter." }, - An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: ts.DiagnosticCategory.Error, key: "An_index_signature_cannot_have_a_rest_parameter_1017", message: "An index signature cannot have a rest parameter." }, - An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", message: "An index signature parameter cannot have an accessibility modifier." }, - An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_a_question_mark_1019", message: "An index signature parameter cannot have a question mark." }, - An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_initializer_1020", message: "An index signature parameter cannot have an initializer." }, - An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, - An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, - An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, - readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, - Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, - _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, - _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, - _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_class_element_1031", message: "'{0}' modifier cannot appear on a class element." }, - super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: ts.DiagnosticCategory.Error, key: "super_must_be_followed_by_an_argument_list_or_member_access_1034", message: "'super' must be followed by an argument list or member access." }, - Only_ambient_modules_can_use_quoted_names: { code: 1035, category: ts.DiagnosticCategory.Error, key: "Only_ambient_modules_can_use_quoted_names_1035", message: "Only ambient modules can use quoted names." }, - Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: ts.DiagnosticCategory.Error, key: "Statements_are_not_allowed_in_ambient_contexts_1036", message: "Statements are not allowed in ambient contexts." }, - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", message: "A 'declare' modifier cannot be used in an already ambient context." }, - Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: ts.DiagnosticCategory.Error, key: "Initializers_are_not_allowed_in_ambient_contexts_1039", message: "Initializers are not allowed in ambient contexts." }, - _0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_in_an_ambient_context_1040", message: "'{0}' modifier cannot be used in an ambient context." }, - _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, - _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, - _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, - A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, - A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, - A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, - A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_have_an_initializer_1048", message: "A rest parameter cannot have an initializer." }, - A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_must_have_exactly_one_parameter_1049", message: "A 'set' accessor must have exactly one parameter." }, - A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_an_optional_parameter_1051", message: "A 'set' accessor cannot have an optional parameter." }, - A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, - A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, - A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, - An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, - The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", message: "The return type of an async function must either be a valid promise or must not contain a callable 'then' member." }, - A_promise_must_have_a_then_method: { code: 1059, category: ts.DiagnosticCategory.Error, key: "A_promise_must_have_a_then_method_1059", message: "A promise must have a 'then' method." }, - The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: { code: 1060, category: ts.DiagnosticCategory.Error, key: "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", message: "The first parameter of the 'then' method of a promise must be a callback." }, - Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, - Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, - An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, - In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, - Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, - _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, - _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, - A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, - Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." }, - An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_be_declared_in_an_ambient_context_1086", message: "An accessor cannot be declared in an ambient context." }, - _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", message: "'{0}' modifier cannot appear on a constructor declaration." }, - _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_parameter_1090", message: "'{0}' modifier cannot appear on a parameter." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", message: "Only a single variable declaration is allowed in a 'for...in' statement." }, - Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: ts.DiagnosticCategory.Error, key: "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", message: "Type parameters cannot appear on a constructor declaration." }, - Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: ts.DiagnosticCategory.Error, key: "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", message: "Type annotation cannot appear on a constructor declaration." }, - An_accessor_cannot_have_type_parameters: { code: 1094, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_have_type_parameters_1094", message: "An accessor cannot have type parameters." }, - A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_a_return_type_annotation_1095", message: "A 'set' accessor cannot have a return type annotation." }, - An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_exactly_one_parameter_1096", message: "An index signature must have exactly one parameter." }, - _0_list_cannot_be_empty: { code: 1097, category: ts.DiagnosticCategory.Error, key: "_0_list_cannot_be_empty_1097", message: "'{0}' list cannot be empty." }, - Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type_parameter_list_cannot_be_empty_1098", message: "Type parameter list cannot be empty." }, - Type_argument_list_cannot_be_empty: { code: 1099, category: ts.DiagnosticCategory.Error, key: "Type_argument_list_cannot_be_empty_1099", message: "Type argument list cannot be empty." }, - Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_in_strict_mode_1100", message: "Invalid use of '{0}' in strict mode." }, - with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_strict_mode_1101", message: "'with' statements are not allowed in strict mode." }, - delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", message: "'delete' cannot be called on an identifier in strict mode." }, - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: { code: 1103, category: ts.DiagnosticCategory.Error, key: "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", message: "A 'for-await-of' statement is only allowed within an async function or async generator." }, - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", message: "A 'continue' statement can only be used within an enclosing iteration statement." }, - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", message: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, - Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump_target_cannot_cross_function_boundary_1107", message: "Jump target cannot cross function boundary." }, - A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: ts.DiagnosticCategory.Error, key: "A_return_statement_can_only_be_used_within_a_function_body_1108", message: "A 'return' statement can only be used within a function body." }, - Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." }, - Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." }, - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", message: "A 'default' clause cannot appear more than once in a 'switch' statement." }, - Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'." }, - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", message: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", message: "A 'break' statement can only jump to a label of an enclosing statement." }, - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", message: "An object literal cannot have multiple properties with the same name in strict mode." }, - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", message: "An object literal cannot have multiple get/set accessors with the same name." }, - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", message: "An object literal cannot have property and accessor with the same name." }, - An_export_assignment_cannot_have_modifiers: { code: 1120, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_have_modifiers_1120", message: "An export assignment cannot have modifiers." }, - Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_strict_mode_1121", message: "Octal literals are not allowed in strict mode." }, - A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: ts.DiagnosticCategory.Error, key: "A_tuple_type_element_list_cannot_be_empty_1122", message: "A tuple type element list cannot be empty." }, - Variable_declaration_list_cannot_be_empty: { code: 1123, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_list_cannot_be_empty_1123", message: "Variable declaration list cannot be empty." }, - Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit_expected_1124", message: "Digit expected." }, - Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal_digit_expected_1125", message: "Hexadecimal digit expected." }, - Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected_end_of_text_1126", message: "Unexpected end of text." }, - Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid_character_1127", message: "Invalid character." }, - Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration_or_statement_expected_1128", message: "Declaration or statement expected." }, - Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement_expected_1129", message: "Statement expected." }, - case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "case_or_default_expected_1130", message: "'case' or 'default' expected." }, - Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property_or_signature_expected_1131", message: "Property or signature expected." }, - Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum_member_expected_1132", message: "Enum member expected." }, - Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_expected_1134", message: "Variable declaration expected." }, - Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument_expression_expected_1135", message: "Argument expression expected." }, - Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property_assignment_expected_1136", message: "Property assignment expected." }, - Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression_or_comma_expected_1137", message: "Expression or comma expected." }, - Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter_declaration_expected_1138", message: "Parameter declaration expected." }, - Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type_parameter_declaration_expected_1139", message: "Type parameter declaration expected." }, - Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type_argument_expected_1140", message: "Type argument expected." }, - String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, - Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, - or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, - Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, - File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing." }, - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, - const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized." }, - const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "const_declarations_can_only_be_declared_inside_a_block_1156", message: "'const' declarations can only be declared inside a block." }, - let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "let_declarations_can_only_be_declared_inside_a_block_1157", message: "'let' declarations can only be declared inside a block." }, - Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." }, - Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated_regular_expression_literal_1161", message: "Unterminated regular expression literal." }, - An_object_member_cannot_be_declared_optional: { code: 1162, category: ts.DiagnosticCategory.Error, key: "An_object_member_cannot_be_declared_optional_1162", message: "An object member cannot be declared optional." }, - A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: ts.DiagnosticCategory.Error, key: "A_yield_expression_is_only_allowed_in_a_generator_body_1163", message: "A 'yield' expression is only allowed in a generator body." }, - Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "Computed_property_names_are_not_allowed_in_enums_1164", message: "Computed property names are not allowed in enums." }, - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", message: "A computed property name in an ambient context must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", message: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", message: "A computed property name in a method overload must directly refer to a built-in symbol." }, - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", message: "A computed property name in an interface must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", message: "A computed property name in a type literal must directly refer to a built-in symbol." }, - A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: ts.DiagnosticCategory.Error, key: "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", message: "A comma expression is not allowed in a computed property name." }, - extends_clause_already_seen: { code: 1172, category: ts.DiagnosticCategory.Error, key: "extends_clause_already_seen_1172", message: "'extends' clause already seen." }, - extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "extends_clause_must_precede_implements_clause_1173", message: "'extends' clause must precede 'implements' clause." }, - Classes_can_only_extend_a_single_class: { code: 1174, category: ts.DiagnosticCategory.Error, key: "Classes_can_only_extend_a_single_class_1174", message: "Classes can only extend a single class." }, - implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "implements_clause_already_seen_1175", message: "'implements' clause already seen." }, - Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface_declaration_cannot_have_implements_clause_1176", message: "Interface declaration cannot have 'implements' clause." }, - Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary_digit_expected_1177", message: "Binary digit expected." }, - Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal_digit_expected_1178", message: "Octal digit expected." }, - Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_expected_1179", message: "Unexpected token. '{' expected." }, - Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property_destructuring_pattern_expected_1180", message: "Property destructuring pattern expected." }, - Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array_element_destructuring_pattern_expected_1181", message: "Array element destructuring pattern expected." }, - A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: ts.DiagnosticCategory.Error, key: "A_destructuring_declaration_must_have_an_initializer_1182", message: "A destructuring declaration must have an initializer." }, - An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1183, category: ts.DiagnosticCategory.Error, key: "An_implementation_cannot_be_declared_in_ambient_contexts_1183", message: "An implementation cannot be declared in ambient contexts." }, - Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, - Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, - A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, - The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, - The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, - An_import_declaration_cannot_have_modifiers: { code: 1191, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_cannot_have_modifiers_1191", message: "An import declaration cannot have modifiers." }, - Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, - An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, - Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, - Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, - An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, - Unterminated_Unicode_escape_sequence: { code: 1199, category: ts.DiagnosticCategory.Error, key: "Unterminated_Unicode_escape_sequence_1199", message: "Unterminated Unicode escape sequence." }, - 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." }, - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", message: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." }, - Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", message: "Invalid use of '{0}'. Class definitions are automatically in strict mode." }, - A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, - Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, - Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, - Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, - Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, - Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: ts.DiagnosticCategory.Error, key: "Generators_are_not_allowed_in_an_ambient_context_1221", message: "Generators are not allowed in an ambient context." }, - An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, - _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "_0_tag_already_specified_1223", message: "'{0}' tag already specified." }, - Signature_0_must_have_a_type_predicate: { code: 1224, category: ts.DiagnosticCategory.Error, key: "Signature_0_must_have_a_type_predicate_1224", message: "Signature '{0}' must have a type predicate." }, - Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot_find_parameter_0_1225", message: "Cannot find parameter '{0}'." }, - Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: ts.DiagnosticCategory.Error, key: "Type_predicate_0_is_not_assignable_to_1_1226", message: "Type predicate '{0}' is not assignable to '{1}'." }, - Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: ts.DiagnosticCategory.Error, key: "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", message: "Parameter '{0}' is not in the same position as parameter '{1}'." }, - A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", message: "A type predicate is only allowed in return type position for functions and methods." }, - A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_a_rest_parameter_1229", message: "A type predicate cannot reference a rest parameter." }, - A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", message: "A type predicate cannot reference element '{0}' in a binding pattern." }, - An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_can_only_be_used_in_a_module_1231", message: "An export assignment can only be used in a module." }, - An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", message: "An import declaration can only be used in a namespace or module." }, - An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_can_only_be_used_in_a_module_1233", message: "An export declaration can only be used in a module." }, - An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", message: "An ambient module declaration is only allowed at the top level in a file." }, - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", message: "A namespace declaration is only allowed in a namespace or module." }, - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", message: "The return type of a property decorator function must be either 'void' or 'any'." }, - The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", message: "The return type of a parameter decorator function must be either 'void' or 'any'." }, - Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", message: "Unable to resolve signature of class decorator when called as an expression." }, - Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, - Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, - Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, - _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, - Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, - Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, - An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, - A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, - A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, - A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: { code: 1250, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, - _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, - with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, - await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, - The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, - Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, - Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, - Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, - A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, - An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, - A_default_export_can_only_be_used_in_an_ECMAScript_style_module: { code: 1319, category: ts.DiagnosticCategory.Error, key: "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", message: "A default export can only be used in an ECMAScript-style module." }, - Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1320, category: ts.DiagnosticCategory.Error, key: "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", message: "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1321, category: ts.DiagnosticCategory.Error, key: "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", message: "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1322, category: ts.DiagnosticCategory.Error, key: "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", message: "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member." }, - Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, - Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, - Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, - Circular_definition_of_import_alias_0: { code: 2303, category: ts.DiagnosticCategory.Error, key: "Circular_definition_of_import_alias_0_2303", message: "Circular definition of import alias '{0}'." }, - Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_2304", message: "Cannot find name '{0}'." }, - Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, - File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, - Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, - Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, - An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, - Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, - A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, - An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, - Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, - Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, - Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, - Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_have_1_type_parameter_s_2317", message: "Global type '{0}' must have {1} type parameter(s)." }, - Cannot_find_global_type_0: { code: 2318, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_type_0_2318", message: "Cannot find global type '{0}'." }, - Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: ts.DiagnosticCategory.Error, key: "Named_property_0_of_types_1_and_2_are_not_identical_2319", message: "Named property '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, - Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, - Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, - Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, - Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, - Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: ts.DiagnosticCategory.Error, key: "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", message: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: ts.DiagnosticCategory.Error, key: "Types_of_parameters_0_and_1_are_incompatible_2328", message: "Types of parameters '{0}' and '{1}' are incompatible." }, - Index_signature_is_missing_in_type_0: { code: 2329, category: ts.DiagnosticCategory.Error, key: "Index_signature_is_missing_in_type_0_2329", message: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index_signatures_are_incompatible_2330", message: "Index signatures are incompatible." }, - this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", message: "'this' cannot be referenced in a module or namespace body." }, - this_cannot_be_referenced_in_current_location: { code: 2332, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_current_location_2332", message: "'this' cannot be referenced in current location." }, - this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_constructor_arguments_2333", message: "'this' cannot be referenced in constructor arguments." }, - this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_static_property_initializer_2334", message: "'this' cannot be referenced in a static property initializer." }, - super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_a_derived_class_2335", message: "'super' can only be referenced in a derived class." }, - super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_constructor_arguments_2336", message: "'super' cannot be referenced in constructor arguments." }, - Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: ts.DiagnosticCategory.Error, key: "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", message: "Super calls are not permitted outside constructors or in nested functions inside constructors." }, - super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: ts.DiagnosticCategory.Error, key: "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", message: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." }, - Property_0_does_not_exist_on_type_1: { code: 2339, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_2339", message: "Property '{0}' does not exist on type '{1}'." }, - Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, - Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, - An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, - 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}'." }, - 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." }, - Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, - Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, - Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, - Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, - The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, - The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter." }, - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, - Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, - Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, - Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'." }, - A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", message: "A parameter property is only allowed in a constructor implementation." }, - A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_of_an_array_type_2370", message: "A rest parameter must be of an array type." }, - A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", message: "A parameter initializer is only allowed in a function or constructor implementation." }, - Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: ts.DiagnosticCategory.Error, key: "Parameter_0_cannot_be_referenced_in_its_initializer_2372", message: "Parameter '{0}' cannot be referenced in its initializer." }, - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: ts.DiagnosticCategory.Error, key: "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", message: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, - Duplicate_string_index_signature: { code: 2374, category: ts.DiagnosticCategory.Error, key: "Duplicate_string_index_signature_2374", message: "Duplicate string index signature." }, - Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, - Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, - Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, - get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, - A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, - Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, - Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, - Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, - Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, - Function_overload_must_be_static: { code: 2387, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_be_static_2387", message: "Function overload must be static." }, - Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_not_be_static_2388", message: "Function overload must not be static." }, - Function_implementation_name_must_be_0: { code: 2389, category: ts.DiagnosticCategory.Error, key: "Function_implementation_name_must_be_0_2389", message: "Function implementation name must be '{0}'." }, - Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor_implementation_is_missing_2390", message: "Constructor implementation is missing." }, - Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: ts.DiagnosticCategory.Error, key: "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", message: "Function implementation is missing or not immediately following the declaration." }, - Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: ts.DiagnosticCategory.Error, key: "Multiple_constructor_implementations_are_not_allowed_2392", message: "Multiple constructor implementations are not allowed." }, - Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate_function_implementation_2393", message: "Duplicate function implementation." }, - Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, - Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, - Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, - Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, - Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, - Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, - Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", message: "Expression resolves to '_super' that compiler uses to capture base class reference." }, - Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, - The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, - The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, - Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, - Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class." }, - The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, - Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, - Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, - Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, - Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'." }, - Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, - A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, - Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'." }, - All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, - Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'." }, - In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, - A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged." }, - A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged." }, - Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", message: "Ambient modules cannot be nested in other modules or namespaces." }, - Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient_module_declaration_cannot_specify_relative_module_name_2436", message: "Ambient module declaration cannot specify relative module name." }, - Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name." }, - Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'." }, - Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", message: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." }, - Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." }, - Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types_have_separate_declarations_of_a_private_property_0_2442", message: "Types have separate declarations of a private property '{0}'." }, - Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", message: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." }, - Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", message: "Property '{0}' is protected in type '{1}' but public in type '{2}'." }, - Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", message: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, - The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, - Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - Class_0_used_before_its_declaration: { code: 2449, category: ts.DiagnosticCategory.Error, key: "Class_0_used_before_its_declaration_2449", message: "Class '{0}' used before its declaration." }, - Enum_0_used_before_its_declaration: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Enum_0_used_before_its_declaration_2450", message: "Enum '{0}' used before its declaration." }, - Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, - An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, - The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, - Variable_0_is_used_before_being_assigned: { code: 2454, category: ts.DiagnosticCategory.Error, key: "Variable_0_is_used_before_being_assigned_2454", message: "Variable '{0}' is used before being assigned." }, - Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", message: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, - Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type_alias_0_circularly_references_itself_2456", message: "Type alias '{0}' circularly references itself." }, - Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'." }, - An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An_AMD_module_cannot_have_multiple_name_assignments_2458", message: "An AMD module cannot have multiple name assignments." }, - Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, - Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, - Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern." }, - A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, - A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, - this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, - super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_a_computed_property_name_2466", message: "'super' cannot be referenced in a computed property name." }, - A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", message: "A computed property name cannot reference a type parameter from its containing type." }, - Cannot_find_global_value_0: { code: 2468, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_value_0_2468", message: "Cannot find global value '{0}'." }, - The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: ts.DiagnosticCategory.Error, key: "The_0_operator_cannot_be_applied_to_type_symbol_2469", message: "The '{0}' operator cannot be applied to type 'symbol'." }, - Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: ts.DiagnosticCategory.Error, key: "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", message: "'Symbol' reference does not refer to the global Symbol constructor object." }, - A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", message: "A computed property name of the form '{0}' must be of type 'symbol'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", message: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." }, - Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: ts.DiagnosticCategory.Error, key: "Enum_declarations_must_all_be_const_or_non_const_2473", message: "Enum declarations must all be const or non-const." }, - In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: ts.DiagnosticCategory.Error, key: "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", message: "In 'const' enum declarations member initializer must be constant expression." }, - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: ts.DiagnosticCategory.Error, key: "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", message: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." }, - A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: ts.DiagnosticCategory.Error, key: "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", message: "A const enum member can only be accessed using a string literal." }, - const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", message: "'const' enum member initializer was evaluated to a non-finite value." }, - const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", message: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, - Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_const_enum_1_2479", message: "Property '{0}' does not exist on 'const' enum '{1}'." }, - let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", message: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." }, - Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, - The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, - Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'." }, - The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, - An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, - The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", message: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." }, - Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause." }, - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", message: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." }, - Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", message: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." }, - Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_2495", message: "Type '{0}' is not an array type or a string type." }, - The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", message: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." }, - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: ts.DiagnosticCategory.Error, key: "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", message: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." }, - Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: ts.DiagnosticCategory.Error, key: "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", message: "Module '{0}' uses 'export =' and cannot be used with 'export *'." }, - An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", message: "An interface can only extend an identifier/qualified-name with optional type arguments." }, - A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", message: "A class can only implement an identifier/qualified-name with optional type arguments." }, - A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, - _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, - Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: { code: 2504, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", message: "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator." }, - A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, - _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, - Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, - No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: ts.DiagnosticCategory.Error, key: "No_base_constructor_has_the_specified_number_of_type_arguments_2508", message: "No base constructor has the specified number of type arguments." }, - Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, - Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, - Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, - Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, - Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, - Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, - All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, - Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, - A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, - An_async_iterator_must_have_a_next_method: { code: 2519, category: ts.DiagnosticCategory.Error, key: "An_async_iterator_must_have_a_next_method_2519", message: "An async iterator must have a 'next()' method." }, - Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, - Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, - yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, - await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, - A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, - A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, - Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, - Object_is_possibly_null: { code: 2531, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_2531", message: "Object is possibly 'null'." }, - Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, - Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, - A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, - Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, - Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, - Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, - Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, - The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, - Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, - Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, - Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, - A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, - The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: { code: 2547, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", message: "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property." }, - Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { 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." }, - Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'." }, - JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", message: "JSX element type '{0}' does not have any construct or call signatures." }, - JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", message: "JSX element type '{0}' is not a constructor function for JSX elements." }, - Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", message: "Property '{0}' of JSX spread attribute is not assignable to target property." }, - JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property." }, - The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property." }, - JSX_spread_child_must_be_an_array_type: { code: 2609, category: ts.DiagnosticCategory.Error, key: "JSX_spread_child_must_be_an_array_type_2609", message: "JSX spread child must be an array type." }, - Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: { code: 2649, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", message: "Cannot augment module '{0}' with value exports because it resolves to a non-module entity." }, - Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React." }, - A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", message: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." }, - Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", message: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, - Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", message: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." }, - Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, - Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, - JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element." }, - Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'." }, - super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, - super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, - Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", message: "Cannot export '{0}'. Only local declarations can be exported from a module." }, - Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, - Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, - Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, - Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, - Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, - Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, - export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, - Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, - Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, - Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, - Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, - Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, - Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, - Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, - Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, - A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: { code: 2677, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", message: "A type predicate's type must be assignable to its parameter's type." }, - Type_0_is_not_comparable_to_type_1: { code: 2678, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_comparable_to_type_1_2678", message: "Type '{0}' is not comparable to type '{1}'." }, - A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: { code: 2679, category: ts.DiagnosticCategory.Error, key: "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", message: "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'." }, - A_this_parameter_must_be_the_first_parameter: { code: 2680, category: ts.DiagnosticCategory.Error, key: "A_this_parameter_must_be_the_first_parameter_2680", message: "A 'this' parameter must be the first parameter." }, - A_constructor_cannot_have_a_this_parameter: { code: 2681, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_have_a_this_parameter_2681", message: "A constructor cannot have a 'this' parameter." }, - get_and_set_accessor_must_have_the_same_this_type: { code: 2682, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_this_type_2682", message: "'get' and 'set' accessor must have the same 'this' type." }, - this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, - The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, - The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, - All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, - Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, - Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, - Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, - The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, - Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, - Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: { code: 2699, category: ts.DiagnosticCategory.Error, key: "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", message: "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'." }, - Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, - The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, - The_operand_of_a_delete_operator_must_be_a_property_reference: { code: 2703, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", message: "The operand of a delete operator must be a property reference." }, - The_operand_of_a_delete_operator_cannot_be_a_read_only_property: { code: 2704, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", message: "The operand of a delete operator cannot be a read-only property." }, - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: { code: 2705, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", message: "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option." }, - Required_type_parameters_may_not_follow_optional_type_parameters: { code: 2706, category: ts.DiagnosticCategory.Error, key: "Required_type_parameters_may_not_follow_optional_type_parameters_2706", message: "Required type parameters may not follow optional type parameters." }, - Generic_type_0_requires_between_1_and_2_type_arguments: { code: 2707, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_between_1_and_2_type_arguments_2707", message: "Generic type '{0}' requires between {1} and {2} type arguments." }, - Cannot_use_namespace_0_as_a_value: { code: 2708, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_value_2708", message: "Cannot use namespace '{0}' as a value." }, - Cannot_use_namespace_0_as_a_type: { code: 2709, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_type_2709", message: "Cannot use namespace '{0}' as a type." }, - _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: { code: 2710, category: ts.DiagnosticCategory.Error, key: "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", message: "'{0}' are specified twice. The attribute named '{0}' will be overwritten." }, - Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, - Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, - Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", message: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", message: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", message: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", message: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", message: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", message: "Type parameter '{0}' of exported function has or is using private name '{1}'." }, - Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", message: "Implements clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "'extends' clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "'extends' clause of exported interface '{0}' has or is using private name '{1}'." }, - Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", message: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." }, - Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", message: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." }, - Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_private_name_1_4025", message: "Exported variable '{0}' has or is using private name '{1}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", message: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", message: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", message: "Public static property '{0}' of exported class has or is using private name '{1}'." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", message: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", message: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", message: "Public property '{0}' of exported class has or is using private name '{1}'." }, - Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", message: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." }, - Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", message: "Property '{0}' of exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", message: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", message: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", message: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", message: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", message: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", message: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", message: "Return type of public static property getter from exported class has or is using private name '{0}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", message: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", message: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", message: "Return type of public property getter from exported class has or is using private name '{0}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", message: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", message: "Return type of constructor signature from exported interface has or is using private name '{0}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", message: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", message: "Return type of call signature from exported interface has or is using private name '{0}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", message: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", message: "Return type of index signature from exported interface has or is using private name '{0}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", message: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", message: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", message: "Return type of public static method from exported class has or is using private name '{0}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", message: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", message: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", message: "Return type of public method from exported class has or is using private name '{0}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", message: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", message: "Return type of method from exported interface has or is using private name '{0}'." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", message: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", message: "Return type of exported function has or is using name '{0}' from private module '{1}'." }, - Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", message: "Return type of exported function has or is using private name '{0}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", message: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", message: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", message: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", message: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", message: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", message: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", message: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", message: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", message: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", message: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", message: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, - Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, - Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced: { code: 4093, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced_4093", message: "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced." }, - The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, - Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, - File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, - Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}." }, - Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, - Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "Unknown compiler option '{0}'." }, - Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_requires_a_value_of_type_1_5024", message: "Compiler option '{0}' requires a value of type {1}." }, - Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}." }, - Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", message: "Option 'project' cannot be mixed with source files on a command line." }, - Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher." }, - Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", message: "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." }, - Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, - Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, - A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, - Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, - Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, - Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'." }, - The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'." }, - Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, - Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, - Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character." }, - Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character." }, - Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, - Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, - File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, - Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, - Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, - Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, - Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, - Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", message: "Specify the location where debugger should locate TypeScript files instead of source locations." }, - Watch_input_files: { code: 6005, category: ts.DiagnosticCategory.Message, key: "Watch_input_files_6005", message: "Watch input files." }, - Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect_output_structure_to_the_directory_6006", message: "Redirect output structure to the directory." }, - Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: ts.DiagnosticCategory.Message, key: "Do_not_erase_const_enum_declarations_in_generated_code_6007", message: "Do not erase const enum declarations in generated code." }, - Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, - Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, - Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, - Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, - Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'." }, - Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'." }, - Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, - Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, - Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", message: "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'." }, - Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" }, - options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" }, - file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" }, - Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples_Colon_0_6026", message: "Examples: {0}" }, - Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options_Colon_6027", message: "Options:" }, - Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version_0_6029", message: "Version {0}" }, - Insert_command_line_options_and_files_from_a_file: { code: 6030, category: ts.DiagnosticCategory.Message, key: "Insert_command_line_options_and_files_from_a_file_6030", message: "Insert command line options and files from a file." }, - File_change_detected_Starting_incremental_compilation: { code: 6032, category: ts.DiagnosticCategory.Message, key: "File_change_detected_Starting_incremental_compilation_6032", message: "File change detected. Starting incremental compilation..." }, - KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND_6034", message: "KIND" }, - FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE_6035", message: "FILE" }, - VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, - LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, - DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, - STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, - FILE_OR_DIRECTORY: { code: 6040, category: ts.DiagnosticCategory.Message, key: "FILE_OR_DIRECTORY_6040", message: "FILE OR DIRECTORY" }, - Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, - Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, - Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, - Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}." }, - Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, - Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, - Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." }, - Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted_locale_file_0_6051", message: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", message: "Raise error on expressions and declarations with an implied 'any' type." }, - File_0_not_found: { code: 6053, category: ts.DiagnosticCategory.Error, key: "File_0_not_found_6053", message: "File '{0}' not found." }, - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: ts.DiagnosticCategory.Error, key: "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", message: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, - Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: ts.DiagnosticCategory.Message, key: "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", message: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, - Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", message: "Do not emit declarations for code that has an '@internal' annotation." }, - Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: ts.DiagnosticCategory.Message, key: "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", message: "Specify the root directory of input files. Use to control the output directory structure with --outDir." }, - File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", message: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, - Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", message: "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, - NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, - Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, - Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, - Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, - Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, - Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: { code: 6069, category: ts.DiagnosticCategory.Message, key: "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", message: "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)." }, - Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, - Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, - Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context (experimental)." }, - Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, - Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, - Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, - Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, - Specify_library_files_to_be_included_in_the_compilation_Colon: { code: 6079, category: ts.DiagnosticCategory.Message, key: "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", message: "Specify library files to be included in the compilation: " }, - Specify_JSX_code_generation_Colon_preserve_react_native_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", message: "Specify JSX code generation: 'preserve', 'react-native', or 'react'." }, - File_0_has_an_unsupported_extension_so_skipping_it: { code: 6081, category: ts.DiagnosticCategory.Message, key: "File_0_has_an_unsupported_extension_so_skipping_it_6081", message: "File '{0}' has an unsupported extension, so skipping it." }, - Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, - Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, - Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", message: "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit" }, - Enable_tracing_of_the_name_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_name_resolution_process_6085", message: "Enable tracing of the name resolution process." }, - Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, - Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, - Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, - Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, - Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, - paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, - Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, - Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, - Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, - Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", message: "Loading module as file / folder, candidate module location '{0}', target file type '{1}'." }, - File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, - File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, - Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, - Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, - package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, - Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, - Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, - Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, - Expected_type_of_0_field_in_package_json_to_be_string_got_1: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", message: "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'." }, - baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'." }, - rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'." }, - Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'." }, - Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'." }, - Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'." }, - Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed." }, - Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, - Enable_strict_null_checks: { code: 6113, category: ts.DiagnosticCategory.Message, key: "Enable_strict_null_checks_6113", message: "Enable strict null checks." }, - Unknown_option_excludes_Did_you_mean_exclude: { code: 6114, category: ts.DiagnosticCategory.Error, key: "Unknown_option_excludes_Did_you_mean_exclude_6114", message: "Unknown option 'excludes'. Did you mean 'exclude'?" }, - Raise_error_on_this_expressions_with_an_implied_any_type: { code: 6115, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_this_expressions_with_an_implied_any_type_6115", message: "Raise error on 'this' expressions with an implied 'any' type." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_2: { code: 6116, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========" }, - Resolving_using_primary_search_paths: { code: 6117, category: ts.DiagnosticCategory.Message, key: "Resolving_using_primary_search_paths_6117", message: "Resolving using primary search paths..." }, - Resolving_from_node_modules_folder: { code: 6118, category: ts.DiagnosticCategory.Message, key: "Resolving_from_node_modules_folder_6118", message: "Resolving from node_modules folder..." }, - Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: { code: 6119, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", message: "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========" }, - Type_reference_directive_0_was_not_resolved: { code: 6120, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_not_resolved_6120", message: "======== Type reference directive '{0}' was not resolved. ========" }, - Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'." }, - Root_directory_cannot_be_determined_skipping_primary_search_paths: { code: 6122, category: ts.DiagnosticCategory.Message, key: "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", message: "Root directory cannot be determined, skipping primary search paths." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: { code: 6123, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========" }, - Type_declaration_files_to_be_included_in_compilation: { code: 6124, category: ts.DiagnosticCategory.Message, key: "Type_declaration_files_to_be_included_in_compilation_6124", message: "Type declaration files to be included in compilation." }, - Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'." }, - Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: { code: 6126, category: ts.DiagnosticCategory.Message, key: "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", message: "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder." }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: { code: 6127, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", message: "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========" }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, - The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, - Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'." }, - Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, - File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it." }, - _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - 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}'." }, - Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file." }, - Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, - Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, - Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, - Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, - Resolution_for_module_0_was_found_in_cache: { code: 6147, category: ts.DiagnosticCategory.Message, key: "Resolution_for_module_0_was_found_in_cache_6147", message: "Resolution for module '{0}' was found in cache." }, - Directory_0_does_not_exist_skipping_all_lookups_in_it: { code: 6148, category: ts.DiagnosticCategory.Message, key: "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", message: "Directory '{0}' does not exist, skipping all lookups in it." }, - Show_diagnostic_information: { code: 6149, category: ts.DiagnosticCategory.Message, key: "Show_diagnostic_information_6149", message: "Show diagnostic information." }, - Show_verbose_diagnostic_information: { code: 6150, category: ts.DiagnosticCategory.Message, key: "Show_verbose_diagnostic_information_6150", message: "Show verbose diagnostic information." }, - Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: { code: 6151, category: ts.DiagnosticCategory.Message, key: "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", message: "Emit a single file with source maps instead of having a separate file." }, - Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: { code: 6152, category: ts.DiagnosticCategory.Message, key: "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", message: "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set." }, - Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: { code: 6153, category: ts.DiagnosticCategory.Message, key: "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", message: "Transpile each file as a separate module (similar to 'ts.transpileModule')." }, - Print_names_of_generated_files_part_of_the_compilation: { code: 6154, category: ts.DiagnosticCategory.Message, key: "Print_names_of_generated_files_part_of_the_compilation_6154", message: "Print names of generated files part of the compilation." }, - Print_names_of_files_part_of_the_compilation: { code: 6155, category: ts.DiagnosticCategory.Message, key: "Print_names_of_files_part_of_the_compilation_6155", message: "Print names of files part of the compilation." }, - The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: { code: 6156, category: ts.DiagnosticCategory.Message, key: "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", message: "The locale used when displaying messages to the user (e.g. 'en-us')" }, - Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: { code: 6157, category: ts.DiagnosticCategory.Message, key: "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", message: "Do not generate custom helper functions like '__extends' in compiled output." }, - Do_not_include_the_default_library_file_lib_d_ts: { code: 6158, category: ts.DiagnosticCategory.Message, key: "Do_not_include_the_default_library_file_lib_d_ts_6158", message: "Do not include the default library file (lib.d.ts)." }, - Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: { code: 6159, category: ts.DiagnosticCategory.Message, key: "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", message: "Do not add triple-slash references or imported modules to the list of compiled files." }, - Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: { code: 6160, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", message: "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files." }, - List_of_folders_to_include_type_definitions_from: { code: 6161, category: ts.DiagnosticCategory.Message, key: "List_of_folders_to_include_type_definitions_from_6161", message: "List of folders to include type definitions from." }, - Disable_size_limitations_on_JavaScript_projects: { code: 6162, category: ts.DiagnosticCategory.Message, key: "Disable_size_limitations_on_JavaScript_projects_6162", message: "Disable size limitations on JavaScript projects." }, - The_character_set_of_the_input_files: { code: 6163, category: ts.DiagnosticCategory.Message, key: "The_character_set_of_the_input_files_6163", message: "The character set of the input files." }, - Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: { code: 6164, category: ts.DiagnosticCategory.Message, key: "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", message: "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files." }, - Do_not_truncate_error_messages: { code: 6165, category: ts.DiagnosticCategory.Message, key: "Do_not_truncate_error_messages_6165", message: "Do not truncate error messages." }, - Output_directory_for_generated_declaration_files: { code: 6166, category: ts.DiagnosticCategory.Message, key: "Output_directory_for_generated_declaration_files_6166", message: "Output directory for generated declaration files." }, - A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: { code: 6167, category: ts.DiagnosticCategory.Message, key: "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", message: "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'." }, - List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: { code: 6168, category: ts.DiagnosticCategory.Message, key: "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", message: "List of root folders whose combined content represents the structure of the project at runtime." }, - Show_all_compiler_options: { code: 6169, category: ts.DiagnosticCategory.Message, key: "Show_all_compiler_options_6169", message: "Show all compiler options." }, - Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: { code: 6170, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", message: "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file" }, - Command_line_Options: { code: 6171, category: ts.DiagnosticCategory.Message, key: "Command_line_Options_6171", message: "Command-line Options" }, - Basic_Options: { code: 6172, category: ts.DiagnosticCategory.Message, key: "Basic_Options_6172", message: "Basic Options" }, - Strict_Type_Checking_Options: { code: 6173, category: ts.DiagnosticCategory.Message, key: "Strict_Type_Checking_Options_6173", message: "Strict Type-Checking Options" }, - Module_Resolution_Options: { code: 6174, category: ts.DiagnosticCategory.Message, key: "Module_Resolution_Options_6174", message: "Module Resolution Options" }, - Source_Map_Options: { code: 6175, category: ts.DiagnosticCategory.Message, key: "Source_Map_Options_6175", message: "Source Map Options" }, - Additional_Checks: { code: 6176, category: ts.DiagnosticCategory.Message, key: "Additional_Checks_6176", message: "Additional Checks" }, - Experimental_Options: { code: 6177, category: ts.DiagnosticCategory.Message, key: "Experimental_Options_6177", message: "Experimental Options" }, - Advanced_Options: { code: 6178, category: ts.DiagnosticCategory.Message, key: "Advanced_Options_6178", message: "Advanced Options" }, - Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: { code: 6179, category: ts.DiagnosticCategory.Message, key: "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", message: "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'." }, - 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." }, - new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: ts.DiagnosticCategory.Error, key: "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", message: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, - _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, - Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, - Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, - Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, - Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, - Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, - Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", message: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." }, - _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: { code: 7023, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", message: "'{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." }, - 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: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "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." }, - Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, - JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists." }, - Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, - Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, - Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, - Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, - Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, - Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: { code: 7035, category: ts.DiagnosticCategory.Error, key: "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", message: "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`" }, - You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, - You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, - import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, - export_can_only_be_used_in_a_ts_file: { code: 8003, category: ts.DiagnosticCategory.Error, key: "export_can_only_be_used_in_a_ts_file_8003", message: "'export=' can only be used in a .ts file." }, - type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: ts.DiagnosticCategory.Error, key: "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", message: "'type parameter declarations' can only be used in a .ts file." }, - implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: ts.DiagnosticCategory.Error, key: "implements_clauses_can_only_be_used_in_a_ts_file_8005", message: "'implements clauses' can only be used in a .ts file." }, - interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: ts.DiagnosticCategory.Error, key: "interface_declarations_can_only_be_used_in_a_ts_file_8006", message: "'interface declarations' can only be used in a .ts file." }, - module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: ts.DiagnosticCategory.Error, key: "module_declarations_can_only_be_used_in_a_ts_file_8007", message: "'module declarations' can only be used in a .ts file." }, - type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: ts.DiagnosticCategory.Error, key: "type_aliases_can_only_be_used_in_a_ts_file_8008", message: "'type aliases' can only be used in a .ts file." }, - _0_can_only_be_used_in_a_ts_file: { code: 8009, category: ts.DiagnosticCategory.Error, key: "_0_can_only_be_used_in_a_ts_file_8009", message: "'{0}' can only be used in a .ts file." }, - types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, - type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, - parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, - type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, - Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, - JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, - JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, - Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, - JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "JSX attribute expected." }, - Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, - A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'." }, - An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, - super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, - super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, - _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: { code: 17012, category: ts.DiagnosticCategory.Error, key: "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", message: "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" }, - Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: { code: 17013, category: ts.DiagnosticCategory.Error, key: "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", message: "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." }, - Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, - The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, - No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, - Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, - Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, - Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'." }, - Remove_declaration_for_Colon_0: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_declaration_for_Colon_0_90004", message: "Remove declaration for: '{0}'." }, - Implement_interface_0: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_0_90006", message: "Implement interface '{0}'." }, - Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class." }, - Add_this_to_unresolved_variable: { code: 90008, category: ts.DiagnosticCategory.Message, key: "Add_this_to_unresolved_variable_90008", message: "Add 'this.' to unresolved variable." }, - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig." }, - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, - Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}." }, - Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}." }, - Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}." }, - Add_declaration_for_missing_property_0: { code: 90016, category: ts.DiagnosticCategory.Message, key: "Add_declaration_for_missing_property_0_90016", message: "Add declaration for missing property '{0}'." }, - Add_index_signature_for_missing_property_0: { code: 90017, category: ts.DiagnosticCategory.Message, key: "Add_index_signature_for_missing_property_0_90017", message: "Add index signature for missing property '{0}'." }, - Disable_checking_for_this_file: { code: 90018, category: ts.DiagnosticCategory.Message, key: "Disable_checking_for_this_file_90018", message: "Disable checking for this file." }, - 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." }, + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), + A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), + A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), + A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), + A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "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: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "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: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "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: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "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: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), + Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "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: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _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: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{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."), + 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), }; })(ts || (ts = {})); /// @@ -5135,13 +5277,20 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function computePositionOfLineAndCharacter(lineStarts, line, character) { + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { ts.Debug.assert(line >= 0 && line < lineStarts.length); - return lineStarts[line] + character; + var res = lineStarts[line] + character; + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res < debugText.length); + } + return res; } ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; /* @internal */ @@ -5236,6 +5385,7 @@ var ts; case 47 /* slash */: // starts of normal trivia case 60 /* lessThan */: + case 124 /* bar */: case 61 /* equals */: case 62 /* greaterThan */: // Starts of conflict marker trivia @@ -5302,6 +5452,7 @@ var ts; } break; case 60 /* lessThan */: + case 124 /* bar */: case 61 /* equals */: case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { @@ -5358,12 +5509,12 @@ var ts; } } else { - ts.Debug.assert(ch === 61 /* equals */); - // Consume everything from the start of the mid-conflict marker to the start of the next - // end-conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + // Consume everything from the start of a ||||||| or ======= marker to the start + // of the next ======= or >>>>>>> marker. while (pos < len) { - var ch_1 = text.charCodeAt(pos); - if (ch_1 === 62 /* greaterThan */ && isConflictMarkerTrivia(text, pos)) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { break; } pos++; @@ -6110,13 +6261,13 @@ var ts; pos += 2; var commentClosed = false; while (pos < end) { - var ch_2 = text.charCodeAt(pos); - if (ch_2 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { pos += 2; commentClosed = true; break; } - if (isLineBreak(ch_2)) { + if (isLineBreak(ch_1)) { precedingLineBreak = true; } pos++; @@ -6276,6 +6427,15 @@ var ts; pos++; return token = 17 /* OpenBraceToken */; case 124 /* bar */: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7 /* ConflictMarkerTrivia */; + } + } if (text.charCodeAt(pos + 1) === 124 /* bar */) { return pos += 2, token = 54 /* BarBarToken */; } @@ -6636,6 +6796,8 @@ var ts; /* @internal */ var ts; (function (ts) { + ts.emptyArray = []; + ts.emptyMap = ts.createMap(); ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; @@ -6663,51 +6825,51 @@ var ts; return undefined; } ts.findDeclaration = findDeclaration; - // Pool writers to avoid needing to allocate them for every symbol we write. - var stringWriters = []; - function getSingleLineStringWriter() { - if (stringWriters.length === 0) { - var str_1 = ""; - var writeText = function (text) { return str_1 += text; }; - return { - string: function () { return str_1; }, - writeKeyword: writeText, - writeOperator: writeText, - writePunctuation: writeText, - writeSpace: writeText, - writeStringLiteral: writeText, - writeParameter: writeText, - writeProperty: writeText, - writeSymbol: writeText, - // Completely ignore indentation for string writers. And map newlines to - // a single space. - writeLine: function () { return str_1 += " "; }, - increaseIndent: ts.noop, - decreaseIndent: ts.noop, - clear: function () { return str_1 = ""; }, - trackSymbol: ts.noop, - reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop - }; + var stringWriter = createSingleLineStringWriter(); + var stringWriterAcquired = false; + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + string: function () { return str; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + // Completely ignore indentation for string writers. And map newlines to + // a single space. + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function usingSingleLineStringWriter(action) { + try { + ts.Debug.assert(!stringWriterAcquired); + stringWriterAcquired = true; + action(stringWriter); + return stringWriter.string(); + } + finally { + stringWriter.clear(); + stringWriterAcquired = false; } - return stringWriters.pop(); } - ts.getSingleLineStringWriter = getSingleLineStringWriter; - function releaseStringWriter(writer) { - writer.clear(); - stringWriters.push(writer); - } - ts.releaseStringWriter = releaseStringWriter; + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; function getFullWidth(node) { return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function hasResolvedModule(sourceFile, moduleNameText) { - return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText)); - } - ts.hasResolvedModule = hasResolvedModule; function getResolvedModule(sourceFile, moduleNameText) { - return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined; + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); } ts.getResolvedModule = getResolvedModule; function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { @@ -6863,17 +7025,13 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 142 /* LastToken */; - } - ts.isToken = isToken; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. if (nodeIsMissing(node)) { return node.pos; } - if (isJSDocNode(node)) { + if (ts.isJSDocNode(node)) { return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { @@ -6883,20 +7041,12 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 294 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 286 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; - function isJSDocNode(node) { - return node.kind >= 267 /* FirstJSDocNode */ && node.kind <= 293 /* LastJSDocNode */; - } - ts.isJSDocNode = isJSDocNode; - function isJSDocTag(node) { - return node.kind >= 283 /* FirstJSDocTagNode */ && node.kind <= 293 /* LastJSDocTagNode */; - } - ts.isJSDocTag = isJSDocTag; function getNonDecoratorTokenPosOfNode(node, sourceFile) { if (nodeIsMissing(node) || !node.decorators) { return getTokenPosOfNode(node, sourceFile); @@ -6925,13 +7075,21 @@ var ts; return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } ts.getTextOfNode = getTextOfNode; + /** + * Gets flags that control emit behavior of a node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent) { return getSourceTextOfNodeFromSourceFile(sourceFile, node); } - var escapeText = ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + var escapeText = getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; // If we can't reach the original source text, use the canonical form if it's a number, // or a (possibly escaped) quoted form of the original text if it's string-like. switch (node.kind) { @@ -6956,8 +7114,16 @@ var ts; } ts.getTextOfConstantValue = getTextOfConstantValue; // Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + /** + * @deprecated Use `id.escapedText` to get the escaped text of an Identifier. + * @param identifier The identifier to escape + */ function escapeIdentifier(identifier) { - return identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier; + return identifier; } ts.escapeIdentifier = escapeIdentifier; // Make an identifier from an external module name by extracting the string after the last "/" and replacing @@ -6981,6 +7147,11 @@ var ts; (node.name.kind === 9 /* StringLiteral */ || isGlobalScopeAugmentation(node)); } ts.isAmbientModule = isAmbientModule; + /* @internal */ + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; /** Given a symbol for a module, checks that it is a shorthand ambient module. */ function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); @@ -6993,7 +7164,7 @@ var ts; function isBlockScopedContainerTopLevel(node) { return node.kind === 265 /* SourceFile */ || node.kind === 233 /* ModuleDeclaration */ || - isFunctionLike(node); + ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; function isGlobalScopeAugmentation(module) { @@ -7040,7 +7211,7 @@ var ts; case 207 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block - return parentNode && !isFunctionLike(parentNode); + return parentNode && !ts.isFunctionLike(parentNode); } return false; } @@ -7071,13 +7242,13 @@ var ts; function getTextOfPropertyName(name) { switch (name.kind) { case 71 /* Identifier */: - return name.text; + return name.escapedText; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return name.text; + return escapeLeadingUnderscores(name.text); case 144 /* ComputedPropertyName */: if (isStringOrNumericLiteral(name.expression)) { - return name.expression.text; + return escapeLeadingUnderscores(name.expression.text); } } return undefined; @@ -7086,7 +7257,7 @@ var ts; function entityNameToString(name) { switch (name.kind) { case 71 /* Identifier */: - return getFullWidth(name) === 0 ? ts.unescapeIdentifier(name.text) : getTextOfNode(name); + return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); case 143 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); case 179 /* PropertyAccessExpression */: @@ -7200,6 +7371,10 @@ var ts; return n.kind === 181 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 181 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + } + ts.isImportCall = isImportCall; function isPrologueDirective(node) { return node.kind === 210 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; @@ -7217,7 +7392,8 @@ var ts; var commentRanges = (node.kind === 146 /* Parameter */ || node.kind === 145 /* TypeParameter */ || node.kind === 186 /* FunctionExpression */ || - node.kind === 187 /* ArrowFunction */) ? + node.kind === 187 /* ArrowFunction */ || + node.kind === 185 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRangesOfNodeFromText(node, text); // True if the comment starts with '/**' but not if it is '/**/' @@ -7323,10 +7499,6 @@ var ts; return false; } ts.isChildOfNodeWithKind = isChildOfNodeWithKind; - function isPrefixUnaryExpression(node) { - return node.kind === 192 /* PrefixUnaryExpression */; - } - ts.isPrefixUnaryExpression = isPrefixUnaryExpression; // Warning: This has the same semantics as the forEach family of functions, // in that traversal terminates in the event that 'visitor' supplies a truthy value. function forEachReturnStatement(body, visitor) { @@ -7377,7 +7549,7 @@ var ts; // skipped in this traversal. return; default: - if (isFunctionLike(node)) { + if (ts.isFunctionLike(node)) { var name = node.name; if (name && name.kind === 144 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require @@ -7430,47 +7602,6 @@ var ts; return false; } ts.isVariableLike = isVariableLike; - function isAccessor(node) { - return node && (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */); - } - ts.isAccessor = isAccessor; - function isClassLike(node) { - return node && (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */); - } - ts.isClassLike = isClassLike; - function isFunctionLike(node) { - return node && isFunctionLikeKind(node.kind); - } - ts.isFunctionLike = isFunctionLike; - function isFunctionLikeKind(kind) { - switch (kind) { - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - return true; - } - 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 */: @@ -7485,20 +7616,6 @@ var ts; return false; } ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; - function isIterationStatement(node, lookInLabeledStatements) { - switch (node.kind) { - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - return true; - case 222 /* LabeledStatement */: - return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); - } - return false; - } - ts.isIterationStatement = isIterationStatement; function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { while (true) { if (beforeUnwrapLabelCallback) { @@ -7512,7 +7629,7 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 207 /* Block */ && isFunctionLike(node.parent); + return node && node.kind === 207 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { @@ -7533,10 +7650,19 @@ var ts; return predicate && predicate.kind === 0 /* This */; } ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return ts.filter(objectLiteral.properties, function (property) { + if (property.kind === 261 /* PropertyAssignment */) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (key2 && key2 === propName); + } + }); + } + ts.getPropertyAssignment = getPropertyAssignment; function getContainingFunction(node) { while (true) { node = node.parent; - if (!node || isFunctionLike(node)) { + if (!node || ts.isFunctionLike(node)) { return node; } } @@ -7545,7 +7671,7 @@ var ts; function getContainingClass(node) { while (true) { node = node.parent; - if (!node || isClassLike(node)) { + if (!node || ts.isClassLike(node)) { return node; } } @@ -7563,7 +7689,7 @@ var ts; // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container // so that we can error on it. - if (isClassLike(node.parent.parent)) { + if (ts.isClassLike(node.parent.parent)) { return node; } // If this is a computed property, then the parent should not @@ -7575,12 +7701,12 @@ var ts; break; case 147 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. node = node.parent; @@ -7659,12 +7785,12 @@ var ts; return node; case 147 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 146 /* Parameter */ && isClassElement(node.parent.parent)) { + if (node.parent.kind === 146 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; } - else if (isClassElement(node.parent)) { + else if (ts.isClassElement(node.parent)) { // If the decorator's parent is a class element, we resolve the 'this' container // from the parent class declaration. node = node.parent; @@ -7700,7 +7826,6 @@ var ts; function getEntityNameFromTypeNode(node) { switch (node.kind) { case 159 /* TypeReference */: - case 277 /* JSDocTypeReference */: return node.typeName; case 201 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) @@ -7713,29 +7838,11 @@ var ts; return undefined; } ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; - function isCallLikeExpression(node) { - switch (node.kind) { - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 183 /* TaggedTemplateExpression */: - case 147 /* Decorator */: - return true; - default: - return false; - } - } - 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; } - else if (isJsxOpeningLikeElement(node)) { + else if (ts.isJsxOpeningLikeElement(node)) { return node.tagName; } // Will either be a CallExpression, NewExpression, or Decorator. @@ -7798,7 +7905,6 @@ var ts; ts.isJSXTagName = isJSXTagName; function isPartOfExpression(node) { switch (node.kind) { - case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: case 95 /* NullKeyword */: case 101 /* TrueKeyword */: @@ -7867,7 +7973,6 @@ var ts; case 221 /* SwitchStatement */: case 257 /* CaseClause */: case 223 /* ThrowStatement */: - case 221 /* SwitchStatement */: return parent.expression === node; case 214 /* ForStatement */: var forStatement = parent; @@ -7902,12 +8007,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isInstantiatedModule(node, preserveConstEnums) { - var moduleState = ts.getModuleInstanceState(node); - return moduleState === 1 /* Instantiated */ || - (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); - } - ts.isInstantiatedModule = isInstantiatedModule; function isExternalModuleImportEqualsDeclaration(node) { return node.kind === 237 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 248 /* ExternalModuleReference */; } @@ -7929,6 +8028,10 @@ var ts; return node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJSDoc(node) { + return node && !!(node.flags & 1048576 /* JSDoc */); + } + ts.isInJSDoc = isInJSDoc; /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). @@ -7939,7 +8042,7 @@ var ts; return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; - if (expression.kind !== 71 /* Identifier */ || expression.text !== "require") { + if (expression.kind !== 71 /* Identifier */ || expression.escapedText !== "require") { return false; } if (args.length !== 1) { @@ -7973,11 +8076,11 @@ var ts; } ts.getRightMostAssignedExpression = getRightMostAssignedExpression; function isExportsIdentifier(node) { - return isIdentifier(node) && node.text === "exports"; + return ts.isIdentifier(node) && node.escapedText === "exports"; } ts.isExportsIdentifier = isExportsIdentifier; function isModuleExportsPropertyAccessExpression(node) { - return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports"; + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property @@ -7993,11 +8096,11 @@ var ts; var lhs = expr.left; if (lhs.expression.kind === 71 /* Identifier */) { var lhsId = lhs.expression; - if (lhsId.text === "exports") { + if (lhsId.escapedText === "exports") { // exports.name = expr return 1 /* ExportsProperty */; } - else if (lhsId.text === "module" && lhs.name.text === "exports") { + else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { // module.exports = expr return 2 /* ModuleExports */; } @@ -8015,10 +8118,10 @@ var ts; if (innerPropertyAccess.expression.kind === 71 /* Identifier */) { // module.exports.name = expr var innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { + if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { return 1 /* ExportsProperty */; } - if (innerPropertyAccess.name.text === "prototype") { + if (innerPropertyAccess.name.escapedText === "prototype") { return 3 /* PrototypeProperty */; } } @@ -8077,52 +8180,41 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 279 /* JSDocFunctionType */ && + return node.kind === 273 /* JSDocFunctionType */ && node.parameters.length > 0 && - node.parameters[0].type.kind === 281 /* JSDocConstructorType */; + node.parameters[0].name && + node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getCommentsFromJSDoc(node) { - return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); - } - ts.getCommentsFromJSDoc = getCommentsFromJSDoc; function hasJSDocParameterTags(node) { - var parameterTags = getJSDocTags(node, 286 /* JSDocParameterTag */); - return parameterTags && parameterTags.length > 0; + return !!getFirstJSDocTag(node, 279 /* JSDocParameterTag */); } ts.hasJSDocParameterTags = hasJSDocParameterTags; - function getJSDocTags(node, kind) { - var docs = getJSDocs(node); - if (docs) { - var result = []; - for (var _i = 0, docs_1 = docs; _i < docs_1.length; _i++) { - var doc = docs_1[_i]; - if (doc.kind === 286 /* JSDocParameterTag */) { - if (doc.kind === kind) { - result.push(doc); - } - } - else { - var tags = doc.tags; - if (tags) { - result.push.apply(result, ts.filter(tags, function (tag) { return tag.kind === kind; })); - } - } - } - return result; - } - } function getFirstJSDocTag(node, kind) { - return node && ts.firstOrUndefined(getJSDocTags(node, kind)); + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); } - function getJSDocs(node) { - var cache = node.jsDocCache; - if (!cache) { - getJSDocsWorker(node); - node.jsDocCache = cache; + function getAllJSDocs(node) { + if (ts.isJSDocTypedefTag(node)) { + return [node.parent]; } - return cache; - function getJSDocsWorker(node) { + return getJSDocCommentsAndTags(node); + } + ts.getAllJSDocs = getAllJSDocs; + function getJSDocTags(node) { + var tags = node.jsDocCache; + // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getJSDocCommentsAndTags(node) { + var result; + getJSDocCommentsAndTagsWorker(node); + return result || ts.emptyArray; + function getJSDocCommentsAndTagsWorker(node) { var parent = node.parent; // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. // /** @@ -8139,7 +8231,7 @@ var ts; isVariableOfVariableDeclarationStatement ? parent.parent : undefined; if (variableStatementNode) { - getJSDocsWorker(variableStatementNode); + getJSDocCommentsAndTagsWorker(variableStatementNode); } // Also recognize when the node is the RHS of an assignment expression var isSourceOfAssignmentExpressionStatement = parent && parent.parent && @@ -8147,52 +8239,61 @@ var ts; parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.kind === 210 /* ExpressionStatement */; if (isSourceOfAssignmentExpressionStatement) { - getJSDocsWorker(parent.parent); + getJSDocCommentsAndTagsWorker(parent.parent); } var isModuleDeclaration = node.kind === 233 /* ModuleDeclaration */ && parent && parent.kind === 233 /* ModuleDeclaration */; var isPropertyAssignmentExpression = parent && parent.kind === 261 /* PropertyAssignment */; if (isModuleDeclaration || isPropertyAssignmentExpression) { - getJSDocsWorker(parent); + getJSDocCommentsAndTagsWorker(parent); } // Pull parameter comments from declaring function as well if (node.kind === 146 /* Parameter */) { - cache = ts.concatenate(cache, getJSDocParameterTags(node)); + result = ts.addRange(result, getJSDocParameterTags(node)); } if (isVariableLike(node) && node.initializer) { - cache = ts.concatenate(cache, node.initializer.jsDoc); + result = ts.addRange(result, node.initializer.jsDoc); } - cache = ts.concatenate(cache, node.jsDoc); + result = ts.addRange(result, node.jsDoc); } } - ts.getJSDocs = getJSDocs; function getJSDocParameterTags(param) { - if (!isParameter(param)) { - return undefined; - } - var func = param.parent; - var tags = getJSDocTags(func, 286 /* JSDocParameterTag */); - if (!param.name) { - // this is an anonymous jsdoc param from a `function(type1, type2): type3` specification - var i = func.parameters.indexOf(param); - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 286 /* JSDocParameterTag */; }); - if (paramTags && 0 <= i && i < paramTags.length) { - return [paramTags[i]]; - } - } - else if (param.name.kind === 71 /* Identifier */) { - var name_1 = param.name.text; - return ts.filter(tags, function (tag) { return tag.kind === 286 /* JSDocParameterTag */ && tag.parameterName.text === name_1; }); - } - else { - // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines - // But multi-line object types aren't supported yet either - return undefined; + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); } + // a binding pattern doesn't have a name, so it's not possible to match it a jsdoc parameter, which is identified by name + return undefined; } ts.getJSDocParameterTags = getJSDocParameterTags; + /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + ts.Debug.assert(node.parent.kind === 275 /* JSDocComment */); + var func = node.parent.parent; + if (!ts.isFunctionLike(func)) { + return undefined; + } + var parameter = ts.find(func.parameters, function (p) { + return p.name.kind === 71 /* Identifier */ && p.name.escapedText === name; + }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 288 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, 281 /* JSDocTypeTag */); if (!tag && node.kind === 146 /* Parameter */) { var paramTags = getJSDocParameterTags(node); if (paramTags) { @@ -8203,15 +8304,24 @@ var ts; } ts.getJSDocType = getJSDocType; function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, 277 /* JSDocAugmentsTag */); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278 /* JSDocClassTag */); + } + ts.getJSDocClassTag = getJSDocClassTag; function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 287 /* JSDocReturnTag */); + return getFirstJSDocTag(node, 280 /* JSDocReturnTag */); } ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 289 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, 282 /* JSDocTemplateTag */); } ts.getJSDocTemplateTag = getJSDocTemplateTag; function hasRestParameter(s) { @@ -8223,9 +8333,9 @@ var ts; } ts.hasDeclaredRestParameter = hasDeclaredRestParameter; function isRestParameter(node) { - if (node && (node.flags & 65536 /* JavaScriptFile */)) { - if (node.type && node.type.kind === 280 /* JSDocVariadicType */ || - ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 280 /* JSDocVariadicType */; })) { + if (isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 274 /* JSDocVariadicType */ || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274 /* JSDocVariadicType */; })) { return true; } } @@ -8327,46 +8437,33 @@ var ts; case 71 /* Identifier */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - return isDeclaration(name.parent) && name.parent.name === name; + return ts.isDeclaration(name.parent) && name.parent.name === name; default: 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; + /* @internal */ + // See GH#16030 + function isAnyDeclarationName(name) { + switch (name.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + if (ts.isDeclaration(name.parent)) { + return name.parent.name === name; + } + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + default: + return false; } } - ts.getNameOfDeclaration = getNameOfDeclaration; + ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && - isDeclaration(node.parent.parent); + ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; // Return true if the given identifier is classified as an IdentifierName @@ -8398,7 +8495,8 @@ var ts; // Property name in binding element or import specifier return parent.propertyName === node; case 246 /* ExportSpecifier */: - // Any name in an export specifier + case 253 /* JsxAttribute */: + // Any name in an export specifier or JSX Attribute return true; } return false; @@ -8556,10 +8654,6 @@ var ts; return false; } ts.isAsyncFunction = isAsyncFunction; - function isNumericLiteral(node) { - return node.kind === 8 /* NumericLiteral */; - } - ts.isNumericLiteral = isNumericLiteral; function isStringOrNumericLiteral(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ @@ -8574,7 +8668,7 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - var name = getNameOfDeclaration(declaration); + var name = ts.getNameOfDeclaration(declaration); return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; @@ -8590,26 +8684,55 @@ var ts; * where Symbol is literally the word "Symbol", and name is any identifierName */ function isWellKnownSymbolSyntactically(node) { - return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); } ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; function getPropertyNameForPropertyNameNode(name) { - if (name.kind === 71 /* Identifier */ || name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */ || name.kind === 146 /* Parameter */) { - return name.text; + if (name.kind === 71 /* Identifier */) { + return name.escapedText; + } + if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { + return escapeLeadingUnderscores(name.text); } if (name.kind === 144 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - var rightHandSideName = nameExpression.name.text; - return getPropertyNameForKnownSymbolName(rightHandSideName); + var rightHandSideName = nameExpression.name.escapedText; + return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); } else if (nameExpression.kind === 9 /* StringLiteral */ || nameExpression.kind === 8 /* NumericLiteral */) { - return nameExpression.text; + return escapeLeadingUnderscores(nameExpression.text); } } return undefined; } ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71 /* Identifier */) { + return ts.unescapeLeadingUnderscores(node.escapedText); + } + if (node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { + return node.text; + } + } + return undefined; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71 /* Identifier */) { + return node.escapedText; + } + if (node.kind === 9 /* StringLiteral */ || + node.kind === 8 /* NumericLiteral */) { + return escapeLeadingUnderscores(node.text); + } + } + return undefined; + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; function getPropertyNameForKnownSymbolName(symbolName) { return "__@" + symbolName; } @@ -8618,31 +8741,13 @@ var ts; * Includes the word "Symbol" with unicode escapes */ function isESSymbolIdentifier(node) { - return node.kind === 71 /* Identifier */ && node.text === "Symbol"; + return node.kind === 71 /* Identifier */ && node.escapedText === "Symbol"; } ts.isESSymbolIdentifier = isESSymbolIdentifier; function isPushOrUnshiftIdentifier(node) { - return node.text === "push" || node.text === "unshift"; + return node.escapedText === "push" || node.escapedText === "unshift"; } ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; - function isModifierKind(token) { - switch (token) { - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 76 /* ConstKeyword */: - case 124 /* DeclareKeyword */: - case 79 /* DefaultKeyword */: - case 84 /* ExportKeyword */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 131 /* ReadonlyKeyword */: - case 115 /* StaticKeyword */: - return true; - } - return false; - } - ts.isModifierKind = isModifierKind; function isParameterDeclaration(node) { var root = getRootDeclaration(node); return root.kind === 146 /* Parameter */; @@ -8673,25 +8778,14 @@ var ts; || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 266 /* Bundle */) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile)); - } - return getOriginalSourceFile(sourceFileOrBundle); - } - ts.getOriginalSourceFileOrBundle = getOriginalSourceFileOrBundle; function getOriginalSourceFile(sourceFile) { - return ts.getParseTreeNode(sourceFile, isSourceFile) || sourceFile; + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } + ts.getOriginalSourceFile = getOriginalSourceFile; function getOriginalSourceFiles(sourceFiles) { return ts.sameMap(sourceFiles, getOriginalSourceFile); } ts.getOriginalSourceFiles = getOriginalSourceFiles; - function getOriginalNodeId(node) { - node = ts.getOriginalNode(node); - return node ? ts.getNodeId(node) : 0; - } - ts.getOriginalNodeId = getOriginalNodeId; var Associativity; (function (Associativity) { Associativity[Associativity["Left"] = 0] = "Left"; @@ -8858,7 +8952,7 @@ var ts; return 2; case 198 /* SpreadElement */: return 1; - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: return 0; default: return -1; @@ -8963,6 +9057,8 @@ var ts; return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); } function isIntrinsicJsxName(name) { + // An escaped identifier had a leading underscore prior to being escaped, which would return true + // The escape adds an extra underscore which does not change the result var ch = name.substr(0, 1); return ch.toLowerCase() === ch; } @@ -9105,7 +9201,7 @@ var ts; var path = outputDir ? getSourceFilePathInNewDir(sourceFile, host, outputDir) : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; /** @@ -9139,57 +9235,6 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - /** - * Iterates over the source files that are expected to have an emit output. - * - * @param host An EmitHost. - * @param action The action to execute. - * @param sourceFilesOrTargetSourceFile - * If an array, the full list of source files to emit. - * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. - */ - function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { - var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); - var options = host.getCompilerOptions(); - if (options.outFile || options.out) { - if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); - } - } - else { - for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { - var sourceFile = sourceFiles_1[_i]; - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); - } - } - } - ts.forEachEmittedFile = forEachEmittedFile; - function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; - } - // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. - // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. - // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve - function getOutputExtension(sourceFile, options) { - if (options.jsx === 1 /* Preserve */) { - if (isSourceFileJavaScript(sourceFile)) { - if (ts.fileExtensionIs(sourceFile.fileName, ".jsx")) { - return ".jsx"; - } - } - else if (sourceFile.languageVariant === 1 /* JSX */) { - // TypeScript source file preserving JSX syntax - return ".jsx"; - } - } - return ".js"; - } function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); var commonSourceDirectory = host.getCommonSourceDirectory(); @@ -9220,13 +9265,17 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; - /** Get the type annotaion for the value parameter. */ - function getSetAccessorTypeAnnotationNode(accessor) { + function getSetAccessorValueParameter(accessor) { if (accessor && accessor.parameters.length > 0) { var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); - return accessor.parameters[hasThis ? 1 : 0].type; + return accessor.parameters[hasThis ? 1 : 0]; } } + /** Get the type annotation for the value parameter. */ + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { if (signature.parameters.length) { @@ -9297,6 +9346,55 @@ var ts; }; } ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + /** + * Gets the effective type annotation of a variable, parameter, or property. If the node was + * parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveTypeAnnotationNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocType(node); + } + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + /** + * Gets the effective return type annotation of a signature. If the node was parsed in a + * JavaScript file, gets the return type annotation from JSDoc. + */ + function getEffectiveReturnTypeNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocReturnType(node); + } + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (node.typeParameters) { + return node.typeParameters; + } + if (isInJavaScriptFile(node)) { + var templateTag = getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + /** + * Gets the effective type annotation of the value parameter of a set accessor. If the node + * was parsed in a JavaScript file, gets the type annotation from JSDoc. + */ + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); } @@ -9502,6 +9600,13 @@ var ts; if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) { return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */; } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; + return flags; + } + ts.getModifierFlags = getModifierFlags; + /* @internal */ + function getModifierFlagsNoCache(node) { var flags = 0 /* None */; if (node.modifiers) { for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { @@ -9512,10 +9617,9 @@ var ts; if (node.flags & 4 /* NestedNamespace */ || (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace)) { flags |= 1 /* Export */; } - node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */; return flags; } - ts.getModifierFlags = getModifierFlags; + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; function modifierToFlag(token) { switch (token) { case 115 /* StaticKeyword */: return 32 /* Static */; @@ -9547,17 +9651,17 @@ var ts; function tryGetClassExtendingExpressionWithTypeArguments(node) { if (node.kind === 201 /* ExpressionWithTypeArguments */ && node.parent.token === 85 /* ExtendsKeyword */ && - isClassLike(node.parent.parent)) { + ts.isClassLike(node.parent.parent)) { return node.parent.parent; } } ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; function isAssignmentExpression(node, excludeCompoundAssignment) { - return isBinaryExpression(node) + return ts.isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 58 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) - && isLeftHandSideExpression(node.left); + && ts.isLeftHandSideExpression(node.left); } ts.isAssignmentExpression = isAssignmentExpression; function isDestructuringAssignment(node) { @@ -9579,7 +9683,7 @@ var ts; if (node.kind === 71 /* Identifier */) { return true; } - else if (isPropertyAccessExpression(node)) { + else if (ts.isPropertyAccessExpression(node)) { return isSupportedExpressionWithTypeArgumentsRest(node.expression); } else { @@ -9596,7 +9700,7 @@ var ts; && node.parent && node.parent.token === 108 /* ImplementsKeyword */ && node.parent.parent - && isClassLike(node.parent.parent); + && ts.isClassLike(node.parent.parent); } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { @@ -9620,11 +9724,11 @@ var ts; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined; + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isExportDefaultSymbol(symbol) { - return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */); + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */); } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { @@ -9784,27 +9888,77 @@ var ts; } return false; } - var syntaxKindCache = []; - function formatSyntaxKind(kind) { - var syntaxKindEnum = ts.SyntaxKind; - if (syntaxKindEnum) { - var cached = syntaxKindCache[kind]; - if (cached !== undefined) { - return cached; - } - for (var name in syntaxKindEnum) { - if (syntaxKindEnum[name] === kind) { - var result = kind + " (" + name + ")"; - syntaxKindCache[kind] = result; - return result; + /** + * Formats an enum value as a string for debugging and debug assertions. + */ + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; } } + if (remainingFlags === 0) { + return result; + } } else { - return kind.toString(); + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false); } ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true); + } + ts.formatObjectFlags = formatObjectFlags; function getRangePos(range) { return range ? range.pos : -1; } @@ -9987,675 +10141,13 @@ var ts; return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; } ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; - // Node tests - // - // All node tests in the following list should *not* reference parent pointers so that - // they may be used with transformations. - // Node Arrays - function isNodeArray(array) { - return array.hasOwnProperty("pos") - && array.hasOwnProperty("end"); - } - ts.isNodeArray = isNodeArray; - // Literals - function isNoSubstitutionTemplateLiteral(node) { - return node.kind === 13 /* NoSubstitutionTemplateLiteral */; - } - ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; - function isLiteralKind(kind) { - return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; - } - ts.isLiteralKind = isLiteralKind; - function isTextualLiteralKind(kind) { - return kind === 9 /* StringLiteral */ || kind === 13 /* NoSubstitutionTemplateLiteral */; - } - ts.isTextualLiteralKind = isTextualLiteralKind; - function isLiteralExpression(node) { - return isLiteralKind(node.kind); - } - ts.isLiteralExpression = isLiteralExpression; - // Pseudo-literals - function isTemplateLiteralKind(kind) { - return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; - } - ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateHead(node) { - return node.kind === 14 /* TemplateHead */; - } - ts.isTemplateHead = isTemplateHead; - function isTemplateMiddleOrTemplateTail(node) { - var kind = node.kind; - return kind === 15 /* TemplateMiddle */ - || kind === 16 /* TemplateTail */; - } - ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; - // Identifiers - function isIdentifier(node) { - return node.kind === 71 /* Identifier */; - } - ts.isIdentifier = isIdentifier; - function isGeneratedIdentifier(node) { - // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return isIdentifier(node) && node.autoGenerateKind > 0 /* None */; - } - ts.isGeneratedIdentifier = isGeneratedIdentifier; - // Keywords - function isModifier(node) { - return isModifierKind(node.kind); - } - ts.isModifier = isModifier; - // Names - function isQualifiedName(node) { - return node.kind === 143 /* QualifiedName */; - } - ts.isQualifiedName = isQualifiedName; - function isComputedPropertyName(node) { - return node.kind === 144 /* ComputedPropertyName */; - } - ts.isComputedPropertyName = isComputedPropertyName; - function isEntityName(node) { - var kind = node.kind; - return kind === 143 /* QualifiedName */ - || kind === 71 /* Identifier */; - } - ts.isEntityName = isEntityName; - function isPropertyName(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 144 /* ComputedPropertyName */; - } - ts.isPropertyName = isPropertyName; - function isModuleName(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 9 /* StringLiteral */; - } - ts.isModuleName = isModuleName; - function isBindingName(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 174 /* ObjectBindingPattern */ - || kind === 175 /* ArrayBindingPattern */; - } - ts.isBindingName = isBindingName; - // Signature elements - function isTypeParameter(node) { - return node.kind === 145 /* TypeParameter */; - } - ts.isTypeParameter = isTypeParameter; - function isParameter(node) { - return node.kind === 146 /* Parameter */; - } - ts.isParameter = isParameter; - function isDecorator(node) { - return node.kind === 147 /* Decorator */; - } - ts.isDecorator = isDecorator; - // Type members - function isMethodDeclaration(node) { - return node.kind === 151 /* MethodDeclaration */; - } - ts.isMethodDeclaration = isMethodDeclaration; - function isClassElement(node) { - var kind = node.kind; - return kind === 152 /* Constructor */ - || kind === 149 /* PropertyDeclaration */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 157 /* IndexSignature */ - || 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 */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 263 /* SpreadAssignment */ - || kind === 151 /* MethodDeclaration */ - || kind === 153 /* GetAccessor */ - || kind === 154 /* SetAccessor */ - || kind === 247 /* MissingDeclaration */; - } - ts.isObjectLiteralElementLike = isObjectLiteralElementLike; - // Type - function isTypeNodeKind(kind) { - return (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) - || kind === 119 /* AnyKeyword */ - || kind === 133 /* NumberKeyword */ - || kind === 134 /* ObjectKeyword */ - || kind === 122 /* BooleanKeyword */ - || kind === 136 /* StringKeyword */ - || kind === 137 /* SymbolKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 105 /* VoidKeyword */ - || kind === 139 /* UndefinedKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 130 /* NeverKeyword */ - || kind === 201 /* ExpressionWithTypeArguments */; - } - /** - * Node test that determines whether a node is a valid type node. - * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* - * of a TypeNode. - */ - function isTypeNode(node) { - return isTypeNodeKind(node.kind); - } - ts.isTypeNode = isTypeNode; - // Binding patterns - function isArrayBindingPattern(node) { - return node.kind === 175 /* ArrayBindingPattern */; - } - ts.isArrayBindingPattern = isArrayBindingPattern; - function isObjectBindingPattern(node) { - return node.kind === 174 /* ObjectBindingPattern */; - } - ts.isObjectBindingPattern = isObjectBindingPattern; - function isBindingPattern(node) { - if (node) { - var kind = node.kind; - return kind === 175 /* ArrayBindingPattern */ - || kind === 174 /* ObjectBindingPattern */; - } - return false; - } - ts.isBindingPattern = isBindingPattern; - function isAssignmentPattern(node) { - var kind = node.kind; - return kind === 177 /* ArrayLiteralExpression */ - || kind === 178 /* ObjectLiteralExpression */; - } - ts.isAssignmentPattern = isAssignmentPattern; - function isBindingElement(node) { - return node.kind === 176 /* BindingElement */; - } - ts.isBindingElement = isBindingElement; - function isArrayBindingElement(node) { - var kind = node.kind; - return kind === 176 /* BindingElement */ - || kind === 200 /* OmittedExpression */; - } - ts.isArrayBindingElement = isArrayBindingElement; - /** - * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration - */ - function isDeclarationBindingElement(bindingElement) { - switch (bindingElement.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 176 /* BindingElement */: - return true; - } - return false; - } - ts.isDeclarationBindingElement = isDeclarationBindingElement; - /** - * Determines whether a node is a BindingOrAssignmentPattern - */ - function isBindingOrAssignmentPattern(node) { - return isObjectBindingOrAssignmentPattern(node) - || isArrayBindingOrAssignmentPattern(node); - } - ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; - /** - * Determines whether a node is an ObjectBindingOrAssignmentPattern - */ - function isObjectBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 174 /* ObjectBindingPattern */: - case 178 /* ObjectLiteralExpression */: - return true; - } - return false; - } - ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; - /** - * Determines whether a node is an ArrayBindingOrAssignmentPattern - */ - function isArrayBindingOrAssignmentPattern(node) { - switch (node.kind) { - case 175 /* ArrayBindingPattern */: - case 177 /* ArrayLiteralExpression */: - return true; - } - return false; - } - ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; - // Expression - function isArrayLiteralExpression(node) { - return node.kind === 177 /* ArrayLiteralExpression */; - } - ts.isArrayLiteralExpression = isArrayLiteralExpression; - function isObjectLiteralExpression(node) { - return node.kind === 178 /* ObjectLiteralExpression */; - } - ts.isObjectLiteralExpression = isObjectLiteralExpression; - function isPropertyAccessExpression(node) { - return node.kind === 179 /* PropertyAccessExpression */; - } - ts.isPropertyAccessExpression = isPropertyAccessExpression; - function isPropertyAccessOrQualifiedName(node) { - var kind = node.kind; - return kind === 179 /* PropertyAccessExpression */ - || kind === 143 /* QualifiedName */; - } - ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; - function isElementAccessExpression(node) { - return node.kind === 180 /* ElementAccessExpression */; - } - ts.isElementAccessExpression = isElementAccessExpression; - function isBinaryExpression(node) { - return node.kind === 194 /* BinaryExpression */; - } - ts.isBinaryExpression = isBinaryExpression; - function isConditionalExpression(node) { - return node.kind === 195 /* ConditionalExpression */; - } - ts.isConditionalExpression = isConditionalExpression; - function isCallExpression(node) { - return node.kind === 181 /* CallExpression */; - } - ts.isCallExpression = isCallExpression; - function isTemplateLiteral(node) { - var kind = node.kind; - return kind === 196 /* TemplateExpression */ - || kind === 13 /* NoSubstitutionTemplateLiteral */; - } - ts.isTemplateLiteral = isTemplateLiteral; - function isSpreadExpression(node) { - return node.kind === 198 /* SpreadElement */; - } - ts.isSpreadExpression = isSpreadExpression; - function isExpressionWithTypeArguments(node) { - return node.kind === 201 /* ExpressionWithTypeArguments */; - } - ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; - function isLeftHandSideExpressionKind(kind) { - return kind === 179 /* PropertyAccessExpression */ - || kind === 180 /* ElementAccessExpression */ - || kind === 182 /* NewExpression */ - || kind === 181 /* CallExpression */ - || kind === 249 /* JsxElement */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 183 /* TaggedTemplateExpression */ - || kind === 177 /* ArrayLiteralExpression */ - || kind === 185 /* ParenthesizedExpression */ - || kind === 178 /* ObjectLiteralExpression */ - || kind === 199 /* ClassExpression */ - || kind === 186 /* FunctionExpression */ - || kind === 71 /* Identifier */ - || kind === 12 /* RegularExpressionLiteral */ - || kind === 8 /* NumericLiteral */ - || kind === 9 /* StringLiteral */ - || kind === 13 /* NoSubstitutionTemplateLiteral */ - || kind === 196 /* TemplateExpression */ - || kind === 86 /* FalseKeyword */ - || kind === 95 /* NullKeyword */ - || kind === 99 /* ThisKeyword */ - || kind === 101 /* TrueKeyword */ - || kind === 97 /* SuperKeyword */ - || kind === 203 /* NonNullExpression */ - || kind === 204 /* MetaProperty */; - } - function isLeftHandSideExpression(node) { - return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isLeftHandSideExpression = isLeftHandSideExpression; - function isUnaryExpressionKind(kind) { - return kind === 192 /* PrefixUnaryExpression */ - || kind === 193 /* PostfixUnaryExpression */ - || kind === 188 /* DeleteExpression */ - || kind === 189 /* TypeOfExpression */ - || kind === 190 /* VoidExpression */ - || kind === 191 /* AwaitExpression */ - || kind === 184 /* TypeAssertionExpression */ - || isLeftHandSideExpressionKind(kind); - } - function isUnaryExpression(node) { - return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isUnaryExpression = isUnaryExpression; - function isExpressionKind(kind) { - return kind === 195 /* ConditionalExpression */ - || kind === 197 /* YieldExpression */ - || kind === 187 /* ArrowFunction */ - || kind === 194 /* BinaryExpression */ - || kind === 198 /* SpreadElement */ - || kind === 202 /* AsExpression */ - || kind === 200 /* OmittedExpression */ - || kind === 297 /* CommaListExpression */ - || isUnaryExpressionKind(kind); - } - function isExpression(node) { - return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); - } - ts.isExpression = isExpression; - function isAssertionExpression(node) { - var kind = node.kind; - return kind === 184 /* TypeAssertionExpression */ - || kind === 202 /* AsExpression */; - } - ts.isAssertionExpression = isAssertionExpression; - function isPartiallyEmittedExpression(node) { - return node.kind === 296 /* PartiallyEmittedExpression */; - } - ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; - function isNotEmittedStatement(node) { - return node.kind === 295 /* NotEmittedStatement */; - } - ts.isNotEmittedStatement = isNotEmittedStatement; - function isNotEmittedOrPartiallyEmittedNode(node) { - return isNotEmittedStatement(node) - || isPartiallyEmittedExpression(node); - } - ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; - function isOmittedExpression(node) { - return node.kind === 200 /* OmittedExpression */; - } - ts.isOmittedExpression = isOmittedExpression; - // Misc - function isTemplateSpan(node) { - return node.kind === 205 /* TemplateSpan */; - } - ts.isTemplateSpan = isTemplateSpan; - // Element - function isBlock(node) { - return node.kind === 207 /* Block */; - } - ts.isBlock = isBlock; - function isConciseBody(node) { - return isBlock(node) - || isExpression(node); - } - ts.isConciseBody = isConciseBody; - function isFunctionBody(node) { - return isBlock(node); - } - ts.isFunctionBody = isFunctionBody; - function isForInitializer(node) { - return isVariableDeclarationList(node) - || isExpression(node); - } - ts.isForInitializer = isForInitializer; - function isVariableDeclaration(node) { - return node.kind === 226 /* VariableDeclaration */; - } - ts.isVariableDeclaration = isVariableDeclaration; - function isVariableDeclarationList(node) { - return node.kind === 227 /* VariableDeclarationList */; - } - ts.isVariableDeclarationList = isVariableDeclarationList; - function isCaseBlock(node) { - return node.kind === 235 /* CaseBlock */; - } - ts.isCaseBlock = isCaseBlock; - function isModuleBody(node) { - var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */ - || kind === 71 /* Identifier */; - } - ts.isModuleBody = isModuleBody; - function isNamespaceBody(node) { - var kind = node.kind; - return kind === 234 /* ModuleBlock */ - || kind === 233 /* ModuleDeclaration */; - } - ts.isNamespaceBody = isNamespaceBody; - function isJSDocNamespaceBody(node) { - var kind = node.kind; - return kind === 71 /* Identifier */ - || kind === 233 /* ModuleDeclaration */; - } - ts.isJSDocNamespaceBody = isJSDocNamespaceBody; - function isImportEqualsDeclaration(node) { - 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 */; - } - ts.isImportClause = isImportClause; - function isNamedImportBindings(node) { - var kind = node.kind; - return kind === 241 /* NamedImports */ - || kind === 240 /* NamespaceImport */; - } - ts.isNamedImportBindings = isNamedImportBindings; - function isImportSpecifier(node) { - return node.kind === 242 /* ImportSpecifier */; - } - ts.isImportSpecifier = isImportSpecifier; - function isNamedExports(node) { - return node.kind === 245 /* NamedExports */; - } - ts.isNamedExports = isNamedExports; - function isExportSpecifier(node) { - 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 */; - } - ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; - function isDeclarationKind(kind) { - return kind === 187 /* ArrowFunction */ - || kind === 176 /* BindingElement */ - || kind === 229 /* ClassDeclaration */ - || kind === 199 /* ClassExpression */ - || kind === 152 /* Constructor */ - || kind === 232 /* EnumDeclaration */ - || kind === 264 /* EnumMember */ - || kind === 246 /* ExportSpecifier */ - || kind === 228 /* FunctionDeclaration */ - || kind === 186 /* FunctionExpression */ - || kind === 153 /* GetAccessor */ - || kind === 239 /* ImportClause */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 242 /* ImportSpecifier */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 253 /* JsxAttribute */ - || kind === 151 /* MethodDeclaration */ - || kind === 150 /* MethodSignature */ - || kind === 233 /* ModuleDeclaration */ - || kind === 236 /* NamespaceExportDeclaration */ - || kind === 240 /* NamespaceImport */ - || kind === 146 /* Parameter */ - || kind === 261 /* PropertyAssignment */ - || kind === 149 /* PropertyDeclaration */ - || kind === 148 /* PropertySignature */ - || kind === 154 /* SetAccessor */ - || kind === 262 /* ShorthandPropertyAssignment */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 145 /* TypeParameter */ - || kind === 226 /* VariableDeclaration */ - || kind === 290 /* JSDocTypedefTag */; - } - function isDeclarationStatementKind(kind) { - return kind === 228 /* FunctionDeclaration */ - || kind === 247 /* MissingDeclaration */ - || kind === 229 /* ClassDeclaration */ - || kind === 230 /* InterfaceDeclaration */ - || kind === 231 /* TypeAliasDeclaration */ - || kind === 232 /* EnumDeclaration */ - || kind === 233 /* ModuleDeclaration */ - || kind === 238 /* ImportDeclaration */ - || kind === 237 /* ImportEqualsDeclaration */ - || kind === 244 /* ExportDeclaration */ - || kind === 243 /* ExportAssignment */ - || kind === 236 /* NamespaceExportDeclaration */; - } - function isStatementKindButNotDeclarationKind(kind) { - return kind === 218 /* BreakStatement */ - || kind === 217 /* ContinueStatement */ - || kind === 225 /* DebuggerStatement */ - || kind === 212 /* DoStatement */ - || kind === 210 /* ExpressionStatement */ - || kind === 209 /* EmptyStatement */ - || kind === 215 /* ForInStatement */ - || kind === 216 /* ForOfStatement */ - || kind === 214 /* ForStatement */ - || kind === 211 /* IfStatement */ - || kind === 222 /* LabeledStatement */ - || kind === 219 /* ReturnStatement */ - || kind === 221 /* SwitchStatement */ - || kind === 223 /* ThrowStatement */ - || kind === 224 /* TryStatement */ - || kind === 208 /* VariableStatement */ - || kind === 213 /* WhileStatement */ - || kind === 220 /* WithStatement */ - || kind === 295 /* NotEmittedStatement */ - || kind === 299 /* EndOfDeclarationMarker */ - || kind === 298 /* MergeDeclarationMarker */; - } - function isDeclaration(node) { - return isDeclarationKind(node.kind); - } - ts.isDeclaration = isDeclaration; - function isDeclarationStatement(node) { - return isDeclarationStatementKind(node.kind); - } - ts.isDeclarationStatement = isDeclarationStatement; - /** - * Determines whether the node is a statement that is not also a declaration - */ - function isStatementButNotDeclaration(node) { - return isStatementKindButNotDeclarationKind(node.kind); - } - ts.isStatementButNotDeclaration = isStatementButNotDeclaration; - function isStatement(node) { - var kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) - || isDeclarationStatementKind(kind) - || kind === 207 /* Block */; - } - ts.isStatement = isStatement; - // Module references - function isModuleReference(node) { - var kind = node.kind; - return kind === 248 /* ExternalModuleReference */ - || kind === 143 /* QualifiedName */ - || kind === 71 /* Identifier */; - } - ts.isModuleReference = isModuleReference; - // JSX - function isJsxOpeningElement(node) { - return node.kind === 251 /* JsxOpeningElement */; - } - ts.isJsxOpeningElement = isJsxOpeningElement; - function isJsxClosingElement(node) { - return node.kind === 252 /* JsxClosingElement */; - } - ts.isJsxClosingElement = isJsxClosingElement; - function isJsxTagNameExpression(node) { - var kind = node.kind; - return kind === 99 /* ThisKeyword */ - || kind === 71 /* Identifier */ - || kind === 179 /* PropertyAccessExpression */; - } - ts.isJsxTagNameExpression = isJsxTagNameExpression; - function isJsxChild(node) { - var kind = node.kind; - return kind === 249 /* JsxElement */ - || kind === 256 /* JsxExpression */ - || kind === 250 /* JsxSelfClosingElement */ - || kind === 10 /* JsxText */; - } - ts.isJsxChild = isJsxChild; - function isJsxAttributes(node) { - var kind = node.kind; - return kind === 254 /* JsxAttributes */; - } - ts.isJsxAttributes = isJsxAttributes; - function isJsxAttributeLike(node) { - var kind = node.kind; - return kind === 253 /* JsxAttribute */ - || kind === 255 /* JsxSpreadAttribute */; - } - ts.isJsxAttributeLike = isJsxAttributeLike; - function isJsxSpreadAttribute(node) { - return node.kind === 255 /* JsxSpreadAttribute */; - } - ts.isJsxSpreadAttribute = isJsxSpreadAttribute; - function isJsxAttribute(node) { - return node.kind === 253 /* JsxAttribute */; - } - ts.isJsxAttribute = isJsxAttribute; - function isStringLiteralOrJsxExpression(node) { - var kind = node.kind; - return kind === 9 /* StringLiteral */ - || kind === 256 /* JsxExpression */; - } - ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; - function isJsxOpeningLikeElement(node) { - var kind = node.kind; - return kind === 251 /* JsxOpeningElement */ - || kind === 250 /* JsxSelfClosingElement */; - } - ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; - // Clauses - function isCaseOrDefaultClause(node) { - var kind = node.kind; - return kind === 257 /* CaseClause */ - || kind === 258 /* DefaultClause */; - } - ts.isCaseOrDefaultClause = isCaseOrDefaultClause; - function isHeritageClause(node) { - return node.kind === 259 /* HeritageClause */; - } - ts.isHeritageClause = isHeritageClause; - function isCatchClause(node) { - return node.kind === 260 /* CatchClause */; - } - ts.isCatchClause = isCatchClause; - // Property assignments - function isPropertyAssignment(node) { - return node.kind === 261 /* PropertyAssignment */; - } - ts.isPropertyAssignment = isPropertyAssignment; - function isShorthandPropertyAssignment(node) { - return node.kind === 262 /* ShorthandPropertyAssignment */; - } - ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; - // Enum - function isEnumMember(node) { - return node.kind === 264 /* EnumMember */; - } - ts.isEnumMember = isEnumMember; - // Top-level nodes - function isSourceFile(node) { - return node.kind === 265 /* SourceFile */; - } - ts.isSourceFile = isSourceFile; function isWatchSet(options) { // Firefox has Object.prototype.watch return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; function getCheckFlags(symbol) { - return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } ts.getCheckFlags = getCheckFlags; function getDeclarationModifierFlagsFromSymbol(s) { @@ -10671,7 +10163,7 @@ var ts; var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } - if (s.flags & 16777216 /* Prototype */) { + if (s.flags & 4194304 /* Prototype */) { return 4 /* Public */ | 32 /* Static */; } return 0; @@ -10697,6 +10189,15 @@ var ts; return previous[previous.length - 1]; } ts.levenshtein = levenshtein; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + /** See comment on `declareModuleMember` in `binder.ts`. */ + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -11067,10 +10568,34762 @@ var ts; * @param identifier The escaped identifier text. * @returns The unescaped identifier text. */ - function unescapeIdentifier(identifier) { - return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier; + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + /** + * Remove extra underscore from escaped identifier text content. + * @deprecated Use `id.text` for the unescaped text. + * @param identifier The escaped identifier text. + * @returns The unescaped identifier text. + */ + function unescapeIdentifier(id) { + return id; } ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143 /* QualifiedName */) { + return declaration.name.right; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1 /* ExportsProperty */: + case 4 /* ThisProperty */: + case 5 /* Property */: + case 3 /* PrototypeProperty */: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; +})(ts || (ts = {})); +// Simple node tests of the form `node.kind === SyntaxKind.Foo`. +(function (ts) { + // Literals + function isNumericLiteral(node) { + return node.kind === 8 /* NumericLiteral */; + } + ts.isNumericLiteral = isNumericLiteral; + function isStringLiteral(node) { + return node.kind === 9 /* StringLiteral */; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 10 /* JsxText */; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 12 /* RegularExpressionLiteral */; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 13 /* NoSubstitutionTemplateLiteral */; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + // Pseudo-literals + function isTemplateHead(node) { + return node.kind === 14 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 15 /* TemplateMiddle */; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 16 /* TemplateTail */; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 71 /* Identifier */; + } + ts.isIdentifier = isIdentifier; + // Names + function isQualifiedName(node) { + return node.kind === 143 /* QualifiedName */; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 144 /* ComputedPropertyName */; + } + ts.isComputedPropertyName = isComputedPropertyName; + // Signature elements + function isTypeParameterDeclaration(node) { + return node.kind === 145 /* TypeParameter */; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 146 /* Parameter */; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 147 /* Decorator */; + } + ts.isDecorator = isDecorator; + // TypeMember + function isPropertySignature(node) { + return node.kind === 148 /* PropertySignature */; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 149 /* PropertyDeclaration */; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 150 /* MethodSignature */; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 151 /* MethodDeclaration */; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 152 /* Constructor */; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 153 /* GetAccessor */; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 154 /* SetAccessor */; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 155 /* CallSignature */; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 156 /* ConstructSignature */; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 157 /* IndexSignature */; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + // Type + function isTypePredicateNode(node) { + return node.kind === 158 /* TypePredicate */; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 159 /* TypeReference */; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 160 /* FunctionType */; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 161 /* ConstructorType */; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 162 /* TypeQuery */; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 163 /* TypeLiteral */; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 164 /* ArrayType */; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 165 /* TupleType */; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 166 /* UnionType */; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 167 /* IntersectionType */; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 168 /* ParenthesizedType */; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 169 /* ThisType */; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 170 /* TypeOperator */; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 171 /* IndexedAccessType */; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 172 /* MappedType */; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 173 /* LiteralType */; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + // Binding patterns + function isObjectBindingPattern(node) { + return node.kind === 174 /* ObjectBindingPattern */; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 175 /* ArrayBindingPattern */; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 176 /* BindingElement */; + } + ts.isBindingElement = isBindingElement; + // Expression + function isArrayLiteralExpression(node) { + return node.kind === 177 /* ArrayLiteralExpression */; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 178 /* ObjectLiteralExpression */; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 179 /* PropertyAccessExpression */; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 180 /* ElementAccessExpression */; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 181 /* CallExpression */; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 182 /* NewExpression */; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 183 /* TaggedTemplateExpression */; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 184 /* TypeAssertionExpression */; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 185 /* ParenthesizedExpression */; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288 /* PartiallyEmittedExpression */) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 186 /* FunctionExpression */; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 187 /* ArrowFunction */; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 188 /* DeleteExpression */; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 191 /* AwaitExpression */; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 190 /* VoidExpression */; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 191 /* AwaitExpression */; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 192 /* PrefixUnaryExpression */; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 193 /* PostfixUnaryExpression */; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 194 /* BinaryExpression */; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 195 /* ConditionalExpression */; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 196 /* TemplateExpression */; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 197 /* YieldExpression */; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 198 /* SpreadElement */; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 199 /* ClassExpression */; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 200 /* OmittedExpression */; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 201 /* ExpressionWithTypeArguments */; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 202 /* AsExpression */; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 203 /* NonNullExpression */; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 204 /* MetaProperty */; + } + ts.isMetaProperty = isMetaProperty; + // Misc + function isTemplateSpan(node) { + return node.kind === 205 /* TemplateSpan */; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 206 /* SemicolonClassElement */; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + // Block + function isBlock(node) { + return node.kind === 207 /* Block */; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 208 /* VariableStatement */; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 209 /* EmptyStatement */; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 210 /* ExpressionStatement */; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 211 /* IfStatement */; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 212 /* DoStatement */; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 213 /* WhileStatement */; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 214 /* ForStatement */; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 215 /* ForInStatement */; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 216 /* ForOfStatement */; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 217 /* ContinueStatement */; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 218 /* BreakStatement */; + } + ts.isBreakStatement = isBreakStatement; + function isReturnStatement(node) { + return node.kind === 219 /* ReturnStatement */; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 220 /* WithStatement */; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 221 /* SwitchStatement */; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 222 /* LabeledStatement */; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 223 /* ThrowStatement */; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 224 /* TryStatement */; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 225 /* DebuggerStatement */; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 226 /* VariableDeclaration */; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 227 /* VariableDeclarationList */; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 228 /* FunctionDeclaration */; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 229 /* ClassDeclaration */; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 230 /* InterfaceDeclaration */; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 231 /* TypeAliasDeclaration */; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 232 /* EnumDeclaration */; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 233 /* ModuleDeclaration */; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 234 /* ModuleBlock */; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 235 /* CaseBlock */; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 236 /* NamespaceExportDeclaration */; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + 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 */; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 240 /* NamespaceImport */; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 241 /* NamedImports */; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 242 /* ImportSpecifier */; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 243 /* ExportAssignment */; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 244 /* ExportDeclaration */; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 245 /* NamedExports */; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 246 /* ExportSpecifier */; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 247 /* MissingDeclaration */; + } + ts.isMissingDeclaration = isMissingDeclaration; + // Module References + function isExternalModuleReference(node) { + return node.kind === 248 /* ExternalModuleReference */; + } + ts.isExternalModuleReference = isExternalModuleReference; + // JSX + function isJsxElement(node) { + return node.kind === 249 /* JsxElement */; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 250 /* JsxSelfClosingElement */; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 251 /* JsxOpeningElement */; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 252 /* JsxClosingElement */; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxAttribute(node) { + return node.kind === 253 /* JsxAttribute */; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 254 /* JsxAttributes */; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 255 /* JsxSpreadAttribute */; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 256 /* JsxExpression */; + } + ts.isJsxExpression = isJsxExpression; + // Clauses + function isCaseClause(node) { + return node.kind === 257 /* CaseClause */; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 258 /* DefaultClause */; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 259 /* HeritageClause */; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 260 /* CatchClause */; + } + ts.isCatchClause = isCatchClause; + // Property assignments + function isPropertyAssignment(node) { + return node.kind === 261 /* PropertyAssignment */; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 262 /* ShorthandPropertyAssignment */; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 263 /* SpreadAssignment */; + } + ts.isSpreadAssignment = isSpreadAssignment; + // Enum + function isEnumMember(node) { + return node.kind === 264 /* EnumMember */; + } + ts.isEnumMember = isEnumMember; + // Top-level nodes + function isSourceFile(node) { + return node.kind === 265 /* SourceFile */; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 266 /* Bundle */; + } + ts.isBundle = isBundle; + // JSDoc + function isJSDocTypeExpression(node) { + return node.kind === 267 /* JSDocTypeExpression */; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 268 /* JSDocAllType */; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 269 /* JSDocUnknownType */; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 270 /* JSDocNullableType */; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 271 /* JSDocNonNullableType */; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 272 /* JSDocOptionalType */; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 273 /* JSDocFunctionType */; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 274 /* JSDocVariadicType */; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 275 /* JSDocComment */; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 277 /* JSDocAugmentsTag */; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocParameterTag(node) { + return node.kind === 279 /* JSDocParameterTag */; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 280 /* JSDocReturnTag */; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 281 /* JSDocTypeTag */; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 282 /* JSDocTemplateTag */; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 283 /* JSDocTypedefTag */; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 284 /* JSDocPropertyTag */; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 284 /* JSDocPropertyTag */ || node.kind === 279 /* JSDocParameterTag */; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 285 /* JSDocTypeLiteral */; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; +})(ts || (ts = {})); +// Node tests +// +// All node tests in the following list should *not* reference parent pointers so that +// they may be used with transformations. +(function (ts) { + /* @internal */ + function isSyntaxList(n) { + return n.kind === 286 /* SyntaxList */; + } + ts.isSyntaxList = isSyntaxList; + /* @internal */ + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + /* @internal */ + function isNodeKind(kind) { + return kind >= 143 /* FirstNode */; + } + ts.isNodeKind = isNodeKind; + /** + * True if node is of some token syntax kind. + * For example, this is true for an IfKeyword but not for an IfStatement. + */ + function isToken(n) { + return n.kind >= 0 /* FirstToken */ && n.kind <= 142 /* LastToken */; + } + ts.isToken = isToken; + // Node Arrays + /* @internal */ + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + // Literals + /* @internal */ + function isLiteralKind(kind) { + return 8 /* FirstLiteralToken */ <= kind && kind <= 13 /* LastLiteralToken */; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + // Pseudo-literals + /* @internal */ + function isTemplateLiteralKind(kind) { + return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 15 /* TemplateMiddle */ + || kind === 16 /* TemplateTail */; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isStringTextContainingNode(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + case 13 /* NoSubstitutionTemplateLiteral */: + return true; + default: + return false; + } + } + ts.isStringTextContainingNode = isStringTextContainingNode; + // Identifiers + /* @internal */ + function isGeneratedIdentifier(node) { + // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. + return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + // Keywords + /* @internal */ + function isModifierKind(token) { + switch (token) { + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 79 /* DefaultKeyword */: + case 84 /* ExportKeyword */: + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 115 /* StaticKeyword */: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 143 /* QualifiedName */ + || kind === 71 /* Identifier */; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 71 /* Identifier */ + || kind === 9 /* StringLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 144 /* ComputedPropertyName */; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 71 /* Identifier */ + || kind === 174 /* ObjectBindingPattern */ + || kind === 175 /* ArrayBindingPattern */; + } + ts.isBindingName = isBindingName; + // Functions + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + /* @internal */ + function isFunctionLikeKind(kind) { + switch (kind) { + case 152 /* Constructor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 160 /* FunctionType */: + case 273 /* JSDocFunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionLikeKind = isFunctionLikeKind; + // Classes + function isClassElement(node) { + var kind = node.kind; + return kind === 152 /* Constructor */ + || kind === 149 /* PropertyDeclaration */ + || kind === 151 /* MethodDeclaration */ + || kind === 153 /* GetAccessor */ + || kind === 154 /* SetAccessor */ + || kind === 157 /* IndexSignature */ + || kind === 206 /* SemicolonClassElement */ + || kind === 247 /* MissingDeclaration */; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */); + } + ts.isAccessor = isAccessor; + // Type members + 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 */ + || kind === 262 /* ShorthandPropertyAssignment */ + || kind === 263 /* SpreadAssignment */ + || kind === 151 /* MethodDeclaration */ + || kind === 153 /* GetAccessor */ + || kind === 154 /* SetAccessor */ + || kind === 247 /* MissingDeclaration */; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + // Type + function isTypeNodeKind(kind) { + return (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) + || kind === 119 /* AnyKeyword */ + || kind === 133 /* NumberKeyword */ + || kind === 134 /* ObjectKeyword */ + || kind === 122 /* BooleanKeyword */ + || kind === 136 /* StringKeyword */ + || kind === 137 /* SymbolKeyword */ + || kind === 99 /* ThisKeyword */ + || kind === 105 /* VoidKeyword */ + || kind === 139 /* UndefinedKeyword */ + || kind === 95 /* NullKeyword */ + || kind === 130 /* NeverKeyword */ + || kind === 201 /* ExpressionWithTypeArguments */; + } + /** + * Node test that determines whether a node is a valid type node. + * This differs from the `isPartOfTypeNode` function which determines whether a node is *part* + * of a TypeNode. + */ + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + // Binding patterns + /* @internal */ + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 175 /* ArrayBindingPattern */ + || kind === 174 /* ObjectBindingPattern */; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + /* @internal */ + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 177 /* ArrayLiteralExpression */ + || kind === 178 /* ObjectLiteralExpression */; + } + ts.isAssignmentPattern = isAssignmentPattern; + /* @internal */ + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 176 /* BindingElement */ + || kind === 200 /* OmittedExpression */; + } + ts.isArrayBindingElement = isArrayBindingElement; + /** + * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration + */ + /* @internal */ + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 226 /* VariableDeclaration */: + case 146 /* Parameter */: + case 176 /* BindingElement */: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + /** + * Determines whether a node is a BindingOrAssignmentPattern + */ + /* @internal */ + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + /** + * Determines whether a node is an ObjectBindingOrAssignmentPattern + */ + /* @internal */ + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 174 /* ObjectBindingPattern */: + case 178 /* ObjectLiteralExpression */: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + /** + * Determines whether a node is an ArrayBindingOrAssignmentPattern + */ + /* @internal */ + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 175 /* ArrayBindingPattern */: + case 177 /* ArrayLiteralExpression */: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + // Expression + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 179 /* PropertyAccessExpression */ + || kind === 143 /* QualifiedName */; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 251 /* JsxOpeningElement */: + case 250 /* JsxSelfClosingElement */: + case 181 /* CallExpression */: + case 182 /* NewExpression */: + case 183 /* TaggedTemplateExpression */: + case 147 /* Decorator */: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 /* CallExpression */ || node.kind === 182 /* NewExpression */; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 196 /* TemplateExpression */ + || kind === 13 /* NoSubstitutionTemplateLiteral */; + } + ts.isTemplateLiteral = isTemplateLiteral; + function isLeftHandSideExpressionKind(kind) { + return kind === 179 /* PropertyAccessExpression */ + || kind === 180 /* ElementAccessExpression */ + || kind === 182 /* NewExpression */ + || kind === 181 /* CallExpression */ + || kind === 249 /* JsxElement */ + || kind === 250 /* JsxSelfClosingElement */ + || kind === 183 /* TaggedTemplateExpression */ + || kind === 177 /* ArrayLiteralExpression */ + || kind === 185 /* ParenthesizedExpression */ + || kind === 178 /* ObjectLiteralExpression */ + || kind === 199 /* ClassExpression */ + || kind === 186 /* FunctionExpression */ + || kind === 71 /* Identifier */ + || kind === 12 /* RegularExpressionLiteral */ + || kind === 8 /* NumericLiteral */ + || kind === 9 /* StringLiteral */ + || kind === 13 /* NoSubstitutionTemplateLiteral */ + || kind === 196 /* TemplateExpression */ + || kind === 86 /* FalseKeyword */ + || kind === 95 /* NullKeyword */ + || kind === 99 /* ThisKeyword */ + || kind === 101 /* TrueKeyword */ + || kind === 97 /* SuperKeyword */ + || kind === 91 /* ImportKeyword */ + || kind === 203 /* NonNullExpression */ + || kind === 204 /* MetaProperty */; + } + /* @internal */ + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 192 /* PrefixUnaryExpression */ + || kind === 193 /* PostfixUnaryExpression */ + || kind === 188 /* DeleteExpression */ + || kind === 189 /* TypeOfExpression */ + || kind === 190 /* VoidExpression */ + || kind === 191 /* AwaitExpression */ + || kind === 184 /* TypeAssertionExpression */ + || isLeftHandSideExpressionKind(kind); + } + /* @internal */ + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 195 /* ConditionalExpression */ + || kind === 197 /* YieldExpression */ + || kind === 187 /* ArrowFunction */ + || kind === 194 /* BinaryExpression */ + || kind === 198 /* SpreadElement */ + || kind === 202 /* AsExpression */ + || kind === 200 /* OmittedExpression */ + || kind === 289 /* CommaListExpression */ + || isUnaryExpressionKind(kind); + } + /* @internal */ + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 184 /* TypeAssertionExpression */ + || kind === 202 /* AsExpression */; + } + ts.isAssertionExpression = isAssertionExpression; + /* @internal */ + function isPartiallyEmittedExpression(node) { + return node.kind === 288 /* PartiallyEmittedExpression */; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + /* @internal */ + function isNotEmittedStatement(node) { + return node.kind === 287 /* NotEmittedStatement */; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + /* @internal */ + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + // Statement + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + return true; + case 222 /* LabeledStatement */: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + /* @internal */ + function isForInOrOfStatement(node) { + return node.kind === 215 /* ForInStatement */ || node.kind === 216 /* ForOfStatement */; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + // Element + /* @internal */ + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + /* @internal */ + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + /* @internal */ + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + /* @internal */ + function isModuleBody(node) { + var kind = node.kind; + return kind === 234 /* ModuleBlock */ + || kind === 233 /* ModuleDeclaration */ + || kind === 71 /* Identifier */; + } + ts.isModuleBody = isModuleBody; + /* @internal */ + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 234 /* ModuleBlock */ + || kind === 233 /* ModuleDeclaration */; + } + ts.isNamespaceBody = isNamespaceBody; + /* @internal */ + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 71 /* Identifier */ + || kind === 233 /* ModuleDeclaration */; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + /* @internal */ + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 241 /* NamedImports */ + || kind === 240 /* NamespaceImport */; + } + ts.isNamedImportBindings = isNamedImportBindings; + /* @internal */ + function isModuleOrEnumDeclaration(node) { + return node.kind === 233 /* ModuleDeclaration */ || node.kind === 232 /* EnumDeclaration */; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 187 /* ArrowFunction */ + || kind === 176 /* BindingElement */ + || kind === 229 /* ClassDeclaration */ + || kind === 199 /* ClassExpression */ + || kind === 152 /* Constructor */ + || kind === 232 /* EnumDeclaration */ + || kind === 264 /* EnumMember */ + || kind === 246 /* ExportSpecifier */ + || kind === 228 /* FunctionDeclaration */ + || kind === 186 /* FunctionExpression */ + || kind === 153 /* GetAccessor */ + || kind === 239 /* ImportClause */ + || kind === 237 /* ImportEqualsDeclaration */ + || kind === 242 /* ImportSpecifier */ + || kind === 230 /* InterfaceDeclaration */ + || kind === 253 /* JsxAttribute */ + || kind === 151 /* MethodDeclaration */ + || kind === 150 /* MethodSignature */ + || kind === 233 /* ModuleDeclaration */ + || kind === 236 /* NamespaceExportDeclaration */ + || kind === 240 /* NamespaceImport */ + || kind === 146 /* Parameter */ + || kind === 261 /* PropertyAssignment */ + || kind === 149 /* PropertyDeclaration */ + || kind === 148 /* PropertySignature */ + || kind === 154 /* SetAccessor */ + || kind === 262 /* ShorthandPropertyAssignment */ + || kind === 231 /* TypeAliasDeclaration */ + || kind === 145 /* TypeParameter */ + || kind === 226 /* VariableDeclaration */ + || kind === 283 /* JSDocTypedefTag */; + } + function isDeclarationStatementKind(kind) { + return kind === 228 /* FunctionDeclaration */ + || kind === 247 /* MissingDeclaration */ + || kind === 229 /* ClassDeclaration */ + || kind === 230 /* InterfaceDeclaration */ + || kind === 231 /* TypeAliasDeclaration */ + || kind === 232 /* EnumDeclaration */ + || kind === 233 /* ModuleDeclaration */ + || kind === 238 /* ImportDeclaration */ + || kind === 237 /* ImportEqualsDeclaration */ + || kind === 244 /* ExportDeclaration */ + || kind === 243 /* ExportAssignment */ + || kind === 236 /* NamespaceExportDeclaration */; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 218 /* BreakStatement */ + || kind === 217 /* ContinueStatement */ + || kind === 225 /* DebuggerStatement */ + || kind === 212 /* DoStatement */ + || kind === 210 /* ExpressionStatement */ + || kind === 209 /* EmptyStatement */ + || kind === 215 /* ForInStatement */ + || kind === 216 /* ForOfStatement */ + || kind === 214 /* ForStatement */ + || kind === 211 /* IfStatement */ + || kind === 222 /* LabeledStatement */ + || kind === 219 /* ReturnStatement */ + || kind === 221 /* SwitchStatement */ + || kind === 223 /* ThrowStatement */ + || kind === 224 /* TryStatement */ + || kind === 208 /* VariableStatement */ + || kind === 213 /* WhileStatement */ + || kind === 220 /* WithStatement */ + || kind === 287 /* NotEmittedStatement */ + || kind === 291 /* EndOfDeclarationMarker */ + || kind === 290 /* MergeDeclarationMarker */; + } + /* @internal */ + function isDeclaration(node) { + if (node.kind === 145 /* TypeParameter */) { + return node.parent.kind !== 282 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + /* @internal */ + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + /** + * Determines whether the node is a statement that is not also a declaration + */ + /* @internal */ + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + /* @internal */ + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 207 /* Block */; + } + ts.isStatement = isStatement; + // Module references + /* @internal */ + function isModuleReference(node) { + var kind = node.kind; + return kind === 248 /* ExternalModuleReference */ + || kind === 143 /* QualifiedName */ + || kind === 71 /* Identifier */; + } + ts.isModuleReference = isModuleReference; + // JSX + /* @internal */ + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 99 /* ThisKeyword */ + || kind === 71 /* Identifier */ + || kind === 179 /* PropertyAccessExpression */; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + /* @internal */ + function isJsxChild(node) { + var kind = node.kind; + return kind === 249 /* JsxElement */ + || kind === 256 /* JsxExpression */ + || kind === 250 /* JsxSelfClosingElement */ + || kind === 10 /* JsxText */; + } + ts.isJsxChild = isJsxChild; + /* @internal */ + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 253 /* JsxAttribute */ + || kind === 255 /* JsxSpreadAttribute */; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + /* @internal */ + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 /* StringLiteral */ + || kind === 256 /* JsxExpression */; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 251 /* JsxOpeningElement */ + || kind === 250 /* JsxSelfClosingElement */; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + // Clauses + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 257 /* CaseClause */ + || kind === 258 /* DefaultClause */; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + // JSDoc + /** True if node is of some JSDoc syntax kind. */ + /* @internal */ + function isJSDocNode(node) { + return node.kind >= 267 /* FirstJSDocNode */ && node.kind <= 285 /* LastJSDocNode */; + } + ts.isJSDocNode = isJSDocNode; + /** True if node is of a kind that may contain comment text. */ + function isJSDocCommentContainingNode(node) { + return node.kind === 275 /* JSDocComment */ || isJSDocTag(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + // TODO: determine what this does before making it public. + /* @internal */ + function isJSDocTag(node) { + return node.kind >= 276 /* FirstJSDocTagNode */ && node.kind <= 285 /* LastJSDocTagNode */; + } + ts.isJSDocTag = isJSDocTag; +})(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield"; + SignatureFlags[SignatureFlags["Await"] = 2] = "Await"; + SignatureFlags[SignatureFlags["Type"] = 4] = "Type"; + SignatureFlags[SignatureFlags["RequireCompleteParameterList"] = 8] = "RequireCompleteParameterList"; + SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace"; + SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc"; + })(SignatureFlags || (SignatureFlags = {})); + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 265 /* SourceFile */) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 71 /* Identifier */) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + /** + * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes + * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, + * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns + * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. + * + * @param node a given node to visit its children + * @param cbNode a callback to be invoked for all child nodes + * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. + */ + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 142 /* LastToken */) { + return; + } + switch (node.kind) { + case 143 /* QualifiedName */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 145 /* TypeParameter */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 262 /* ShorthandPropertyAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 263 /* SpreadAssignment */: + return visitNode(cbNode, node.expression); + case 146 /* Parameter */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 261 /* PropertyAssignment */: + case 226 /* VariableDeclaration */: + case 176 /* BindingElement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 159 /* TypeReference */: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 158 /* TypePredicate */: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 162 /* TypeQuery */: + return visitNode(cbNode, node.exprName); + case 163 /* TypeLiteral */: + return visitNodes(cbNode, cbNodes, node.members); + case 164 /* ArrayType */: + return visitNode(cbNode, node.elementType); + case 165 /* TupleType */: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 166 /* UnionType */: + case 167 /* IntersectionType */: + return visitNodes(cbNode, cbNodes, node.types); + case 168 /* ParenthesizedType */: + case 170 /* TypeOperator */: + return visitNode(cbNode, node.type); + case 171 /* IndexedAccessType */: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 172 /* MappedType */: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 173 /* LiteralType */: + return visitNode(cbNode, node.literal); + case 174 /* ObjectBindingPattern */: + case 175 /* ArrayBindingPattern */: + return visitNodes(cbNode, cbNodes, node.elements); + case 177 /* ArrayLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 178 /* ObjectLiteralExpression */: + return visitNodes(cbNode, cbNodes, node.properties); + case 179 /* PropertyAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 180 /* ElementAccessExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 181 /* CallExpression */: + case 182 /* NewExpression */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 183 /* TaggedTemplateExpression */: + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.template); + case 184 /* TypeAssertionExpression */: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 185 /* ParenthesizedExpression */: + return visitNode(cbNode, node.expression); + case 188 /* DeleteExpression */: + return visitNode(cbNode, node.expression); + case 189 /* TypeOfExpression */: + return visitNode(cbNode, node.expression); + case 190 /* VoidExpression */: + return visitNode(cbNode, node.expression); + case 192 /* PrefixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 197 /* YieldExpression */: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 191 /* AwaitExpression */: + return visitNode(cbNode, node.expression); + case 193 /* PostfixUnaryExpression */: + return visitNode(cbNode, node.operand); + case 194 /* BinaryExpression */: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 202 /* AsExpression */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 203 /* NonNullExpression */: + return visitNode(cbNode, node.expression); + case 204 /* MetaProperty */: + return visitNode(cbNode, node.name); + case 195 /* ConditionalExpression */: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 198 /* SpreadElement */: + return visitNode(cbNode, node.expression); + case 207 /* Block */: + case 234 /* ModuleBlock */: + return visitNodes(cbNode, cbNodes, node.statements); + case 265 /* SourceFile */: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 208 /* VariableStatement */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 227 /* VariableDeclarationList */: + return visitNodes(cbNode, cbNodes, node.declarations); + case 210 /* ExpressionStatement */: + return visitNode(cbNode, node.expression); + case 211 /* IfStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 212 /* DoStatement */: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 213 /* WhileStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214 /* ForStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 215 /* ForInStatement */: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 216 /* ForOfStatement */: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 217 /* ContinueStatement */: + case 218 /* BreakStatement */: + return visitNode(cbNode, node.label); + case 219 /* ReturnStatement */: + return visitNode(cbNode, node.expression); + case 220 /* WithStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 221 /* SwitchStatement */: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 235 /* CaseBlock */: + return visitNodes(cbNode, cbNodes, node.clauses); + case 257 /* CaseClause */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 258 /* DefaultClause */: + return visitNodes(cbNode, cbNodes, node.statements); + case 222 /* LabeledStatement */: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 223 /* ThrowStatement */: + return visitNode(cbNode, node.expression); + case 224 /* TryStatement */: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 260 /* CatchClause */: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 147 /* Decorator */: + return visitNode(cbNode, node.expression); + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 230 /* InterfaceDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 231 /* TypeAliasDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 232 /* EnumDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 264 /* EnumMember */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 233 /* ModuleDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 237 /* ImportEqualsDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 238 /* ImportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 239 /* ImportClause */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 236 /* NamespaceExportDeclaration */: + return visitNode(cbNode, node.name); + case 240 /* NamespaceImport */: + return visitNode(cbNode, node.name); + case 241 /* NamedImports */: + case 245 /* NamedExports */: + return visitNodes(cbNode, cbNodes, node.elements); + case 244 /* ExportDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 243 /* ExportAssignment */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 196 /* TemplateExpression */: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 205 /* TemplateSpan */: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 144 /* ComputedPropertyName */: + return visitNode(cbNode, node.expression); + case 259 /* HeritageClause */: + return visitNodes(cbNode, cbNodes, node.types); + case 201 /* ExpressionWithTypeArguments */: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 248 /* ExternalModuleReference */: + return visitNode(cbNode, node.expression); + case 247 /* MissingDeclaration */: + return visitNodes(cbNode, cbNodes, node.decorators); + case 289 /* CommaListExpression */: + return visitNodes(cbNode, cbNodes, node.elements); + case 249 /* JsxElement */: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 250 /* JsxSelfClosingElement */: + case 251 /* JsxOpeningElement */: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.attributes); + case 254 /* JsxAttributes */: + return visitNodes(cbNode, cbNodes, node.properties); + case 253 /* JsxAttribute */: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 255 /* JsxSpreadAttribute */: + return visitNode(cbNode, node.expression); + case 256 /* JsxExpression */: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 252 /* JsxClosingElement */: + return visitNode(cbNode, node.tagName); + case 267 /* JSDocTypeExpression */: + return visitNode(cbNode, node.type); + case 271 /* JSDocNonNullableType */: + return visitNode(cbNode, node.type); + case 270 /* JSDocNullableType */: + return visitNode(cbNode, node.type); + case 272 /* JSDocOptionalType */: + return visitNode(cbNode, node.type); + case 273 /* JSDocFunctionType */: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 274 /* JSDocVariadicType */: + return visitNode(cbNode, node.type); + case 275 /* JSDocComment */: + return visitNodes(cbNode, cbNodes, node.tags); + case 279 /* JSDocParameterTag */: + case 284 /* JSDocPropertyTag */: + if (node.isNameFirst) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression); + } + else { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name); + } + case 280 /* JSDocReturnTag */: + return visitNode(cbNode, node.typeExpression); + case 281 /* JSDocTypeTag */: + return visitNode(cbNode, node.typeExpression); + case 277 /* JSDocAugmentsTag */: + return visitNode(cbNode, node.typeExpression); + case 282 /* JSDocTemplateTag */: + return visitNodes(cbNode, cbNodes, node.typeParameters); + case 283 /* JSDocTypedefTag */: + if (node.typeExpression && + node.typeExpression.kind === 267 /* JSDocTypeExpression */) { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName); + } + else { + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + } + case 285 /* JSDocTypeLiteral */: + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } + return; + case 288 /* PartiallyEmittedExpression */: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + /** + * Parse json text into SyntaxTree and return node and parse errors if any + * @param fileName + * @param sourceText + */ + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + // See also `isExternalOrCommonJsModule` in utilities.ts + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. + // We will manually port the flag to the new source file. + newSourceFile.flags |= (sourceFile.flags & 524288 /* PossiblyContainsDynamicImport */); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + /* @internal */ + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + // because the jsDocComment was parsed out of the source file, it might + // not be covered by the fixupParentReferences. + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + /* @internal */ + // Exposed only for testing. + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + // Implement the parser as a singleton module. We do this for perf reasons because creating + // parser instances can actually be expensive enough to impact us on projects with many source + // files. + var Parser; + (function (Parser) { + // Share a single scanner across all calls to parse a source file. This helps speed things + // up by avoiding the cost of creating/compiling scanners over and over again. + var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); + var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; + // capture constructors in 'initializeState' to avoid null checks + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + // Flags that dictate what parsing context we're in. For example: + // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is + // that some tokens that would be considered identifiers may be considered keywords. + // + // When adding more parser context flags, consider which is the more common case that the + // flag will be in. This should be the 'false' state for that flag. The reason for this is + // that we don't store data in our nodes unless the value is in the *non-default* state. So, + // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for + // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost + // all nodes would need extra state on them to store this info. + // + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // grammar specification. + // + // An important thing about these context concepts. By default they are effectively inherited + // while parsing through every grammar production. i.e. if you don't change them, then when + // you parse a sub-production, it will have the same context values as the parent production. + // This is great most of the time. After all, consider all the 'expression' grammar productions + // and how nearly all of them pass along the 'in' and 'yield' context values: + // + // EqualityExpression[In, Yield] : + // RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] + // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] + // + // Where you have to be careful is then understanding what the points are in the grammar + // where the values are *not* passed along. For example: + // + // SingleNameBinding[Yield,GeneratorParameter] + // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt + // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt + // + // Here this is saying that if the GeneratorParameter context flag is set, that we should + // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier + // and we should explicitly unset the 'yield' context flag before calling into the Initializer. + // production. Conversely, if the GeneratorParameter context flag is not set, then we + // should leave the 'yield' context flag alone. + // + // Getting this all correct is tricky and requires careful reading of the grammar to + // understand when these values should be changed versus when they should be inherited. + // + // Note: it should not be necessary to save/restore these flags during speculative/lookahead + // parsing. These context flags are naturally stored and restored through normal recursive + // descent parsing and unwinding. + var contextFlags; + // Whether or not we've had a parse error since creating the last AST node. If we have + // encountered an error, it will be stored on the next AST node we create. Parse errors + // can be broken down into three categories: + // + // 1) An error that occurred during scanning. For example, an unterminated literal, or a + // character that was completely not understood. + // + // 2) A token was expected, but was not present. This type of error is commonly produced + // by the 'parseExpected' function. + // + // 3) A token was present that no parsing function was able to consume. This type of error + // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser + // decides to skip the token. + // + // In all of these cases, we want to mark the next node as having had an error before it. + // With this mark, we can know in incremental settings if this node can be reused, or if + // we have to reparse it. If we don't keep this information around, we may just reuse the + // node. in that event we would then not produce the same errors as we did before, causing + // significant confusion problems. + // + // Note: it is necessary that this value be saved/restored during speculative/lookahead + // parsing. During lookahead parsing, we will often create a node. That node will have + // this value attached, and then this value will be set back to 'false'. If we decide to + // rewind, we must get back to the same value we had prior to the lookahead. + // + // Note: any errors at the end of the file that do not precede a regular node, should get + // attached to the EOF token. + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); + // Prime the scanner. + nextToken(); + var entityName = parseEntityName(/*allowReservedWords*/ true); + var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + // Set source file so that errors will be reported with this file name + sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */); + var result = sourceFile; + // Prime the scanner. + nextToken(); + if (token() === 1 /* EndOfFileToken */) { + sourceFile.endOfFileToken = parseTokenNode(); + } + else if (token() === 17 /* OpenBraceToken */ || + lookAhead(function () { return token() === 9 /* StringLiteral */; })) { + result.jsonObject = parseObjectLiteralExpression(); + sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Unexpected_token); + } + else { + parseExpected(17 /* OpenBraceToken */); + } + sourceFile.parseDiagnostics = parseDiagnostics; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + // .tsx and .jsx files are treated as jsx language variant. + return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ || scriptKind === 6 /* JSON */ ? 65536 /* JavaScriptFile */ : 0 /* None */; + parseErrorBeforeNextFinishedNode = false; + // Initialize and prime the scanner before parsing the source elements. + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. + scanner.setText(""); + scanner.setOnError(undefined); + // Clear any data. We don't want to accidentally hold onto it for too long. + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; + // Prime the scanner. + nextToken(); + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); + ts.Debug.assert(token() === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + } + function addJSDocComment(node) { + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; + } + if (!node.jsDoc) { + node.jsDoc = []; + } + node.jsDoc.push(jsDoc); + } + } + return node; + } + function fixupParentReferences(rootNode) { + // normally parent references are set during binding. However, for clients that only need + // a syntax tree, and no semantic features, then the binding process is an unnecessary + // overhead. This functions allows us to set all the parents, without all the expense of + // binding. + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + // walk down setting parents that differ from the parent we think it should be. This + // allows us to quickly bail out of setting parents for subtrees during incremental + // parsing + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind) { + // code from createNode is inlined here so createNode won't have to deal with special case of creating source files + // this is quite rare comparing to other nodes and createNode should be as fast as possible + var sourceFile = new SourceFileConstructor(265 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */); + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048 /* DisallowInContext */); + } + function setYieldContext(val) { + setContextFlag(val, 4096 /* YieldContext */); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192 /* DecoratorContext */); + } + function setAwaitContext(val) { + setContextFlag(val, 16384 /* AwaitContext */); + } + function doOutsideOfContext(context, func) { + // contextFlagsToClear will contain only the context flags that are + // currently set that we need to temporarily clear + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + // clear the requested context flags + setContextFlag(/*val*/ false, contextFlagsToClear); + var result = func(); + // restore the context flags we just cleared + setContextFlag(/*val*/ true, contextFlagsToClear); + return result; + } + // no need to do anything special as we are not in any of the requested contexts + return func(); + } + function doInsideOfContext(context, func) { + // contextFlagsToSet will contain only the context flags that + // are not currently set that we need to temporarily enable. + // We don't just blindly reset to the previous flags to ensure + // that we do not mutate cached flags for the incremental + // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and + // HasAggregatedChildData). + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + // set the requested context flags + setContextFlag(/*val*/ true, contextFlagsToSet); + var result = func(); + // reset the context flags we just set + setContextFlag(/*val*/ false, contextFlagsToSet); + return result; + } + // no need to do anything special as we are already in all of the requested contexts + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048 /* DisallowInContext */, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048 /* DisallowInContext */, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096 /* YieldContext */, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192 /* DecoratorContext */, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384 /* AwaitContext */, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384 /* AwaitContext */, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096 /* YieldContext */); + } + function inDisallowInContext() { + return inContext(2048 /* DisallowInContext */); + } + function inDecoratorContext() { + return inContext(8192 /* DecoratorContext */); + } + function inAwaitContext() { + return inContext(16384 /* AwaitContext */); + } + function parseErrorAtCurrentToken(message, arg0) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + parseErrorAtPosition(start, length, message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + // Don't report another error if it would just be at the same position as the last error. + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + // Mark that we've encountered an error. We'll set an appropriate bit on the next + // node we finish so that it can't be reused incrementally. + parseErrorBeforeNextFinishedNode = true; + } + function scanError(message, length) { + var pos = scanner.getTextPos(); + parseErrorAtPosition(pos, length || 0, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + // Use this function to access the current token instead of reading the currentToken + // variable. Since function results aren't narrowed in control flow analysis, this ensures + // that the type checker doesn't make wrong assumptions about the type of the current + // token (e.g. a call to nextToken() changes the current token but the checker doesn't + // reason about this side effect). Mainstream VMs inline simple functions like this, so + // there is no performance penalty. + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + // Keep track of the state we'll need to rollback to if lookahead fails (or if the + // caller asked us to always reset our state). + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + // Note: it is not actually necessary to save/restore the context flags here. That's + // because the saving/restoring of these flags happens naturally through the recursive + // descent nature of our parser. However, we still store this here just so we can + // assert that invariant holds. + var saveContextFlags = contextFlags; + // If we're only looking ahead, then tell the scanner to only lookahead as well. + // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the + // same. + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + // If our callback returned something 'falsy' or we're just looking ahead, + // then unconditionally restore us to where we were. + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + /** Invokes the provided callback then unconditionally restores the parser to the state it + * was in immediately prior to invoking the callback. The result of invoking the callback + * is returned from this function. + */ + function lookAhead(callback) { + return speculationHelper(callback, /*isLookAhead*/ true); + } + /** Invokes the provided callback. If the callback returns something falsy, then it restores + * the parser to the state it was in immediately prior to invoking the callback. If the + * callback returns something truthy, then the parser state is not rolled back. The result + * of invoking the callback is returned from this function. + */ + function tryParse(callback) { + return speculationHelper(callback, /*isLookAhead*/ false); + } + // Ignore strict mode flag because we will report an error in type checker instead. + function isIdentifier() { + if (token() === 71 /* Identifier */) { + return true; + } + // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is + // considered a keyword and is not an identifier. + if (token() === 116 /* YieldKeyword */ && inYieldContext()) { + return false; + } + // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is + // considered a keyword and is not an identifier. + if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { + return false; + } + return token() > 107 /* LastReservedWord */; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + // Report specific message if provided with one. Otherwise, report generic fallback message. + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + // If there's a real semicolon, then we can always parse it out. + if (token() === 25 /* SemicolonToken */) { + return true; + } + // We can parse out an optional semicolon in ASI cases in the following cases. + return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 25 /* SemicolonToken */) { + // consume the semicolon if it was explicitly provided. + nextToken(); + } + return true; + } + else { + return parseExpected(25 /* SemicolonToken */); + } + } + // note: this function creates only node + function createNode(kind, pos) { + nodeCount++; + if (!(pos >= 0)) { + pos = scanner.getStartPos(); + } + return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : + kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + // Keep track on the node if we encountered an error while parsing it. If we did, then + // we cannot reuse the node incrementally. Once we've marked this node, clear out the + // flag so that we don't mark any subsequent nodes. + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768 /* ThisNodeHasError */; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind, scanner.getStartPos()); + if (kind === 71 /* Identifier */) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues + // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for + // each identifier in order to reduce memory consumption. + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(71 /* Identifier */); + // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker + if (token() !== 71 /* Identifier */) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName() { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); + } + function parseComputedPropertyName() { + // PropertyName [Yield]: + // LiteralPropertyName + // ComputedPropertyName[?Yield] + var node = createNode(144 /* ComputedPropertyName */); + parseExpected(21 /* OpenBracketToken */); + // We parse any expression (including a comma expression). But the grammar + // says that only an assignment expression is allowed, so the grammar checker + // will error if it sees a comma expression. + node.expression = allowInAnd(parseExpression); + parseExpected(22 /* CloseBracketToken */); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + if (token() === 76 /* ConstKeyword */) { + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; + } + if (token() === 84 /* ExportKeyword */) { + nextToken(); + if (token() === 79 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); + } + if (token() === 79 /* DefaultKeyword */) { + return nextTokenCanFollowDefaultKeyword(); + } + if (token() === 115 /* StaticKeyword */) { + nextToken(); + return canFollowModifier(); + } + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 21 /* OpenBracketToken */ + || token() === 17 /* OpenBraceToken */ + || token() === 39 /* AsteriskToken */ + || token() === 24 /* DotDotDotToken */ + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || + token() === 109 /* InterfaceKeyword */ || + (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + // True if positioned at the start of a list element + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + // If we're in error recovery, then we don't want to treat ';' as an empty statement. + // The problem is that ';' can show up in far too many contexts, and if we see one + // and assume it's a statement, then we may bail out inappropriately from whatever + // we're parsing. For example, if we have a semicolon in the middle of a class, then + // we really don't want to assume the class is over and we're on a statement in the + // outer module. We just want to consume and move on. + return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); + case 2 /* SwitchClauses */: + return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + case 4 /* TypeMembers */: + return lookAhead(isTypeMemberStart); + case 5 /* ClassMembers */: + // We allow semicolons as class elements (as specified by ES6) as long as we're + // not in error recovery. If we're in error recovery, we don't want an errant + // semicolon to be treated as a class member (since they're almost always used + // for statements. + return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); + case 6 /* EnumMembers */: + // Include open bracket computed properties. This technically also lets in indexers, + // which would be a candidate for improved error reporting. + return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); + case 12 /* ObjectLiteralMembers */: + return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + case 17 /* RestProperties */: + return isLiteralPropertyName(); + case 9 /* ObjectBindingElements */: + return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); + case 7 /* HeritageClauseElement */: + // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` + // That way we won't consume the body of a class in its heritage clause. + if (token() === 17 /* OpenBraceToken */) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + // If we're in error recovery we tighten up what we're willing to match. + // That way we don't treat something like "this" as a valid heritage clause + // element during recovery. + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8 /* VariableDeclarations */: + return isIdentifierOrPattern(); + case 10 /* ArrayBindingElements */: + return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); + case 18 /* TypeParameters */: + return isIdentifier(); + case 11 /* ArgumentExpressions */: + case 15 /* ArrayLiteralMembers */: + return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + case 16 /* Parameters */: + return isStartOfParameter(); + case 19 /* TypeArguments */: + case 20 /* TupleElementTypes */: + return token() === 26 /* CommaToken */ || isStartOfType(); + case 21 /* HeritageClauses */: + return isHeritageClause(); + case 22 /* ImportOrExportSpecifiers */: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13 /* JsxAttributes */: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; + case 14 /* JsxChildren */: + return true; + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 17 /* OpenBraceToken */); + if (nextToken() === 18 /* CloseBraceToken */) { + // if we see "extends {}" then only treat the {} as what we're extending (and not + // the class body) if we have: + // + // extends {} { + // extends {}, + // extends {} extends + // extends {} implements + var next = nextToken(); + return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 108 /* ImplementsKeyword */ || + token() === 85 /* ExtendsKeyword */) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + // True if positioned at a list terminator + function isListTerminator(kind) { + if (token() === 1 /* EndOfFileToken */) { + // Being at the end of the file ends all lists. + return true; + } + switch (kind) { + case 1 /* BlockStatements */: + case 2 /* SwitchClauses */: + case 4 /* TypeMembers */: + case 5 /* ClassMembers */: + case 6 /* EnumMembers */: + case 12 /* ObjectLiteralMembers */: + case 9 /* ObjectBindingElements */: + case 22 /* ImportOrExportSpecifiers */: + return token() === 18 /* CloseBraceToken */; + case 3 /* SwitchClauseStatements */: + return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; + case 7 /* HeritageClauseElement */: + return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + case 8 /* VariableDeclarations */: + return isVariableDeclaratorListTerminator(); + case 18 /* TypeParameters */: + // Tokens other than '>' are here for better error recovery + return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + case 11 /* ArgumentExpressions */: + // Tokens other than ')' are here for better error recovery + return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; + case 15 /* ArrayLiteralMembers */: + case 20 /* TupleElementTypes */: + case 10 /* ArrayBindingElements */: + return token() === 22 /* CloseBracketToken */; + case 16 /* Parameters */: + case 17 /* RestProperties */: + // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery + return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; + case 19 /* TypeArguments */: + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 26 /* CommaToken */; + case 21 /* HeritageClauses */: + return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; + case 13 /* JsxAttributes */: + return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; + case 14 /* JsxChildren */: + return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + } + } + function isVariableDeclaratorListTerminator() { + // If we can consume a semicolon (either explicitly, or with ASI), then consider us done + // with parsing the list of variable declarators. + if (canParseSemicolon()) { + return true; + } + // in the case where we're parsing the variable declarator of a 'for-in' statement, we + // are done if we see an 'in' keyword in front of us. Same with for-of + if (isInOrOfKeyword(token())) { + return true; + } + // ERROR RECOVERY TWEAK: + // For better error recovery, if we see an '=>' then we just stop immediately. We've got an + // arrow function here and it's going to be very unlikely that we'll resynchronize and get + // another variable declaration. + if (token() === 36 /* EqualsGreaterThanToken */) { + return true; + } + // Keep trying to parse out variable declarators. + return false; + } + // True if positioned at element or terminator of the current list or any enclosing list + function isInSomeParsingContext() { + for (var kind = 0; kind < 23 /* Count */; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + // Parses a list of elements + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + while (!isListTerminator(kind)) { + if (isListElement(kind, /*inErrorRecovery*/ false)) { + var element = parseListElement(kind, parseElement); + result.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse the node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + // Can't reuse a missing node. + if (ts.nodeIsMissing(node)) { + return undefined; + } + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (ts.containsParseError(node)) { + return undefined; + } + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presence of strict mode may cause us to parse the tokens in the file + // differently. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.flags & 96256 /* ContextFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the current list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + return isReusableClassMember(node); + case 2 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 6 /* EnumMembers */: + return isReusableEnumMember(node); + case 4 /* TypeMembers */: + return isReusableTypeMember(node); + case 8 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 16 /* Parameters */: + return isReusableParameter(node); + case 17 /* RestProperties */: + return false; + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case 21 /* HeritageClauses */: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + case 18 /* TypeParameters */: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + case 20 /* TupleElementTypes */: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case 19 /* TypeArguments */: + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case 11 /* ArgumentExpressions */: + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case 12 /* ObjectLiteralMembers */: + // This is probably not safe to reuse. There can be speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list, and there can be left hand side expressions (which can have type + // arguments.) + case 7 /* HeritageClauseElement */: + // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes + // on any given element. Same for children. + case 13 /* JsxAttributes */: + case 14 /* JsxChildren */: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 152 /* Constructor */: + case 157 /* IndexSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 149 /* PropertyDeclaration */: + case 206 /* SemicolonClassElement */: + return true; + case 151 /* MethodDeclaration */: + // Method declarations are not necessarily reusable. An object-literal + // may have a method calls "constructor(...)" and we must reparse that + // into an actual .ConstructorDeclaration. + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && + methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 257 /* CaseClause */: + case 258 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 228 /* FunctionDeclaration */: + case 208 /* VariableStatement */: + case 207 /* Block */: + case 211 /* IfStatement */: + case 210 /* ExpressionStatement */: + case 223 /* ThrowStatement */: + case 219 /* ReturnStatement */: + case 221 /* SwitchStatement */: + case 218 /* BreakStatement */: + case 217 /* ContinueStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + case 214 /* ForStatement */: + case 213 /* WhileStatement */: + case 220 /* WithStatement */: + case 209 /* EmptyStatement */: + case 224 /* TryStatement */: + case 222 /* LabeledStatement */: + case 212 /* DoStatement */: + case 225 /* DebuggerStatement */: + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + case 244 /* ExportDeclaration */: + case 243 /* ExportAssignment */: + case 233 /* ModuleDeclaration */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 232 /* EnumDeclaration */: + case 231 /* TypeAliasDeclaration */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 264 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 156 /* ConstructSignature */: + case 150 /* MethodSignature */: + case 157 /* IndexSignature */: + case 148 /* PropertySignature */: + case 155 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 226 /* VariableDeclaration */) { + return false; + } + // Very subtle incremental parsing bug. Consider the following code: + // + // let v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new List= 0) { + // Always preserve a trailing comma by marking it on the NodeArray + result.hasTrailingComma = true; + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + return createNodeArray(); + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(23 /* DotToken */)) { + if (token() === 27 /* LessThanToken */) { + // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(143 /* QualifiedName */, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + // Technically a keyword is valid here as all identifiers and keywords are identifier names. + // However, often we'll encounter this in error situations when the identifier or keyword + // is actually starting another valid construct. + // + // So, we check for the following specific case: + // + // name. + // identifierOrKeyword identifierNameOrKeyword + // + // Note: the newlines are important here. For example, if that above code + // were rewritten into: + // + // name.identifierOrKeyword + // identifierNameOrKeyword + // + // Then we would consider it valid. That's because ASI would take effect and + // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". + // In the first case though, ASI will not take effect because there is not a + // line terminator after the identifier or keyword. + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + // Report that we need an identifier. However, report it right after the dot, + // and not on the next token. This is because the next token might actually + // be an identifier and the error would be quite confusing. + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(196 /* TemplateExpression */); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + var templateSpans = createNodeArray(); + do { + templateSpans.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 15 /* TemplateMiddle */); + templateSpans.end = getNodeEnd(); + template.templateSpans = templateSpans; + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(205 /* TemplateSpan */); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 18 /* CloseBraceToken */) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(16 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + var text = scanner.getTokenValue(); + node.text = text; + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + // Octal literals are not allowed in strict mode or ES5 + // Note that theoretically the following condition would hold true literals like 009, + // which is not octal.But because of how the scanner separates the tokens, we would + // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. + // We also do not need to check for negatives because any prefix operator would be part of a + // parent unary expression. + if (node.kind === 8 /* NumericLiteral */) { + node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + } + nextToken(); + finishNode(node); + return node; + } + // TYPES + function parseTypeReference() { + var node = createNode(159 /* TypeReference */); + node.typeName = parseEntityName(/*allowReservedWords*/ !!(contextFlags & 1048576 /* JSDoc */), ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + } + return finishNode(node); + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(158 /* TypePredicate */, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(169 /* ThisType */); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType() { + var result = createNode(268 /* JSDocAllType */); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + // skip the ? + nextToken(); + // Need to lookahead to decide if this is a nullable or unknown type. + // Here are cases where we'll pick the unknown type: + // + // Foo(?, + // { a: ? } + // Foo(?) + // Foo + // Foo(?= + // (?| + if (token() === 26 /* CommaToken */ || + token() === 18 /* CloseBraceToken */ || + token() === 20 /* CloseParenToken */ || + token() === 29 /* GreaterThanToken */ || + token() === 58 /* EqualsToken */ || + token() === 49 /* BarToken */) { + var result = createNode(269 /* JSDocUnknownType */, pos); + return finishNode(result); + } + else { + var result = createNode(270 /* JSDocNullableType */, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNode(273 /* JSDocFunctionType */); + nextToken(); + fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); + return finishNode(result); + } + var node = createNode(159 /* TypeReference */); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(146 /* Parameter */); + if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { + parameter.name = parseIdentifierName(); + parseExpected(56 /* ColonToken */); + } + parameter.type = parseType(); + return finishNode(parameter); + } + function parseJSDocNodeWithType(kind) { + var result = createNode(kind); + nextToken(); + result.type = parseType(); + return finishNode(result); + } + function parseTypeQuery() { + var node = createNode(162 /* TypeQuery */); + parseExpected(103 /* TypeOfKeyword */); + node.exprName = parseEntityName(/*allowReservedWords*/ true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(145 /* TypeParameter */); + node.name = parseIdentifier(); + if (parseOptional(85 /* ExtendsKeyword */)) { + // It's not uncommon for people to write improper constraints to a generic. If the + // user writes a constraint that is an expression and not an actual type, then parse + // it out as an expression (so we can recover well), but report that a type is needed + // instead. + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + // It was not a type, and it looked like an expression. Parse out an expression + // here so we recover well. Note: it is important that we call parseUnaryExpression + // and not parseExpression here. If the user has: + // + // + // + // We do *not* want to consume the > as we're consuming the expression for "". + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(58 /* EqualsToken */)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 27 /* LessThanToken */) { + return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + } + } + function parseParameterType() { + if (parseOptional(56 /* ColonToken */)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter() { + return token() === 24 /* DotDotDotToken */ || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 57 /* AtToken */ || isStartOfType(); + } + function parseParameter() { + var node = createNode(146 /* Parameter */); + if (token() === 99 /* ThisKeyword */) { + node.name = createIdentifier(/*isIdentifier*/ true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + // FormalParameter [Yield,Await]: + // BindingElement[?Yield,?Await] + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + // in cases like + // 'use strict' + // function foo(static) + // isParameter('static') === true, because of isModifier('static') + // however 'static' is not a legal identifier in a strict mode. + // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) + // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) + // to avoid this we'll advance cursor to the next token. + nextToken(); + } + node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.type = parseParameterType(); + node.initializer = parseBindingElementInitializer(/*inParameter*/ true); + return addJSDocComment(finishNode(node)); + } + function parseBindingElementInitializer(inParameter) { + return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); + } + function parseParameterInitializer() { + return parseInitializer(/*inParameter*/ true); + } + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32 /* JSDoc */)) { + signature.typeParameters = parseTypeParameters(); + } + signature.parameters = parseParameterList(flags); + var returnTokenRequired = returnToken === 36 /* EqualsGreaterThanToken */; + if (returnTokenRequired) { + parseExpected(returnToken); + signature.type = parseTypeOrTypePredicate(); + } + else if (parseOptional(returnToken)) { + signature.type = parseTypeOrTypePredicate(); + } + else if (flags & 4 /* Type */) { + var start = scanner.getTokenPos(); + var length_1 = scanner.getTextPos() - start; + var backwardToken = parseOptional(returnToken === 56 /* ColonToken */ ? 36 /* EqualsGreaterThanToken */ : 56 /* ColonToken */); + if (backwardToken) { + // This is easy to get backward, especially in type contexts, so parse the type anyway + signature.type = parseTypeOrTypePredicate(); + parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); + } + } + } + function parseParameterList(flags) { + // FormalParameters [Yield,Await]: (modified) + // [empty] + // FormalParameterList[?Yield,Await] + // + // FormalParameter[Yield,Await]: (modified) + // BindingElement[?Yield,Await] + // + // BindingElement [Yield,Await]: (modified) + // SingleNameBinding[?Yield,?Await] + // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + // + // SingleNameBinding [Yield,Await]: + // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt + if (parseExpected(19 /* OpenParenToken */)) { + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { + // Caller insisted that we had to end with a ) We didn't. So just return + // undefined here. + return undefined; + } + return result; + } + // We didn't even have an open paren. If the caller requires a complete parameter list, + // we definitely can't provide that. However, if they're ok with an incomplete one, + // then just return an empty set of parameters. + return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); + } + function parseTypeMemberSemicolon() { + // We allow type members to be separated by commas or (possibly ASI) semicolons. + // First check if it was a comma. If so, we're done with the member. + if (parseOptional(26 /* CommaToken */)) { + return; + } + // Didn't have a comma. We must have a (possible ASI) semicolon. + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNode(kind); + if (kind === 156 /* ConstructSignature */) { + parseExpected(94 /* NewKeyword */); + } + fillSignature(56 /* ColonToken */, 4 /* Type */, node); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(node)); + } + function isIndexSignature() { + if (token() !== 21 /* OpenBracketToken */) { + return false; + } + return lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + // The only allowed sequence is: + // + // [id: + // + // However, for error recovery, we also check the following cases: + // + // [... + // [id, + // [id?, + // [id?: + // [id?] + // [public id + // [private id + // [protected id + // [] + // + nextToken(); + if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + // Skip the identifier + nextToken(); + } + // A colon signifies a well formed indexer + // A comma should be a badly formed indexer because comma expressions are not allowed + // in computed properties. + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { + return true; + } + // Question mark could be an indexer with an optional property, + // or it could be a conditional expression in a computed property. + if (token() !== 55 /* QuestionToken */) { + return false; + } + // If any of the following tokens are after the question mark, it cannot + // be a conditional expression, so treat it as an indexer. + nextToken(); + return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; + } + function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { + var node = createNode(157 /* IndexSignature */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(fullStart, modifiers) { + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + var method = createNode(150 /* MethodSignature */, fullStart); + method.modifiers = modifiers; + method.name = name; + method.questionToken = questionToken; + // Method signatures don't exist in expression contexts. So they have neither + // [Yield] nor [Await] + fillSignature(56 /* ColonToken */, 4 /* Type */, method); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(method)); + } + else { + var property = createNode(148 /* PropertySignature */, fullStart); + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + if (token() === 58 /* EqualsToken */) { + // Although type literal properties cannot not have initializers, we attempt + // to parse an initializer so we can report in the checker that an interface + // property or type literal property cannot have an initializer. + property.initializer = parseNonParameterInitializer(); + } + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(property)); + } + } + function isTypeMemberStart() { + // Return true if we have the start of a signature member + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return true; + } + var idToken; + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + // Index signatures and computed property names are type members + if (token() === 21 /* OpenBracketToken */) { + return true; + } + // Try to get the first property-like token following all modifiers + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + // If we were able to get any potential identifier, check that it is + // the start of a member declaration + if (idToken) { + return token() === 19 /* OpenParenToken */ || + token() === 27 /* LessThanToken */ || + token() === 55 /* QuestionToken */ || + token() === 56 /* ColonToken */ || + token() === 26 /* CommaToken */ || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseSignatureMember(155 /* CallSignature */); + } + if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(156 /* ConstructSignature */); + } + var fullStart = getNodePos(); + var modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; + } + function parseTypeLiteral() { + var node = createNode(163 /* TypeLiteral */); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(17 /* OpenBraceToken */)) { + members = parseList(4 /* TypeMembers */, parseTypeMember); + parseExpected(18 /* CloseBraceToken */); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 131 /* ReadonlyKeyword */) { + nextToken(); + } + return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; + } + function parseMappedTypeParameter() { + var node = createNode(145 /* TypeParameter */); + node.name = parseIdentifier(); + parseExpected(92 /* InKeyword */); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(172 /* MappedType */); + parseExpected(17 /* OpenBraceToken */); + node.readonlyToken = parseOptionalToken(131 /* ReadonlyKeyword */); + parseExpected(21 /* OpenBracketToken */); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(22 /* CloseBracketToken */); + node.questionToken = parseOptionalToken(55 /* QuestionToken */); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseTupleType() { + var node = createNode(165 /* TupleType */); + node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(168 /* ParenthesizedType */); + parseExpected(19 /* OpenParenToken */); + node.type = parseType(); + parseExpected(20 /* CloseParenToken */); + return finishNode(node); + } + function parseFunctionOrConstructorType(kind) { + var node = createNode(kind); + if (kind === 161 /* ConstructorType */) { + parseExpected(94 /* NewKeyword */); + } + fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 23 /* DotToken */ ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(173 /* LiteralType */); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8 /* NumericLiteral */; + } + function parseNonArrayType() { + switch (token()) { + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 139 /* UndefinedKeyword */: + case 130 /* NeverKeyword */: + case 134 /* ObjectKeyword */: + // If these are followed by a dot, then parse these out as a dotted type reference instead. + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 39 /* AsteriskToken */: + return parseJSDocAllType(); + case 55 /* QuestionToken */: + return parseJSDocUnknownOrNullableType(); + case 89 /* FunctionKeyword */: + return parseJSDocFunctionType(); + case 24 /* DotDotDotToken */: + return parseJSDocNodeWithType(274 /* JSDocVariadicType */); + case 51 /* ExclamationToken */: + return parseJSDocNodeWithType(271 /* JSDocNonNullableType */); + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + return parseLiteralTypeNode(); + case 38 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + case 105 /* VoidKeyword */: + case 95 /* NullKeyword */: + return parseTokenNode(); + case 99 /* ThisKeyword */: { + var thisKeyword = parseThisTypeNode(); + if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 103 /* TypeOfKeyword */: + return parseTypeQuery(); + case 17 /* OpenBraceToken */: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 21 /* OpenBracketToken */: + return parseTupleType(); + case 19 /* OpenParenToken */: + return parseParenthesizedType(); + default: + return parseTypeReference(); + } + } + function isStartOfType() { + switch (token()) { + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 99 /* ThisKeyword */: + case 103 /* TypeOfKeyword */: + case 130 /* NeverKeyword */: + case 17 /* OpenBraceToken */: + case 21 /* OpenBracketToken */: + case 27 /* LessThanToken */: + case 49 /* BarToken */: + case 48 /* AmpersandToken */: + case 94 /* NewKeyword */: + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 134 /* ObjectKeyword */: + return true; + case 38 /* MinusToken */: + return lookAhead(nextTokenIsNumericLiteral); + case 19 /* OpenParenToken */: + // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, + // or something that starts a type. We don't want to consider things like '(1)' a type. + return lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); + } + function parseJSDocPostfixTypeOrHigher() { + var type = parseNonArrayType(); + var kind = getKind(token()); + if (!kind) + return type; + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + function getKind(tokenKind) { + switch (tokenKind) { + case 58 /* EqualsToken */: + // only parse postfix = inside jsdoc, because it's ambiguous elsewhere + return contextFlags & 1048576 /* JSDoc */ ? 272 /* JSDocOptionalType */ : undefined; + case 51 /* ExclamationToken */: + return 271 /* JSDocNonNullableType */; + case 55 /* QuestionToken */: + return 270 /* JSDocNullableType */; + } + } + } + function parseArrayTypeOrHigher() { + var type = parseJSDocPostfixTypeOrHigher(); + while (!scanner.hasPrecedingLineBreak() && parseOptional(21 /* OpenBracketToken */)) { + if (isStartOfType()) { + var node = createNode(171 /* IndexedAccessType */, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + else { + var node = createNode(164 /* ArrayType */, type.pos); + node.elementType = type; + parseExpected(22 /* CloseBracketToken */); + type = finishNode(node); + } + } + return type; + } + function parseTypeOperator(operator) { + var node = createNode(170 /* TypeOperator */); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 127 /* KeyOfKeyword */: + return parseTypeOperator(127 /* KeyOfKeyword */); + } + return parseArrayTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = createNodeArray([type], type.pos); + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + types.end = getNodeEnd(); + var node = createNode(kind, type.pos); + node.types = types; + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(167 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(166 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + } + function isStartOfFunctionType() { + if (token() === 27 /* LessThanToken */) { + return true; + } + return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + // Skip modifiers + parseModifiers(); + } + if (isIdentifier() || token() === 99 /* ThisKeyword */) { + nextToken(); + return true; + } + if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { + // Return true if we can parse an array or object binding pattern with no errors + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + // ( ) + // ( ... + return true; + } + if (skipParameterStart()) { + // We successfully skipped modifiers (if any) and an identifier or binding pattern, + // now see if we have something that indicates a parameter declaration + if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || + token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { + // ( xxx : + // ( xxx , + // ( xxx ? + // ( xxx = + return true; + } + if (token() === 20 /* CloseParenToken */) { + nextToken(); + if (token() === 36 /* EqualsGreaterThanToken */) { + // ( xxx ) => + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(158 /* TypePredicate */, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + // The rules about 'yield' only apply to actual code/expression contexts. They don't + // apply to 'type' contexts. So we disable these parameters here before moving on. + return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); + } + function parseTypeWorker() { + if (isStartOfFunctionType()) { + return parseFunctionOrConstructorType(160 /* FunctionType */); + } + if (token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(161 /* ConstructorType */); + } + return parseUnionTypeOrHigher(); + } + function parseTypeAnnotation() { + return parseOptional(56 /* ColonToken */) ? parseType() : undefined; + } + // EXPRESSIONS + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 19 /* OpenParenToken */: + case 21 /* OpenBracketToken */: + case 17 /* OpenBraceToken */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 94 /* NewKeyword */: + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + case 71 /* Identifier */: + return true; + case 91 /* ImportKeyword */: + return lookAhead(nextTokenIsOpenParenOrLessThan); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 80 /* DeleteKeyword */: + case 103 /* TypeOfKeyword */: + case 105 /* VoidKeyword */: + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + case 27 /* LessThanToken */: + case 121 /* AwaitKeyword */: + case 116 /* YieldKeyword */: + // Yield/await always starts an expression. Either it is an identifier (in which case + // it is definitely an expression). Or it's a keyword (either because we're in + // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. + return true; + default: + // Error tolerance. If we see the start of some binary operator, we consider + // that the start of an expression. That way we'll parse out a missing identifier, + // give a good message about an identifier being missing, and then consume the + // rest of the binary expression. + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. + return token() !== 17 /* OpenBraceToken */ && + token() !== 89 /* FunctionKeyword */ && + token() !== 75 /* ClassKeyword */ && + token() !== 57 /* AtToken */ && + isStartOfExpression(); + } + function parseExpression() { + // Expression[in]: + // AssignmentExpression[in] + // Expression[in] , AssignmentExpression[in] + // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return expr; + } + function parseInitializer(inParameter) { + if (token() !== 58 /* EqualsToken */) { + // It's not uncommon during typing for the user to miss writing the '=' token. Check if + // there is no newline after the last token and if we're on an expression. If so, parse + // this as an equals-value clause with a missing equals. + // NOTE: There are two places where we allow equals-value clauses. The first is in a + // variable declarator. The second is with a parameter. For variable declarators + // it's more likely that a { would be a allowed (as an object literal). While this + // is also allowed for parameters, the risk is that we consume the { as an object + // literal when it really will be for the block following the parameter. + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17 /* OpenBraceToken */) || !isStartOfExpression()) { + // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - + // do not try to parse initializer + return undefined; + } + } + // Initializer[In, Yield] : + // = AssignmentExpression[?In, ?Yield] + parseExpected(58 /* EqualsToken */); + return parseAssignmentExpressionOrHigher(); + } + function parseAssignmentExpressionOrHigher() { + // AssignmentExpression[in,yield]: + // 1) ConditionalExpression[?in,?yield] + // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] + // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] + // 4) ArrowFunctionExpression[?in,?yield] + // 5) AsyncArrowFunctionExpression[in,yield,await] + // 6) [+Yield] YieldExpression[?In] + // + // Note: for ease of implementation we treat productions '2' and '3' as the same thing. + // (i.e. they're both BinaryExpressions with an assignment operator in it). + // First, do the simple check if we have a YieldExpression (production '6'). + if (isYieldExpression()) { + return parseYieldExpression(); + } + // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized + // parameter list or is an async arrow function. + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". + // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". + // + // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // with AssignmentExpression if we see one. + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + // Now try to see if we're in production '1', '2' or '3'. A conditional expression can + // start with a LogicalOrExpression, while the assignment productions can only start with + // LeftHandSideExpressions. + // + // So, first, we try to just parse out a BinaryExpression. If we get something that is a + // LeftHandSide or higher, then we can try to parse out the assignment expression part. + // Otherwise, we try to parse out the conditional expression bit. We want to allow any + // binary expression here, so we pass in the 'lowest' precedence here so that it matches + // and consumes anything. + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized + // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single + // identifier and the current token is an arrow. + if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + return parseSimpleArrowFunctionExpression(expr); + } + // Now see if we might be in cases '2' or '3'. + // If the expression was a LHS expression, and we have an assignment operator, then + // we're in '2' or '3'. Consume the assignment and return. + // + // Note: we call reScanGreaterToken so that we get an appropriately merged token + // for cases like > > = becoming >>= + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + // It wasn't an assignment or a lambda. This is a conditional expression: + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 116 /* YieldKeyword */) { + // If we have a 'yield' keyword, and this is a context where yield expressions are + // allowed, then definitely parse out a yield expression. + if (inYieldContext()) { + return true; + } + // We're in a context where 'yield expr' is not allowed. However, if we can + // definitely tell that the user was trying to parse a 'yield expr' and not + // just a normal expr that start with a 'yield' identifier, then parse out + // a 'yield expr'. We can then report an error later that they are only + // allowed in generator expressions. + // + // for example, if we see 'yield(foo)', then we'll have to treat that as an + // invocation expression of something called 'yield'. However, if we have + // 'yield foo' then that is not legal as a normal expression, so we can + // definitely recognize this as a yield expression. + // + // for now we just check if the next token is an identifier. More heuristics + // can be added here later as necessary. We just need to make sure that we + // don't accidentally consume something legal. + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(197 /* YieldExpression */); + // YieldExpression[In] : + // yield + // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + // if the next token is not on the same line as yield. or we don't have an '*' or + // the start of an expression, then this is just a simple "yield" expression. + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(187 /* ArrowFunction */, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(187 /* ArrowFunction */, identifier.pos); + } + var parameter = createNode(146 /* Parameter */, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos); + node.parameters.end = parameter.end; + node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0 /* False */) { + // It's definitely not a parenthesized arrow function expression. + return undefined; + } + // If we definitely have an arrow function, then we can just parse one, not requiring a + // following => or { token. Otherwise, we *might* have an arrow function. Try to parse + // it out, but don't allow any ambiguity, and return 'undefined' if this could be an + // expression instead. + var arrowFunction = triState === 1 /* True */ + ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + // Didn't appear to actually be a parenthesized arrow function. Just bail out. + return undefined; + } + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); + // If we have an arrow, then try to parse the body. Even if not, try to parse if we + // have an opening brace, just in case we're in an error state. + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return addJSDocComment(finishNode(arrowFunction)); + } + // True -> We definitely expect a parenthesized arrow function here. + // False -> There *cannot* be a parenthesized arrow function here. + // Unknown -> There *might* be a parenthesized arrow function here. + // Speculatively look ahead to be sure, and rollback if not. + function isParenthesizedArrowFunctionExpression() { + if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 36 /* EqualsGreaterThanToken */) { + // ERROR RECOVERY TWEAK: + // If we see a standalone => try to parse it as an arrow function expression as that's + // likely what the user intended to write. + return 1 /* True */; + } + // Definitely not a parenthesized arrow function. + return 0 /* False */; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 120 /* AsyncKeyword */) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0 /* False */; + } + if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { + return 0 /* False */; + } + } + var first = token(); + var second = nextToken(); + if (first === 19 /* OpenParenToken */) { + if (second === 20 /* CloseParenToken */) { + // Simple cases: "() =>", "(): ", and "() {". + // This is an arrow function with no parameters. + // The last one is not actually an arrow function, + // but this is probably what the user intended. + var third = nextToken(); + switch (third) { + case 36 /* EqualsGreaterThanToken */: + case 56 /* ColonToken */: + case 17 /* OpenBraceToken */: + return 1 /* True */; + default: + return 0 /* False */; + } + } + // If encounter "([" or "({", this could be the start of a binding pattern. + // Examples: + // ([ x ]) => { } + // ({ x }) => { } + // ([ x ]) + // ({ x }) + if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { + return 2 /* Unknown */; + } + // Simple case: "(..." + // This is an arrow function with a rest parameter. + if (second === 24 /* DotDotDotToken */) { + return 1 /* True */; + } + // If we had "(" followed by something that's not an identifier, + // then this definitely doesn't look like a lambda. + // Note: we could be a little more lenient and allow + // "(public" or "(private". These would not ever actually be allowed, + // but we could provide a good error message instead of bailing out. + if (!isIdentifier()) { + return 0 /* False */; + } + // If we have something like "(a:", then we must have a + // type-annotated parameter in an arrow function expression. + if (nextToken() === 56 /* ColonToken */) { + return 1 /* True */; + } + // This *could* be a parenthesized arrow function. + // Return Unknown to let the caller know. + return 2 /* Unknown */; + } + else { + ts.Debug.assert(first === 27 /* LessThanToken */); + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if (!isIdentifier()) { + return 0 /* False */; + } + // JSX overrides + if (sourceFile.languageVariant === 1 /* JSX */) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 85 /* ExtendsKeyword */) { + var fourth = nextToken(); + switch (fourth) { + case 58 /* EqualsToken */: + case 29 /* GreaterThanToken */: + return false; + default: + return true; + } + } + else if (third === 26 /* CommaToken */) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1 /* True */; + } + return 0 /* False */; + } + // This *could* be a parenthesized arrow function. + return 2 /* Unknown */; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + // We do a check here so that we won't be doing unnecessarily call to "lookAhead" + if (token() === 120 /* AsyncKeyword */) { + var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); + if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + // AsyncArrowFunctionExpression: + // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] + // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] + if (token() === 120 /* AsyncKeyword */) { + nextToken(); + // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" + if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { + return 0 /* False */; + } + // Check for un-parenthesized AsyncArrowFunction + var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { + return 1 /* True */; + } + } + return 0 /* False */; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNode(187 /* ArrowFunction */); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + // Arrow functions are never generators. + // + // If we're speculatively parsing a signature for a parenthesized arrow function, then + // we have to have a complete parameter list. Otherwise we might see something like + // a => (b => c) + // And think that "(b =>" was actually a parenthesized arrow function with a missing + // close paren. + fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); + // If we couldn't get parameters, we definitely could not parse out an arrow function. + if (!node.parameters) { + return undefined; + } + // Parsing a signature isn't enough. + // Parenthesized arrow signatures often look like other valid expressions. + // For instance: + // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. + // - "(x,y)" is a comma expression parsed as a signature with two parameters. + // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. + // + // So we need just a bit of lookahead to ensure that it can only be a signature. + if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { + // Returning undefined here will cause our caller to rewind to where we started from. + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 17 /* OpenBraceToken */) { + return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */); + } + if (token() !== 25 /* SemicolonToken */ && + token() !== 89 /* FunctionKeyword */ && + token() !== 75 /* ClassKeyword */ && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) + // + // Here we try to recover from a potential error situation in the case where the + // user meant to supply a block. For example, if the user wrote: + // + // a => + // let v = 0; + // } + // + // they may be missing an open brace. Check to see if that's the case so we can + // try to recover better. If we don't do this, then the next close curly we see may end + // up preemptively closing the containing construct. + // + // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. + return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (!questionToken) { + return leftOperand; + } + // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and + // we do not that for the 'whenFalse' part. + var node = createNode(195 /* ConditionalExpression */, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); + node.whenFalse = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 92 /* InKeyword */ || t === 142 /* OfKeyword */; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + // We either have a binary operator here, or we're finished. We call + // reScanGreaterToken so that we merge token sequences like > and = into >= + reScanGreaterToken(); + var newPrecedence = getBinaryOperatorPrecedence(); + // Check the precedence to see if we should "take" this operator + // - For left associative operator (all operator but **), consume the operator, + // recursively call the function below, and parse binaryExpression as a rightOperand + // of the caller if the new precedence of the operator is greater then or equal to the current precedence. + // For example: + // a - b - c; + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a * b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + // a - b * c; + // ^token; leftOperand = b. Return b * c to the caller as a rightOperand + // - For right associative operator (**), consume the operator, recursively call the function + // and parse binaryExpression as a rightOperand of the caller if the new precedence of + // the operator is strictly grater than the current precedence + // For example: + // a ** b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a - b ** c; + // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand + // a ** b - c + // ^token; leftOperand = b. Return b to the caller as a rightOperand + var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 92 /* InKeyword */ && inDisallowInContext()) { + break; + } + if (token() === 118 /* AsKeyword */) { + // Make sure we *do* perform ASI for constructs like this: + // var x = foo + // as (Bar) + // This should be parsed as an initialized variable, followed + // by a function call to 'as' with the argument 'Bar' + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 92 /* InKeyword */) { + return false; + } + return getBinaryOperatorPrecedence() > 0; + } + function getBinaryOperatorPrecedence() { + switch (token()) { + case 54 /* BarBarToken */: + return 1; + case 53 /* AmpersandAmpersandToken */: + return 2; + case 49 /* BarToken */: + return 3; + case 50 /* CaretToken */: + return 4; + case 48 /* AmpersandToken */: + return 5; + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return 6; + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: + return 7; + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + return 8; + case 37 /* PlusToken */: + case 38 /* MinusToken */: + return 9; + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + return 10; + case 40 /* AsteriskAsteriskToken */: + return 11; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(194 /* BinaryExpression */, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(202 /* AsExpression */, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(192 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(188 /* DeleteExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(189 /* TypeOfExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(190 /* VoidExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 121 /* AwaitKeyword */) { + if (inAwaitContext()) { + return true; + } + // here we are using similar heuristics as 'isYieldExpression' + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(191 /* AwaitExpression */); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + /** + * Parse ES7 exponential expression and await expression + * + * ES7 ExponentiationExpression: + * 1) UnaryExpression[?Yield] + * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] + * + */ + function parseUnaryExpressionOrHigher() { + /** + * ES7 UpdateExpression: + * 1) LeftHandSideExpression[?Yield] + * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ + * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- + * 4) ++UnaryExpression[?Yield] + * 5) --UnaryExpression[?Yield] + */ + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 40 /* AsteriskAsteriskToken */ ? + parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + updateExpression; + } + /** + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UpdateExpression[?yield] + * 3) void UpdateExpression[?yield] + * 4) typeof UpdateExpression[?yield] + * 5) + UpdateExpression[?yield] + * 6) - UpdateExpression[?yield] + * 7) ~ UpdateExpression[?yield] + * 8) ! UpdateExpression[?yield] + */ + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 40 /* AsteriskAsteriskToken */) { + var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + if (simpleUnaryExpression.kind === 184 /* TypeAssertionExpression */) { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + /** + * Parse ES7 simple-unary expression or higher: + * + * ES7 UnaryExpression: + * 1) UpdateExpression[?yield] + * 2) delete UnaryExpression[?yield] + * 3) void UnaryExpression[?yield] + * 4) typeof UnaryExpression[?yield] + * 5) + UnaryExpression[?yield] + * 6) - UnaryExpression[?yield] + * 7) ~ UnaryExpression[?yield] + * 8) ! UnaryExpression[?yield] + * 9) [+Await] await UnaryExpression[?yield] + */ + function parseSimpleUnaryExpression() { + switch (token()) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + return parsePrefixUnaryExpression(); + case 80 /* DeleteKeyword */: + return parseDeleteExpression(); + case 103 /* TypeOfKeyword */: + return parseTypeOfExpression(); + case 105 /* VoidKeyword */: + return parseVoidExpression(); + case 27 /* LessThanToken */: + // This is modified UnaryExpression grammar in TypeScript + // UnaryExpression (modified): + // < type > UnaryExpression + return parseTypeAssertion(); + case 121 /* AwaitKeyword */: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + // falls through + default: + return parseUpdateExpression(); + } + } + /** + * Check if the current token can possibly be an ES7 increment expression. + * + * ES7 UpdateExpression: + * LeftHandSideExpression[?Yield] + * LeftHandSideExpression[?Yield][no LineTerminator here]++ + * LeftHandSideExpression[?Yield][no LineTerminator here]-- + * ++LeftHandSideExpression[?Yield] + * --LeftHandSideExpression[?Yield] + */ + function isUpdateExpression() { + // This function is called inside parseUnaryExpression to decide + // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly + switch (token()) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + case 51 /* ExclamationToken */: + case 80 /* DeleteKeyword */: + case 103 /* TypeOfKeyword */: + case 105 /* VoidKeyword */: + case 121 /* AwaitKeyword */: + return false; + case 27 /* LessThanToken */: + // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression + if (sourceFile.languageVariant !== 1 /* JSX */) { + return false; + } + // We are in JSX context and the token is part of JSXElement. + // falls through + default: + return true; + } + } + /** + * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression. + * + * ES7 UpdateExpression[yield]: + * 1) LeftHandSideExpression[?yield] + * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ + * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- + * 4) ++LeftHandSideExpression[?yield] + * 5) --LeftHandSideExpression[?yield] + * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression + */ + function parseUpdateExpression() { + if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { + var node = createNode(192 /* PrefixUnaryExpression */); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { + // JSXElement is part of primaryExpression + return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(193 /* PostfixUnaryExpression */, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + // Original Ecma: + // LeftHandSideExpression: See 11.2 + // NewExpression + // CallExpression + // + // Our simplification: + // + // LeftHandSideExpression: See 11.2 + // MemberExpression + // CallExpression + // + // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with + // MemberExpression to make our lives easier. + // + // to best understand the below code, it's important to see how CallExpression expands + // out into its own productions: + // + // CallExpression: + // MemberExpression Arguments + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // import (AssignmentExpression) + // super Arguments + // super.IdentifierName + // + // Because of the recursion in these calls, we need to bottom out first. There are three + // bottom out states we can run into: 1) We see 'super' which must start either of + // the last two CallExpression productions. 2) We see 'import' which must start import call. + // 3)we have a MemberExpression which either completes the LeftHandSideExpression, + // or starts the beginning of the first four CallExpression productions. + var expression; + if (token() === 91 /* ImportKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else { + expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + // Now, we *may* be complete. However, we might have consumed the start of a + // CallExpression. As such, we need to consume the rest of it here to be complete. + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + // Note: to make our lives simpler, we decompose the NewExpression productions and + // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. + // like so: + // + // PrimaryExpression : See 11.1 + // this + // Identifier + // Literal + // ArrayLiteral + // ObjectLiteral + // (Expression) + // FunctionExpression + // new MemberExpression Arguments? + // + // MemberExpression : See 11.2 + // PrimaryExpression + // MemberExpression[Expression] + // MemberExpression.IdentifierName + // + // CallExpression : See 11.2 + // MemberExpression + // CallExpression Arguments + // CallExpression[Expression] + // CallExpression.IdentifierName + // + // Technically this is ambiguous. i.e. CallExpression defines: + // + // CallExpression: + // CallExpression Arguments + // + // If you see: "new Foo()" + // + // Then that could be treated as a single ObjectCreationExpression, or it could be + // treated as the invocation of "new Foo". We disambiguate that in code (to match + // the original grammar) by making sure that if we see an ObjectCreationExpression + // we always consume arguments if they are there. So we treat "new Foo()" as an + // object creation only, and not at all as an invocation) Another way to think + // about this is that for every "new" that we see, we will consume an argument list if + // it is there as part of the *associated* object creation node. Any additional + // argument lists we see, will become invocation expressions. + // + // Because there are no other places in the grammar now that refer to FunctionExpression + // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression + // production. + // + // Because CallExpression and MemberExpression are left recursive, we need to bottom out + // of the recursion immediately. So we parse out a primary expression to start with. + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { + return expression; + } + // If we have seen "super" it must be followed by '(' or '.'. + // If it wasn't then just try to parse out a '.' and report an error. + var node = createNode(179 /* PropertyAccessExpression */, expression.pos); + node.expression = expression; + parseExpectedToken(23 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + return finishNode(node); + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 71 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 99 /* ThisKeyword */) { + return true; + } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + function parseJsxElementOrSelfClosingElement(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + var result; + if (opening.kind === 251 /* JsxOpeningElement */) { + var node = createNode(249 /* JsxElement */, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement.tagName); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 250 /* JsxSelfClosingElement */); + // Nothing else to do for self-closing elements + result = opening; + } + // If the user writes the invalid code '
' in an expression context (i.e. not wrapped in + // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag + // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX + // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter + // does less damage and we can report a better error. + // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios + // of one sort or another. + if (inExpressionContext && token() === 27 /* LessThanToken */) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(194 /* BinaryExpression */, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(10 /* JsxText */, scanner.getStartPos()); + node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild() { + switch (token()) { + case 10 /* JsxText */: + case 11 /* JsxTextAllWhiteSpaces */: + return parseJsxText(); + case 17 /* OpenBraceToken */: + return parseJsxExpression(/*inExpressionContext*/ false); + case 27 /* LessThanToken */: + return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); + } + ts.Debug.fail("Unknown JSX child kind " + token()); + } + function parseJsxChildren(openingTagName) { + var result = createNodeArray(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14 /* JsxChildren */; + while (true) { + currentToken = scanner.reScanJsxToken(); + if (token() === 28 /* LessThanSlashToken */) { + // Closing tag + break; + } + else if (token() === 1 /* EndOfFileToken */) { + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + break; + } + else if (token() === 7 /* ConflictMarkerTrivia */) { + break; + } + var child = parseJsxChild(); + if (child) { + result.push(child); + } + } + result.end = scanner.getTokenPos(); + parsingContext = saveParsingContext; + return result; + } + function parseJsxAttributes() { + var jsxAttributes = createNode(254 /* JsxAttributes */); + jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(27 /* LessThanToken */); + var tagName = parseJsxElementName(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 29 /* GreaterThanToken */) { + // Closing tag, so scan the immediately-following text with the JSX scanning instead + // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate + // scanning errors + node = createNode(251 /* JsxOpeningElement */, fullStart); + scanJsxText(); + } + else { + parseExpected(41 /* SlashToken */); + if (inExpressionContext) { + parseExpected(29 /* GreaterThanToken */); + } + else { + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + node = createNode(250 /* JsxSelfClosingElement */, fullStart); + } + node.tagName = tagName; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + // JsxElement can have name in the form of + // propertyAccessExpression + // primaryExpression in the form of an identifier and "this" keyword + // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword + // We only want to consider "this" as a primaryExpression + var expression = token() === 99 /* ThisKeyword */ ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(23 /* DotToken */)) { + var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(256 /* JsxExpression */); + parseExpected(17 /* OpenBraceToken */); + if (token() !== 18 /* CloseBraceToken */) { + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(18 /* CloseBraceToken */); + } + else { + parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 17 /* OpenBraceToken */) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(253 /* JsxAttribute */); + node.name = parseIdentifierName(); + if (token() === 58 /* EqualsToken */) { + switch (scanJsxAttributeValue()) { + case 9 /* StringLiteral */: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(/*inExpressionContext*/ true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(255 /* JsxSpreadAttribute */); + parseExpected(17 /* OpenBraceToken */); + parseExpected(24 /* DotDotDotToken */); + node.expression = parseExpression(); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(252 /* JsxClosingElement */); + parseExpected(28 /* LessThanSlashToken */); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(29 /* GreaterThanToken */); + } + else { + parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(184 /* TypeAssertionExpression */); + parseExpected(27 /* LessThanToken */); + node.type = parseType(); + parseExpected(29 /* GreaterThanToken */); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(23 /* DotToken */); + if (dotToken) { + var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(203 /* NonNullExpression */, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName + if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { + var indexedAccess = createNode(180 /* ElementAccessExpression */, expression.pos); + indexedAccess.expression = expression; + // It's not uncommon for a user to write: "new Type[]". + // Check for that common pattern and report a better error message. + if (token() !== 22 /* CloseBracketToken */) { + indexedAccess.argumentExpression = allowInAnd(parseExpression); + if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { + var literal = indexedAccess.argumentExpression; + literal.text = internIdentifier(literal.text); + } + } + parseExpected(22 /* CloseBracketToken */); + expression = finishNode(indexedAccess); + continue; + } + if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { + var tagExpression = createNode(183 /* TaggedTemplateExpression */, expression.pos); + tagExpression.tag = expression; + tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + expression = finishNode(tagExpression); + continue; + } + return expression; + } + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 27 /* LessThanToken */) { + // See if this is the start of a generic invocation. If so, consume it and + // keep checking for postfix expressions. Otherwise, it's just a '<' that's + // part of an arithmetic expression. Break out so we consume it higher in the + // stack. + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + var callExpr = createNode(181 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 19 /* OpenParenToken */) { + var callExpr = createNode(181 /* CallExpression */, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(19 /* OpenParenToken */); + var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); + parseExpected(20 /* CloseParenToken */); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(27 /* LessThanToken */)) { + return undefined; + } + var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); + if (!parseExpected(29 /* GreaterThanToken */)) { + // If it doesn't have the closing > then it's definitely not an type argument list. + return undefined; + } + // If we have a '<', then only parse this as a argument list if the type arguments + // are complete and we have an open paren. if we don't, rewind and return nothing. + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 19 /* OpenParenToken */: // foo( + // this case are the only case where this token can legally follow a type argument + // list. So we definitely want to treat this as a type arg list. + case 23 /* DotToken */: // foo. + case 20 /* CloseParenToken */: // foo) + case 22 /* CloseBracketToken */: // foo] + case 56 /* ColonToken */: // foo: + case 25 /* SemicolonToken */: // foo; + case 55 /* QuestionToken */: // foo? + case 32 /* EqualsEqualsToken */: // foo == + case 34 /* EqualsEqualsEqualsToken */: // foo === + case 33 /* ExclamationEqualsToken */: // foo != + case 35 /* ExclamationEqualsEqualsToken */: // foo !== + case 53 /* AmpersandAmpersandToken */: // foo && + case 54 /* BarBarToken */: // foo || + case 50 /* CaretToken */: // foo ^ + case 48 /* AmpersandToken */: // foo & + case 49 /* BarToken */: // foo | + case 18 /* CloseBraceToken */: // foo } + case 1 /* EndOfFileToken */:// foo + // these cases can't legally follow a type arg list. However, they're not legal + // expressions either. The user is probably in the middle of a generic type. So + // treat it as such. + return true; + case 26 /* CommaToken */: // foo, + case 17 /* OpenBraceToken */: // foo { + // We don't want to treat these as type arguments. Otherwise we'll parse this + // as an invocation expression. Instead, we want to parse out the expression + // in isolation from the type arguments. + default: + // Anything else treat as an expression. + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + return parseTokenNode(); + case 19 /* OpenParenToken */: + return parseParenthesizedExpression(); + case 21 /* OpenBracketToken */: + return parseArrayLiteralExpression(); + case 17 /* OpenBraceToken */: + return parseObjectLiteralExpression(); + case 120 /* AsyncKeyword */: + // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. + // If we encounter `async [no LineTerminator here] function` then this is an async + // function; otherwise, its an identifier. + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 75 /* ClassKeyword */: + return parseClassExpression(); + case 89 /* FunctionKeyword */: + return parseFunctionExpression(); + case 94 /* NewKeyword */: + return parseNewExpression(); + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { + return parseLiteralNode(); + } + break; + case 14 /* TemplateHead */: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNode(185 /* ParenthesizedExpression */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + return addJSDocComment(finishNode(node)); + } + function parseSpreadElement() { + var node = createNode(198 /* SpreadElement */); + parseExpected(24 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : + token() === 26 /* CommaToken */ ? createNode(200 /* OmittedExpression */) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(177 /* ArrayLiteralExpression */); + parseExpected(21 /* OpenBracketToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); + parseExpected(22 /* CloseBracketToken */); + return finishNode(node); + } + function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { + if (parseContextualModifier(125 /* GetKeyword */)) { + return parseAccessorDeclaration(153 /* GetAccessor */, fullStart, decorators, modifiers); + } + else if (parseContextualModifier(135 /* SetKeyword */)) { + return parseAccessorDeclaration(154 /* SetAccessor */, fullStart, decorators, modifiers); + } + return undefined; + } + function parseObjectLiteralElement() { + var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + if (dotDotDotToken) { + var spreadElement = createNode(263 /* SpreadAssignment */, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + // Disallowing of optional property assignments happens in the grammar checker. + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + } + // check if it is short-hand property assignment or normal property assignment + // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production + // CoverInitializedName[Yield] : + // IdentifierReference[?Yield] Initializer[In, ?Yield] + // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); + if (isShorthandPropertyAssignment) { + var shorthandDeclaration = createNode(262 /* ShorthandPropertyAssignment */, fullStart); + shorthandDeclaration.name = propertyName; + shorthandDeclaration.questionToken = questionToken; + var equalsToken = parseOptionalToken(58 /* EqualsToken */); + if (equalsToken) { + shorthandDeclaration.equalsToken = equalsToken; + shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return addJSDocComment(finishNode(shorthandDeclaration)); + } + else { + var propertyAssignment = createNode(261 /* PropertyAssignment */, fullStart); + propertyAssignment.modifiers = modifiers; + propertyAssignment.name = propertyName; + propertyAssignment.questionToken = questionToken; + parseExpected(56 /* ColonToken */); + propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + return addJSDocComment(finishNode(propertyAssignment)); + } + } + function parseObjectLiteralExpression() { + var node = createNode(178 /* ObjectLiteralExpression */); + parseExpected(17 /* OpenBraceToken */); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseFunctionExpression() { + // GeneratorExpression: + // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } + // + // FunctionExpression: + // function BindingIdentifier[opt](FormalParameters){ FunctionBody } + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var node = createNode(186 /* FunctionExpression */); + node.modifiers = parseModifiers(); + parseExpected(89 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = (ts.getModifierFlags(node) & 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + return addJSDocComment(finishNode(node)); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpression() { + var fullStart = scanner.getStartPos(); + parseExpected(94 /* NewKeyword */); + if (parseOptional(23 /* DotToken */)) { + var node_1 = createNode(204 /* MetaProperty */, fullStart); + node_1.keywordToken = 94 /* NewKeyword */; + node_1.name = parseIdentifierName(); + return finishNode(node_1); + } + var node = createNode(182 /* NewExpression */, fullStart); + node.expression = parseMemberExpressionOrHigher(); + node.typeArguments = tryParse(parseTypeArgumentsInExpression); + if (node.typeArguments || token() === 19 /* OpenParenToken */) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + // STATEMENTS + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(207 /* Block */); + if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2 /* Await */)); + // We may be in a [Decorator] context when parsing a function expression or + // arrow function. The body of the function is not in [Decorator] context. + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ false); + } + var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(/*val*/ true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(209 /* EmptyStatement */); + parseExpected(25 /* SemicolonToken */); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(211 /* IfStatement */); + parseExpected(90 /* IfKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(212 /* DoStatement */); + parseExpected(81 /* DoKeyword */); + node.statement = parseStatement(); + parseExpected(106 /* WhileKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html + // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in + // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby + // do;while(0)x will have a semicolon inserted before x. + parseOptional(25 /* SemicolonToken */); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(213 /* WhileStatement */); + parseExpected(106 /* WhileKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(88 /* ForKeyword */); + var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); + parseExpected(19 /* OpenParenToken */); + var initializer = undefined; + if (token() !== 25 /* SemicolonToken */) { + if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(142 /* OfKeyword */) : parseOptional(142 /* OfKeyword */)) { + var forOfStatement = createNode(216 /* ForOfStatement */, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(20 /* CloseParenToken */); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(92 /* InKeyword */)) { + var forInStatement = createNode(215 /* ForInStatement */, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(214 /* ForStatement */, pos); + forStatement.initializer = initializer; + parseExpected(25 /* SemicolonToken */); + if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(25 /* SemicolonToken */); + if (token() !== 20 /* CloseParenToken */) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(20 /* CloseParenToken */); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 218 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(219 /* ReturnStatement */); + parseExpected(96 /* ReturnKeyword */); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(220 /* WithStatement */); + parseExpected(107 /* WithKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + node.statement = parseStatement(); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(257 /* CaseClause */); + parseExpected(73 /* CaseKeyword */); + node.expression = allowInAnd(parseExpression); + parseExpected(56 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(258 /* DefaultClause */); + parseExpected(79 /* DefaultKeyword */); + parseExpected(56 /* ColonToken */); + node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(221 /* SwitchStatement */); + parseExpected(98 /* SwitchKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = allowInAnd(parseExpression); + parseExpected(20 /* CloseParenToken */); + var caseBlock = createNode(235 /* CaseBlock */, scanner.getStartPos()); + parseExpected(17 /* OpenBraceToken */); + caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); + parseExpected(18 /* CloseBraceToken */); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + // ThrowStatement[Yield] : + // throw [no LineTerminator here]Expression[In, ?Yield]; + // Because of automatic semicolon insertion, we need to report error if this + // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' + // directly as that might consume an expression on the following line. + // We just return 'undefined' in that case. The actual error will be reported in the + // grammar walker. + var node = createNode(223 /* ThrowStatement */); + parseExpected(100 /* ThrowKeyword */); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + // TODO: Review for error recovery + function parseTryStatement() { + var node = createNode(224 /* TryStatement */); + parseExpected(102 /* TryKeyword */); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; + // If we don't have a catch clause, then we must have a finally clause. Try to parse + // one out no matter what. + if (!node.catchClause || token() === 87 /* FinallyKeyword */) { + parseExpected(87 /* FinallyKeyword */); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(260 /* CatchClause */); + parseExpected(74 /* CatchKeyword */); + if (parseExpected(19 /* OpenParenToken */)) { + result.variableDeclaration = parseVariableDeclaration(); + } + parseExpected(20 /* CloseParenToken */); + result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(225 /* DebuggerStatement */); + parseExpected(78 /* DebuggerKeyword */); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + // Avoiding having to do the lookahead for a labeled statement by just trying to parse + // out an expression, seeing if it is identifier and then seeing if it is followed by + // a colon. + var fullStart = scanner.getStartPos(); + var expression = allowInAnd(parseExpression); + if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { + var labeledStatement = createNode(222 /* LabeledStatement */, fullStart); + labeledStatement.label = expression; + labeledStatement.statement = parseStatement(); + return addJSDocComment(finishNode(labeledStatement)); + } + else { + var expressionStatement = createNode(210 /* ExpressionStatement */, fullStart); + expressionStatement.expression = expression; + parseSemicolon(); + return addJSDocComment(finishNode(expressionStatement)); + } + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* StringLiteral */) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 83 /* EnumKeyword */: + return true; + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. + case 109 /* InterfaceKeyword */: + case 138 /* TypeKeyword */: + return nextTokenIsIdentifierOnSameLine(); + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 124 /* DeclareKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 131 /* ReadonlyKeyword */: + nextToken(); + // ASI takes effect for this modifier. + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 141 /* GlobalKeyword */: + nextToken(); + return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; + case 91 /* ImportKeyword */: + nextToken(); + return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); + case 84 /* ExportKeyword */: + nextToken(); + if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || + token() === 118 /* AsKeyword */) { + return true; + } + continue; + case 115 /* StaticKeyword */: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 57 /* AtToken */: + case 25 /* SemicolonToken */: + case 17 /* OpenBraceToken */: + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 89 /* FunctionKeyword */: + case 75 /* ClassKeyword */: + case 83 /* EnumKeyword */: + case 90 /* IfKeyword */: + case 81 /* DoKeyword */: + case 106 /* WhileKeyword */: + case 88 /* ForKeyword */: + case 77 /* ContinueKeyword */: + case 72 /* BreakKeyword */: + case 96 /* ReturnKeyword */: + case 107 /* WithKeyword */: + case 98 /* SwitchKeyword */: + case 100 /* ThrowKeyword */: + case 102 /* TryKeyword */: + case 78 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: + return true; + case 91 /* ImportKeyword */: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + case 76 /* ConstKeyword */: + case 84 /* ExportKeyword */: + return isStartOfDeclaration(); + case 120 /* AsyncKeyword */: + case 124 /* DeclareKeyword */: + case 109 /* InterfaceKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + case 138 /* TypeKeyword */: + case 141 /* GlobalKeyword */: + // When these don't start a declaration, they're an identifier in an expression statement + return true; + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + // When these don't start a declaration, they may be the start of a class member if an identifier + // immediately follows. Otherwise they're an identifier in an expression statement. + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; + } + function isLetDeclaration() { + // In ES6 'let' always starts a lexical declaration if followed by an identifier or { + // or [. + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 25 /* SemicolonToken */: + return parseEmptyStatement(); + case 17 /* OpenBraceToken */: + return parseBlock(/*ignoreMissingOpenBrace*/ false); + case 104 /* VarKeyword */: + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 110 /* LetKeyword */: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + } + break; + case 89 /* FunctionKeyword */: + return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 75 /* ClassKeyword */: + return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); + case 90 /* IfKeyword */: + return parseIfStatement(); + case 81 /* DoKeyword */: + return parseDoStatement(); + case 106 /* WhileKeyword */: + return parseWhileStatement(); + case 88 /* ForKeyword */: + return parseForOrForInOrForOfStatement(); + case 77 /* ContinueKeyword */: + return parseBreakOrContinueStatement(217 /* ContinueStatement */); + case 72 /* BreakKeyword */: + return parseBreakOrContinueStatement(218 /* BreakStatement */); + case 96 /* ReturnKeyword */: + return parseReturnStatement(); + case 107 /* WithKeyword */: + return parseWithStatement(); + case 98 /* SwitchKeyword */: + return parseSwitchStatement(); + case 100 /* ThrowKeyword */: + return parseThrowStatement(); + case 102 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + case 74 /* CatchKeyword */: + case 87 /* FinallyKeyword */: + return parseTryStatement(); + case 78 /* DebuggerKeyword */: + return parseDebuggerStatement(); + case 57 /* AtToken */: + return parseDeclaration(); + case 120 /* AsyncKeyword */: + case 109 /* InterfaceKeyword */: + case 138 /* TypeKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 83 /* EnumKeyword */: + case 84 /* ExportKeyword */: + case 91 /* ImportKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 117 /* AbstractKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + case 141 /* GlobalKeyword */: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function parseDeclaration() { + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + switch (token()) { + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + return parseVariableStatement(fullStart, decorators, modifiers); + case 89 /* FunctionKeyword */: + return parseFunctionDeclaration(fullStart, decorators, modifiers); + case 75 /* ClassKeyword */: + return parseClassDeclaration(fullStart, decorators, modifiers); + case 109 /* InterfaceKeyword */: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 138 /* TypeKeyword */: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 83 /* EnumKeyword */: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 141 /* GlobalKeyword */: + case 128 /* ModuleKeyword */: + case 129 /* NamespaceKeyword */: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 91 /* ImportKeyword */: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 84 /* ExportKeyword */: + nextToken(); + switch (token()) { + case 79 /* DefaultKeyword */: + case 58 /* EqualsToken */: + return parseExportAssignment(fullStart, decorators, modifiers); + case 118 /* AsKeyword */: + return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + default: + return parseExportDeclaration(fullStart, decorators, modifiers); + } + default: + if (decorators || modifiers) { + // We reached this point because we encountered decorators and/or modifiers and assumed a declaration + // would follow. For recovery and error reporting purposes, return an incomplete declaration. + var node = createMissingNode(247 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + node.modifiers = modifiers; + return finishNode(node); + } + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + // DECLARATIONS + function parseArrayBindingElement() { + if (token() === 26 /* CommaToken */) { + return createNode(200 /* OmittedExpression */); + } + var node = createNode(176 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + node.name = parseIdentifierOrPattern(); + node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(176 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { + node.name = propertyName; + } + else { + parseExpected(56 /* ColonToken */); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseBindingElementInitializer(/*inParameter*/ false); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(174 /* ObjectBindingPattern */); + parseExpected(17 /* OpenBraceToken */); + node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); + parseExpected(18 /* CloseBraceToken */); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(175 /* ArrayBindingPattern */); + parseExpected(21 /* OpenBracketToken */); + node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); + parseExpected(22 /* CloseBracketToken */); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 21 /* OpenBracketToken */) { + return parseArrayBindingPattern(); + } + if (token() === 17 /* OpenBraceToken */) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclaration() { + var node = createNode(226 /* VariableDeclaration */); + node.name = parseIdentifierOrPattern(); + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(/*inParameter*/ false); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(227 /* VariableDeclarationList */); + switch (token()) { + case 104 /* VarKeyword */: + break; + case 110 /* LetKeyword */: + node.flags |= 1 /* Let */; + break; + case 76 /* ConstKeyword */: + node.flags |= 2 /* Const */; + break; + default: + ts.Debug.fail(); + } + nextToken(); + // The user may have written the following: + // + // for (let of X) { } + // + // In this case, we want to parse an empty declaration list, and then parse 'of' + // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. + // So we need to look ahead to determine if 'of' should be treated as a keyword in + // this context. + // The checker will then give an error that there is an empty declaration list. + if (token() === 142 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; + } + function parseVariableStatement(fullStart, decorators, modifiers) { + var node = createNode(208 /* VariableStatement */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseFunctionDeclaration(fullStart, decorators, modifiers) { + var node = createNode(228 /* FunctionDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(89 /* FunctionKeyword */); + node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseConstructorDeclaration(pos, decorators, modifiers) { + var node = createNode(152 /* Constructor */, pos); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(123 /* ConstructorKeyword */); + fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { + var method = createNode(151 /* MethodDeclaration */, fullStart); + method.decorators = decorators; + method.modifiers = modifiers; + method.asteriskToken = asteriskToken; + method.name = name; + method.questionToken = questionToken; + var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; + var isAsync = ts.hasModifier(method, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; + fillSignature(56 /* ColonToken */, isGenerator | isAsync, method); + method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return addJSDocComment(finishNode(method)); + } + function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { + var property = createNode(149 /* PropertyDeclaration */, fullStart); + property.decorators = decorators; + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + // For instance properties specifically, since they are evaluated inside the constructor, + // we do *not * want to parse yield expressions, so we specifically turn the yield context + // off. The grammar would look something like this: + // + // MemberVariableDeclaration[Yield]: + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // + // The checker may still error in the static case to explicitly disallow the yield expression. + property.initializer = ts.hasModifier(property, 32 /* Static */) + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); + parseSemicolon(); + return addJSDocComment(finishNode(property)); + } + function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); + var name = parsePropertyName(); + // Note: this is not legal as per the grammar. But we allow it in the parser and + // report an error in the grammar checker. + var questionToken = parseOptionalToken(55 /* QuestionToken */); + if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + } + else { + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + } + } + function parseNonParameterInitializer() { + return parseInitializer(/*inParameter*/ false); + } + function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.name = parsePropertyName(); + fillSignature(56 /* ColonToken */, 0 /* None */, node); + node.body = parseFunctionBlockOrSemicolon(0 /* None */); + return addJSDocComment(finishNode(node)); + } + function isClassMemberModifier(idToken) { + switch (idToken) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 115 /* StaticKeyword */: + case 131 /* ReadonlyKeyword */: + return true; + default: + return false; + } + } + function isClassMemberStart() { + var idToken; + if (token() === 57 /* AtToken */) { + return true; + } + // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. + while (ts.isModifierKind(token())) { + idToken = token(); + // If the idToken is a class modifier (protected, private, public, and static), it is + // certain that we are starting to parse class member. This allows better error recovery + // Example: + // public foo() ... // true + // public @dec blah ... // true; we will then report an error later + // export public ... // true; we will then report an error later + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 39 /* AsteriskToken */) { + return true; + } + // Try to get the first property-like token following all modifiers. + // This can either be an identifier or the 'get' or 'set' keywords. + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + // Index signatures and computed properties are class members; we can parse. + if (token() === 21 /* OpenBracketToken */) { + return true; + } + // If we were able to get any potential identifier... + if (idToken !== undefined) { + // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. + if (!ts.isKeyword(idToken) || idToken === 135 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { + return true; + } + // If it *is* a keyword, but not an accessor, check a little farther along + // to see if it should actually be parsed as a class member. + switch (token()) { + case 19 /* OpenParenToken */: // Method declaration + case 27 /* LessThanToken */: // Generic Method declaration + case 56 /* ColonToken */: // Type Annotation for declaration + case 58 /* EqualsToken */: // Initializer for declaration + case 55 /* QuestionToken */:// Not valid, but permitted so that it gets caught later on. + return true; + default: + // Covers + // - Semicolons (declaration termination) + // - Closing braces (end-of-class, must be declaration) + // - End-of-files (not valid, but permitted so that it gets caught later on) + // - Line-breaks (enabling *automatic semicolon insertion*) + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var decorators; + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(57 /* AtToken */)) { + break; + } + var decorator = createNode(147 /* Decorator */, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } + } + if (decorators) { + decorators.end = getNodeEnd(); + } + return decorators; + } + /* + * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. + * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect + * and turns it into a standalone declaration), then it is better to parse it and report an error later. + * + * In such situations, 'permitInvalidConstAsModifier' should be set to true. + */ + function parseModifiers(permitInvalidConstAsModifier) { + var modifiers; + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { + // We need to ensure that any subsequent modifiers appear on the same line + // so that when 'const' is a standalone declaration, we don't issue an error. + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + if (!modifiers) { + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); + } + } + if (modifiers) { + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 120 /* AsyncKeyword */) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseClassElement() { + if (token() === 25 /* SemicolonToken */) { + var result = createNode(206 /* SemicolonClassElement */); + nextToken(); + return finishNode(result); + } + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + if (token() === 123 /* ConstructorKeyword */) { + return parseConstructorDeclaration(fullStart, decorators, modifiers); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + } + // It is very important that we check this *after* checking indexers because + // the [ token can start an index signature or a computed property name + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 /* StringLiteral */ || + token() === 8 /* NumericLiteral */ || + token() === 39 /* AsteriskToken */ || + token() === 21 /* OpenBracketToken */) { + return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + } + if (decorators || modifiers) { + // treat this as a property declaration with a missing name. + var name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); + } + // 'isClassMemberStart' should have hinted not to attempt parsing. + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression( + /*fullStart*/ scanner.getStartPos(), + /*decorators*/ undefined, + /*modifiers*/ undefined, 199 /* ClassExpression */); + } + function parseClassDeclaration(fullStart, decorators, modifiers) { + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229 /* ClassDeclaration */); + } + function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(75 /* ClassKeyword */); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(17 /* OpenBraceToken */)) { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + node.members = parseClassMembers(); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseNameOfClassDeclarationOrExpression() { + // implements is a future reserved word so + // 'class implements' might mean either + // - class expression with omitted name, 'implements' starts heritage clause + // - class with name 'implements' + // 'isImplementsClause' helps to disambiguate between these two cases + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + // ClassTail[Yield,Await] : (Modified) See 14.5 + // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } + if (isHeritageClause()) { + return parseList(21 /* HeritageClauses */, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { + var node = createNode(259 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); + } + return undefined; + } + function parseExpressionWithTypeArguments() { + var node = createNode(201 /* ExpressionWithTypeArguments */); + node.expression = parseLeftHandSideExpressionOrHigher(); + if (token() === 27 /* LessThanToken */) { + node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); + } + return finishNode(node); + } + function isHeritageClause() { + return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; + } + function parseClassMembers() { + return parseList(5 /* ClassMembers */, parseClassElement); + } + function parseInterfaceDeclaration(fullStart, decorators, modifiers) { + var node = createNode(230 /* InterfaceDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(109 /* InterfaceKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return addJSDocComment(finishNode(node)); + } + function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { + var node = createNode(231 /* TypeAliasDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(138 /* TypeKeyword */); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(58 /* EqualsToken */); + node.type = parseType(); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + // In an ambient declaration, the grammar only allows integer literals as initializers. + // In a non-ambient declaration, the grammar allows uninitialized members only in a + // ConstantEnumMemberSection, which starts at the beginning of an enum declaration + // or any time an integer literal initializer is encountered. + function parseEnumMember() { + var node = createNode(264 /* EnumMember */, scanner.getStartPos()); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseNonParameterInitializer); + return addJSDocComment(finishNode(node)); + } + function parseEnumDeclaration(fullStart, decorators, modifiers) { + var node = createNode(232 /* EnumDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(83 /* EnumKeyword */); + node.name = parseIdentifier(); + if (parseExpected(17 /* OpenBraceToken */)) { + node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseModuleBlock() { + var node = createNode(234 /* ModuleBlock */, scanner.getStartPos()); + if (parseExpected(17 /* OpenBraceToken */)) { + node.statements = parseList(1 /* BlockStatements */, parseStatement); + parseExpected(18 /* CloseBraceToken */); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { + var node = createNode(233 /* ModuleDeclaration */, fullStart); + // If we are parsing a dotted namespace name, we want to + // propagate the 'Namespace' flag across the names if set. + var namespaceFlag = flags & 16 /* Namespace */; + node.decorators = decorators; + node.modifiers = modifiers; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(23 /* DotToken */) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) + : parseModuleBlock(); + return addJSDocComment(finishNode(node)); + } + function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { + var node = createNode(233 /* ModuleDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (token() === 141 /* GlobalKeyword */) { + // parse 'global' as name of global scope augmentation + node.name = parseIdentifier(); + node.flags |= 512 /* GlobalAugmentation */; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 17 /* OpenBraceToken */) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(fullStart, decorators, modifiers) { + var flags = 0; + if (token() === 141 /* GlobalKeyword */) { + // global augmentation + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(129 /* NamespaceKeyword */)) { + flags |= 16 /* Namespace */; + } + else { + parseExpected(128 /* ModuleKeyword */); + if (token() === 9 /* StringLiteral */) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + } + return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + } + function isExternalModuleReference() { + return token() === 132 /* RequireKeyword */ && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 19 /* OpenParenToken */; + } + function nextTokenIsSlash() { + return nextToken() === 41 /* SlashToken */; + } + function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { + var exportDeclaration = createNode(236 /* NamespaceExportDeclaration */, fullStart); + exportDeclaration.decorators = decorators; + exportDeclaration.modifiers = modifiers; + parseExpected(118 /* AsKeyword */); + parseExpected(129 /* NamespaceKeyword */); + exportDeclaration.name = parseIdentifier(); + parseSemicolon(); + return finishNode(exportDeclaration); + } + function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + parseExpected(91 /* ImportKeyword */); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 26 /* CommaToken */ && token() !== 140 /* FromKeyword */) { + return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + } + } + // Import statement + var importDeclaration = createNode(238 /* ImportDeclaration */, fullStart); + importDeclaration.decorators = decorators; + importDeclaration.modifiers = modifiers; + // ImportDeclaration: + // import ImportClause from ModuleSpecifier ; + // import ModuleSpecifier; + if (identifier || + token() === 39 /* AsteriskToken */ || + token() === 17 /* OpenBraceToken */) { + importDeclaration.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(140 /* FromKeyword */); + } + importDeclaration.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(importDeclaration); + } + function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { + var importEqualsDeclaration = createNode(237 /* ImportEqualsDeclaration */, fullStart); + importEqualsDeclaration.decorators = decorators; + importEqualsDeclaration.modifiers = modifiers; + importEqualsDeclaration.name = identifier; + parseExpected(58 /* EqualsToken */); + importEqualsDeclaration.moduleReference = parseModuleReference(); + parseSemicolon(); + return addJSDocComment(finishNode(importEqualsDeclaration)); + } + function parseImportClause(identifier, fullStart) { + // ImportClause: + // ImportedDefaultBinding + // NameSpaceImport + // NamedImports + // ImportedDefaultBinding, NameSpaceImport + // ImportedDefaultBinding, NamedImports + var importClause = createNode(239 /* ImportClause */, fullStart); + if (identifier) { + // ImportedDefaultBinding: + // ImportedBinding + importClause.name = identifier; + } + // If there was no default import or if there is comma token after default import + // parse namespace or named imports + if (!importClause.name || + parseOptional(26 /* CommaToken */)) { + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(241 /* NamedImports */); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(/*allowReservedWords*/ false); + } + function parseExternalModuleReference() { + var node = createNode(248 /* ExternalModuleReference */); + parseExpected(132 /* RequireKeyword */); + parseExpected(19 /* OpenParenToken */); + node.expression = parseModuleSpecifier(); + parseExpected(20 /* CloseParenToken */); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 9 /* StringLiteral */) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + // We allow arbitrary expressions here, even though the grammar only allows string + // literals. We check to ensure that it is only a string literal later in the grammar + // check pass. + return parseExpression(); + } + } + function parseNamespaceImport() { + // NameSpaceImport: + // * as ImportedBinding + var namespaceImport = createNode(240 /* NamespaceImport */); + parseExpected(39 /* AsteriskToken */); + parseExpected(118 /* AsKeyword */); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + // NamedImports: + // { } + // { ImportsList } + // { ImportsList, } + // ImportsList: + // ImportSpecifier + // ImportsList, ImportSpecifier + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 241 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(246 /* ExportSpecifier */); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(242 /* ImportSpecifier */); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + // ImportSpecifier: + // BindingIdentifier + // IdentifierName as BindingIdentifier + // ExportSpecifier: + // IdentifierName + // IdentifierName as IdentifierName + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 118 /* AsKeyword */) { + node.propertyName = identifierName; + parseExpected(118 /* AsKeyword */); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 242 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + // Report error identifier expected + parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(fullStart, decorators, modifiers) { + var node = createNode(244 /* ExportDeclaration */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(39 /* AsteriskToken */)) { + parseExpected(140 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(245 /* NamedExports */); + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token() === 140 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(140 /* FromKeyword */); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(fullStart, decorators, modifiers) { + var node = createNode(243 /* ExportAssignment */, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(58 /* EqualsToken */)) { + node.isExportEquals = true; + } + else { + parseExpected(79 /* DefaultKeyword */); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function processReferenceComments(sourceFile) { + var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); + var referencedFiles = []; + var typeReferenceDirectives = []; + var amdDependencies = []; + var amdModuleName; + var checkJsDirective = undefined; + // Keep scanning all the leading trivia in the file until we get to something that + // isn't trivia. Any single line comment will be analyzed to see if it is a + // reference comment. + while (true) { + var kind = triviaScanner.scan(); + if (kind !== 2 /* SingleLineCommentTrivia */) { + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); + if (referencePathMatchResult) { + var fileReference = referencePathMatchResult.fileReference; + sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + if (fileReference) { + if (referencePathMatchResult.isTypeReferenceDirective) { + typeReferenceDirectives.push(fileReference); + } + else { + referencedFiles.push(fileReference); + } + } + if (diagnosticMessage) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + } + } + else { + var amdModuleNameRegEx = /^\/\/\/\s*= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + var tags; + var comments = []; + var result; + // Check for /** (JSDoc opening part) + if (!isJsDocStart(content, start)) { + return result; + } + // + 3 for leading /**, - 5 in total for /** */ + scanner.scanRange(start + 3, length - 5, function () { + // Initially we can parse out a tag. We also have seen a starting asterisk. + // This is so that /** * @type */ doesn't parse. + var advanceToken = true; + var state = 1 /* SawAsterisk */; + var margin = undefined; + // + 4 for leading '/** ' + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5 /* WhitespaceTrivia */) { + nextJSDocToken(); + } + if (token() === 4 /* NewLineTrivia */) { + state = 0 /* BeginningOfLine */; + indent = 0; + nextJSDocToken(); + } + while (token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 57 /* AtToken */: + if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { + removeTrailingNewlines(comments); + parseTag(indent); + // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. + // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning + // for malformed examples like `/** @param {string} x @returns {number} the length */` + state = 0 /* BeginningOfLine */; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4 /* NewLineTrivia */: + comments.push(scanner.getTokenText()); + state = 0 /* BeginningOfLine */; + indent = 0; + break; + case 39 /* AsteriskToken */: + var asterisk = scanner.getTokenText(); + if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { + // If we've already seen an asterisk, then we can no longer parse a tag on this line + state = 2 /* SavingComments */; + pushComment(asterisk); + } + else { + // Ignore the first asterisk on a line + state = 1 /* SawAsterisk */; + indent += asterisk.length; + } + break; + case 71 /* Identifier */: + // Anything else is doc comment text. We just save it. Because it + // wasn't a tag, we can no longer parse a tag on this line until we hit the next + // line break. + pushComment(scanner.getTokenText()); + state = 2 /* SavingComments */; + break; + case 5 /* WhitespaceTrivia */: + // only collect whitespace if we're already saving comments or have just crossed the comment indent margin + var whitespace = scanner.getTokenText(); + if (state === 2 /* SavingComments */) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1 /* EndOfFileToken */: + break; + default: + // anything other than whitespace or asterisk at the beginning of the line starts the comment text + state = 2 /* SavingComments */; + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { + nextJSDocToken(); + } + else { + advanceToken = true; + } + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 /* slash */ && + content.charCodeAt(start + 1) === 42 /* asterisk */ && + content.charCodeAt(start + 2) === 42 /* asterisk */ && + content.charCodeAt(start + 3) !== 42 /* asterisk */; + } + function createJSDocComment() { + var result = createNode(275 /* JSDocComment */, start); + result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function skipWhitespace() { + while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 57 /* AtToken */); + var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return; + } + var tag; + if (tagName) { + switch (tagName.escapedText) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + tag = parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */); + break; + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; + } + } + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + // a badly malformed tag should not be added to the list of tags + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + } + function parseTagComments(indent) { + var comments = []; + var state = 0 /* BeginningOfLine */; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { + switch (token()) { + case 4 /* NewLineTrivia */: + if (state >= 1 /* SawAsterisk */) { + state = 0 /* BeginningOfLine */; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 57 /* AtToken */: + // Done + break; + case 5 /* WhitespaceTrivia */: + if (state === 2 /* SavingComments */) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + // if the whitespace crosses the margin, take only the whitespace that passes the margin + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 39 /* AsteriskToken */: + if (state === 0 /* BeginningOfLine */) { + // leading asterisks start recording on the *next* (non-whitespace) token + state = 1 /* SawAsterisk */; + indent += scanner.getTokenText().length; + break; + } + // record the * as a comment + // falls through + default: + state = 2 /* SavingComments */; // leading identifiers start recording as well + pushComment(scanner.getTokenText()); + break; + } + if (token() === 57 /* AtToken */) { + // Done + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { + var result = createNode(276 /* JSDocTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); + } + else { + tags.push(tag); + } + tags.end = tag.end; + } + function tryParseTypeExpression() { + return tryParse(function () { + skipWhitespace(); + if (token() !== 17 /* OpenBraceToken */) { + return undefined; + } + return parseJSDocTypeExpression(); + }); + } + function parseBracketNameInPropertyAndParamTag() { + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' + var isBracketed = parseOptional(21 /* OpenBracketToken */); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + // May have an optional default, e.g. '[foo = 42]' + if (parseOptionalToken(58 /* EqualsToken */)) { + parseExpression(); + } + parseExpected(22 /* CloseBracketToken */); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 134 /* ObjectKeyword */: + return true; + case 164 /* ArrayType */: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(atToken, tagName, target) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespace(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 /* Parameter */ ? + createNode(279 /* JSDocParameterTag */, atToken.pos) : + createNode(284 /* JSDocPropertyTag */, atToken.pos); + var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(267 /* JSDocTypeExpression */, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { + if (!children) { + children = []; + } + children.push(child); + } + if (children) { + jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 164 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 280 /* JSDocReturnTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(280 /* JSDocReturnTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 281 /* JSDocTypeTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(281 /* JSDocTypeTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(277 /* JSDocAugmentsTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } + function parseClassTag(atToken, tagName) { + var tag = createNode(278 /* JSDocClassTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var typedefTag = createNode(283 /* JSDocTypedefTag */, atToken.pos); + typedefTag.atToken = atToken; + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (true) { + if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { + // if node is identifier - use it as name + // otherwise use name of the rightmost part that we were able to parse + typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; + break; + } + rightNode = rightNode.body; + } + } + skipWhitespace(); + typedefTag.typeExpression = typeExpression; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var alreadyHasTypeTag = false; + var start_3 = scanner.getStartPos(); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(285 /* JSDocTypeLiteral */, start_3); + } + if (child.kind === 281 /* JSDocTypeTag */) { + if (alreadyHasTypeTag) { + break; + } + else { + jsdocTypeLiteral.jsDocTypeTag = child; + alreadyHasTypeTag = true; + } + } + else { + if (!jsdocTypeLiteral.jsDocPropertyTags) { + jsdocTypeLiteral.jsDocPropertyTags = []; + } + jsdocTypeLiteral.jsDocPropertyTags.push(child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 164 /* ArrayType */) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + } + } + return finishNode(typedefTag); + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(233 /* ModuleDeclaration */, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildParameterOrPropertyTag(target, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + nextJSDocToken(); + switch (token()) { + case 57 /* AtToken */: + if (canParseTag) { + var child = tryParseChildTag(target); + if (child && child.kind === 279 /* JSDocParameterTag */ && + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4 /* NewLineTrivia */: + canParseTag = true; + seenAsterisk = false; + break; + case 39 /* AsteriskToken */: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 71 /* Identifier */: + canParseTag = false; + break; + case 1 /* EndOfFileToken */: + return false; + } + } + } + function tryParseChildTag(target) { + ts.Debug.assert(token() === 57 /* AtToken */); + var atToken = createNode(57 /* AtToken */, scanner.getStartPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return false; + } + switch (tagName.escapedText) { + case "type": + return target === 0 /* Property */ && parseTypeTag(atToken, tagName); + case "prop": + case "property": + return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + case "arg": + case "argument": + case "param": + return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + } + return false; + } + function parseTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 282 /* JSDocTemplateTag */; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + // Type parameter list looks like '@template T,U,V' + var typeParameters = createNodeArray(); + while (true) { + var name = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(145 /* TypeParameter */, name.pos); + typeParameter.name = name; + finishNode(typeParameter); + typeParameters.push(typeParameter); + if (token() === 26 /* CommaToken */) { + nextJSDocToken(); + skipWhitespace(); + } + else { + break; + } + } + var result = createNode(282 /* JSDocTemplateTag */, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + finishNode(result); + typeParameters.end = result.end; + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(21 /* OpenBracketToken */)) { + parseExpected(22 /* CloseBracketToken */); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(23 /* DotToken */)) { + var name = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(21 /* OpenBracketToken */)) { + parseExpected(22 /* CloseBracketToken */); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(createIfMissing) { + if (createIfMissing === void 0) { createIfMissing = false; } + if (!ts.tokenIsIdentifierOrKeyword(token())) { + if (createIfMissing) { + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); + return undefined; + } + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(71 /* Identifier */, pos); + result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); + } + // Make sure we're not trying to incrementally update a source file more than once. Once + // we do an update the original source file is considered unusable from that point onwards. + // + // This is because we do incremental parsing in-place. i.e. we take nodes from the old + // tree and give them new positions and parents. From that point on, trusting the old + // tree at all is not possible as far too much of it may violate invariants. + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + // Ensure that extending the affected range only moved the start of the change range + // earlier in the file. + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they + // may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If the node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + forEachChild(jsDocComment, visitNode, visitArray); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 71 /* Identifier */: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // children have spans within the span of their parent, and all siblings are ordered + // properly. + // We may need to update both the 'pos' and the 'end' of the element. + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element that started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element that ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + checkNodePositions(child, aggressiveChecks); + return; + } + // Otherwise, the node is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + return; + } + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; + visitNode(node); + } + return; + } + // Otherwise, the array is entirely before the change range. No need to do anything with it. + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + var start = changeRange.span.start; + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + ts.Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + // Either we don'd have a node, or we have a node at the position being asked for. + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + // don't proceed any further in the search. + return true; + } + // position wasn't in this node, have to keep searching. + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + // position wasn't in this array, have to keep searching. + return false; + } + } + } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + })(IncrementalParser || (IncrementalParser = {})); +})(ts || (ts = {})); +/// +/// +/* @internal */ +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) { + // A module is uninstantiated if it contains only + // 1. interface declarations, type alias declarations + if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 231 /* TypeAliasDeclaration */) { + return 0 /* NonInstantiated */; + } + else if (ts.isConstEnumDeclaration(node)) { + return 2 /* ConstEnumOnly */; + } + else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + else if (node.kind === 234 /* ModuleBlock */) { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + switch (getModuleInstanceState(n)) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return false; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return false; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + } + }); + return state_1; + } + else if (node.kind === 233 /* ModuleDeclaration */) { + var body = node.body; + return body ? getModuleInstanceState(body) : 1 /* Instantiated */; + } + else if (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + else { + return 1 /* Instantiated */; + } + } + ts.getModuleInstanceState = getModuleInstanceState; + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + 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"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var blockScopeContainer; + var lastContainer; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + if (!symbol.declarations) { + symbol.declarations = []; + } + symbol.declarations.push(node); + if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 107455 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233 /* ModuleDeclaration */)) { + // 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) { + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + 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 ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(nameExpression.name.escapedText)); + } + return ts.getEscapedTextOfIdentifierOrLiteral(name); + } + switch (node.kind) { + case 152 /* Constructor */: + return "__constructor" /* Constructor */; + case 160 /* FunctionType */: + case 155 /* CallSignature */: + return "__call" /* Call */; + case 161 /* ConstructorType */: + case 156 /* ConstructSignature */: + return "__new" /* New */; + case 157 /* IndexSignature */: + return "__index" /* Index */; + case 244 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 243 /* ExportAssignment */: + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + case 194 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 228 /* FunctionDeclaration */: + case 229 /* ClassDeclaration */: + return (ts.hasModifier(node, 512 /* Default */) ? "default" /* Default */ : undefined); + case 273 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 146 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 273 /* JSDocFunctionType */); + var functionType = node.parent; + var index = ts.indexOf(functionType.parameters, node); + return "arg" + index; + case 283 /* JSDocTypedefTag */: + var parentNode = node.parent && node.parent.parent; + var nameFromParentNode = void 0; + if (parentNode && parentNode.kind === 208 /* VariableStatement */) { + if (parentNode.declarationList.declarations.length > 0) { + var nameIdentifier = parentNode.declarationList.declarations[0].name; + if (ts.isIdentifier(nameIdentifier)) { + nameFromParentNode = nameIdentifier.escapedText; + } + } + } + return nameFromParentNode; + } + } + function getDisplayName(node) { + return node.name ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 788448 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else { + if (node.name) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 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 === 243 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } + ts.forEach(symbol.declarations, function (declaration) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); + }); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + symbol.parent = parent; + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 246 /* ExportSpecifier */ || (node.kind === 237 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // 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 === 283 /* JSDocTypedefTag */) + ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + var isJSDocTypedefInJSDocNamespace = node.kind === 283 /* JSDocTypedefTag */ && + node.name && + node.name.kind === 71 /* Identifier */ && + node.name.isInJSDocNamespace; + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { + var exportKind = symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we proactively initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (isIIFE) { + currentReturnTarget = createBranchLabel(); + } + else { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + currentReturnTarget = undefined; + } + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 265 /* SourceFile */) { + node.flags |= emitFlags; + } + if (isIIFE) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + } + else { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEach(nodes) { + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bind(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + // 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 (node.jsDoc) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + if (checkUnreachable(node)) { + bindEachChild(node); + return; + } + switch (node.kind) { + case 213 /* WhileStatement */: + bindWhileStatement(node); + break; + case 212 /* DoStatement */: + bindDoStatement(node); + break; + case 214 /* ForStatement */: + bindForStatement(node); + break; + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 211 /* IfStatement */: + bindIfStatement(node); + break; + case 219 /* ReturnStatement */: + case 223 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 218 /* BreakStatement */: + case 217 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 224 /* TryStatement */: + bindTryStatement(node); + break; + case 221 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 235 /* CaseBlock */: + bindCaseBlock(node); + break; + case 257 /* CaseClause */: + bindCaseClause(node); + break; + case 222 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 192 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 193 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 194 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 188 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 195 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 226 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 181 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 275 /* JSDocComment */: + bindJSDocComment(node); + break; + case 283 /* JSDocTypedefTag */: + bindJSDocTypedefTag(node); + break; + default: + bindEachChild(node); + break; + } + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 179 /* PropertyAccessExpression */: + return isNarrowableReference(expr); + case 181 /* CallExpression */: + return hasNarrowableArgument(expr); + case 185 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 194 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 192 /* PrefixUnaryExpression */: + return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 71 /* Identifier */ || + expr.kind === 99 /* ThisKeyword */ || + expr.kind === 97 /* SuperKeyword */ || + expr.kind === 179 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 179 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return expr1.kind === 189 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 93 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 26 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 185 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 194 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 26 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: flags, + expression: expression, + antecedent: antecedent + }; + } + function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { + if (!isNarrowingExpression(switchStatement.expression)) { + return antecedent; + } + setFlowNodeReferenced(antecedent); + return { + flags: 128 /* SwitchClause */, + switchStatement: switchStatement, + clauseStart: clauseStart, + clauseEnd: clauseEnd, + antecedent: antecedent + }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 16 /* Assignment */, + antecedent: antecedent, + node: node + }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { + flags: 256 /* ArrayMutation */, + antecedent: antecedent, + node: node + }; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 211 /* IfStatement */: + case 213 /* WhileStatement */: + case 212 /* DoStatement */: + return parent.expression === node; + case 214 /* ForStatement */: + case 195 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 185 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 192 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 194 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 54 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 185 /* ParenthesizedExpression */ || + node.parent.kind === 192 /* PrefixUnaryExpression */ && + node.parent.operator === 51 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 222 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 216 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 227 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 219 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 218 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); + } + if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 177 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 198 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 178 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 261 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 262 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 263 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 51 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 58 /* EqualsToken */ && node.left.kind === 180 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 179 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocComment(node) { + ts.forEachChild(node, function (n) { + if (n.kind !== 283 /* JSDocTypedefTag */) { + bind(n); + } + }); + } + function bindJSDocTypedefTag(node) { + ts.forEachChild(node, function (n) { + // if the node has a fullName "A.B.C", that means symbol "C" was already bound + // when we visit "fullName"; so when we visit the name "C" as the next child of + // the jsDocTypedefTag, we should skip binding it. + if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { + return; + } + bind(n); + }); + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 185 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 186 /* FunctionExpression */ || expr.kind === 187 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 179 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 199 /* ClassExpression */: + case 229 /* ClassDeclaration */: + case 232 /* EnumDeclaration */: + case 178 /* ObjectLiteralExpression */: + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 254 /* JsxAttributes */: + return 1 /* IsContainer */; + case 230 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 233 /* ModuleDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 172 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 265 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 151 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 152 /* Constructor */: + case 228 /* FunctionDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 155 /* CallSignature */: + case 273 /* JSDocFunctionType */: + case 160 /* FunctionType */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 161 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 234 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 149 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 260 /* CatchClause */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + case 235 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 207 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + // Just call this directly so that the return type of this function stays "void". + return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); + } + function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 233 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 265 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 199 /* ClassExpression */: + case 229 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 232 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 178 /* ObjectLiteralExpression */: + case 230 /* InterfaceDeclaration */: + case 254 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 273 /* JSDocFunctionType */: + case 231 /* TypeAliasDeclaration */: + case 172 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 265 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 265 /* SourceFile */ || body.kind === 234 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 244 /* ExportDeclaration */ || stat.kind === 243 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isExternalModuleAugmentation(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 9 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); + if (pattern) { + (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); + } + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { + // if module was already merged with some function, class or non-const enum + // treat is a non-const-enum-only + node.symbol.constEnumOnlyModule = false; + } + else { + var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; + if (node.symbol.constEnumOnlyModule === undefined) { + // non-merged case - use the current state + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + // merged case: module is const enum only if all its pieces are non-instantiated or const enum + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } + } + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + typeLiteralSymbol.members.set(symbol.escapedName, 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.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */ || prop.kind === 151 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span_1 = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + addDeclarationToSymbol(symbol, node, symbolFlags); + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 233 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 265 /* SourceFile */: + if (ts.isExternalModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !ts.isInAmbientContext(node)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span_2 = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 71 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span_3 = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.unescapeLeadingUnderscores(identifier.escapedText))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 265 /* SourceFile */ && + blockScopeContainer.kind !== 233 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // 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 (ts.isInJavaScriptFile(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 + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 142 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + } + inStrictMode = saveInStrictMode; + } + function bindJSDocTypedefTagIfAny(node) { + if (!node.jsDoc) { + return; + } + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + if (!jsDoc.tags) { + continue; + } + for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { + var tag = _c[_b]; + if (tag.kind === 283 /* JSDocTypedefTag */) { + var savedParent = parent; + parent = jsDoc; + bind(tag); + parent = savedParent; + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 71 /* Identifier */: + // 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) { + var parentNode = node.parent; + while (parentNode && parentNode.kind !== 283 /* JSDocTypedefTag */) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + break; + } + // falls through + case 99 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 262 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 179 /* PropertyAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + break; + case 194 /* BinaryExpression */: + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindStaticPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 260 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 188 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 193 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 192 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 220 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 169 /* ThisType */: + seenThisKeyword = true; + return; + case 158 /* TypePredicate */: + return checkTypePredicate(node); + case 145 /* TypeParameter */: + return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); + case 146 /* Parameter */: + return bindParameter(node); + case 226 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 176 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + return bindPropertyWorker(node); + case 261 /* PropertyAssignment */: + case 262 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 264 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + case 228 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 152 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 153 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); + case 154 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); + case 160 /* FunctionType */: + case 273 /* JSDocFunctionType */: + case 161 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 172 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 178 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return bindFunctionExpression(node); + case 181 /* CallExpression */: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 199 /* ClassExpression */: + case 229 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 230 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); + case 231 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + case 232 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 233 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 254 /* JsxAttributes */: + return bindJsxAttributes(node); + case 253 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 237 /* ImportEqualsDeclaration */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 236 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 239 /* ImportClause */: + return bindImportClause(node); + case 244 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 243 /* ExportAssignment */: + return bindExportAssignment(node); + case 265 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 207 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 234 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 279 /* JSDocParameterTag */: + if (node.parent.kind !== 285 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 284 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression.type.kind === 272 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 283 /* JSDocTypedefTag */: { + var fullName = node.fullName; + if (!fullName || fullName.kind === 71 /* Identifier */) { + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); + } + break; + } + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function checkTypePredicate(node) { + var parameterName = node.parameterName, type = node.type; + if (parameterName && parameterName.kind === 71 /* Identifier */) { + checkStrictModeIdentifier(parameterName); + } + if (parameterName && parameterName.kind === 169 /* ThisType */) { + seenThisKeyword = true; + } + bind(type); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. + var flags = node.kind === 243 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */; + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 2097152 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + if (node.parent.kind !== 265 /* SourceFile */) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + if (!file.externalModuleIndicator) { + bindSourceFileAsExternalModule(); + } + } + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); + } + function isExportsOrModuleExportsOrAlias(node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + isNameOfExportsOrModuleExportsAliasDeclaration(node); + } + function isNameOfExportsOrModuleExportsAliasDeclaration(node) { + if (ts.isIdentifier(node)) { + var symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); + } + return false; + } + function isExportsOrModuleExportsOrAliasOrAssignment(node) { + return isExportsOrModuleExportsOrAlias(node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(node.left) || isExportsOrModuleExportsOrAliasOrAssignment(node.right))); + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { + // Mark it as a module in case there are no other exports in the file + setCommonJsModuleIndicator(node); + return; + } + // 'module.exports = expr' assignment + setCommonJsModuleIndicator(node); + declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (container.kind) { + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + // Declare a 'member' if the container is an ES5 class or ES6 constructor + container.symbol.members = container.symbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + break; + case 152 /* Constructor */: + case 149 /* PropertyDeclaration */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = container.parent; + var symbolTable = ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + } + } + function bindPrototypePropertyAssignment(node) { + // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var leftSideOfAssignment = node.left; + var classPrototype = leftSideOfAssignment.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + constructorFunction.parent = classPrototype; + classPrototype.parent = leftSideOfAssignment; + bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ true); + } + function bindStaticPropertyAssignment(node) { + // We saw a node of the form 'x.y = z'. Declare a 'member' y on x if x was a function. + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var leftSideOfAssignment = node.left; + var target = leftSideOfAssignment.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + leftSideOfAssignment.parent = node; + target.parent = leftSideOfAssignment; + if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); + } + } + function lookupSymbolForName(name) { + return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); + } + function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { + var targetSymbol = lookupSymbolForName(functionName); + if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { + targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; + } + if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */))) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (targetSymbol.members || (targetSymbol.members = ts.createSymbolTable())) : + (targetSymbol.exports || (targetSymbol.exports = ts.createSymbolTable())); + // Declare the method/property + declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4 /* Property */, 0 /* PropertyExcludes */); + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 229 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(prototypeSymbol.escapedName))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); + } + } + } + function bindParameter(node) { + 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); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !ts.isInAmbientContext(node) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 209 /* EmptyStatement */) || + // report error on class declarations + node.kind === 229 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 233 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 232 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 208 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + } + return true; + } + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 181 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 182 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 233 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 185 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 194 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 210 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 146 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 187 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 186 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 228 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 226 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 227 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 208 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 222 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 229 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 199 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 259 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 260 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 201 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 152 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 149 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 151 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 237 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 179 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */ + || isSuperOrSuperProperty(expression, expressionKind)) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + if (expression.kind === 91 /* ImportKeyword */) { + transformFlags |= 67108864 /* ContainsDynamicImport */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + } + function isSuperOrSuperProperty(node, kind) { + switch (kind) { + case 97 /* SuperKeyword */: + return true; + case 179 /* PropertyAccessExpression */: + case 180 /* ElementAccessExpression */: + var expression = node.expression; + var expressionKind = expression.kind; + return expressionKind === 97 /* SuperKeyword */; + } + return false; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 177 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ + || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var modifierFlags = ts.getModifierFlags(node); + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & 4096 /* ContainsDecorators */ + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (modifierFlags & 92 /* ParameterPropertyModifier */) { + transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 202 /* AsExpression */ + || expressionKind === 184 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + if (modifierFlags & 2 /* Ambient */) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~539358529 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~539358529 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 85 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 108 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~537920833 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer) { + transformFlags |= 8192 /* ContainsPropertyInitializer */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601281857 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601281857 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionKind === 97 /* SuperKeyword */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (modifierFlags & 2 /* Ambient */) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~574674241 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 536872257 /* NodeExcludes */; + switch (kind) { + case 120 /* AsyncKeyword */: + case 191 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 117 /* AbstractKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 232 /* EnumDeclaration */: + case 264 /* EnumMember */: + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + case 203 /* NonNullExpression */: + case 131 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 249 /* JsxElement */: + case 250 /* JsxSelfClosingElement */: + case 251 /* JsxOpeningElement */: + case 10 /* JsxText */: + case 252 /* JsxClosingElement */: + case 253 /* JsxAttribute */: + case 254 /* JsxAttributes */: + case 255 /* JsxSpreadAttribute */: + case 256 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + case 196 /* TemplateExpression */: + case 183 /* TaggedTemplateExpression */: + case 262 /* ShorthandPropertyAssignment */: + case 115 /* StaticKeyword */: + case 204 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 9 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 216 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 197 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + break; + case 119 /* AnyKeyword */: + case 133 /* NumberKeyword */: + case 130 /* NeverKeyword */: + case 134 /* ObjectKeyword */: + case 136 /* StringKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 145 /* TypeParameter */: + case 148 /* PropertySignature */: + case 150 /* MethodSignature */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 158 /* TypePredicate */: + case 159 /* TypeReference */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 162 /* TypeQuery */: + case 163 /* TypeLiteral */: + case 164 /* ArrayType */: + case 165 /* TupleType */: + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 168 /* ParenthesizedType */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 169 /* ThisType */: + case 170 /* TypeOperator */: + case 171 /* IndexedAccessType */: + case 172 /* MappedType */: + case 173 /* LiteralType */: + case 236 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 144 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 2097152 /* ContainsComputedPropertyName */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 198 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + break; + case 263 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + break; + case 97 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 99 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 16384 /* ContainsLexicalThis */; + break; + case 174 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + if (subtreeFlags & 524288 /* ContainsRest */) { + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + } + excludeFlags = 537396545 /* BindingPatternExcludes */; + break; + case 175 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + excludeFlags = 537396545 /* BindingPatternExcludes */; + break; + case 176 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 524288 /* ContainsRest */; + } + break; + case 147 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + break; + case 178 /* ObjectLiteralExpression */: + excludeFlags = 540087617 /* ObjectLiteralExcludes */; + if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 177 /* ArrayLiteralExpression */: + case 182 /* NewExpression */: + excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 265 /* SourceFile */: + if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 219 /* ReturnStatement */: + case 217 /* ContinueStatement */: + case 218 /* BreakStatement */: + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 181 /* CallExpression */: + case 182 /* NewExpression */: + case 177 /* ArrayLiteralExpression */: + return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + case 233 /* ModuleDeclaration */: + return 574674241 /* ModuleExcludes */; + case 146 /* Parameter */: + return 536872257 /* ParameterExcludes */; + case 187 /* ArrowFunction */: + return 601249089 /* ArrowFunctionExcludes */; + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + return 601281857 /* FunctionExcludes */; + case 227 /* VariableDeclarationList */: + return 546309441 /* VariableDeclarationListExcludes */; + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + return 539358529 /* ClassExcludes */; + case 152 /* Constructor */: + return 601015617 /* ConstructorExcludes */; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return 601015617 /* MethodOrAccessorExcludes */; + case 119 /* AnyKeyword */: + case 133 /* NumberKeyword */: + case 130 /* NeverKeyword */: + case 136 /* StringKeyword */: + case 134 /* ObjectKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 145 /* TypeParameter */: + case 148 /* PropertySignature */: + case 150 /* MethodSignature */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 178 /* ObjectLiteralExpression */: + return 540087617 /* ObjectLiteralExcludes */; + case 260 /* CatchClause */: + return 537920833 /* CatchClauseExcludes */; + case 174 /* ObjectBindingPattern */: + case 175 /* ArrayBindingPattern */: + return 537396545 /* BindingPatternExcludes */; + default: + return 536872257 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); + } +})(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /** + * Kinds of file that we are currently looking for. + * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. + */ + var Extensions; + (function (Extensions) { + Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; + Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; + Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + })(Extensions || (Extensions = {})); + /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ + function resolvedTypeScriptOnly(resolved) { + if (!resolved) { + return undefined; + } + ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); + return resolved.path; + } + function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { + return { + resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, + failedLookupLocations: failedLookupLocations + }; + } + /** Reads from "main" or "types"/"typings" depending on `extensions`. */ + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); + function tryReadFromField(fieldName) { + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); + } + return; + } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + if (currentDirectory !== undefined) { + return getDefaultTypeRoots(currentDirectory, host); + } + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. + } + var typeRoots; + forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { + var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + return undefined; + }); + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + var resolved = primaryLookup(); + var primary = true; + if (!resolved) { + resolved = secondaryLookup(); + primary = false; + } + var resolvedTypeReferenceDirective; + if (resolved) { + resolved = realpath(resolved, host, traceEnabled); + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); + } + resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; + } + return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; + function primaryLookup() { + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + return ts.forEach(typeRoots, function (typeRoot) { + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var directoryExists = directoryProbablyExists(candidateDirectory, host); + if (!directoryExists && traceEnabled) { + trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); + } + return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); + }); + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + } + function secondaryLookup() { + var resolvedFile; + var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + resolvedFile = resolvedTypeScriptOnly(result && result.value); + if (!resolvedFile && traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + return resolvedFile; + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + } + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { + var directoryToModuleNameMap = ts.createMap(); + var moduleNameToDirectoryMap = ts.createMap(); + return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; + function getOrCreateCacheForDirectory(directoryName) { + var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); + var perFolderCache = directoryToModuleNameMap.get(path); + if (!perFolderCache) { + perFolderCache = ts.createMap(); + directoryToModuleNameMap.set(path, perFolderCache); + } + return perFolderCache; + } + function getOrCreateCacheForModuleName(nonRelativeModuleName) { + if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { + return undefined; + } + var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); + if (!perModuleNameCache) { + perModuleNameCache = createPerModuleNameCache(); + moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); + } + return perModuleNameCache; + } + function createPerModuleNameCache() { + var directoryPathMap = ts.createMap(); + return { get: get, set: set }; + function get(directory) { + return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); + } + /** + * At first this function add entry directory -> module resolution result to the table. + * Then it computes the set of parent folders for 'directory' that should have the same module resolution result + * and for every parent folder in set it adds entry: parent -> module resolution. . + * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. + * Set of parent folders that should have the same result will be: + * [ + * /a/b/c/d, /a/b/c, /a/b + * ] + * this means that request for module resolution from file in any of these folder will be immediately found in cache. + */ + function set(directory, result) { + var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); + // if entry is already in cache do nothing + if (directoryPathMap.has(path)) { + return; + } + directoryPathMap.set(path, result); + var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; + // find common prefix between directory and resolved file name + // this common prefix should be the shorted path that has the same resolution + // directory: /a/b/c/d/e + // resolvedFileName: /a/b/foo.d.ts + var commonPrefix = getCommonPrefix(path, resolvedFileName); + var current = path; + while (true) { + var parent = ts.getDirectoryPath(current); + if (parent === current || directoryPathMap.has(parent)) { + break; + } + directoryPathMap.set(parent, result); + current = parent; + if (current === commonPrefix) { + break; + } + } + } + function getCommonPrefix(directory, resolution) { + if (resolution === undefined) { + return undefined; + } + var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); + // find first position where directory and resolution differs + var i = 0; + while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { + i++; + } + // find last directory separator before position i + var sep = directory.lastIndexOf(ts.directorySeparator, i); + if (sep < 0) { + return undefined; + } + return directory.substr(0, sep); + } + } + } + ts.createModuleResolutionCache = createModuleResolutionCache; + function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + var result = perFolderCache && perFolderCache.get(moduleName); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + } + } + else { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); + break; + 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); + // put result in per-module name cache + var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); + if (perModuleNameCache) { + perModuleNameCache.set(containingDirectory, result); + } + } + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!ts.isExternalModuleNameRelative(moduleName)) { + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + } + else { + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + } + } + function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { + var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (path_1 !== undefined) { + return { path: path_1, extension: extension }; + } + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + }); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + /** + * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. + * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 + * Throws an error if the module can't be resolved. + */ + /* @internal */ + function resolveJavaScriptModule(moduleName, initialDir, host) { + var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + 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 }; + var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + if (result && result.value) { + var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; + return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); + } + return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + function tryResolve(extensions) { + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + if (resolved) { + return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); + } + if (!ts.isExternalModuleNameRelative(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); + } + var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. + return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); + } + } + } + function realpath(path, host, traceEnabled) { + if (!host.realpath) { + return path; + } + var real = ts.normalizePath(host.realpath(path)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); + } + return real; + } + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); + } + if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!onlyRecordFailures) { + var parentOfCandidate = ts.getDirectoryPath(candidate); + if (!directoryProbablyExists(parentOfCandidate, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); + } + onlyRecordFailures = true; + } + } + var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + if (resolvedFromFile) { + return resolvedFromFile; + } + } + if (!onlyRecordFailures) { + var candidateExists = directoryProbablyExists(candidate, state.host); + if (!candidateExists) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); + } + onlyRecordFailures = true; + } + } + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + switch (extensions) { + case Extensions.DtsOnly: + return tryExtension(".d.ts" /* Dts */); + case Extensions.TypeScript: + return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); + case Extensions.JavaScript: + return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + } + function tryExtension(extension) { + var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); + return path && { path: path, extension: extension }; + } + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + if (state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + } + } + failedLookupLocations.push(fileName); + return undefined; + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; + } + } + else { + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); + } + } + return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + } + /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ + function resolvedIfExtensionMatches(extensions, path) { + var extension = ts.tryGetExtensionFromPath(path); + return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; + } + /** True if `extension` is one of the supported `extensions`. */ + function extensionIsOk(extensions, extension) { + switch (extensions) { + case Extensions.JavaScript: + return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.TypeScript: + return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; + case Extensions.DtsOnly: + return extension === ".d.ts" /* Dts */; + } + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || + loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + } + function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { + return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + } + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + } + function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + } + }); + } + /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ + function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { + if (typesOnly === void 0) { typesOnly = false; } + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + if (!nodeModulesFolderExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); + } + var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + if (packageResult) { + return packageResult; + } + if (extensions !== Extensions.JavaScript) { + var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); + var nodeModulesAtTypesExists = nodeModulesFolderExists; + if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); + } + nodeModulesAtTypesExists = false; + } + return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); + } + } + /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */ + var mangledScopedPackageSeparator = "__"; + /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ + function mangleScopedPackage(moduleName, state) { + if (ts.startsWith(moduleName, "@")) { + var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + if (replaceSlash !== moduleName) { + var mangled = replaceSlash.slice(1); // Take off the "@" + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); + } + return mangled; + } + } + return moduleName; + } + /* @internal */ + function getPackageNameFromAtTypesDirectory(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { + var result = cache && cache.get(containingDirectory); + if (result) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); + } + return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; + } + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); + return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); + function tryResolve(extensions) { + var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); + if (resolvedUsingSettings) { + return { value: resolvedUsingSettings }; + } + var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + if (!ts.isExternalModuleNameRelative(moduleName)) { + // Climb up parent directories looking for a module. + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); + if (resolutionFromCache) { + return resolutionFromCache; + } + var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + }); + if (resolved_3) { + return resolved_3; + } + if (extensions === Extensions.TypeScript) { + // If we didn't find the file normally, look it up in @types. + return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + } + } + } + ts.classicNameResolver = classicNameResolver; + /** + * LSHost may load a module from a global cache of typings. + * This is the minumum code needed to expose that functionality; the rest is in LSHost. + */ + /* @internal */ + function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; + var failedLookupLocations = []; + var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); + } + ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; + /** + * Wraps value to SearchResult. + * @returns undefined if value is undefined or { value } otherwise + */ + function toSearchResult(value) { + return value !== undefined ? { value: value } : undefined; + } + /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } +})(ts || (ts = {})); +/// +/// +/* @internal */ +var ts; +(function (ts) { + var ambientModuleSymbolRegex = /^".+"$/; + var nextSymbolId = 1; + var nextNodeId = 1; + var nextMergeId = 1; + var nextFlowId = 1; + function getNodeId(node) { + if (!node.id) { + node.id = nextNodeId; + nextNodeId++; + } + return node.id; + } + ts.getNodeId = getNodeId; + function getSymbolId(symbol) { + if (!symbol.id) { + symbol.id = nextSymbolId; + nextSymbolId++; + } + return symbol.id; + } + ts.getSymbolId = getSymbolId; + function isInstantiatedModule(node, preserveConstEnums) { + var moduleState = ts.getModuleInstanceState(node); + return moduleState === 1 /* Instantiated */ || + (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */); + } + ts.isInstantiatedModule = isInstantiatedModule; + function createTypeChecker(host, produceDiagnostics) { + // Cancellation that controls whether or not we can cancel in the middle of type checking. + // In general cancelling is *not* safe for the type checker. We might be in the middle of + // computing something, and we will leave our internals in an inconsistent state. Callers + // who set the cancellation token should catch if a cancellation exception occurs, and + // should throw away and create a new TypeChecker. + // + // Currently we only support setting the cancellation token when getting diagnostics. This + // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if + // they no longer need the information (for example, if the user started editing again). + var cancellationToken; + var requestedExternalEmitHelpers; + var externalHelpersModule; + var Symbol = ts.objectAllocator.getSymbolConstructor(); + var Type = ts.objectAllocator.getTypeConstructor(); + var Signature = ts.objectAllocator.getSignatureConstructor(); + var typeCount = 0; + var symbolCount = 0; + var enumCount = 0; + var symbolInstantiationDepth = 0; + var emptySymbols = ts.createSymbolTable(); + var compilerOptions = host.getCompilerOptions(); + var languageVersion = ts.getEmitScriptTarget(compilerOptions); + var modulekind = ts.getEmitModuleKind(compilerOptions); + var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; + var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; + var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; + var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; + var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; + var emitResolver = createResolver(); + var nodeBuilder = createNodeBuilder(); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); + undefinedSymbol.declarations = []; + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount; + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible + // extra cost of calling `getParseTreeNode` when calling these functions from inside the + // checker. + var checker = { + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, + getTypeCount: function () { return typeCount; }, + isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, + isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, + isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, + getMergedSymbol: getMergedSymbol, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getTypeOfSymbolAtLocation: function (symbol, location) { + location = ts.getParseTreeNode(location); + return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; + }, + getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { + parameter = ts.getParseTreeNode(parameter, ts.isParameter); + ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); + }, + getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, + getPropertiesOfType: getPropertiesOfType, + getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getIndexInfoOfType: getIndexInfoOfType, + getSignaturesOfType: getSignaturesOfType, + getIndexTypeOfType: getIndexTypeOfType, + getBaseTypes: getBaseTypes, + getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, + getWidenedType: getWidenedType, + getTypeFromTypeNode: function (node) { + node = ts.getParseTreeNode(node, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : unknownType; + }, + getParameterType: getTypeAtPosition, + getReturnTypeOfSignature: getReturnTypeOfSignature, + getNullableType: getNullableType, + getNonNullableType: getNonNullableType, + typeToTypeNode: nodeBuilder.typeToTypeNode, + indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, + signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + getSymbolsInScope: function (location, meaning) { + location = ts.getParseTreeNode(location); + return location ? getSymbolsInScope(location, meaning) : []; + }, + getSymbolAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getSymbolAtLocation(node) : undefined; + }, + getShorthandAssignmentValueSymbol: function (node) { + node = ts.getParseTreeNode(node); + return node ? getShorthandAssignmentValueSymbol(node) : undefined; + }, + getExportSpecifierLocalTargetSymbol: function (node) { + node = ts.getParseTreeNode(node, ts.isExportSpecifier); + return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; + }, + getTypeAtLocation: function (node) { + node = ts.getParseTreeNode(node); + return node ? getTypeOfNode(node) : unknownType; + }, + getPropertySymbolOfDestructuringAssignment: function (location) { + location = ts.getParseTreeNode(location, ts.isIdentifier); + return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; + }, + signatureToString: function (signature, enclosingDeclaration, flags, kind) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); + }, + typeToString: function (type, enclosingDeclaration, flags) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, + symbolToString: function (symbol, enclosingDeclaration, meaning) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + }, + getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, + getRootSymbols: getRootSymbols, + getContextualType: function (node) { + node = ts.getParseTreeNode(node, ts.isExpression); + return node ? getContextualType(node) : undefined; + }, + getFullyQualifiedName: getFullyQualifiedName, + getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { + node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + apparentArgumentCount = theArgumentCount; + var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; + apparentArgumentCount = undefined; + return res; + }, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + isValidPropertyAccess: function (node, propertyName) { + node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); + return node ? isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)) : false; + }, + getSignatureFromDeclaration: function (declaration) { + declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + return declaration ? getSignatureFromDeclaration(declaration) : undefined; + }, + isImplementationOfOverload: function (node) { + var parsed = ts.getParseTreeNode(node, ts.isFunctionLike); + return parsed ? isImplementationOfOverload(parsed) : undefined; + }, + getImmediateAliasedSymbol: function (symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.immediateTarget) { + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); + } + return links.immediateTarget; + }, + getAliasedSymbol: resolveAlias, + getEmitResolver: getEmitResolver, + getExportsOfModule: getExportsOfModuleAsArray, + getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, + getAmbientModules: getAmbientModules, + getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { + node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; + }, + getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, + isOptionalParameter: function (node) { + node = ts.getParseTreeNode(node, ts.isParameter); + return node ? isOptionalParameter(node) : false; + }, + tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, + tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); }, + tryFindAmbientModuleWithoutAugmentations: function (moduleName) { + // we deliberately exclude augmentations + // since we are only interested in declarations of the module itself + return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); + }, + getApparentType: getApparentType, + getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, + getSuggestionForNonexistentProperty: function (node, type) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentProperty(node, type)); }, + getSuggestionForNonexistentSymbol: function (location, name, meaning) { return ts.unescapeLeadingUnderscores(getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning)); }, + getBaseConstraintOfType: getBaseConstraintOfType, + getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, + resolveNameAtLocation: function (location, name, meaning) { + location = ts.getParseTreeNode(location); + return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, ts.escapeLeadingUnderscores(name)); + }, + }; + var tupleTypes = []; + var unionTypes = ts.createMap(); + var intersectionTypes = ts.createMap(); + var literalTypes = ts.createMap(); + var indexedAccessTypes = ts.createMap(); + var evolvingArrayTypes = []; + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */); + var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); + var unknownType = createIntrinsicType(1 /* Any */, "unknown"); + var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(4096 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(2 /* String */, "string"); + var numberType = createIntrinsicType(4 /* Number */, "number"); + var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); + var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); + var booleanType = createBooleanType([trueType, falseType]); + var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(1024 /* Void */, "void"); + var neverType = createIntrinsicType(8192 /* Never */, "never"); + var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + emptyTypeLiteralSymbol.members = ts.createSymbolTable(); + var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + emptyGenericType.instantiations = ts.createMap(); + var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; + var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); + var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + var globals = ts.createSymbolTable(); + /** + * List of every ambient module with a "*" wildcard. + * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. + * This is only used if there is no exact match. + */ + var patternAmbientModules; + var globalObjectType; + var globalFunctionType; + var globalArrayType; + var globalReadonlyArrayType; + var globalStringType; + var globalNumberType; + var globalBooleanType; + var globalRegExpType; + var globalThisType; + var anyArrayType; + var autoArrayType; + var anyReadonlyArrayType; + // The library files are only loaded when the feature is used. + // This allows users to just specify library files they want to used through --lib + // and they will not get an error from not having unrelated library files + var deferredGlobalESSymbolConstructorSymbol; + var deferredGlobalESSymbolType; + var deferredGlobalTypedPropertyDescriptorType; + var deferredGlobalPromiseType; + var deferredGlobalPromiseConstructorSymbol; + var deferredGlobalPromiseConstructorLikeType; + var deferredGlobalIterableType; + var deferredGlobalIteratorType; + var deferredGlobalIterableIteratorType; + var deferredGlobalAsyncIterableType; + var deferredGlobalAsyncIteratorType; + var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalTemplateStringsArrayType; + var deferredJsxElementClassType; + var deferredJsxElementType; + var deferredJsxStatelessElementType; + var deferredNodes; + var deferredUnusedIdentifierNodes; + var flowLoopStart = 0; + var flowLoopCount = 0; + var visitedFlowCount = 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 = []; + var flowLoopCaches = []; + var flowLoopNodes = []; + var flowLoopKeys = []; + var flowLoopTypes = []; + var visitedFlowNodes = []; + var visitedFlowTypes = []; + var potentialThisCollisions = []; + 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"; + // The following members encode facts about particular kinds of types for use in the getTypeFacts function. + // The presence of a particular fact means that the given test is true for some (and possibly all) values + // of that kind of type. + 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 /* TypeofEQString */, + "number": 2 /* TypeofEQNumber */, + "boolean": 4 /* TypeofEQBoolean */, + "symbol": 8 /* TypeofEQSymbol */, + "undefined": 16384 /* EQUndefined */, + "object": 16 /* TypeofEQObject */, + "function": 32 /* TypeofEQFunction */ + }); + var typeofNEFacts = ts.createMapFromTemplate({ + "string": 128 /* TypeofNEString */, + "number": 256 /* TypeofNENumber */, + "boolean": 512 /* TypeofNEBoolean */, + "symbol": 1024 /* TypeofNESymbol */, + "undefined": 131072 /* NEUndefined */, + "object": 2048 /* TypeofNEObject */, + "function": 4096 /* TypeofNEFunction */ + }); + var typeofTypesByName = ts.createMapFromTemplate({ + "string": stringType, + "number": numberType, + "boolean": booleanType, + "symbol": esSymbolType, + "undefined": undefinedType + }); + var typeofType = createTypeofType(); + var _jsxNamespace; + var _jsxFactoryEntity; + var _jsxElementPropertiesName; + var _hasComputedJsxElementPropertiesName = false; + var _jsxElementChildrenPropertyName; + var _hasComputedJsxElementChildrenPropertyName = false; + /** Things we lazy load from the JSX namespace */ + var jsxTypes = ts.createUnderscoreEscapedMap(); + var JsxNames = { + JSX: "JSX", + IntrinsicElements: "IntrinsicElements", + ElementClass: "ElementClass", + ElementAttributesPropertyNameContainer: "ElementAttributesProperty", + ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", + Element: "Element", + IntrinsicAttributes: "IntrinsicAttributes", + IntrinsicClassAttributes: "IntrinsicClassAttributes" + }; + var subtypeRelation = ts.createMap(); + var assignableRelation = ts.createMap(); + var comparableRelation = ts.createMap(); + var identityRelation = ts.createMap(); + var enumRelation = ts.createMap(); + // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. + 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.createSymbolTable(); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); + initializeTypeChecker(); + return checker; + function getJsxNamespace() { + if (!_jsxNamespace) { + _jsxNamespace = "React"; + if (compilerOptions.jsxFactory) { + _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); + if (_jsxFactoryEntity) { + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + } + } + else if (compilerOptions.reactNamespace) { + _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace); + } + } + return _jsxNamespace; + } + function getEmitResolver(sourceFile, cancellationToken) { + // Ensure we have all the type information in place for this file so that all the + // emitter questions of this resolver will return the right information. + getDiagnostics(sourceFile, cancellationToken); + return emitResolver; + } + function error(location, message, arg0, arg1, arg2) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); + diagnostics.add(diagnostic); + } + function createSymbol(flags, name) { + symbolCount++; + var symbol = (new Symbol(flags | 33554432 /* Transient */, name)); + symbol.checkFlags = 0; + return symbol; + } + function isTransientSymbol(symbol) { + return (symbol.flags & 33554432 /* Transient */) !== 0; + } + function getExcludedSymbolFlags(flags) { + var result = 0; + if (flags & 2 /* BlockScopedVariable */) + result |= 107455 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) + result |= 107454 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) + result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) + result |= 900095 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) + result |= 106927 /* FunctionExcludes */; + if (flags & 32 /* Class */) + result |= 899519 /* ClassExcludes */; + if (flags & 64 /* Interface */) + result |= 792968 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) + result |= 899327 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) + result |= 899967 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) + result |= 106639 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) + result |= 99263 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) + result |= 41919 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) + result |= 74687 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) + result |= 530920 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) + result |= 793064 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) + result |= 2097152 /* AliasExcludes */; + return result; + } + function recordMergedSymbol(target, source) { + if (!source.mergeId) { + source.mergeId = nextMergeId; + nextMergeId++; + } + mergedSymbols[source.mergeId] = target; + } + function cloneSymbol(symbol) { + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations.slice(0); + result.parent = symbol.parent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + recordMergedSymbol(result, symbol); + return result; + } + function mergeSymbol(target, source) { + if (!(target.flags & getExcludedSymbolFlags(source.flags))) { + if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { + // reset flag when merging instantiated module into value module that has only const enums + target.constEnumOnlyModule = false; + } + target.flags |= source.flags; + if (source.valueDeclaration && + (!target.valueDeclaration || + (target.valueDeclaration.kind === 233 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 233 /* ModuleDeclaration */))) { + // other kinds of value declarations take precedence over modules + target.valueDeclaration = source.valueDeclaration; + } + ts.addRange(target.declarations, source.declarations); + if (source.members) { + if (!target.members) + target.members = ts.createSymbolTable(); + mergeSymbolTable(target.members, source.members); + } + if (source.exports) { + if (!target.exports) + target.exports = ts.createSymbolTable(); + mergeSymbolTable(target.exports, source.exports); + } + recordMergedSymbol(target, source); + } + else if (target.flags & 1024 /* NamespaceModule */) { + 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + ts.forEach(target.declarations, function (node) { + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); + }); + } + } + function mergeSymbolTable(target, source) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + } + else { + if (!(targetSymbol.flags & 33554432 /* Transient */)) { + targetSymbol = cloneSymbol(targetSymbol); + target.set(id, targetSymbol); + } + mergeSymbol(targetSymbol, sourceSymbol); + } + }); + } + function mergeModuleAugmentation(moduleName) { + var moduleAugmentation = moduleName.parent; + if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { + // this is a combined symbol for multiple augmentations within the same file. + // its symbol already has accumulated information for all declarations + // so we need to add it just once - do the work only for first declaration + ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); + return; + } + if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { + mergeSymbolTable(globals, moduleAugmentation.symbol.exports); + } + else { + // find a module that about to be augmented + // do not validate names of augmentations that are defined in ambient context + var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) + ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found + : undefined; + var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); + if (!mainModule) { + return; + } + // obtain item referenced by 'export=' + mainModule = resolveExternalModuleSymbol(mainModule); + if (mainModule.flags & 1920 /* Namespace */) { + // if module symbol has already been merged - it is safe to use it. + // otherwise clone it + mainModule = mainModule.flags & 33554432 /* Transient */ ? mainModule : cloneSymbol(mainModule); + mergeSymbol(mainModule, moduleAugmentation.symbol); + } + else { + error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); + } + } + } + function addToSymbolTable(target, source, message) { + source.forEach(function (sourceSymbol, id) { + var targetSymbol = target.get(id); + if (targetSymbol) { + // Error on redeclarations + ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message)); + } + else { + target.set(id, sourceSymbol); + } + }); + function addDeclarationDiagnostic(id, message) { + return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; + } + } + function getSymbolLinks(symbol) { + if (symbol.flags & 33554432 /* Transient */) + return symbol; + var id = getSymbolId(symbol); + return symbolLinks[id] || (symbolLinks[id] = {}); + } + function getNodeLinks(node) { + var nodeId = getNodeId(node); + return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); + } + function getObjectFlags(type) { + return type.flags & 32768 /* Object */ ? type.objectFlags : 0; + } + function isGlobalSourceFile(node) { + return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + } + function getSymbol(symbols, name, meaning) { + if (meaning) { + var symbol = symbols.get(name); + if (symbol) { + ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + if (symbol.flags & meaning) { + return symbol; + } + if (symbol.flags & 2097152 /* Alias */) { + var target = resolveAlias(symbol); + // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors + if (target === unknownSymbol || target.flags & meaning) { + return symbol; + } + } + } + } + // return undefined if we can't find a symbol. + } + /** + * Get symbols that represent parameter-property-declaration as parameter and as property declaration + * @param parameter a parameterDeclaration node + * @param parameterName a name of the parameter to get the symbols for. + * @return a tuple of two symbols + */ + function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { + var constructorDeclaration = parameter.parent; + var classDeclaration = parameter.parent.parent; + var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); + var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); + if (parameterSymbol && propertySymbol) { + return [parameterSymbol, propertySymbol]; + } + ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + } + function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { + var declarationFile = ts.getSourceFileOfNode(declaration); + var useFile = ts.getSourceFileOfNode(usage); + if (declarationFile !== useFile) { + if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + (!compilerOptions.outFile && !compilerOptions.out) || + isInTypeQuery(usage) || + ts.isInAmbientContext(declaration)) { + // nodes are in different files and order cannot be determined + return true; + } + // declaration is after usage + // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) + if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { + return true; + } + var sourceFiles = host.getSourceFiles(); + return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + } + if (declaration.pos <= usage.pos) { + // declaration is before usage + if (declaration.kind === 176 /* BindingElement */) { + // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) + var errorBindingElement = ts.getAncestor(usage, 176 /* BindingElement */); + if (errorBindingElement) { + return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || + declaration.pos < errorBindingElement.pos; + } + // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226 /* VariableDeclaration */), usage); + } + else if (declaration.kind === 226 /* VariableDeclaration */) { + // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); + } + return true; + } + // declaration is after usage, but it can still be legal if usage is deferred: + // 1. inside an export specifier + // 2. inside a function + // 3. inside an instance property initializer, a reference to a non-instance property + // 4. inside a static property initializer, a reference to a static method in the same class + // or if usage is in a type context: + // 1. inside a type query (typeof in type position) + if (usage.parent.kind === 246 /* ExportSpecifier */) { + // export specifiers do not use the variable, they only make it available for use + return true; + } + var container = ts.getEnclosingBlockScopeContainer(declaration); + return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { + var container = ts.getEnclosingBlockScopeContainer(declaration); + switch (declaration.parent.parent.kind) { + case 208 /* VariableStatement */: + case 214 /* ForStatement */: + case 216 /* ForOfStatement */: + // variable statement/for/for-of statement case, + // use site should not be inside variable declaration (initializer of declaration or binding element) + if (isSameScopeDescendentOf(usage, declaration, container)) { + return true; + } + break; + } + // ForIn/ForOf case - use site should not be used in expression part + return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + } + function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { + return !!ts.findAncestor(usage, function (current) { + if (current === container) { + return "quit"; + } + if (ts.isFunctionLike(current)) { + return true; + } + var initializerOfProperty = current.parent && + current.parent.kind === 149 /* PropertyDeclaration */ && + current.parent.initializer === current; + if (initializerOfProperty) { + if (ts.getModifierFlags(current.parent) & 32 /* Static */) { + if (declaration.kind === 151 /* MethodDeclaration */) { + return true; + } + } + else { + var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !(ts.getModifierFlags(declaration) & 32 /* Static */); + if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { + return true; + } + } + } + }); + } + } + // 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, 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; + var errorLocation = location; + var grandparent; + var isInExternalModule = false; + 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 = lookup(location.locals, name, meaning)) { + var useResult = true; + if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { + // symbol lookup restrictions for function-like declarations + // - Type parameters of a function are in scope in the entire function declaration, including the parameter + // list and return type. However, local types are only in scope in the function body. + // - parameters are only in the scope of function body + // This restriction does not apply to JSDoc comment types because they are parented + // at a higher level than type parameters would normally be + if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 275 /* JSDocComment */) { + useResult = result.flags & 262144 /* TypeParameter */ + ? lastLocation === location.type || + lastLocation.kind === 146 /* Parameter */ || + lastLocation.kind === 145 /* TypeParameter */ + : false; + } + if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { + // parameters are visible only inside function body, parameter list and return type + // technically for parameter list case here we might mix parameters and variables declared in function, + // however it is detected separately when checking initializers of parameters + // to make sure that they reference no variables declared after them. + useResult = + lastLocation.kind === 146 /* Parameter */ || + (lastLocation === location.type && + result.valueDeclaration.kind === 146 /* Parameter */); + } + } + if (useResult) { + break loop; + } + else { + result = undefined; + } + } + } + switch (location.kind) { + case 265 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) + break; + isInExternalModule = true; + // falls through + case 233 /* ModuleDeclaration */: + var moduleExports = getSymbolOfNode(location).exports; + if (location.kind === 265 /* SourceFile */ || ts.isAmbientModule(location)) { + // It's an external module. First see if the module has an export default and if the local + // name of that export default matches. + if (result = moduleExports.get("default")) { + var localSymbol = ts.getLocalSymbolForExportDefault(result); + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { + break loop; + } + result = undefined; + } + // Because of module/namespace merging, a module's exports are in scope, + // yet we never want to treat an export specifier as putting a member in scope. + // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. + // Two things to note about this: + // 1. We have to check this without calling getSymbol. The problem with calling getSymbol + // on an export specifier is that it might find the export specifier itself, and try to + // resolve it as an alias. This will cause the checker to consider the export specifier + // a circular alias reference when it might not be. + // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* + // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, + // which is not the desired behavior. + var moduleExport = moduleExports.get(name); + if (moduleExport && + moduleExport.flags === 2097152 /* Alias */ && + ts.getDeclarationOfKind(moduleExport, 246 /* ExportSpecifier */)) { + break; + } + } + if (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */)) { + break loop; + } + break; + case 232 /* EnumDeclaration */: + if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { + break loop; + } + break; + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + // TypeScript 1.0 spec (April 2014): 8.4.1 + // Initializer expressions for instance member variables are evaluated in the scope + // of the class constructor body but are not permitted to reference parameters or + // local variables of the constructor. This effectively means that entities from outer scopes + // by the same name as a constructor parameter or local variable are inaccessible + // in initializer expressions for instance member variables. + if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { + var ctor = findConstructorDeclaration(location.parent); + if (ctor && ctor.locals) { + if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { + // Remember the property node, it will be used later to report appropriate error + propertyWithInvalidInitializer = location; + } + } + } + break; + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { + if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { + // ignore type parameters not declared in this container + result = undefined; + break; + } + if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { + // TypeScript 1.0 spec (April 2014): 3.4.1 + // The scope of a type parameter extends over the entire declaration with which the type + // parameter list is associated, with the exception of static member declarations in classes. + error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); + return undefined; + } + break loop; + } + if (location.kind === 199 /* ClassExpression */ && meaning & 32 /* Class */) { + var className = location.name; + if (className && name === className.escapedText) { + result = location.symbol; + break loop; + } + } + break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // + case 144 /* ComputedPropertyName */: + 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 = 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; + } + } + break; + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + break; + case 186 /* FunctionExpression */: + if (meaning & 3 /* Variable */ && name === "arguments") { + result = argumentsSymbol; + break loop; + } + if (meaning & 16 /* Function */) { + var functionName = location.name; + if (functionName && name === functionName.escapedText) { + result = location.symbol; + break loop; + } + } + break; + case 147 /* Decorator */: + // Decorators are resolved at the class declaration. Resolving at the parameter + // or member would result in looking up locals in the method. + // + // function y() {} + // class C { + // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. + // } + // + if (location.parent && location.parent.kind === 146 /* Parameter */) { + location = location.parent; + } + // + // function y() {} + // class C { + // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. + // } + // + if (location.parent && ts.isClassElement(location.parent)) { + location = location.parent; + } + break; + } + lastLocation = location; + location = location.parent; + } + if (result && nameNotFoundMessage && noUnusedIdentifiers) { + result.isReferenced = true; + } + if (!result) { + result = lookup(globals, name, meaning); + } + if (!result) { + if (nameNotFoundMessage) { + if (!errorLocation || + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForExtendingInterface(errorLocation) && + !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && + !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + var suggestion = void 0; + if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { + suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + if (suggestion) { + error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), ts.unescapeLeadingUnderscores(suggestion)); + } + } + if (!suggestion) { + error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg)); + } + suggestionCount++; + } + } + return undefined; + } + // Perform extra checks only if error reporting was requested + if (nameNotFoundMessage) { + if (propertyWithInvalidInitializer) { + // We have a match, but the reference occurred within a property initializer and the identifier also binds + // to a local variable in the constructor where the code will be emitted. + var propertyName = propertyWithInvalidInitializer.name; + error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg)); + return undefined; + } + // Only check for block-scoped variable if we have an error location and are looking for the + // name with variable meaning + // For example, + // declare module foo { + // interface bar {} + // } + // const foo/*1*/: foo/*2*/.bar; + // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: + // block-scoped variable and namespace module. However, only when we + // try to resolve name in /*1*/ which is used in variable position, + // we want to check for block-scoped + if (errorLocation && + (meaning & 2 /* BlockScopedVariable */ || + ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */))) { + var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); + if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { + checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); + } + } + // If we're in an external module, we can't reference value symbols created from UMD export declarations + if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { + var decls = result.declarations; + if (decls && decls.length === 1 && decls[0].kind === 236 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + } + } + } + return result; + } + function diagnosticName(nameArg) { + return typeof nameArg === "string" ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); + } + function isTypeParameterSymbolDeclaredInContainer(symbol, container) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.kind === 145 /* TypeParameter */ && decl.parent === container) { + return true; + } + } + return false; + } + function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { + if ((errorLocation.kind === 71 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { + return false; + } + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true); + var location = container; + while (location) { + if (ts.isClassLike(location.parent)) { + var classSymbol = getSymbolOfNode(location.parent); + if (!classSymbol) { + break; + } + // Check to see if a static member exists. + var constructorType = getTypeOfSymbol(classSymbol); + if (getPropertyOfType(constructorType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol)); + return true; + } + // No static member is present. + // Check if we're in an instance method and look for a relevant instance member. + if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + if (getPropertyOfType(instanceType, name)) { + error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); + return true; + } + } + } + location = location.parent; + } + return false; + } + function checkAndReportErrorForExtendingInterface(errorLocation) { + var expression = getEntityNameForExtendingInterface(errorLocation); + var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); + if (isError) { + error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + } + return isError; + } + /** + * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, + * but returns undefined if that expression is not an EntityNameExpression. + */ + function getEntityNameForExtendingInterface(node) { + switch (node.kind) { + case 71 /* Identifier */: + case 179 /* PropertyAccessExpression */: + return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; + case 201 /* ExpressionWithTypeArguments */: + ts.Debug.assert(ts.isEntityNameExpression(node.expression)); + return node.expression; + default: + return undefined; + } + } + function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { + if (meaning === 1920 /* Namespace */) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + var parent = errorLocation.parent; + if (symbol) { + if (ts.isQualifiedName(parent)) { + ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + var propName = parent.right.escapedText; + var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error(parent, ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, ts.unescapeLeadingUnderscores(name), ts.unescapeLeadingUnderscores(propName)); + return true; + } + } + error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + 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, ts.unescapeLeadingUnderscores(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, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { + if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { + var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); + if (symbol) { + error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkResolvedBlockScopedVariable(result, errorLocation) { + ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); + // Block-scoped variables cannot be used before their definition + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232 /* EnumDeclaration */) ? d : undefined; }); + 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(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 32 /* Class */) { + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + else if (result.flags & 256 /* RegularEnum */) { + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + } + } + } + /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. + * If at any point current node is equal to 'parent' node - return true. + * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. + */ + function isSameScopeDescendentOf(initial, parent, stopAt) { + return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + } + function getAnyImportSyntax(node) { + if (ts.isAliasSymbolDeclaration(node)) { + if (node.kind === 237 /* ImportEqualsDeclaration */) { + return node; + } + return ts.findAncestor(node, ts.isImportDeclaration); + } + } + function getDeclarationOfAliasSymbol(symbol) { + return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); + } + function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { + if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); + } + return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); + } + function getTargetOfImportClause(node, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); + if (moduleSymbol) { + var exportDefaultSymbol = void 0; + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + exportDefaultSymbol = moduleSymbol; + } + else { + var exportValue = moduleSymbol.exports.get("export="); + exportDefaultSymbol = exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") + : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + } + if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + return exportDefaultSymbol; + } + } + function getTargetOfNamespaceImport(node, dontResolveAlias) { + var moduleSpecifier = node.parent.parent.moduleSpecifier; + return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); + } + // This function creates a synthetic symbol that combines the value side of one symbol with the + // type/namespace side of another symbol. Consider this example: + // + // declare module graphics { + // interface Point { + // x: number; + // y: number; + // } + // } + // declare var graphics: { + // Point: new (x: number, y: number) => graphics.Point; + // } + // declare module "graphics" { + // export = graphics; + // } + // + // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' + // property with the type/namespace side interface 'Point'. + function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { + if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) { + return unknownSymbol; + } + if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { + return valueSymbol; + } + var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); + result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.parent = valueSymbol.parent || typeSymbol.parent; + if (valueSymbol.valueDeclaration) + result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) + result.members = typeSymbol.members; + if (valueSymbol.exports) + result.exports = valueSymbol.exports; + return result; + } + function getExportOfModule(symbol, name, dontResolveAlias) { + if (symbol.flags & 1536 /* Module */) { + return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); + } + } + function getPropertyOfVariable(symbol, name) { + if (symbol.flags & 3 /* Variable */) { + var typeAnnotation = symbol.valueDeclaration.type; + if (typeAnnotation) { + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + } + } + } + function getExternalModuleMember(node, specifier, dontResolveAlias) { + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); + if (targetSymbol) { + var name = specifier.propertyName || specifier.name; + if (name.escapedText) { + if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + return moduleSymbol; + } + var symbolFromVariable = void 0; + // First check if module was specified with "export=". If so, get the member from the resolved type + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); + } + else { + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + } + // if symbolFromVariable is export - get its final target + symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); + var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); + // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } + var symbol = symbolFromModule && symbolFromVariable ? + combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : + symbolFromModule || symbolFromVariable; + if (!symbol) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); + } + return symbol; + } + } + } + function getTargetOfImportSpecifier(node, dontResolveAlias) { + return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); + } + function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { + return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); + } + function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node, 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); + } + function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + switch (node.kind) { + case 237 /* ImportEqualsDeclaration */: + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); + case 239 /* ImportClause */: + return getTargetOfImportClause(node, dontRecursivelyResolve); + case 240 /* NamespaceImport */: + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); + case 242 /* ImportSpecifier */: + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); + case 246 /* ExportSpecifier */: + return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); + case 243 /* ExportAssignment */: + return getTargetOfExportAssignment(node, dontRecursivelyResolve); + case 236 /* NamespaceExportDeclaration */: + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + } + } + /** + * Indicates that a symbol is an alias that does not merge with a local declaration. + */ + function isNonLocalAlias(symbol, excludes) { + if (excludes === void 0) { excludes = 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */; } + return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; + } + function resolveSymbol(symbol, dontResolveAlias) { + var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); + return shouldResolve ? resolveAlias(symbol) : symbol; + } + function resolveAlias(symbol) { + ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); + var links = getSymbolLinks(symbol); + if (!links.target) { + links.target = resolvingSymbol; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + var target = getTargetOfAliasDeclaration(node); + if (links.target === resolvingSymbol) { + links.target = target || unknownSymbol; + } + else { + error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); + } + } + else if (links.target === resolvingSymbol) { + links.target = unknownSymbol; + } + return links.target; + } + function markExportAsReferenced(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target) { + var markAlias = target === unknownSymbol || + ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until + // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of + // the alias as an expression (which recursively takes us back here if the target references another alias). + function markAliasSymbolAsReferenced(symbol) { + var links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + var node = getDeclarationOfAliasSymbol(symbol); + ts.Debug.assert(!!node); + if (node.kind === 243 /* ExportAssignment */) { + // export default + checkExpressionCached(node.expression); + } + else if (node.kind === 246 /* ExportSpecifier */) { + // export { } or export { as foo } + checkExpressionCached(node.propertyName || node.name); + } + else if (ts.isInternalModuleImportEqualsDeclaration(node)) { + // import foo = + checkExpressionCached(node.moduleReference); + } + } + } + // This function is only for imports with entity names + function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { + // There are three things we might try to look for. In the following examples, + // the search term is enclosed in |...|: + // + // import a = |b|; // Namespace + // import a = |b.c|; // Value, type, namespace + // import a = |b.c|.d; // Namespace + if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + // Check for case 1 and 3 in the above example + if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 143 /* QualifiedName */) { + return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + else { + // Case 2 in above example + // entityName.kind could be a QualifiedName or a Missing identifier + ts.Debug.assert(entityName.parent.kind === 237 /* ImportEqualsDeclaration */); + return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + } + } + function getFullyQualifiedName(symbol) { + return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); + } + /** + * Resolves a qualified name and any involved aliases. + */ + function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { + if (ts.nodeIsMissing(name)) { + return undefined; + } + var symbol; + if (name.kind === 71 /* Identifier */) { + var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); + if (!symbol) { + return undefined; + } + } + else if (name.kind === 143 /* QualifiedName */ || name.kind === 179 /* PropertyAccessExpression */) { + var left = void 0; + if (name.kind === 143 /* QualifiedName */) { + left = name.left; + } + else if (name.kind === 179 /* PropertyAccessExpression */ && + (name.expression.kind === 185 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { + left = name.expression; + } + else { + // If the expression in property-access expression is not entity-name or parenthsizedExpression (e.g. it is a call expression), it won't be able to successfully resolve the name. + // This is the case when we are trying to do any language service operation in heritage clauses. By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression + // will attempt to checkPropertyAccessExpression to resolve symbol. + // i.e class C extends foo()./*do language service operation here*/B {} + return undefined; + } + var right = name.kind === 143 /* QualifiedName */ ? name.right : name.name; + var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); + if (!namespace || ts.nodeIsMissing(right)) { + return undefined; + } + else if (namespace === unknownSymbol) { + return namespace; + } + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); + if (!symbol) { + if (!ignoreErrors) { + error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); + } + return undefined; + } + } + else if (name.kind === 185 /* ParenthesizedExpression */) { + // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name. + // This is the case when we are trying to do any language service operation in heritage clauses. + // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol. + // i.e class C extends foo()./*do language service operation here*/B {} + return ts.isEntityNameExpression(name.expression) ? + resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : + undefined; + } + else { + ts.Debug.fail("Unknown entity name kind."); + } + 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) { + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); + } + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReferenceExpression.kind !== 9 /* StringLiteral */ && moduleReferenceExpression.kind !== 13 /* NoSubstitutionTemplateLiteral */) { + return; + } + var moduleReferenceLiteral = moduleReferenceExpression; + return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); + } + function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { + if (isForAugmentation === void 0) { isForAugmentation = false; } + if (moduleReference === 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(moduleReference, /*withAugmentations*/ true); + if (ambientModule) { + return ambientModule; + } + var isRelative = ts.isExternalModuleNameRelative(moduleReference); + var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); + var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); + var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + if (sourceFile) { + if (sourceFile.symbol) { + // merged symbol is module declaration symbol combined with all augmentations + return getMergedSymbol(sourceFile.symbol); + } + if (moduleNotFoundError) { + // report errors only if it was requested + error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); + } + return undefined; + } + if (patternAmbientModules) { + var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference); + if (pattern) { + return getMergedSymbol(pattern.symbol); + } + } + // May be an untyped module. If so, ignore resolutionDiagnostic. + if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { + if (isForAugmentation) { + var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; + error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); + } + else if (noImplicitAny && moduleNotFoundError) { + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. + return undefined; + } + if (moduleNotFoundError) { + // report errors only if it was requested + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } + else { + var tsExtension = ts.tryExtractTypeScriptExtension(moduleReference); + if (tsExtension) { + var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; + error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension)); + } + else { + error(errorNode, moduleNotFoundError, moduleReference); + } + } + } + return undefined; + } + // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, + // and an external module with no 'export =' declaration resolves to the module itself. + function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { + return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; + } + // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' + // 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, moduleReferenceExpression, dontResolveAlias) { + 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)); + } + return symbol; + } + function hasExportAssignmentSymbol(moduleSymbol) { + return moduleSymbol.exports.get("export=") !== undefined; + } + function getExportsOfModuleAsArray(moduleSymbol) { + return symbolsToArray(getExportsOfModule(moduleSymbol)); + } + function getExportsAndPropertiesOfModule(moduleSymbol) { + var exports = getExportsOfModuleAsArray(moduleSymbol); + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); + } + return exports; + } + function tryGetMemberInModuleExports(memberName, moduleSymbol) { + var symbolTable = getExportsOfModule(moduleSymbol); + if (symbolTable) { + return symbolTable.get(memberName); + } + } + function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) { + var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (!symbol) { + var exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); + } + } + return symbol; + } + function getExportsOfSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; + } + function getExportsOfModule(moduleSymbol) { + var links = getSymbolLinks(moduleSymbol); + return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol)); + } + /** + * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument + * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables + */ + function extendExportSymbols(target, source, lookupTable, exportNode) { + source && source.forEach(function (sourceSymbol, id) { + if (id === "default") + return; + var targetSymbol = target.get(id); + if (!targetSymbol) { + target.set(id, sourceSymbol); + if (lookupTable && exportNode) { + lookupTable.set(id, { + specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) + }); + } + } + else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { + var collisionTracker = lookupTable.get(id); + if (!collisionTracker.exportsWithDuplicate) { + collisionTracker.exportsWithDuplicate = [exportNode]; + } + else { + collisionTracker.exportsWithDuplicate.push(exportNode); + } + } + }); + } + function getExportsOfModuleWorker(moduleSymbol) { + var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || emptySymbols; + // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, + // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. + function visit(symbol) { + if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { + return; + } + visitedSymbols.push(symbol); + var symbols = ts.cloneMap(symbol.exports); + // All export * declarations are collected in an __export symbol by the binder + var exportStars = symbol.exports.get("__export" /* ExportStar */); + if (exportStars) { + var nestedSymbols = ts.createSymbolTable(); + var lookupTable_1 = ts.createMap(); + for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + var exportedSymbols = visit(resolvedModule); + extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); + } + lookupTable_1.forEach(function (_a, id) { + var exportsWithDuplicate = _a.exportsWithDuplicate; + // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself + if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { + return; + } + for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { + var node = exportsWithDuplicate_1[_i]; + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, ts.unescapeLeadingUnderscores(id))); + } + }); + extendExportSymbols(symbols, nestedSymbols); + } + return symbols; + } + } + function getMergedSymbol(symbol) { + var merged; + return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; + } + function getSymbolOfNode(node) { + return getMergedSymbol(node.symbol); + } + function getParentOfSymbol(symbol) { + return getMergedSymbol(symbol.parent); + } + function getExportSymbolOfValueSymbolIfExported(symbol) { + return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 + ? getMergedSymbol(symbol.exportSymbol) + : symbol; + } + function symbolIsValue(symbol) { + return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); + } + function findConstructorDeclaration(node) { + var members = node.members; + for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { + var member = members_2[_i]; + if (member.kind === 152 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + } + } + function createType(flags) { + var result = new Type(checker, flags); + typeCount++; + result.id = typeCount; + return result; + } + function createIntrinsicType(kind, intrinsicName) { + var type = createType(kind); + type.intrinsicName = intrinsicName; + return type; + } + function createBooleanType(trueFalseTypes) { + var type = getUnionType(trueFalseTypes); + type.flags |= 8 /* Boolean */; + type.intrinsicName = "boolean"; + return type; + } + function createObjectType(objectFlags, symbol) { + var type = createType(32768 /* Object */); + type.objectFlags = objectFlags; + type.symbol = symbol; + return type; + } + function createTypeofType() { + return getUnionType(ts.arrayFrom(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 + // with at least two underscores. The @ character indicates that the name is denoted by a well known ES + // Symbol instance. + function isReservedMemberName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) !== 95 /* _ */ && + name.charCodeAt(2) !== 64 /* at */; + } + function getNamedMembers(members) { + var result; + members.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + if (!result) + result = []; + if (symbolIsValue(symbol)) { + result.push(symbol); + } + } + }); + return result || ts.emptyArray; + } + function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + type.members = members; + type.properties = getNamedMembers(members); + type.callSignatures = callSignatures; + type.constructSignatures = constructSignatures; + if (stringIndexInfo) + type.stringIndexInfo = stringIndexInfo; + if (numberIndexInfo) + type.numberIndexInfo = numberIndexInfo; + return type; + } + function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { + return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function forEachSymbolTableInScope(enclosingDeclaration, callback) { + var result; + for (var location = enclosingDeclaration; location; location = location.parent) { + // 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 = callback(location.locals)) { + return result; + } + } + switch (location.kind) { + case 265 /* SourceFile */: + if (!ts.isExternalOrCommonJsModule(location)) { + break; + } + // falls through + case 233 /* ModuleDeclaration */: + if (result = callback(getSymbolOfNode(location).exports)) { + return result; + } + break; + } + } + return callback(globals); + } + function getQualifiedLeftMeaning(rightMeaning) { + // If we are looking in value space, the parent meaning is value, other wise it is namespace + return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; + } + function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { + function getAccessibleSymbolChainFromSymbolTable(symbols) { + return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); + } + function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { + if (ts.contains(visitedSymbolTables, symbols)) { + return undefined; + } + visitedSymbolTables.push(symbols); + var result = trySymbolTable(symbols); + visitedSymbolTables.pop(); + return result; + function canQualifySymbol(symbolFromSymbolTable, meaning) { + // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible + if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { + return true; + } + // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too + var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + return !!accessibleParent; + } + function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { + if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { + // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) + // and if symbolFromSymbolTable or alias resolution matches the symbol, + // check the symbol can be qualified, it is only then this symbol is accessible + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + canQualifySymbol(symbolFromSymbolTable, meaning); + } + } + function trySymbolTable(symbols) { + // If symbol is directly available by its name in the symbol table + if (isAccessible(symbols.get(symbol.escapedName))) { + return [symbol]; + } + // Check if symbol is any of the alias + return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { + if (symbolFromSymbolTable.flags & 2097152 /* Alias */ + && symbolFromSymbolTable.escapedName !== "export=" + && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { + if (!useOnlyExternalAliasing || + // Is this external alias, then use it to name + ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { + var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol)) { + return [symbolFromSymbolTable]; + } + // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain + // but only if the symbolFromSymbolTable can be qualified + var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; + if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { + return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); + } + } + } + }); + } + } + if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); + } + } + function needsQualification(symbol, enclosingDeclaration, meaning) { + var qualify = false; + forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { + // If symbol of this name is not available in the symbol table we are ok + var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + if (!symbolFromSymbolTable) { + // Continue to the next symbol table + return false; + } + // If the symbol with this name is present it should refer to the symbol + if (symbolFromSymbolTable === symbol) { + // No need to qualify + return true; + } + // Qualify if the symbol from symbol table has same meaning as expected + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + if (symbolFromSymbolTable.flags & meaning) { + qualify = true; + return true; + } + // Continue to the next symbol table + return false; + }); + return qualify; + } + function isPropertyOrMethodDeclarationSymbol(symbol) { + if (symbol.declarations && symbol.declarations.length) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + switch (declaration.kind) { + case 149 /* PropertyDeclaration */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + continue; + default: + return false; + } + } + return true; + } + return false; + } + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { + if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { + var initialSymbol = symbol; + var meaningToLook = meaning; + while (symbol) { + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (!hasAccessibleDeclarations) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + return hasAccessibleDeclarations; + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + meaningToLook = getQualifiedLeftMeaning(meaning); + symbol = getParentOfSymbol(symbol); + } + // This could be a symbol that is not exported in the external module + // or it could be a symbol from different external module that is not aliased and hence cannot be named + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + if (symbolExternalModule) { + var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + if (symbolExternalModule !== enclosingExternalModule) { + // name from different external module that is not visible + return { + accessibility: 2 /* CannotBeNamed */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: symbolToString(symbolExternalModule) + }; + } + } + // Just a local name that is not accessible + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + }; + } + return { accessibility: 0 /* Accessible */ }; + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); + } + } + function hasExternalModuleSymbol(declaration) { + return ts.isAmbientModule(declaration) || (declaration.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { + var aliasesToMakeVisible; + if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + return undefined; + } + return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; + function getIsDeclarationVisible(declaration) { + if (!isDeclarationVisible(declaration)) { + // Mark the unexported alias as visible if its parent is visible + // because these kind of aliases can be used to name types in declaration file + var anyImportSyntax = getAnyImportSyntax(declaration); + if (anyImportSyntax && + !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && + isDeclarationVisible(anyImportSyntax.parent)) { + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; + } + } + return true; + } + // Declaration is not visible + return false; + } + return true; + } + } + function isEntityNameVisible(entityName, enclosingDeclaration) { + // get symbol of the first identifier of the entityName + var meaning; + if (entityName.parent.kind === 162 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + // Typeof value + meaning = 107455 /* Value */ | 1048576 /* ExportValue */; + } + else if (entityName.kind === 143 /* QualifiedName */ || entityName.kind === 179 /* PropertyAccessExpression */ || + entityName.parent.kind === 237 /* ImportEqualsDeclaration */) { + // Left identifier from type reference or TypeAlias + // Entity name of the import declaration + meaning = 1920 /* Namespace */; + } + else { + // Type Reference or TypeAlias entity = Identifier + meaning = 793064 /* Type */; + } + var firstIdentifier = getFirstIdentifier(entityName); + var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + // Verify if the symbol is accessible + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { + accessibility: 1 /* NotAccessible */, + errorSymbolName: ts.getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + function writeKeyword(writer, kind) { + writer.writeKeyword(ts.tokenToString(kind)); + } + function writePunctuation(writer, kind) { + writer.writePunctuation(ts.tokenToString(kind)); + } + function writeSpace(writer) { + writer.writeSpace(" "); + } + function symbolToString(symbol, enclosingDeclaration, meaning) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); + }); + } + function signatureToString(signature, enclosingDeclaration, flags, kind) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); + }); + } + function typeToString(type, enclosingDeclaration, flags) { + 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); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(3 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); + var result = writer.getText(); + var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; + if (maxLength && result.length >= maxLength) { + return result.substr(0, maxLength - "...".length) + "..."; + } + return result; + function toNodeBuilderFlags(flags) { + var result = ts.NodeBuilderFlags.None; + if (!flags) { + return result; + } + if (flags & 8 /* NoTruncation */) { + result |= ts.NodeBuilderFlags.NoTruncation; + } + if (flags & 256 /* UseFullyQualifiedType */) { + result |= ts.NodeBuilderFlags.UseFullyQualifiedType; + } + if (flags & 4096 /* SuppressAnyReturnType */) { + result |= ts.NodeBuilderFlags.SuppressAnyReturnType; + } + if (flags & 1 /* WriteArrayAsGenericType */) { + result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; + } + if (flags & 64 /* WriteTypeArgumentsOfSignature */) { + result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; + } + return result; + } + } + function createNodeBuilder() { + return { + typeToTypeNode: function (type, enclosingDeclaration, flags) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = typeToTypeNodeHelper(type, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + 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) { + var context = createNodeBuilderContext(enclosingDeclaration, flags); + var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + } + }; + function createNodeBuilderContext(enclosingDeclaration, flags) { + return { + enclosingDeclaration: enclosingDeclaration, + flags: flags, + encounteredError: false, + symbolStack: undefined + }; + } + function typeToTypeNodeHelper(type, context) { + var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; + context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + if (!type) { + context.encounteredError = true; + return undefined; + } + if (type.flags & 1 /* Any */) { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + if (type.flags & 2 /* String */) { + return ts.createKeywordTypeNode(136 /* StringKeyword */); + } + if (type.flags & 4 /* Number */) { + return ts.createKeywordTypeNode(133 /* NumberKeyword */); + } + if (type.flags & 8 /* Boolean */) { + return ts.createKeywordTypeNode(122 /* BooleanKeyword */); + } + 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.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); + } + if (type.flags & (64 /* NumberLiteral */)) { + return ts.createLiteralTypeNode((ts.createLiteral(type.value))); + } + if (type.flags & 128 /* BooleanLiteral */) { + return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); + } + if (type.flags & 1024 /* Void */) { + return ts.createKeywordTypeNode(105 /* VoidKeyword */); + } + if (type.flags & 2048 /* Undefined */) { + return ts.createKeywordTypeNode(139 /* UndefinedKeyword */); + } + if (type.flags & 4096 /* Null */) { + return ts.createKeywordTypeNode(95 /* NullKeyword */); + } + if (type.flags & 8192 /* Never */) { + return ts.createKeywordTypeNode(130 /* NeverKeyword */); + } + if (type.flags & 512 /* ESSymbol */) { + return ts.createKeywordTypeNode(137 /* SymbolKeyword */); + } + if (type.flags & 16777216 /* NonPrimitive */) { + return ts.createKeywordTypeNode(134 /* ObjectKeyword */); + } + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { + if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + context.encounteredError = true; + } + } + return ts.createThis(); + } + var objectFlags = getObjectFlags(type); + if (objectFlags & 4 /* Reference */) { + ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + return typeReferenceToTypeNode(type); + } + 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 (!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); + } + 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)) { + context.encounteredError = true; + } + return undefined; + } + } + if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { + ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + // The type is an object literal type. + return createAnonymousTypeNode(type); + } + if (type.flags & 262144 /* Index */) { + var indexedType = type.type; + var indexTypeNode = typeToTypeNodeHelper(indexedType, context); + return ts.createTypeOperatorNode(indexTypeNode); + } + if (type.flags & 524288 /* IndexedAccess */) { + var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); + var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); + } + ts.Debug.fail("Should be unreachable."); + function createMappedTypeNodeFromType(type) { + ts.Debug.assert(!!(type.flags & 32768 /* Object */)); + var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; + var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; + 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; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || + shouldWriteTypeOfFunctionSymbol()) { + 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, context, 793064 /* Type */, /*expectsIdentifier*/ false); + return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); + } + else { + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + } + 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 + if (!context.symbolStack) { + context.symbolStack = []; + } + context.symbolStack.push(symbol); + var result = createTypeNodeFromObjectType(type); + context.symbolStack.pop(); + return result; + } + } + else { + // Anonymous types without a symbol are never circular. + return createTypeNodeFromObjectType(type); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + } + } + } + function createTypeNodeFromObjectType(type) { + if (type.objectFlags & 32 /* Mapped */) { + if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { + return createMappedTypeNodeFromType(type); + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var signature = resolved.callSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); + return signatureNode; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + var signature = resolved.constructSignatures[0]; + var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); + return signatureNode; + } + } + var savedFlags = context.flags; + context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + var members = createTypeNodesFromResolvedType(resolved); + context.flags = savedFlags; + var typeLiteralNode = ts.createTypeLiteralNode(members); + return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + } + 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.escapedName) ? symbolToName(symbol, context, 793064 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); + return entityName; + } + function typeReferenceToTypeNode(type) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType) { + 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + return ts.createTupleTypeNode(tupleConstituentNodes); + } + } + if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + return ts.createTupleTypeNode([]); + } + context.encounteredError = true; + return undefined; + } + else { + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + var qualifiedName = void 0; + if (outerTypeParameters) { + var length_2 = outerTypeParameters.length; + while (i < length_2) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // 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 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 { + qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); + } + } + } + } + var entityName = undefined; + var nameIdentifier = symbolToTypeReferenceName(type.symbol); + if (qualifiedName) { + ts.Debug.assert(!qualifiedName.right); + qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); + entityName = qualifiedName; + } + else { + entityName = nameIdentifier; + } + var typeArgumentNodes = void 0; + if (typeArguments.length > 0) { + var typeParameterCount = (type.target.typeParameters || ts.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 */, context)); + } + for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); + } + if (resolvedType.stringIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); + } + if (resolvedType.numberIndexInfo) { + typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); + } + var properties = resolvedType.properties; + if (!properties) { + return typeElements; + } + for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { + var propertySymbol = properties_1[_d]; + var propertyType = getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* 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 */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + typeElements.push(methodDeclaration); + } + } + else { + 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 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 indexingParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, name, + /*questionToken*/ undefined, indexerTypeNode, + /*initializer*/ undefined); + var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + return ts.createIndexSignature( + /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : 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 /* 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, context); + } + 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, context) { + var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); + var constraint = getConstraintFromTypeParameter(type); + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var defaultParameter = getDefaultFromTypeParameter(type); + var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); + } + function symbolToParameterDeclaration(parameterSymbol, context) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 146 /* Parameter */); + if (isTransientSymbol(parameterSymbol) && parameterSymbol.isRestParameter) { + // special-case synthetic rest parameters in JS files + return ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, parameterSymbol.isRestParameter ? ts.createToken(24 /* DotDotDotToken */) : undefined, "args", + /*questionToken*/ undefined, typeToTypeNodeHelper(anyArrayType, context), + /*initializer*/ undefined); + } + var modifiers = parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var dotDotDotToken = ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var name = parameterDeclaration.name ? + parameterDeclaration.name.kind === 71 /* Identifier */ ? + ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : + ts.unescapeLeadingUnderscores(parameterSymbol.escapedName); + var questionToken = isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var parameterType = getTypeOfSymbol(parameterSymbol); + 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, 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 || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); + ts.Debug.assert(chain && chain.length > 0); + } + else { + chain = [symbol]; + } + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(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 typeParameterNodes; + if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { + var parentSymbol = chain[index - 1]; + var typeParameters = void 0; + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); + } + else { + var targetSymbol = getTargetSymbol(parentSymbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + } + } + typeParameterNodes = mapToTypeNodes(typeParameters, context); + } + 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. */ + function getSymbolChain(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var parentSymbol; + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + parentSymbol = parent; + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + } + } + } + if (accessibleSymbolChain) { + return accessibleSymbolChain; + } + if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + return [symbol]; + } + } + } + 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 ts.unescapeLeadingUnderscores(symbol.escapedName); + } + } + function typePredicateToString(typePredicate, enclosingDeclaration, flags) { + return ts.usingSingleLineStringWriter(function (writer) { + getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); + }); + } + function formatUnionTypes(types) { + var result = []; + var flags = 0; + for (var i = 0; i < types.length; i++) { + var t = types[i]; + flags |= t.flags; + if (!(t.flags & 6144 /* Nullable */)) { + if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { + 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); + } + } + if (flags & 4096 /* Null */) + result.push(nullType); + if (flags & 2048 /* Undefined */) + result.push(undefinedType); + return result || types; + } + function visibilityToString(flags) { + if (flags === 8 /* Private */) { + return "private"; + } + if (flags === 16 /* Protected */) { + return "protected"; + } + return "public"; + } + function getTypeAliasForTypeLiteral(type) { + if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168 /* ParenthesizedType */; }); + if (node.kind === 231 /* TypeAliasDeclaration */) { + return getSymbolOfNode(node); + } + } + return undefined; + } + function isTopLevelInExternalModuleAugmentation(node) { + return node && node.parent && + node.parent.kind === 234 /* ModuleBlock */ && + ts.isExternalModuleAugmentation(node.parent.parent); + } + function literalTypeToString(type) { + 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]; + 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); + } + switch (declaration.kind) { + case 199 /* ClassExpression */: + return "(Anonymous class)"; + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return "(Anonymous function)"; + } + } + return ts.unescapeLeadingUnderscores(symbol.escapedName); + } + function getSymbolDisplayBuilder() { + /** + * Writes only the name of the symbol out to the writer. Uses the original source text + * for the name of the symbol if it is available to match how the user wrote the name. + */ + function appendSymbolNameOnly(symbol, writer) { + writer.writeSymbol(getNameOfSymbol(symbol), symbol); + } + /** + * Writes a property access or element access with the name of the symbol out to the writer. + * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, + * ensuring that any names written with literals use element accesses. + */ + function appendPropertyOrElementAccessForSymbol(symbol, writer) { + var symbolName = getNameOfSymbol(symbol); + var firstChar = symbolName.charCodeAt(0); + var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); + if (needsElementAccess) { + writePunctuation(writer, 21 /* OpenBracketToken */); + if (ts.isSingleOrDoubleQuote(firstChar)) { + writer.writeStringLiteral(symbolName); + } + else { + writer.writeSymbol(symbolName, symbol); + } + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else { + writePunctuation(writer, 23 /* DotToken */); + writer.writeSymbol(symbolName, symbol); + } + } + /** + * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope + * Meaning needs to be specified if the enclosing declaration is given + */ + function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { + var parentSymbol; + function appendParentTypeArgumentsAndSymbolName(symbol) { + if (parentSymbol) { + // Write type arguments of instantiated class/interface here + if (flags & 1 /* WriteTypeParametersOrArguments */) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); + } + else { + buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); + } + } + appendPropertyOrElementAccessForSymbol(symbol, writer); + } + else { + appendSymbolNameOnly(symbol, writer); + } + parentSymbol = symbol; + } + // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // this to determine if an import it has previously seen (and not written out) needs + // to be written to the file once the walk of the tree is complete. + // + // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree + // up front (for example, during checking) could determine if we need to emit the imports + // and we could then access that data during declaration emit. + writer.trackSymbol(symbol, enclosingDeclaration, meaning); + /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ + function walkSymbol(symbol, meaning, endOfChain) { + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); + if (!accessibleSymbolChain || + needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { + // Go up and add our parent. + var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent) { + walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + } + } + if (accessibleSymbolChain) { + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; + appendParentTypeArgumentsAndSymbolName(accessibleSymbol); + } + } + else if ( + // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. + endOfChain || + // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) + !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + // Get qualified name if the symbol is not a type parameter + // and there is an enclosing declaration or we specifically + // asked for it + var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; + var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; + if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { + walkSymbol(symbol, meaning, /*endOfChain*/ true); + } + else { + appendParentTypeArgumentsAndSymbolName(symbol); + } + } + function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { + var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); + var inObjectTypeLiteral = false; + return writeType(type, globalFlags); + function writeType(type, flags) { + var nextFlags = flags & ~1024 /* InTypeAlias */; + // Write undefined/null type as any + if (type.flags & 16793231 /* Intrinsic */) { + // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving + writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) + ? "any" + : type.intrinsicName); + } + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + if (inObjectTypeLiteral) { + writer.reportInaccessibleThisError(); + } + writer.writeKeyword("this"); + } + else if (getObjectFlags(type) & 4 /* Reference */) { + writeTypeReference(type, nextFlags); + } + 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 & (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); + } + else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); + } + else if (type.flags & 196608 /* UnionOrIntersection */) { + writeUnionOrIntersectionType(type, nextFlags); + } + else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { + writeAnonymousType(type, nextFlags); + } + else if (type.flags & 96 /* StringOrNumberLiteral */) { + writer.writeStringLiteral(literalTypeToString(type)); + } + else if (type.flags & 262144 /* Index */) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + writer.writeKeyword("keyof"); + writeSpace(writer); + writeType(type.type, 128 /* InElementType */); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + } + else if (type.flags & 524288 /* IndexedAccess */) { + writeType(type.objectType, 128 /* InElementType */); + writePunctuation(writer, 21 /* OpenBracketToken */); + writeType(type.indexType, 0 /* None */); + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else { + // Should never get here + // { ... } + writePunctuation(writer, 17 /* OpenBraceToken */); + writeSpace(writer); + writePunctuation(writer, 24 /* DotDotDotToken */); + writeSpace(writer); + writePunctuation(writer, 18 /* CloseBraceToken */); + } + } + function writeTypeList(types, delimiter) { + for (var i = 0; i < types.length; i++) { + if (i > 0) { + if (delimiter !== 26 /* CommaToken */) { + writeSpace(writer); + } + writePunctuation(writer, delimiter); + writeSpace(writer); + } + writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); + } + } + function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { + // Unnamed function expressions and arrow functions have reserved names that we don't want to display + if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { + buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + } + if (pos < end) { + writePunctuation(writer, 27 /* LessThanToken */); + writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); + pos++; + while (pos < end) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + writeType(typeArguments[pos], 0 /* None */); + pos++; + } + writePunctuation(writer, 29 /* GreaterThanToken */); + } + } + function writeTypeReference(type, flags) { + var typeArguments = type.typeArguments || ts.emptyArray; + if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { + writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); + writePunctuation(writer, 21 /* OpenBracketToken */); + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else if (type.target.objectFlags & 8 /* Tuple */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); + writePunctuation(writer, 22 /* CloseBracketToken */); + } + else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 199 /* 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 + // type parameters. + var outerTypeParameters = type.target.outerTypeParameters; + var i = 0; + if (outerTypeParameters) { + var length_3 = outerTypeParameters.length; + while (i < length_3) { + // Find group of type arguments for type parameters with the same declaring container. + var start = i; + var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + do { + i++; + } while (i < length_3 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); + // 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)) { + writeSymbolTypeReference(parent, typeArguments, start, i, flags); + writePunctuation(writer, 23 /* DotToken */); + } + } + } + var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; + writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); + } + } + function writeUnionOrIntersectionType(type, flags) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + if (type.flags & 65536 /* Union */) { + writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); + } + else { + writeTypeList(type.types, 48 /* AmpersandToken */); + } + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + } + function writeAnonymousType(type, flags) { + var symbol = type.symbol; + if (symbol) { + // Always use 'typeof T' for type of class, enum, and module objects + if (symbol.flags & 32 /* Class */ && + !getBaseTypeVariableOfClass(symbol) && + !(symbol.valueDeclaration.kind === 199 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || + symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { + writeTypeOfSymbol(type, flags); + } + else if (shouldWriteTypeOfFunctionSymbol()) { + writeTypeOfSymbol(type, flags); + } + else if (ts.contains(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 + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); + } + else { + // Recursive usage, use any + writeKeyword(writer, 119 /* AnyKeyword */); + } + } + 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 = []; + } + var isConstructorObject = type.flags & 32768 /* Object */ && + getObjectFlags(type) & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & 32 /* Class */; + if (isConstructorObject) { + writeLiteralType(type, flags); + } + else { + symbolStack.push(symbol); + writeLiteralType(type, flags); + symbolStack.pop(); + } + } + } + else { + // Anonymous types with no symbol are never circular + writeLiteralType(type, flags); + } + function shouldWriteTypeOfFunctionSymbol() { + var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && + ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); + var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && + (symbol.parent || + ts.forEach(symbol.declarations, function (declaration) { + return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; + })); + if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { + // typeof is allowed only for static/non local functions + return !!(flags & 4 /* UseTypeOfFunction */) || + (ts.contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively + } + } + } + function writeTypeOfSymbol(type, typeFormatFlags) { + if (typeFormatFlags & 32768 /* InArrayType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + writeKeyword(writer, 103 /* TypeOfKeyword */); + writeSpace(writer); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); + if (typeFormatFlags & 32768 /* InArrayType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + } + function writePropertyWithModifiers(prop) { + if (isReadonlySymbol(prop)) { + writeKeyword(writer, 131 /* ReadonlyKeyword */); + writeSpace(writer); + } + buildSymbolDisplay(prop, writer); + if (prop.flags & 16777216 /* Optional */) { + writePunctuation(writer, 55 /* QuestionToken */); + } + } + function shouldAddParenthesisAroundFunctionType(callSignature, flags) { + if (flags & 128 /* InElementType */) { + return true; + } + else if (flags & 512 /* InFirstTypeArgument */) { + // Add parenthesis around function type for the first type argument to avoid ambiguity + var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? + callSignature.target.typeParameters : callSignature.typeParameters; + return typeParameters && typeParameters.length !== 0; + } + return false; + } + function writeLiteralType(type, flags) { + if (type.objectFlags & 32 /* Mapped */) { + if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { + writeMappedType(type); + return; + } + } + var resolved = resolveStructuredTypeMembers(type); + if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + writePunctuation(writer, 17 /* OpenBraceToken */); + writePunctuation(writer, 18 /* CloseBraceToken */); + return; + } + if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { + var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); + if (parenthesizeSignature) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); + if (parenthesizeSignature) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + return; + } + if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } + writeKeyword(writer, 94 /* NewKeyword */); + writeSpace(writer); + buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } + return; + } + } + var saveInObjectTypeLiteral = inObjectTypeLiteral; + inObjectTypeLiteral = true; + writePunctuation(writer, 17 /* OpenBraceToken */); + writer.writeLine(); + writer.increaseIndent(); + writeObjectLiteralType(resolved); + writer.decreaseIndent(); + writePunctuation(writer, 18 /* CloseBraceToken */); + inObjectTypeLiteral = saveInObjectTypeLiteral; + } + function writeObjectLiteralType(resolved) { + for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { + var signature = _c[_b]; + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); + buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); + for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { + var p = _e[_d]; + if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { + if (p.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { + writer.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(p.escapedName)); + } + } + var t = getTypeOfSymbol(p); + if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { + var signatures = getSignaturesOfType(t, 0 /* Call */); + for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { + var signature = signatures_2[_f]; + writePropertyWithModifiers(p); + buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + } + else { + writePropertyWithModifiers(p); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + } + } + function writeMappedType(type) { + writePunctuation(writer, 17 /* OpenBraceToken */); + writer.writeLine(); + writer.increaseIndent(); + if (type.declaration.readonlyToken) { + writeKeyword(writer, 131 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 21 /* OpenBracketToken */); + appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); + writeSpace(writer); + writeKeyword(writer, 92 /* InKeyword */); + writeSpace(writer); + writeType(getConstraintTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 22 /* CloseBracketToken */); + if (type.declaration.questionToken) { + writePunctuation(writer, 55 /* QuestionToken */); + } + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + writeType(getTemplateTypeFromMappedType(type), 0 /* None */); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + writer.decreaseIndent(); + writePunctuation(writer, 18 /* CloseBraceToken */); + } + } + function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { + buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); + } + } + function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { + appendSymbolNameOnly(tp.symbol, writer); + var constraint = getConstraintOfTypeParameter(tp); + if (constraint) { + writeSpace(writer); + writeKeyword(writer, 85 /* ExtendsKeyword */); + writeSpace(writer); + buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); + } + var defaultType = getDefaultFromTypeParameter(tp); + if (defaultType) { + writeSpace(writer); + writePunctuation(writer, 58 /* EqualsToken */); + writeSpace(writer); + buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { + var parameterNode = p.valueDeclaration; + if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { + writePunctuation(writer, 24 /* DotDotDotToken */); + } + if (parameterNode && ts.isBindingPattern(parameterNode.name)) { + buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + appendSymbolNameOnly(p, writer); + } + if (parameterNode && isOptionalParameter(parameterNode)) { + writePunctuation(writer, 55 /* QuestionToken */); + } + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + var type = getTypeOfSymbol(p); + if (parameterNode && isRequiredInitializedParameter(parameterNode)) { + type = getNullableType(type, 2048 /* Undefined */); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { + // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. + if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { + writePunctuation(writer, 17 /* OpenBraceToken */); + buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 18 /* CloseBraceToken */); + } + else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { + writePunctuation(writer, 21 /* OpenBracketToken */); + var elements = bindingPattern.elements; + buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); + if (elements && elements.hasTrailingComma) { + writePunctuation(writer, 26 /* CommaToken */); + } + writePunctuation(writer, 22 /* CloseBracketToken */); + } + } + function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isOmittedExpression(bindingElement)) { + return; + } + ts.Debug.assert(bindingElement.kind === 176 /* BindingElement */); + if (bindingElement.propertyName) { + writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + } + if (ts.isBindingPattern(bindingElement.name)) { + buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); + } + else { + if (bindingElement.dotDotDotToken) { + writePunctuation(writer, 24 /* DotDotDotToken */); + } + appendSymbolNameOnly(bindingElement.symbol, writer); + } + } + function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27 /* LessThanToken */); + buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); + writePunctuation(writer, 29 /* GreaterThanToken */); + } + } + function buildDisplayForCommaSeparatedList(list, writer, action) { + for (var i = 0; i < list.length; i++) { + if (i > 0) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + } + action(list[i]); + } + } + function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { + if (typeParameters && typeParameters.length) { + writePunctuation(writer, 27 /* LessThanToken */); + var flags = 512 /* InFirstTypeArgument */; + for (var i = 0; i < typeParameters.length; i++) { + if (i > 0) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + flags = 0 /* None */; + } + buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); + } + writePunctuation(writer, 29 /* GreaterThanToken */); + } + } + function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { + writePunctuation(writer, 19 /* OpenParenToken */); + if (thisParameter) { + buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); + } + for (var i = 0; i < parameters.length; i++) { + if (i > 0 || thisParameter) { + writePunctuation(writer, 26 /* CommaToken */); + writeSpace(writer); + } + buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); + } + writePunctuation(writer, 20 /* CloseParenToken */); + } + function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { + if (ts.isIdentifierTypePredicate(predicate)) { + writer.writeParameter(predicate.parameterName); + } + else { + writeKeyword(writer, 99 /* ThisKeyword */); + } + writeSpace(writer); + writeKeyword(writer, 126 /* IsKeyword */); + writeSpace(writer); + buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); + } + function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { + var returnType = getReturnTypeOfSignature(signature); + if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { + return; + } + if (flags & 16 /* WriteArrowStyleSignature */) { + writeSpace(writer); + writePunctuation(writer, 36 /* EqualsGreaterThanToken */); + } + else { + writePunctuation(writer, 56 /* ColonToken */); + } + writeSpace(writer); + if (signature.typePredicate) { + buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); + } + else { + buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); + } + } + function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { + if (kind === 1 /* Construct */) { + writeKeyword(writer, 94 /* NewKeyword */); + writeSpace(writer); + } + if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { + // Instantiated signature, write type arguments instead + // This is achieved by passing in the mapper separately + buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); + } + else { + buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); + } + buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); + buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); + } + function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { + if (info) { + if (info.isReadonly) { + writeKeyword(writer, 131 /* ReadonlyKeyword */); + writeSpace(writer); + } + writePunctuation(writer, 21 /* OpenBracketToken */); + writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + switch (kind) { + case 1 /* Number */: + writeKeyword(writer, 133 /* NumberKeyword */); + break; + case 0 /* String */: + writeKeyword(writer, 136 /* StringKeyword */); + break; + } + writePunctuation(writer, 22 /* CloseBracketToken */); + writePunctuation(writer, 56 /* ColonToken */); + writeSpace(writer); + buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); + writePunctuation(writer, 25 /* SemicolonToken */); + writer.writeLine(); + } + } + return _displayBuilder || (_displayBuilder = { + buildSymbolDisplay: buildSymbolDisplay, + buildTypeDisplay: buildTypeDisplay, + buildTypeParameterDisplay: buildTypeParameterDisplay, + buildTypePredicateDisplay: buildTypePredicateDisplay, + buildParameterDisplay: buildParameterDisplay, + buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, + buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, + buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, + buildSignatureDisplay: buildSignatureDisplay, + buildIndexSignatureDisplay: buildIndexSignatureDisplay, + buildReturnTypeDisplay: buildReturnTypeDisplay + }); + } + function isDeclarationVisible(node) { + if (node) { + var links = getNodeLinks(node); + if (links.isVisible === undefined) { + links.isVisible = !!determineIfDeclarationIsVisible(); + } + return links.isVisible; + } + return false; + function determineIfDeclarationIsVisible() { + switch (node.kind) { + case 176 /* BindingElement */: + return isDeclarationVisible(node.parent.parent); + case 226 /* VariableDeclaration */: + if (ts.isBindingPattern(node.name) && + !node.name.elements.length) { + // If the binding pattern is empty, this variable declaration is not visible + return false; + } + // falls through + case 233 /* ModuleDeclaration */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 228 /* FunctionDeclaration */: + case 232 /* EnumDeclaration */: + case 237 /* ImportEqualsDeclaration */: + // external module augmentation is always visible + if (ts.isExternalModuleAugmentation(node)) { + return true; + } + var parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) + if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && + !(node.kind !== 237 /* ImportEqualsDeclaration */ && parent.kind !== 265 /* SourceFile */ && ts.isInAmbientContext(parent))) { + return isGlobalSourceFile(parent); + } + // Exported members/ambient module elements (exception import declaration) are visible if parent is visible + return isDeclarationVisible(parent); + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { + // Private/protected properties/methods are not visible + return false; + } + // Public properties/methods are visible if its parents are visible, so: + // falls through + case 152 /* Constructor */: + case 156 /* ConstructSignature */: + case 155 /* CallSignature */: + case 157 /* IndexSignature */: + case 146 /* Parameter */: + case 234 /* ModuleBlock */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 163 /* TypeLiteral */: + case 159 /* TypeReference */: + case 164 /* ArrayType */: + case 165 /* TupleType */: + case 166 /* UnionType */: + case 167 /* IntersectionType */: + case 168 /* ParenthesizedType */: + return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible + case 239 /* ImportClause */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */: + return false; + // Type parameters are always visible + case 145 /* TypeParameter */: + // Source file and namespace export are always visible + case 265 /* SourceFile */: + case 236 /* NamespaceExportDeclaration */: + return true; + // Export assignments do not create name bindings outside the module + case 243 /* ExportAssignment */: + return false; + default: + return false; + } + } + } + function collectLinkedAliases(node) { + var exportSymbol; + if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { + exportSymbol = resolveName(node.parent, node.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, ts.Diagnostics.Cannot_find_name_0, node); + } + else if (node.parent.kind === 246 /* ExportSpecifier */) { + exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + var result = []; + if (exportSymbol) { + buildVisibleNodeList(exportSymbol.declarations); + } + return result; + function buildVisibleNodeList(declarations) { + ts.forEach(declarations, function (declaration) { + getNodeLinks(declaration).isVisible = true; + var resultNode = getAnyImportSyntax(declaration) || declaration; + if (!ts.contains(result, resultNode)) { + result.push(resultNode); + } + if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { + // Add the referenced top container visible + var internalModuleReference = declaration.moduleReference; + var firstIdentifier = getFirstIdentifier(internalModuleReference); + var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); + if (importSymbol) { + buildVisibleNodeList(importSymbol.declarations); + } + } + }); + } + } + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target, propertyName) { + var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + var length_4 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_4; i++) { + resolutionResults[i] = false; + } + return false; + } + resolutionTargets.push(target); + resolutionResults.push(/*items*/ true); + resolutionPropertyNames.push(propertyName); + return true; + } + function findResolutionCycleStartIndex(target, propertyName) { + for (var i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + return -1; + } + function hasType(target, propertyName) { + if (propertyName === 0 /* Type */) { + return getSymbolLinks(target).type; + } + if (propertyName === 2 /* DeclaredType */) { + return getSymbolLinks(target).declaredType; + } + if (propertyName === 1 /* ResolvedBaseConstructorType */) { + return target.resolvedBaseConstructorType; + } + if (propertyName === 3 /* ResolvedReturnType */) { + return target.resolvedReturnType; + } + ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + resolutionPropertyNames.pop(); + return resolutionResults.pop(); + } + function getDeclarationContainer(node) { + node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + switch (node.kind) { + case 226 /* VariableDeclaration */: + case 227 /* VariableDeclarationList */: + case 242 /* ImportSpecifier */: + case 241 /* NamedImports */: + case 240 /* NamespaceImport */: + case 239 /* ImportClause */: + return false; + default: + return true; + } + }); + return node && node.parent; + } + function getTypeOfPrototypeProperty(prototype) { + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', + // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. + // It is an error to explicitly declare a static property member with the name 'prototype'. + var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); + return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; + } + // Return the type of the given property in the given type, or undefined if no such property exists + function getTypeOfPropertyOfType(type, name) { + var prop = getPropertyOfType(type, name); + return prop ? getTypeOfSymbol(prop) : undefined; + } + function isTypeAny(type) { + return type && (type.flags & 1 /* Any */) !== 0; + } + // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been + // assigned by contextual typing. + function getTypeForBindingElementParent(node) { + var symbol = getSymbolOfNode(node); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + } + function isComputedNonLiteralName(name) { + return name.kind === 144 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + } + function getRestType(source, properties, symbol) { + source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); + if (source.flags & 8192 /* Never */) { + return emptyObjectType; + } + if (source.flags & 65536 /* Union */) { + return mapType(source, function (t) { return getRestType(t, properties, symbol); }); + } + var members = ts.createSymbolTable(); + var names = ts.createUnderscoreEscapedMap(); + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var name = properties_2[_i]; + names.set(ts.getTextOfPropertyName(name), true); + } + for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { + var prop = _b[_a]; + var inNamesToRemove = names.has(prop.escapedName); + 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.escapedName, prop); + } + } + var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); + return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + /** Return the inferred type for a binding element */ + function getTypeForBindingElement(declaration) { + var pattern = declaration.parent; + var parentType = getTypeForBindingElementParent(pattern.parent); + // If parent has the unknown (error) type, then so does this binding element + if (parentType === unknownType) { + return unknownType; + } + // If no type was specified or inferred for parent, or if the specified or inferred type is any, + // infer from the initializer of the binding element if one is present. Otherwise, go with the + // undefined or any type of the parent. + if (!parentType || isTypeAny(parentType)) { + if (declaration.initializer) { + return checkDeclarationInitializer(declaration); + } + return parentType; + } + var type; + if (pattern.kind === 174 /* ObjectBindingPattern */) { + if (declaration.dotDotDotToken) { + if (!isValidSpreadType(parentType)) { + error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); + return unknownType; + } + var literalMembers = []; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!element.dotDotDotToken) { + literalMembers.push(element.propertyName || element.name); + } + } + type = getRestType(parentType, literalMembers, declaration.symbol); + } + else { + // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) + var name = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name)) { + // computed properties with non-literal names are treated as 'any' + return anyType; + } + if (declaration.initializer) { + getContextualType(declaration.initializer); + } + // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, + // or otherwise the type of the string index signature. + var text = ts.getTextOfPropertyName(name); + var declaredType = getTypeOfPropertyOfType(parentType, text); + type = declaredType && getFlowTypeOfReference(declaration, declaredType) || + isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || + getIndexTypeOfType(parentType, 0 /* String */); + if (!type) { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); + return unknownType; + } + } + } + else { + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + if (declaration.dotDotDotToken) { + // Rest element has an array type with the same element type as the parent type + type = createArrayType(elementType); + } + else { + // Use specific property type when parent is a tuple or numeric index type when parent is an array + var propName = "" + ts.indexOf(pattern.elements, declaration); + type = isTupleLikeType(parentType) + ? getTypeOfPropertyOfType(parentType, propName) + : elementType; + if (!type) { + if (isTupleType(parentType)) { + error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); + } + else { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + } + return unknownType; + } + } + } + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { + type = getTypeWithFacts(type, 131072 /* NEUndefined */); + } + return declaration.initializer ? + getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : + type; + } + function getTypeForDeclarationFromJSDocComment(declaration) { + var jsdocType = ts.getJSDocType(declaration); + if (jsdocType) { + return getTypeFromTypeNode(jsdocType); + } + return undefined; + } + function isNullOrUndefined(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } + function isEmptyArrayLiteral(node) { + var expr = ts.skipParentheses(node); + return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; + } + function addOptionality(type, optional) { + return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; + } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + // A variable declared in a for..in statement is of type string, or of type keyof T when the + // right hand expression is of a type parameter type. + if (declaration.parent.parent.kind === 215 /* ForInStatement */) { + var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); + return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; + } + if (declaration.parent.parent.kind === 216 /* ForOfStatement */) { + // checkRightHandSideOfForOf will return undefined if the for-of expression type was + // missing properties/signatures required to get its iteratedType (like + // [Symbol.iterator] or next). This may be because we accessed properties from anyType, + // or it may have led to an error inside getElementTypeOfIterable. + var forOfStatement = declaration.parent.parent; + return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; + } + if (ts.isBindingPattern(declaration.parent)) { + return getTypeForBindingElement(declaration); + } + // Use type from type annotation if one is present + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + var declaredType = getTypeFromTypeNode(typeNode); + return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); + } + if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && + declaration.kind === 226 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } + } + if (declaration.kind === 146 /* Parameter */) { + var func = declaration.parent; + // For a parameter of a set accessor, use the type of the get accessor if one is present + if (func.kind === 154 /* SetAccessor */ && !ts.hasDynamicName(func)) { + var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153 /* GetAccessor */); + if (getter) { + var getterSignature = getSignatureFromDeclaration(getter); + var thisParameter = getAccessorThisParameter(func); + if (thisParameter && declaration === thisParameter) { + // Use the type from the *getter* + ts.Debug.assert(!thisParameter.type); + return getTypeOfSymbol(getterSignature.thisParameter); + } + return getReturnTypeOfSignature(getterSignature); + } + } + // Use contextual parameter type if one is available + var type = void 0; + if (declaration.symbol.escapedName === "this") { + type = getContextualThisParameterType(func); + } + else { + type = getContextuallyTypedParameterType(declaration); + } + if (type) { + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + } + } + // Use the type of the initializer expression if one is present + if (declaration.initializer) { + var type = checkDeclarationInitializer(declaration); + return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); + } + if (ts.isJsxAttribute(declaration)) { + // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. + // I.e is sugar for + return trueType; + } + // If it is a short-hand property assignment, use the type of the identifier + if (declaration.kind === 262 /* ShorthandPropertyAssignment */) { + return checkIdentifier(declaration.name); + } + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); + } + // No type specified and nothing can be inferred + return undefined; + } + function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { + 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 : + declaration.kind === 179 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 194 /* BinaryExpression */) : + undefined; + if (!expression) { + return unknownType; + } + if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { + if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 152 /* Constructor */) { + definedInConstructor = true; + } + else { + definedInMethod = true; + } + } + // 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)); + } + } + else if (!jsDocType) { + // If we don't have an explicit JSDoc type, get the type from the expression. + types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + } + } + 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 + // pattern. Otherwise, it is the type any. + function getTypeFromBindingElement(element, includePatternInType, reportErrors) { + if (element.initializer) { + return checkDeclarationInitializer(element); + } + if (ts.isBindingPattern(element.name)) { + return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); + } + if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { + reportImplicitAnyError(element, anyType); + } + return anyType; + } + // Return the type implied by an object binding pattern + function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + var hasComputedProperties = false; + ts.forEach(pattern.elements, function (e) { + var name = e.propertyName || e.name; + if (isComputedNonLiteralName(name)) { + // do not include computed properties in the implied type + hasComputedProperties = true; + return; + } + if (e.dotDotDotToken) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + return; + } + var text = ts.getTextOfPropertyName(name); + var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); + var symbol = createSymbol(flags, text); + symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); + symbol.bindingElement = e; + members.set(symbol.escapedName, symbol); + }); + var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + if (includePatternInType) { + result.pattern = pattern; + } + if (hasComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + return result; + } + // Return the type implied by an array binding pattern + function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { + var elements = pattern.elements; + var lastElement = ts.lastOrUndefined(elements); + if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; + } + // If the pattern has at least one element, and no rest element, then it should imply a tuple type. + var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); + var result = createTupleType(elementTypes); + if (includePatternInType) { + result = cloneTypeReference(result); + result.pattern = pattern; + } + return result; + } + // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself + // and without regard to its context (i.e. without regard any type annotation or initializer associated with the + // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] + // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is + // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring + // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of + // the parameter. + function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { + return pattern.kind === 174 /* ObjectBindingPattern */ + ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) + : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); + } + // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type + // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it + // is a bit more involved. For example: + // + // var [x, s = ""] = [1, "one"]; + // + // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the + // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the + // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. + function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { + var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + if (type) { + if (reportErrors) { + reportErrorsFromWidening(declaration, type); + } + // During a normal type check we'll never get to here with a property assignment (the check of the containing + // object literal uses a different path). We exclude widening only so that language services and type verification + // tools see the actual type. + if (declaration.kind === 261 /* PropertyAssignment */) { + return type; + } + return getWidenedType(type); + } + // Rest parameters default to type any[], other parameters default to type any + type = declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration + if (reportErrors && noImplicitAny) { + if (!declarationBelongsToPrivateAmbientMember(declaration)) { + reportImplicitAnyError(declaration, type); + } + } + return type; + } + function declarationBelongsToPrivateAmbientMember(declaration) { + var root = ts.getRootDeclaration(declaration); + var memberDeclaration = root.kind === 146 /* Parameter */ ? root.parent : root; + return isPrivateWithinAmbient(memberDeclaration); + } + function getTypeOfVariableOrParameterOrProperty(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + // Handle prototype property + if (symbol.flags & 4194304 /* Prototype */) { + return links.type = getTypeOfPrototypeProperty(symbol); + } + // Handle catch clause variables + var declaration = symbol.valueDeclaration; + if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { + return links.type = anyType; + } + // Handle export default expressions + if (declaration.kind === 243 /* ExportAssignment */) { + return links.type = checkExpression(declaration.expression); + } + if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + } + // Handle variable, parameter or property + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = void 0; + // Handle certain special assignment kinds, which happen to union across multiple declarations: + // * module.exports = expr + // * exports.p = expr + // * this.p = expr + // * className.prototype.method = expr + if (declaration.kind === 194 /* BinaryExpression */ || + declaration.kind === 179 /* PropertyAccessExpression */ && declaration.parent.kind === 194 /* BinaryExpression */) { + type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } + else { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); + } + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + return links.type; + } + function getAnnotatedAccessorType(accessor) { + if (accessor) { + if (accessor.kind === 153 /* GetAccessor */) { + var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); + return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); + } + else { + var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor); + return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); + } + } + return undefined; + } + function getAnnotatedAccessorThisParameter(accessor) { + var parameter = getAccessorThisParameter(accessor); + return parameter && parameter.symbol; + } + function getThisTypeOfDeclaration(declaration) { + return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); + } + function getTypeOfAccessors(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var getter = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 154 /* SetAccessor */); + if (getter && ts.isInJavaScriptFile(getter)) { + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); + if (jsDocType) { + return links.type = jsDocType; + } + } + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + var type = void 0; + // First try to see if the user specified a return type on the get-accessor. + var getterReturnType = getAnnotatedAccessorType(getter); + if (getterReturnType) { + type = getterReturnType; + } + else { + // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterParameterType = getAnnotatedAccessorType(setter); + if (setterParameterType) { + type = setterParameterType; + } + else { + // If there are no specified types, try to infer it from the body of the get accessor if it exists. + if (getter && getter.body) { + type = getReturnTypeFromBody(getter); + } + else { + if (noImplicitAny) { + if (setter) { + error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); + } + else { + ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); + error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } + } + type = anyType; + } + } + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); + error(getter_1, 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, symbolToString(symbol)); + } + } + links.type = type; + } + return links.type; + } + function getBaseTypeVariableOfClass(symbol) { + var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); + return baseConstructorType.flags & 540672 /* TypeVariable */ ? baseConstructorType : undefined; + } + function getTypeOfFuncClassEnumModule(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { + links.type = anyType; + } + else { + var type = createObjectType(16 /* Anonymous */, symbol); + if (symbol.flags & 32 /* Class */) { + var baseTypeVariable = getBaseTypeVariableOfClass(symbol); + links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; + } + else { + links.type = strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; + } + } + } + return links.type; + } + function getTypeOfEnumMember(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + links.type = getDeclaredTypeOfEnumMember(symbol); + } + return links.type; + } + function getTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + var targetSymbol = resolveAlias(symbol); + // It only makes sense to get the type of a value symbol. If the result of resolving + // the alias is not a value, then it has no type. To get the type associated with a + // type symbol, call getDeclaredTypeOfSymbol. + // This check is important because without it, a call to getTypeOfSymbol could end + // up recursively calling getTypeOfAlias, causing a stack overflow. + links.type = targetSymbol.flags & 107455 /* Value */ + ? getTypeOfSymbol(targetSymbol) + : unknownType; + } + return links.type; + } + function getTypeOfInstantiatedSymbol(symbol) { + var links = getSymbolLinks(symbol); + if (!links.type) { + if (symbolInstantiationDepth === 100) { + error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); + links.type = unknownType; + } + else { + if (!pushTypeResolution(symbol, 0 /* Type */)) { + return unknownType; + } + symbolInstantiationDepth++; + var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); + symbolInstantiationDepth--; + if (!popTypeResolution()) { + type = reportCircularityError(symbol); + } + links.type = type; + } + } + return links.type; + } + function reportCircularityError(symbol) { + // Check if variable has type annotation that circularly references the variable itself + if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + return unknownType; + } + // Otherwise variable has initializer that circularly references the variable itself + if (noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + return anyType; + } + function getTypeOfSymbol(symbol) { + if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { + return getTypeOfInstantiatedSymbol(symbol); + } + if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { + return getTypeOfVariableOrParameterOrProperty(symbol); + } + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getTypeOfEnumMember(symbol); + } + if (symbol.flags & 98304 /* Accessor */) { + return getTypeOfAccessors(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getTypeOfAlias(symbol); + } + return unknownType; + } + function isReferenceToType(type, target) { + return type !== undefined + && target !== undefined + && (getObjectFlags(type) & 4 /* Reference */) !== 0 + && type.target === target; + } + function getTargetType(type) { + return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; + } + function hasBaseType(type, checkBase) { + return check(type); + function check(type) { + if (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { + var target = getTargetType(type); + return target === checkBase || ts.forEach(getBaseTypes(target), check); + } + else if (type.flags & 131072 /* Intersection */) { + return ts.forEach(type.types, check); + } + } + } + // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. + // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set + // in-place and returns the same array. + function appendTypeParameters(typeParameters, declarations) { + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; + var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + if (!typeParameters) { + typeParameters = [tp]; + } + else if (!ts.contains(typeParameters, tp)) { + typeParameters.push(tp); + } + } + return typeParameters; + } + // Appends the outer type parameters of a node to a set of type parameters and returns the resulting set. The function + // allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set in-place and + // returns the same array. + function appendOuterTypeParameters(typeParameters, node) { + while (true) { + node = node.parent; + if (!node) { + return typeParameters; + } + if (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || + node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */ || + node.kind === 151 /* MethodDeclaration */ || node.kind === 187 /* ArrowFunction */) { + var declarations = node.typeParameters; + if (declarations) { + return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); + } + } + } + } + // The outer type parameters are those defined by enclosing generic classes, methods, or functions. + function getOuterTypeParametersOfClassOrInterface(symbol) { + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); + return appendOuterTypeParameters(/*typeParameters*/ undefined, declaration); + } + // The local type parameters are the combined set of type parameters from all declarations of the class, + // interface, or type alias. + function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { + var result; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 229 /* ClassDeclaration */ || + node.kind === 199 /* ClassExpression */ || node.kind === 231 /* TypeAliasDeclaration */) { + var declaration = node; + if (declaration.typeParameters) { + result = appendTypeParameters(result, declaration.typeParameters); + } + } + } + return result; + } + // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus + // its locally declared type parameters. + function getTypeParametersOfClassOrInterface(symbol) { + return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); + } + // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single + // rest parameter of type any[]. + function isMixinConstructorType(type) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length === 1) { + var s = signatures[0]; + return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; + } + return false; + } + function isConstructorType(type) { + if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { + return true; + } + if (type.flags & 540672 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type); + return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + } + return false; + } + function getBaseTypeNodeOfClass(type) { + return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); + } + function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var typeArgCount = ts.length(typeArgumentNodes); + var isJavaScript = ts.isInJavaScriptFile(location); + return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); + } + function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { + var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); + } + /** + * The base constructor of a class can resolve to + * * undefinedType if the class has no extends clause, + * * unknownType if an error occurred during resolution of the extends expression, + * * nullType if the extends expression is the null value, + * * anyType if the extends expression has type any, or + * * an object type with at least one construct signature. + */ + function getBaseConstructorTypeOfClass(type) { + if (!type.resolvedBaseConstructorType) { + var baseTypeNode = getBaseTypeNodeOfClass(type); + if (!baseTypeNode) { + return type.resolvedBaseConstructorType = undefinedType; + } + if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { + return unknownType; + } + var baseConstructorType = checkExpression(baseTypeNode.expression); + if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */)) { + // Resolving the members of a class requires us to resolve the base class of that class. + // We force resolution here such that we catch circularities now. + resolveStructuredTypeMembers(baseConstructorType); + } + if (!popTypeResolution()) { + error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); + return type.resolvedBaseConstructorType = unknownType; + } + if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { + error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); + return type.resolvedBaseConstructorType = unknownType; + } + type.resolvedBaseConstructorType = baseConstructorType; + } + return type.resolvedBaseConstructorType; + } + function getBaseTypes(type) { + if (!type.resolvedBaseTypes) { + if (type.objectFlags & 8 /* Tuple */) { + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + } + else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (type.symbol.flags & 32 /* Class */) { + resolveBaseTypesOfClass(type); + } + if (type.symbol.flags & 64 /* Interface */) { + resolveBaseTypesOfInterface(type); + } + } + else { + ts.Debug.fail("type must be class or interface"); + } + } + return type.resolvedBaseTypes; + } + function resolveBaseTypesOfClass(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); + if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { + 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 */ && + areAllOuterTypeParametersApplied(originalBaseType)) { + // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the + // 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, typeArgs); + } + else if (baseConstructorType.flags & 1 /* Any */) { + baseType = baseConstructorType; + } + else { + // The class derives from a "class-like" constructor function, check that we have at least one construct signature + // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere + // we check that all instantiated signatures return the same type. + var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); + if (!constructors.length) { + error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); + return; + } + baseType = getReturnTypeOfSignature(constructors[0]); + } + // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters + var valueDecl = type.symbol.valueDeclaration; + if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { + var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); + if (augTag) { + baseType = getTypeFromTypeNode(augTag.typeExpression.type); + } + } + if (baseType === unknownType) { + return; + } + if (!isValidBaseType(baseType)) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); + return; + } + if (type === baseType || hasBaseType(baseType, type)) { + error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + return; + } + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + function areAllOuterTypeParametersApplied(type) { + // An unapplied type parameter has its symbol still the same as the matching argument symbol. + // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. + var outerTypeParameters = type.outerTypeParameters; + if (outerTypeParameters) { + var last = outerTypeParameters.length - 1; + var typeArguments = type.typeArguments; + return outerTypeParameters[last].symbol !== typeArguments[last].symbol; + } + return true; + } + // A valid base type is `any`, any non-generic object type or intersection of non-generic + // object types. + function isValidBaseType(type) { + return type.flags & (32768 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || + type.flags & 131072 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + } + function resolveBaseTypesOfInterface(type) { + type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; + for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { + var node = _c[_b]; + var baseType = getTypeFromTypeNode(node); + if (baseType !== unknownType) { + if (isValidBaseType(baseType)) { + if (type !== baseType && !hasBaseType(baseType, type)) { + if (type.resolvedBaseTypes === ts.emptyArray) { + type.resolvedBaseTypes = [baseType]; + } + else { + type.resolvedBaseTypes.push(baseType); + } + } + else { + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + } + } + else { + error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); + } + } + } + } + } + } + // Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is + // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, + // and if none of the base interfaces have a "this" type. + function isIndependentInterface(symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 230 /* InterfaceDeclaration */) { + if (declaration.flags & 64 /* ContainsThis */) { + return false; + } + var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); + if (baseTypeNodes) { + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; + if (ts.isEntityNameExpression(node.expression)) { + var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); + if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { + return false; + } + } + } + } + } + } + return true; + } + function getDeclaredTypeOfClassOrInterface(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; + var type = links.declaredType = createObjectType(kind, symbol); + var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type + // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, + // property types inferred from initializers and method return types inferred from return statements are very hard + // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of + // "this" references. + if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { + type.objectFlags |= 4 /* Reference */; + type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); + type.outerTypeParameters = outerTypeParameters; + type.localTypeParameters = localTypeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.symbol = symbol; + type.thisType.constraint = type; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { + return unknownType; + } + var declaration = ts.findDeclaration(symbol, function (d) { return d.kind === 283 /* JSDocTypedefTag */ || d.kind === 231 /* TypeAliasDeclaration */; }); + var type = getTypeFromTypeNode(declaration.kind === 283 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type); + if (popTypeResolution()) { + var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + if (typeParameters) { + // Initialize the instantiation cache for generic type aliases. The declared type corresponds to + // an instantiation of the type alias with the type parameters supplied as type arguments. + links.typeParameters = typeParameters; + links.instantiations = ts.createMap(); + links.instantiations.set(getTypeListId(typeParameters), type); + } + } + else { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + } + links.declaredType = type; + } + return links.declaredType; + } + function isLiteralEnumMember(member) { + var expr = member.initializer; + if (!expr) { + return !ts.isInAmbientContext(member); + } + switch (expr.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return true; + case 192 /* PrefixUnaryExpression */: + return expr.operator === 38 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + case 71 /* Identifier */: + return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + default: + return false; + } + } + 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 (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { + return links.enumKind = 1 /* Literal */; + } + if (!isLiteralEnumMember(member)) { + hasNonLiteralMember = true; + } + } + } + } + return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; + } + 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) { + 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); + } + } + } + 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; + } + } + 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)); + if (!links.declaredType) { + links.declaredType = enumType; + } + } + return links.declaredType; + } + function getDeclaredTypeOfTypeParameter(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + var type = createType(16384 /* TypeParameter */); + type.symbol = symbol; + links.declaredType = type; + } + return links.declaredType; + } + function getDeclaredTypeOfAlias(symbol) { + var links = getSymbolLinks(symbol); + if (!links.declaredType) { + links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); + } + return links.declaredType; + } + function getDeclaredTypeOfSymbol(symbol) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getDeclaredTypeOfClassOrInterface(symbol); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getDeclaredTypeOfTypeAlias(symbol); + } + if (symbol.flags & 262144 /* TypeParameter */) { + return getDeclaredTypeOfTypeParameter(symbol); + } + if (symbol.flags & 384 /* Enum */) { + return getDeclaredTypeOfEnum(symbol); + } + if (symbol.flags & 8 /* EnumMember */) { + return getDeclaredTypeOfEnumMember(symbol); + } + if (symbol.flags & 2097152 /* Alias */) { + return getDeclaredTypeOfAlias(symbol); + } + return unknownType; + } + // A type reference is considered independent if each type argument is considered independent. + function isIndependentTypeReference(node) { + if (node.typeArguments) { + for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { + var typeNode = _a[_i]; + if (!isIndependentType(typeNode)) { + return false; + } + } + } + return true; + } + // A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string + // literal type, an array with an element type that is considered independent, or a type reference that is + // considered independent. + function isIndependentType(node) { + switch (node.kind) { + case 119 /* AnyKeyword */: + case 136 /* StringKeyword */: + case 133 /* NumberKeyword */: + case 122 /* BooleanKeyword */: + case 137 /* SymbolKeyword */: + case 134 /* ObjectKeyword */: + case 105 /* VoidKeyword */: + case 139 /* UndefinedKeyword */: + case 95 /* NullKeyword */: + case 130 /* NeverKeyword */: + case 173 /* LiteralType */: + return true; + case 164 /* ArrayType */: + return isIndependentType(node.elementType); + case 159 /* TypeReference */: + return isIndependentTypeReference(node); + } + return false; + } + // A variable-like declaration is considered independent (free of this references) if it has a type annotation + // that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any). + function isIndependentVariableLikeDeclaration(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return typeNode ? isIndependentType(typeNode) : !node.initializer; + } + // A function-like declaration is considered independent (free of this references) if it has a return type + // annotation that is considered independent and if each parameter is considered independent. + function isIndependentFunctionLikeDeclaration(node) { + if (node.kind !== 152 /* Constructor */) { + var typeNode = ts.getEffectiveReturnTypeNode(node); + if (!typeNode || !isIndependentType(typeNode)) { + return false; + } + } + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (!isIndependentVariableLikeDeclaration(parameter)) { + return false; + } + } + return true; + } + // Returns true if the class or interface member given by the symbol is free of "this" references. The + // function may return false for symbols that are actually free of "this" references because it is not + // feasible to perform a complete analysis in all cases. In particular, property members with types + // inferred from their initializers and function members with inferred return types are conservatively + // assumed not to be free of "this" references. + function isIndependentMember(symbol) { + if (symbol.declarations && symbol.declarations.length === 1) { + var declaration = symbol.declarations[0]; + if (declaration) { + switch (declaration.kind) { + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + return isIndependentVariableLikeDeclaration(declaration); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + return isIndependentFunctionLikeDeclaration(declaration); + } + } + } + return false; + } + // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, + // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. + function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { + var result = ts.createSymbolTable(); + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; + result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + } + return result; + } + function addInheritedMembers(symbols, baseSymbols) { + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); + } + } + } + function resolveDeclaredMembers(type) { + if (!type.declaredProperties) { + var symbol = type.symbol; + type.declaredProperties = getNamedMembers(symbol.members); + type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call" /* Call */)); + type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new" /* New */)); + type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + } + return type; + } + function getTypeWithThisArgument(type, thisArgument) { + if (getObjectFlags(type) & 4 /* Reference */) { + var target = type.target; + var typeArguments = type.typeArguments; + if (ts.length(target.typeParameters) === ts.length(typeArguments)) { + return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + } + } + else if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + } + return type; + } + function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { + var mapper; + var members; + var callSignatures; + var constructSignatures; + var stringIndexInfo; + var numberIndexInfo; + if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { + mapper = identityMapper; + members = source.symbol ? source.symbol.members : ts.createSymbolTable(source.declaredProperties); + callSignatures = source.declaredCallSignatures; + constructSignatures = source.declaredConstructSignatures; + stringIndexInfo = source.declaredStringIndexInfo; + numberIndexInfo = source.declaredNumberIndexInfo; + } + else { + mapper = createTypeMapper(typeParameters, typeArguments); + members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); + callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); + constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); + stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); + numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); + } + var baseTypes = getBaseTypes(source); + if (baseTypes.length) { + if (source.symbol && members === source.symbol.members) { + members = ts.createSymbolTable(source.declaredProperties); + } + var thisArgument = ts.lastOrUndefined(typeArguments); + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; + var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); + constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); + if (!stringIndexInfo) { + stringIndexInfo = instantiatedBaseType === anyType ? + createIndexInfo(anyType, /*isReadonly*/ false) : + getIndexInfoOfType(instantiatedBaseType, 0 /* String */); + } + numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); + } + } + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function resolveClassOrInterfaceMembers(type) { + resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray); + } + function resolveTypeReferenceMembers(type) { + var source = resolveDeclaredMembers(type.target); + var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); + var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + type.typeArguments : ts.concatenate(type.typeArguments, [type]); + resolveObjectTypeMembers(type, source, typeParameters, typeArguments); + } + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { + var sig = new Signature(checker); + sig.declaration = declaration; + sig.typeParameters = typeParameters; + sig.parameters = parameters; + sig.thisParameter = thisParameter; + sig.resolvedReturnType = resolvedReturnType; + sig.typePredicate = typePredicate; + sig.minArgumentCount = minArgumentCount; + sig.hasRestParameter = hasRestParameter; + sig.hasLiteralTypes = hasLiteralTypes; + return sig; + } + function cloneSignature(sig) { + return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + } + function getDefaultConstructSignatures(classType) { + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); + if (baseSignatures.length === 0) { + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + } + var baseTypeNode = getBaseTypeNodeOfClass(classType); + var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); + var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); + var typeArgCount = ts.length(typeArguments); + var result = []; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var baseSig = baseSignatures_1[_i]; + var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); + var typeParamCount = ts.length(baseSig.typeParameters); + if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { + var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); + sig.typeParameters = classType.localTypeParameters; + sig.resolvedReturnType = classType; + result.push(sig); + } + } + return result; + } + function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; + if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { + return s; + } + } + } + function findMatchingSignatures(signatureLists, signature, listIndex) { + if (signature.typeParameters) { + // We require an exact match for generic signatures, so we only return signatures from the first + // signature list and only if they have exact matches in the other signature lists. + if (listIndex > 0) { + return undefined; + } + for (var i = 1; i < signatureLists.length; i++) { + if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { + return undefined; + } + } + return [signature]; + } + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + // Allow matching non-generic signatures to have excess parameters and different return types + var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); + if (!match) { + return undefined; + } + if (!ts.contains(result, match)) { + (result || (result = [])).push(match); + } + } + return result; + } + // The signatures of a union type are those signatures that are present in each of the constituent types. + // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional + // parameters and may differ in return types. When signatures differ in return types, the resulting return + // type is the union of the constituent return types. + function getUnionSignatures(types, kind) { + var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); + var result = undefined; + for (var i = 0; i < signatureLists.length; i++) { + for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { + var signature = _a[_i]; + // Only process signatures with parameter lists that aren't already in the result list + if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { + var unionSignatures = findMatchingSignatures(signatureLists, signature, i); + if (unionSignatures) { + var s = signature; + // Union the result types when more than one signature matches + if (unionSignatures.length > 1) { + s = cloneSignature(signature); + if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); + } + // Clear resolved return type we possibly got from cloneSignature + s.resolvedReturnType = undefined; + s.unionSignatures = unionSignatures; + } + (result || (result = [])).push(s); + } + } + } + } + return result || ts.emptyArray; + } + function getUnionIndexInfo(types, kind) { + var indexTypes = []; + var isAnyReadonly = false; + 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; + } + indexTypes.push(indexInfo.type); + isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; + } + return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); + } + function resolveUnionTypeMembers(type) { + // The members and properties collections are empty for union types. To get all properties of a union + // type use getPropertiesOfType (only the language service uses this). + var callSignatures = getUnionSignatures(type.types, 0 /* Call */); + var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); + var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); + var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + function intersectTypes(type1, type2) { + return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); + } + function intersectIndexInfos(info1, info2) { + return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); + } + function unionSpreadIndexInfos(info1, info2) { + return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); + } + function includeMixinType(type, types, index) { + var mixedTypes = []; + for (var i = 0; i < types.length; i++) { + if (i === index) { + mixedTypes.push(type); + } + else if (isMixinConstructorType(types[i])) { + mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); + } + } + return getIntersectionType(mixedTypes); + } + function resolveIntersectionTypeMembers(type) { + // The members and properties collections are empty for intersection types. To get all properties of an + // intersection type use getPropertiesOfType (only the language service uses this). + var callSignatures = ts.emptyArray; + var constructSignatures = ts.emptyArray; + var stringIndexInfo; + var numberIndexInfo; + var types = type.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var _loop_3 = function (i) { + var t = type.types[i]; + // When an intersection type contains mixin constructor types, the construct signatures from + // those types are discarded and their return types are mixed into the return types of all + // other construct signatures in the intersection type. For example, the intersection type + // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature + // 'new(s: string) => A & B'. + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { + var signatures = getSignaturesOfType(t, 1 /* Construct */); + if (signatures.length && mixinCount > 0) { + signatures = ts.map(signatures, function (s) { + var clone = cloneSignature(s); + clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); + return clone; + }); + } + constructSignatures = ts.concatenate(constructSignatures, signatures); + } + callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); + stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); + numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); + }; + for (var i = 0; i < types.length; i++) { + _loop_3(i); + } + setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + /** + * Converts an AnonymousType to a ResolvedType. + */ + function resolveAnonymousTypeMembers(type) { + var symbol = type.symbol; + if (type.target) { + var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); + var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); + var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); + var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); + var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else if (symbol.flags & 2048 /* TypeLiteral */) { + var members = symbol.members; + var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); + var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); + var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); + var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); + setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + } + else { + // Combinations of function, class, enum and module + var members = emptySymbols; + var constructSignatures = ts.emptyArray; + var stringIndexInfo = undefined; + if (symbol.exports) { + members = getExportsOfSymbol(symbol); + } + if (symbol.flags & 32 /* Class */) { + var classType = getDeclaredTypeOfClassOrInterface(symbol); + constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)); + if (!constructSignatures.length) { + constructSignatures = getDefaultConstructSignatures(classType); + } + var baseConstructorType = getBaseConstructorTypeOfClass(classType); + if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { + members = ts.createSymbolTable(getNamedMembers(members)); + addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); + } + else if (baseConstructorType === anyType) { + stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); + } + } + var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; + setStructuredTypeMembers(type, members, ts.emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); + // We resolve the members before computing the signatures because a signature may use + // typeof with a qualified name expression that circularly references the type we are + // in the process of resolving (see issue #6072). The temporarily empty signature list + // will never be observed because a qualified name can't reference signatures. + if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { + type.callSignatures = getSignaturesOfSymbol(symbol); + } + } + } + /** Resolve the members of a mapped type { [P in K]: T } */ + function resolveMappedTypeMembers(type) { + var members = ts.createSymbolTable(); + var stringIndexInfo; + // Resolve upfront such that recursive references see an empty object type. + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); + // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, + // and T as the template type. + var typeParameter = getTypeParameterFromMappedType(type); + var constraintType = getConstraintTypeFromMappedType(type); + var templateType = getTemplateTypeFromMappedType(type); + var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' + var templateReadonly = !!type.declaration.readonlyToken; + var templateOptional = !!type.declaration.questionToken; + if (type.declaration.typeParameter.constraint.kind === 170 /* TypeOperator */) { + // We have a { [P in keyof T]: X } + for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { + var propertySymbol = _a[_i]; + addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); + } + if (getIndexInfoOfType(modifiersType, 0 /* String */)) { + addMemberForKeyType(stringType); + } + } + else { + // First, if the constraint type is a type parameter, obtain the base constraint. Then, + // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. + // Finally, iterate over the constituents of the resulting iteration type. + var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + forEachType(iterationType, addMemberForKeyType); + } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + function addMemberForKeyType(t, propertySymbol) { + // Create a mapper from T to the current iteration type constituent. Then, if the + // mapped type is itself an instantiated type, combine the iteration mapper with the + // instantiation mapper. + var iterationMapper = createTypeMapper([typeParameter], [t]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; + var propType = instantiateType(templateType, templateMapper); + // 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 = ts.escapeLeadingUnderscores(t.value); + var modifiersProp = getPropertyOfType(modifiersType, propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 16777216 /* Optional */); + var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; + prop.type = propType; + if (propertySymbol) { + prop.syntheticOrigin = propertySymbol; + prop.declarations = propertySymbol.declarations; + } + members.set(propName, prop); + } + else if (t.flags & 2 /* String */) { + stringIndexInfo = createIndexInfo(propType, templateReadonly); + } + } + } + function getTypeParameterFromMappedType(type) { + return type.typeParameter || + (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); + } + function getConstraintTypeFromMappedType(type) { + return type.constraintType || + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + } + function getTemplateTypeFromMappedType(type) { + return type.templateType || + (type.templateType = type.declaration.type ? + instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : + unknownType); + } + function getModifiersTypeFromMappedType(type) { + if (!type.modifiersType) { + var constraintDeclaration = type.declaration.typeParameter.constraint; + if (constraintDeclaration.kind === 170 /* TypeOperator */) { + // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check + // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves + // 'keyof T' to a literal union type and we can't recover T from that type. + type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + } + else { + // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, + // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', + // the modifiers type is T. Otherwise, the modifiers type is {}. + var declaredType = getTypeFromMappedTypeNode(type.declaration); + var constraint = getConstraintTypeFromMappedType(declaredType); + var extendedConstraint = constraint && constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + } + } + return type.modifiersType; + } + function isPartialMappedType(type) { + return getObjectFlags(type) & 32 /* Mapped */ && !!type.declaration.questionToken; + } + function isGenericMappedType(type) { + return getObjectFlags(type) & 32 /* Mapped */ && + maybeTypeOfKind(getConstraintTypeFromMappedType(type), 540672 /* TypeVariable */ | 262144 /* Index */); + } + function resolveStructuredTypeMembers(type) { + if (!type.members) { + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 4 /* Reference */) { + resolveTypeReferenceMembers(type); + } + else if (type.objectFlags & 3 /* ClassOrInterface */) { + resolveClassOrInterfaceMembers(type); + } + else if (type.objectFlags & 16 /* Anonymous */) { + resolveAnonymousTypeMembers(type); + } + else if (type.objectFlags & 32 /* Mapped */) { + resolveMappedTypeMembers(type); + } + } + else if (type.flags & 65536 /* Union */) { + resolveUnionTypeMembers(type); + } + else if (type.flags & 131072 /* Intersection */) { + resolveIntersectionTypeMembers(type); + } + } + return type; + } + /** Return properties of an object type or an empty array for other types */ + function getPropertiesOfObjectType(type) { + if (type.flags & 32768 /* Object */) { + return resolveStructuredTypeMembers(type).properties; + } + return ts.emptyArray; + } + /** If the given type is an object type and that type has a property by the given name, + * return the symbol for that property. Otherwise return undefined. + */ + function getPropertyOfObjectType(type, name) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + } + } + function getPropertiesOfUnionOrIntersectionType(type) { + if (!type.resolvedProperties) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var current = _a[_i]; + for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); + if (combinedProp) { + members.set(prop.escapedName, combinedProp); + } + } + } + // The properties of a union type are those that are present in all constituent types, so + // we only need to check the properties of the first type + if (type.flags & 65536 /* Union */) { + break; + } + } + type.resolvedProperties = getNamedMembers(members); + } + return type.resolvedProperties; + } + function getPropertiesOfType(type) { + type = getApparentType(type); + return type.flags & 196608 /* UnionOrIntersection */ ? + getPropertiesOfUnionOrIntersectionType(type) : + getPropertiesOfObjectType(type); + } + function getAllPossiblePropertiesOfType(type) { + if (type.flags & 65536 /* Union */) { + var props = ts.createSymbolTable(); + 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 escapedName = _c[_b].escapedName; + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(type, escapedName)); + } + } + } + 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) : + getBaseConstraintOfType(type); + } + function getConstraintOfTypeParameter(typeParameter) { + return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; + } + function getConstraintOfIndexedAccess(type) { + var baseObjectType = getBaseConstraintOfType(type.objectType); + var baseIndexType = getBaseConstraintOfType(type.indexType); + return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; + } + function getBaseConstraintOfType(type) { + if (type.flags & (540672 /* TypeVariable */ | 196608 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + if (constraint !== noConstraintType && constraint !== circularConstraintType) { + return constraint; + } + } + else if (type.flags & 262144 /* Index */) { + return stringType; + } + return undefined; + } + function hasNonCircularBaseConstraint(type) { + return getResolvedBaseConstraint(type) !== circularConstraintType; + } + /** + * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the + * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint + * circularly references the type variable. + */ + function getResolvedBaseConstraint(type) { + var typeStack; + var circular; + if (!type.resolvedBaseConstraint) { + typeStack = []; + var constraint = getBaseConstraint(type); + type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + } + return type.resolvedBaseConstraint; + function getBaseConstraint(t) { + if (ts.contains(typeStack, t)) { + circular = true; + return undefined; + } + typeStack.push(t); + var result = computeBaseConstraint(t); + typeStack.pop(); + return result; + } + function computeBaseConstraint(t) { + if (t.flags & 16384 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(t); + return t.isThisType ? constraint : + constraint ? getBaseConstraint(constraint) : undefined; + } + if (t.flags & 196608 /* UnionOrIntersection */) { + var types = t.types; + var baseTypes = []; + 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); + } + } + return t.flags & 65536 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 131072 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + undefined; + } + if (t.flags & 262144 /* Index */) { + return stringType; + } + if (t.flags & 524288 /* IndexedAccess */) { + var baseObjectType = getBaseConstraint(t.objectType); + var baseIndexType = getBaseConstraint(t.indexType); + var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; + return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; + } + return t; + } + } + function getApparentTypeOfIntersectionType(type) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + } + /** + * Gets the default type for a type parameter. + * + * If the type parameter is the result of an instantiation, this gets the instantiated + * default type of its target. If the type parameter has no default type, `undefined` + * is returned. + * + * This function *does not* perform a circularity check. + */ + function getDefaultFromTypeParameter(typeParameter) { + if (!typeParameter.default) { + if (typeParameter.target) { + var targetDefault = getDefaultFromTypeParameter(typeParameter.target); + typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; + } + else { + var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }); + typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; + } + } + return typeParameter.default === noConstraintType ? undefined : typeParameter.default; + } + /** + * For a type parameter, return the base constraint of the type parameter. For the string, number, + * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the + * type itself. Note that the apparent type of a union type is the union type itself. + */ + function getApparentType(type) { + var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 262178 /* StringLike */ ? globalStringType : + t.flags & 84 /* NumberLike */ ? globalNumberType : + t.flags & 136 /* BooleanLike */ ? globalBooleanType : + t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t; + } + function createUnionOrIntersectionProperty(containingType, name) { + var props; + var types = containingType.types; + var isUnion = containingType.flags & 65536 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; + // Flags we want to propagate to the result if they exist in all source symbols + var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; + var syntheticFlag = 4 /* SyntheticMethod */; + var checkFlags = 0; + 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { + commonFlags &= prop.flags; + if (!props) { + props = [prop]; + } + else if (!ts.contains(props, prop)) { + props.push(prop); + } + checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + if (!isMethodLike(prop)) { + syntheticFlag = 2 /* SyntheticProperty */; + } + } + else if (isUnion) { + checkFlags |= 16 /* Partial */; + } + } + } + if (!props) { + return undefined; + } + if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + return props[0]; + } + var propTypes = []; + var declarations = []; + var commonType = undefined; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; + if (prop.declarations) { + ts.addRange(declarations, prop.declarations); + } + var type = getTypeOfSymbol(prop); + if (!commonType) { + commonType = type; + } + else if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } + propTypes.push(type); + } + var result = createSymbol(4 /* Property */ | commonFlags, name); + result.checkFlags = syntheticFlag | checkFlags; + result.containingType = containingType; + result.declarations = declarations; + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + return result; + } + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { + var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable()); + var property = properties.get(name); + if (!property) { + property = createUnionOrIntersectionProperty(type, name); + if (property) { + properties.set(name, property); + } + } + return property; + } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + 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 + * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from + * Object and Function as appropriate. + * + * @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, name) { + type = getApparentType(type); + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + var symbol = resolved.members.get(name); + if (symbol && symbolIsValue(symbol)) { + return symbol; + } + if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { + var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); + if (symbol_1) { + return symbol_1; + } + } + return getPropertyOfObjectType(globalObjectType, name); + } + if (type.flags & 196608 /* UnionOrIntersection */) { + return getPropertyOfUnionOrIntersectionType(type, name); + } + return undefined; + } + function getSignaturesOfStructuredType(type, kind) { + if (type.flags & 229376 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; + } + return ts.emptyArray; + } + /** + * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and + * maps primitive types and type parameters are to their apparent types. + */ + function getSignaturesOfType(type, kind) { + return getSignaturesOfStructuredType(getApparentType(type), kind); + } + function getIndexInfoOfStructuredType(type, kind) { + if (type.flags & 229376 /* StructuredType */) { + var resolved = resolveStructuredTypeMembers(type); + return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; + } + } + function getIndexTypeOfStructuredType(type, kind) { + var info = getIndexInfoOfStructuredType(type, kind); + return info && info.type; + } + // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexInfoOfType(type, kind) { + return getIndexInfoOfStructuredType(getApparentType(type), kind); + } + // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and + // maps primitive types and type parameters are to their apparent types. + function getIndexTypeOfType(type, kind) { + return getIndexTypeOfStructuredType(getApparentType(type), kind); + } + function getImplicitIndexTypeOfType(type, kind) { + if (isObjectLiteralType(type)) { + var propTypes = []; + for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + propTypes.push(getTypeOfSymbol(prop)); + } + } + if (propTypes.length) { + return getUnionType(propTypes, /*subtypeReduction*/ true); + } + } + return undefined; + } + // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual + // type checking functions). + function getTypeParametersFromDeclaration(declaration) { + var result; + ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { + var tp = getDeclaredTypeOfTypeParameter(node.symbol); + if (!ts.contains(result, tp)) { + if (!result) { + result = []; + } + result.push(tp); + } + }); + return result; + } + function symbolsToArray(symbols) { + var result = []; + symbols.forEach(function (symbol, id) { + if (!isReservedMemberName(id)) { + result.push(symbol); + } + }); + return result; + } + function isJSDocOptionalParameter(node) { + if (ts.isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 272 /* JSDocOptionalType */) { + return true; + } + var paramTags = ts.getJSDocParameterTags(node); + if (paramTags) { + for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { + var paramTag = paramTags_1[_i]; + if (paramTag.isBracketed) { + return true; + } + if (paramTag.typeExpression) { + return paramTag.typeExpression.type.kind === 272 /* JSDocOptionalType */; + } + } + } + } + } + function tryFindAmbientModule(moduleName, withAugmentations) { + if (ts.isExternalModuleNameRelative(moduleName)) { + return undefined; + } + var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); + // merged symbol is module declaration symbol combined with all augmentations + return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; + } + function isOptionalParameter(node) { + if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + return true; + } + if (node.initializer) { + var signatureDeclaration = node.parent; + var signature = getSignatureFromDeclaration(signatureDeclaration); + var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + ts.Debug.assert(parameterIndex >= 0); + return parameterIndex >= signature.minArgumentCount; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } + return false; + } + function createTypePredicateFromTypePredicateNode(node) { + var parameterName = node.parameterName; + if (parameterName.kind === 71 /* Identifier */) { + return { + kind: 1 /* Identifier */, + parameterName: parameterName ? parameterName.escapedText : undefined, + parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, + type: getTypeFromTypeNode(node.type) + }; + } + else { + return { + kind: 0 /* This */, + type: getTypeFromTypeNode(node.type) + }; + } + } + /** + * Gets the minimum number of type arguments needed to satisfy all non-optional type + * parameters. + */ + function getMinTypeArgumentCount(typeParameters) { + var minTypeArgumentCount = 0; + if (typeParameters) { + for (var i = 0; i < typeParameters.length; i++) { + if (!getDefaultFromTypeParameter(typeParameters[i])) { + minTypeArgumentCount = i + 1; + } + } + } + return minTypeArgumentCount; + } + /** + * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined + * when a default type is supplied, a new array will be created and returned. + * + * @param typeArguments The supplied type arguments. + * @param typeParameters The requested type parameters. + * @param minTypeArgumentCount The minimum number of required type arguments. + */ + function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { + var numTypeParameters = ts.length(typeParameters); + if (numTypeParameters) { + var numTypeArguments = ts.length(typeArguments); + var isJavaScript = ts.isInJavaScriptFile(location); + if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { + if (!typeArguments) { + typeArguments = []; + } + // Map an unsatisfied type parameter with a default type. + // If a type parameter does not have a default type, or if the default type + // is a forward reference, the empty object type is used. + for (var i = numTypeArguments; i < numTypeParameters; i++) { + typeArguments[i] = getDefaultTypeArgumentType(isJavaScript); + } + for (var i = numTypeArguments; i < numTypeParameters; i++) { + var mapper = createTypeMapper(typeParameters, typeArguments); + var defaultType = getDefaultFromTypeParameter(typeParameters[i]); + typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScript); + } + } + } + return typeArguments; + } + function getSignatureFromDeclaration(declaration) { + var links = getNodeLinks(declaration); + if (!links.resolvedSignature) { + var parameters = []; + var hasLiteralTypes = false; + var minArgumentCount = 0; + var thisParameter = undefined; + var hasThisParameter = void 0; + var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); + var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + // If this is a JSDoc construct signature, then skip the first parameter in the + // parameter list. The first parameter represents the return type of the construct + // signature. + for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { + var param = declaration.parameters[i]; + var paramSymbol = param.symbol; + // Include parameter symbol instead of property symbol in the signature + if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { + var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 107455 /* Value */, undefined, undefined); + paramSymbol = resolvedSymbol; + } + if (i === 0 && paramSymbol.escapedName === "this") { + hasThisParameter = true; + thisParameter = param.symbol; + } + else { + parameters.push(paramSymbol); + } + if (param.type && param.type.kind === 173 /* LiteralType */) { + hasLiteralTypes = true; + } + // Record a new minimum argument count if this is not an optional parameter + var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !param.type || + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; + if (!isOptionalParameter_1) { + minArgumentCount = parameters.length; + } + } + // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation + if ((declaration.kind === 153 /* GetAccessor */ || declaration.kind === 154 /* SetAccessor */) && + !ts.hasDynamicName(declaration) && + (!hasThisParameter || !thisParameter)) { + var otherKind = declaration.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; + var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); + if (other) { + thisParameter = getAnnotatedAccessorThisParameter(other); + } + } + var classType = declaration.kind === 152 /* Constructor */ ? + getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) + : undefined; + var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); + var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); + var typePredicate = declaration.type && declaration.type.kind === 158 /* TypePredicate */ ? + createTypePredicateFromTypePredicateNode(declaration.type) : + undefined; + // JS functions get a free rest parameter if they reference `arguments` + var hasRestLikeParameter = ts.hasRestParameter(declaration); + if (!hasRestLikeParameter && ts.isInJavaScriptFile(declaration) && containsArgumentsReference(declaration)) { + hasRestLikeParameter = true; + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + syntheticArgsSymbol.type = anyArrayType; + syntheticArgsSymbol.isRestParameter = true; + parameters.push(syntheticArgsSymbol); + } + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + } + return links.resolvedSignature; + } + function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { + if (isJSConstructSignature) { + return getTypeFromTypeNode(declaration.parameters[0].type); + } + else if (classType) { + return classType; + } + var typeNode = ts.getEffectiveReturnTypeNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + // 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 === 153 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(declaration.symbol, 154 /* SetAccessor */); + return getAnnotatedAccessorType(setter); + } + if (ts.nodeIsMissing(declaration.body)) { + return anyType; + } + } + function containsArgumentsReference(declaration) { + var links = getNodeLinks(declaration); + if (links.containsArgumentsReference === undefined) { + if (links.flags & 8192 /* CaptureArguments */) { + links.containsArgumentsReference = true; + } + else { + links.containsArgumentsReference = traverse(declaration.body); + } + } + return links.containsArgumentsReference; + function traverse(node) { + if (!node) + return false; + switch (node.kind) { + case 71 /* Identifier */: + return node.escapedText === "arguments" && ts.isPartOfExpression(node); + case 149 /* PropertyDeclaration */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return node.name.kind === 144 /* ComputedPropertyName */ + && traverse(node.name); + default: + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + } + } + } + function getSignaturesOfSymbol(symbol) { + if (!symbol) + return ts.emptyArray; + var result = []; + for (var i = 0; i < symbol.declarations.length; i++) { + var node = symbol.declarations[i]; + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 273 /* JSDocFunctionType */: + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && node.body) { + var previous = symbol.declarations[i - 1]; + if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { + break; + } + } + result.push(getSignatureFromDeclaration(node)); + } + } + return result; + } + function resolveExternalModuleTypeByLiteral(name) { + var moduleSym = resolveExternalModuleName(name, name); + if (moduleSym) { + var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); + if (resolvedModuleSymbol) { + return getTypeOfSymbol(resolvedModuleSymbol); + } + } + return anyType; + } + function getThisTypeOfSignature(signature) { + if (signature.thisParameter) { + return getTypeOfSymbol(signature.thisParameter); + } + } + function getReturnTypeOfSignature(signature) { + if (!signature.resolvedReturnType) { + if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { + return unknownType; + } + var type = void 0; + if (signature.target) { + type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); + } + else if (signature.unionSignatures) { + type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + } + else { + type = getReturnTypeFromBody(signature.declaration); + } + if (!popTypeResolution()) { + type = anyType; + if (noImplicitAny) { + var declaration = signature.declaration; + 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); + } + } + } + signature.resolvedReturnType = type; + } + return signature.resolvedReturnType; + } + function getRestTypeOfSignature(signature) { + if (signature.hasRestParameter) { + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); + if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { + return type.typeArguments[0]; + } + } + return anyType; + } + function getSignatureInstantiation(signature, typeArguments) { + typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); + var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); + var id = getTypeListId(typeArguments); + var instantiation = instantiations.get(id); + if (!instantiation) { + instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); + } + return instantiation; + } + function createSignatureInstantiation(signature, typeArguments) { + return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); + } + function getErasedSignature(signature) { + if (!signature.typeParameters) + return signature; + if (!signature.erasedSignatureCache) { + signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); + } + return signature.erasedSignatureCache; + } + function getOrCreateTypeFromSignature(signature) { + // There are two ways to declare a construct signature, one is by declaring a class constructor + // using the constructor keyword, and the other is declaring a bare construct signature in an + // object type literal or interface (using the new keyword). Each way of declaring a constructor + // will result in a different declaration kind. + if (!signature.isolatedSignatureType) { + var isConstructor = signature.declaration.kind === 152 /* Constructor */ || signature.declaration.kind === 156 /* ConstructSignature */; + var type = createObjectType(16 /* Anonymous */); + type.members = emptySymbols; + type.properties = ts.emptyArray; + type.callSignatures = !isConstructor ? [signature] : ts.emptyArray; + type.constructSignatures = isConstructor ? [signature] : ts.emptyArray; + signature.isolatedSignatureType = type; + } + return signature.isolatedSignatureType; + } + function getIndexSymbol(symbol) { + return symbol.members.get("__index" /* Index */); + } + function getIndexDeclarationOfSymbol(symbol, kind) { + var syntaxKind = kind === 1 /* Number */ ? 133 /* NumberKeyword */ : 136 /* StringKeyword */; + var indexSymbol = getIndexSymbol(symbol); + if (indexSymbol) { + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var node = decl; + if (node.parameters.length === 1) { + var parameter = node.parameters[0]; + if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + return node; + } + } + } + } + return undefined; + } + function createIndexInfo(type, isReadonly, declaration) { + return { type: type, isReadonly: isReadonly, declaration: declaration }; + } + function getIndexInfoOfSymbol(symbol, kind) { + var declaration = getIndexDeclarationOfSymbol(symbol, kind); + if (declaration) { + return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); + } + return undefined; + } + function getConstraintDeclaration(type) { + return ts.getDeclarationOfKind(type.symbol, 145 /* TypeParameter */).constraint; + } + function getConstraintFromTypeParameter(typeParameter) { + if (!typeParameter.constraint) { + if (typeParameter.target) { + var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); + typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; + } + else { + var constraintDeclaration = getConstraintDeclaration(typeParameter); + typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; + } + } + return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; + } + function getParentSymbolOfTypeParameter(typeParameter) { + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145 /* TypeParameter */).parent); + } + function getTypeListId(types) { + var result = ""; + if (types) { + var length_5 = types.length; + var i = 0; + while (i < length_5) { + var startId = types[i].id; + var count = 1; + while (i + count < length_5 && types[i + count].id === startId + count) { + count++; + } + if (result.length) { + result += ","; + } + result += startId; + if (count > 1) { + result += ":" + count; + } + i += count; + } + } + return result; + } + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // 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_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; + if (!(type.flags & excludeKinds)) { + result |= type.flags; + } + } + return result & 14680064 /* PropagatingFlags */; + } + function createTypeReference(target, typeArguments) { + var id = getTypeListId(typeArguments); + var type = target.instantiations.get(id); + if (!type) { + type = createObjectType(4 /* Reference */, target.symbol); + target.instantiations.set(id, type); + type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.target = target; + type.typeArguments = typeArguments; + } + return type; + } + function cloneTypeReference(source) { + var type = createType(source.flags); + type.symbol = source.symbol; + type.objectFlags = source.objectFlags; + type.target = source.target; + type.typeArguments = source.typeArguments; + return type; + } + function getTypeReferenceArity(type) { + return ts.length(type.target.typeParameters); + } + /** + * Get type from type-reference that reference to class or interface + */ + function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { + var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); + var typeParameters = type.localTypeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); + return unknownType; + } + // 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(typeArgs, typeParameters, minTypeArgumentCount, node)); + return createTypeReference(type, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); + return unknownType; + } + return type; + } + function getTypeAliasInstantiation(symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var links = getSymbolLinks(symbol); + var typeParameters = links.typeParameters; + var id = getTypeListId(typeArguments); + var instantiation = links.instantiations.get(id); + if (!instantiation) { + links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); + } + 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, symbol, typeArguments) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeParameters = getSymbolLinks(symbol).typeParameters; + if (typeParameters) { + var numTypeArguments = ts.length(node.typeArguments); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { + error(node, minTypeArgumentCount === typeParameters.length + ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s + : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); + return unknownType; + } + return getTypeAliasInstantiation(symbol, typeArguments); + } + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return type; + } + /** + * Get type from reference to named type that cannot be generic (enum or type parameter) + */ + function getTypeFromNonGenericTypeReference(node, symbol) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); + return unknownType; + } + return getDeclaredTypeOfSymbol(symbol); + } + function getTypeReferenceName(node) { + switch (node.kind) { + case 159 /* TypeReference */: + return node.typeName; + case 201 /* ExpressionWithTypeArguments */: + // We only support expressions that are simple qualified names. For other + // expressions this produces undefined. + var expr = node.expression; + if (ts.isEntityNameExpression(expr)) { + return expr; + } + } + return undefined; + } + function resolveTypeReferenceName(typeReferenceName, meaning) { + if (!typeReferenceName) { + return unknownSymbol; + } + return resolveEntityName(typeReferenceName, meaning) || unknownSymbol; + } + function getTypeReferenceType(node, symbol) { + var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. + if (symbol === unknownSymbol) { + return unknownType; + } + var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); + if (type) { + return type; + } + if (symbol.flags & 107455 /* Value */ && isJSDocTypeReference(node)) { + // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + // the symbol is a constructor function, return the inferred class type; otherwise, + // the type of this reference is just the type of the value we resolved to. + var valueType = getTypeOfSymbol(symbol); + if (valueType.symbol && !isInferredClassType(valueType)) { + var referenceType = getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType) { + return referenceType; + } + } + // Resolve the type reference as a Type for the purpose of reporting errors. + resolveTypeReferenceName(getTypeReferenceName(node), 793064 /* Type */); + return valueType; + } + return getTypeFromNonGenericTypeReference(node, symbol); + } + function getTypeReferenceTypeWorker(node, symbol, typeArguments) { + if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); + } + if (symbol.flags & 524288 /* TypeAlias */) { + return getTypeFromTypeAliasReference(node, symbol, typeArguments); + } + if (symbol.flags & 16 /* Function */ && + isJSDocTypeReference(node) && + (symbol.members || ts.getJSDocClassTag(symbol.valueDeclaration))) { + return getInferredClassType(symbol); + } + } + function isJSDocTypeReference(node) { + return node.flags & 1048576 /* JSDoc */ && node.kind === 159 /* TypeReference */; + } + function getIntendedTypeFromJSDocTypeReference(node) { + if (ts.isIdentifier(node.typeName)) { + if (node.typeName.escapedText === "Object") { + if (node.typeArguments && node.typeArguments.length === 2) { + var indexed = getTypeFromTypeNode(node.typeArguments[0]); + var target = getTypeFromTypeNode(node.typeArguments[1]); + var index = createIndexInfo(target, /*isReadonly*/ false); + if (indexed === stringType || indexed === numberType) { + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + } + } + return anyType; + } + switch (node.typeName.escapedText) { + case "String": + return stringType; + case "Number": + return numberType; + case "Boolean": + return booleanType; + case "Void": + return voidType; + case "Undefined": + return undefinedType; + case "Null": + return nullType; + case "Function": + case "function": + return globalFunctionType; + case "Array": + case "array": + return !node.typeArguments || !node.typeArguments.length ? anyArrayType : undefined; + case "Promise": + case "promise": + return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; + } + } + } + function getTypeFromJSDocNullableTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getUnionType([type, nullType]) : type; + } + function getTypeFromTypeReference(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var symbol = void 0; + var type = void 0; + var meaning = 793064 /* Type */; + if (isJSDocTypeReference(node)) { + type = getIntendedTypeFromJSDocTypeReference(node); + meaning |= 107455 /* Value */; + } + if (!type) { + symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning); + type = getTypeReferenceType(node, symbol); + } + // Cache both the resolved symbol and the resolved type. The resolved symbol is needed in when we check the + // type reference in checkTypeReferenceOrExpressionWithTypeArguments. + 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) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // The expression is processed as an identifier expression (section 4.3) + // or property access expression(section 4.10), + // the widened type(section 3.9) of which becomes the result. + links.resolvedType = getWidenedType(checkExpression(node.exprName)); + } + return links.resolvedType; + } + function getTypeOfGlobalSymbol(symbol, arity) { + function getTypeDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; + switch (declaration.kind) { + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 232 /* EnumDeclaration */: + return declaration; + } + } + } + if (!symbol) { + return arity ? emptyGenericType : emptyObjectType; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!(type.flags & 32768 /* Object */)) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.unescapeLeadingUnderscores(symbol.escapedName)); + return arity ? emptyGenericType : emptyObjectType; + } + if (ts.length(type.typeParameters) !== arity) { + error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.unescapeLeadingUnderscores(symbol.escapedName), arity); + return arity ? emptyGenericType : emptyObjectType; + } + return type; + } + function getGlobalValueSymbol(name, reportErrors) { + return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); + } + function getGlobalTypeSymbol(name, reportErrors) { + return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); + } + function getGlobalSymbol(name, meaning, diagnostic) { + return resolveName(undefined, name, meaning, diagnostic, name); + } + function getGlobalType(name, arity, reportErrors) { + var symbol = getGlobalTypeSymbol(name, reportErrors); + return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; + } + function getGlobalTypedPropertyDescriptorType() { + return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; + } + function getGlobalTemplateStringsArrayType() { + return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } + function getGlobalESSymbolConstructorSymbol(reportErrors) { + return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); + } + function getGlobalESSymbolType(reportErrors) { + return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalPromiseType(reportErrors) { + return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalPromiseConstructorSymbol(reportErrors) { + return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); + } + function getGlobalPromiseConstructorLikeType(reportErrors) { + return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; + } + function getGlobalAsyncIterableType(reportErrors) { + return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIteratorType(reportErrors) { + return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalAsyncIterableIteratorType(reportErrors) { + return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableType(reportErrors) { + return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIteratorType(reportErrors) { + return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalIterableIteratorType(reportErrors) { + return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; + } + function getGlobalTypeOrUndefined(name, arity) { + if (arity === void 0) { arity = 0; } + var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity); + } + /** + * Returns a type that is inside a namespace at the global scope, e.g. + * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type + */ + function getExportedTypeFromNamespace(namespace, name) { + var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); + return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); + } + /** + * Instantiates a global type that is generic with some element type, and returns that instantiation. + */ + function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { + return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; + } + function createTypedPropertyDescriptorType(propertyType) { + return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); + } + function createAsyncIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createAsyncIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); + } + function createIterableIteratorType(iteratedType) { + return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); + } + function createArrayType(elementType) { + return createTypeFromGenericGlobalType(globalArrayType, [elementType]); + } + function getTypeFromArrayTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); + } + return links.resolvedType; + } + // We represent tuple types as type references to synthesized generic interface types created by + // this function. The types are of the form: + // + // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } + // + // Note that the generic type created by this function has no symbol associated with it. The same + // is true for each of the synthesized type parameters. + function createTupleTypeOfArity(arity) { + var typeParameters = []; + var properties = []; + for (var i = 0; i < arity; i++) { + var typeParameter = createType(16384 /* TypeParameter */); + typeParameters.push(typeParameter); + var property = createSymbol(4 /* Property */, "" + i); + property.type = typeParameter; + properties.push(property); + } + var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); + type.typeParameters = typeParameters; + type.outerTypeParameters = undefined; + type.localTypeParameters = typeParameters; + type.instantiations = ts.createMap(); + type.instantiations.set(getTypeListId(type.typeParameters), type); + type.target = type; + type.typeArguments = type.typeParameters; + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; + type.thisType.constraint = type; + type.declaredProperties = properties; + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; + type.declaredStringIndexInfo = undefined; + type.declaredNumberIndexInfo = undefined; + return type; + } + function getTupleTypeOfArity(arity) { + return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + } + function createTupleType(elementTypes) { + return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + } + function getTypeFromTupleTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + } + return links.resolvedType; + } + function binarySearchTypes(types, type) { + var low = 0; + var high = types.length - 1; + var typeId = type.id; + while (low <= high) { + var middle = low + ((high - low) >> 1); + var id = types[middle].id; + if (id === typeId) { + return middle; + } + else if (id > typeId) { + high = middle - 1; + } + else { + low = middle + 1; + } + } + return ~low; + } + function containsType(types, type) { + return binarySearchTypes(types, type) >= 0; + } + function addTypeToUnion(typeSet, type) { + var flags = type.flags; + if (flags & 65536 /* Union */) { + addTypesToUnion(typeSet, type.types); + } + else if (flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (!strictNullChecks && flags & 6144 /* Nullable */) { + if (flags & 2048 /* Undefined */) + typeSet.containsUndefined = true; + if (flags & 4096 /* Null */) + typeSet.containsNull = true; + if (!(flags & 2097152 /* ContainsWideningType */)) + typeSet.containsNonWideningType = true; + } + else if (!(flags & 8192 /* Never */)) { + if (flags & 2 /* String */) + typeSet.containsString = true; + if (flags & 4 /* Number */) + typeSet.containsNumber = true; + if (flags & 96 /* StringOrNumberLiteral */) + typeSet.containsStringOrNumberLiteral = true; + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); + if (index < 0) { + if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } + } + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToUnion(typeSet, types) { + 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_6 = types; _i < types_6.length; _i++) { + var t = types_6[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + function isSubtypeOfAny(candidate, types) { + 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; + } + } + return false; + } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } + function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } + var i = types.length; + while (i > 0) { + i--; + if (isSubtypeOfAny(types[i], types)) { + ts.orderedRemoveItemAt(types, i); + } + } + } + function removeRedundantLiteralTypes(types) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 32 /* StringLiteral */ && types.containsString || + t.flags & 64 /* NumberLiteral */ && types.containsNumber || + t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction + // flag is specified we also reduce the constituent type set to only include types that aren't subtypes + // of other types. Subtype reduction is expensive for large union types and is possible only when union + // types are known not to circularly reference themselves (as is the case with union types created by + // expression constructs such as array literals and the || and ?: operators). Named types can + // circularly reference themselves and therefore cannot be subtype reduced during their declaration. + // For example, "type Item = string | (() => Item" is a named type that circularly references itself. + function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var typeSet = []; + addTypesToUnion(typeSet, types); + if (typeSet.containsAny) { + return anyType; + } + if (subtypeReduction) { + removeSubtypes(typeSet); + } + else if (typeSet.containsStringOrNumberLiteral) { + removeRedundantLiteralTypes(typeSet); + } + if (typeSet.length === 0) { + return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : + typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : + neverType; + } + return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + } + // This function assumes the constituent type list is sorted and deduplicated. + function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return neverType; + } + if (types.length === 1) { + return types[0]; + } + var id = getTypeListId(types); + var type = unionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); + type = createType(65536 /* Union */ | propagatedFlags); + unionTypes.set(id, type); + type.types = types; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromUnionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function addTypeToIntersection(typeSet, type) { + if (type.flags & 131072 /* Intersection */) { + addTypesToIntersection(typeSet, type.types); + } + else if (type.flags & 1 /* Any */) { + typeSet.containsAny = true; + } + else if (type.flags & 8192 /* Never */) { + typeSet.containsNever = true; + } + else if (getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { + typeSet.containsEmptyObject = true; + } + else if ((strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { + if (type.flags & 32768 /* Object */) { + typeSet.containsObjectType = true; + } + if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { + typeSet.unionIndex = typeSet.length; + } + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } + } + } + // Add the given types to the given type set. Order is preserved, duplicates are removed, + // and nested types of the given kind are flattened into the set. + function addTypesToIntersection(typeSet, types) { + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var type = types_8[_i]; + addTypeToIntersection(typeSet, type); + } + } + // We normalize combinations of intersection and union types based on the distributive property of the '&' + // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection + // types with union type constituents into equivalent union types with intersection type constituents and + // effectively ensure that union types are always at the top level in type representations. + // + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & + // type operator and we can't reduce those because we want to support recursive intersection types. For example, + // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. + // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution + // for intersections of types with signatures can be deterministic. + function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { + if (types.length === 0) { + return emptyObjectType; + } + var typeSet = []; + addTypesToIntersection(typeSet, types); + if (typeSet.containsNever) { + return neverType; + } + if (typeSet.containsAny) { + return anyType; + } + if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { + typeSet.push(emptyObjectType); + } + if (typeSet.length === 1) { + return typeSet[0]; + } + var unionIndex = typeSet.unionIndex; + if (unionIndex !== undefined) { + // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of + // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. + var unionType = typeSet[unionIndex]; + return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), + /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); + } + var id = getTypeListId(typeSet); + var type = intersectionTypes.get(id); + if (!type) { + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); + type = createType(131072 /* Intersection */ | propagatedFlags); + intersectionTypes.set(id, type); + type.types = typeSet; + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = aliasTypeArguments; + } + return type; + } + function getTypeFromIntersectionTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + } + return links.resolvedType; + } + function getIndexTypeForGenericType(type) { + if (!type.resolvedIndexType) { + type.resolvedIndexType = createType(262144 /* Index */); + type.resolvedIndexType.type = type; + } + return type.resolvedIndexType; + } + function getLiteralTypeFromPropertyName(prop) { + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + neverType : + getLiteralType(ts.unescapeLeadingUnderscores(prop.escapedName)); + } + function getLiteralTypeFromPropertyNames(type) { + return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + } + function getIndexType(type) { + return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : + getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : + getLiteralTypeFromPropertyNames(type); + } + function getIndexTypeOrString(type) { + var indexType = getIndexType(type); + return indexType !== neverType ? indexType : stringType; + } + function getTypeFromTypeOperatorNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); + } + return links.resolvedType; + } + function createIndexedAccessType(objectType, indexType) { + var type = createType(524288 /* IndexedAccess */); + type.objectType = objectType; + type.indexType = indexType; + return type; + } + function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { + var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; + var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? + ts.escapeLeadingUnderscores("" + indexType.value) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(accessExpression.argumentExpression.name.escapedText)) : + undefined; + if (propName !== undefined) { + var prop = getPropertyOfType(objectType, propName); + if (prop) { + if (accessExpression) { + if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { + error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); + return unknownType; + } + if (cacheSymbol) { + getNodeLinks(accessNode).resolvedSymbol = prop; + } + } + return getTypeOfSymbol(prop); + } + } + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { + if (isTypeAny(objectType)) { + return anyType; + } + var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + getIndexInfoOfType(objectType, 0 /* String */) || + undefined; + if (indexInfo) { + if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); + return unknownType; + } + return indexInfo.type; + } + if (accessExpression && !isConstEnumObjectType(objectType)) { + if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(objectType, 1 /* Number */)) { + error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } + } + return anyType; + } + } + 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.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)); + } + else { + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + return unknownType; + } + return anyType; + } + function getIndexedAccessForMappedType(type, indexType, accessNode) { + var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; + if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { + error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } + var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); + var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); + } + function getIndexedAccessType(objectType, indexType, accessNode) { + // If the index type is generic, if the object type is generic and doesn't originate in an expression, + // or if the object type is a mapped type with a generic constraint, we are performing a higher-order + // index access where we cannot meaningfully access the properties of the object type. Note that for a + // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to + // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved + // eagerly using the constraint type of 'this' at the given location. + if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || + maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) || + isGenericMappedType(objectType)) { + if (objectType.flags & 1 /* Any */) { + return objectType; + } + // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes + // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the + // type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise we defer the operation by creating an indexed access type. + var id = objectType.id + "," + indexType.id; + var type = indexedAccessTypes.get(id); + if (!type) { + indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); + } + return type; + } + // In the following we resolve T[K] to the type of the property in T selected by K. + var apparentObjectType = getApparentType(objectType); + if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { + var propTypes = []; + for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); + if (propType === unknownType) { + return unknownType; + } + propTypes.push(propType); + } + return getUnionType(propTypes); + } + return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); + } + function getTypeFromIndexedAccessTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); + } + return links.resolvedType; + } + function getTypeFromMappedTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = createObjectType(32 /* Mapped */, node.symbol); + type.declaration = node; + type.aliasSymbol = getAliasSymbolForTypeNode(node); + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + links.resolvedType = type; + // Eagerly resolve the constraint type which forces an error if the constraint type circularly + // references itself through one or more type aliases. + getConstraintTypeFromMappedType(type); + } + return links.resolvedType; + } + function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // Deferred resolution of members is handled by resolveObjectTypeMembers + var aliasSymbol = getAliasSymbolForTypeNode(node); + if (node.symbol.members.size === 0 && !aliasSymbol) { + links.resolvedType = emptyTypeLiteralType; + } + else { + var type = createObjectType(16 /* Anonymous */, node.symbol); + type.aliasSymbol = aliasSymbol; + type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } + links.resolvedType = type; + } + } + return links.resolvedType; + } + function getAliasSymbolForTypeNode(node) { + return node.parent.kind === 231 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + } + function getAliasTypeArgumentsForTypeNode(node) { + var symbol = getAliasSymbolForTypeNode(node); + return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; + } + /** + * Since the source of spread types are object literals, which are not binary, + * this function should be called in a left folding style, with left = previous result of getSpreadType + * and right = the new element to be spread. + */ + function getSpreadType(left, right) { + if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { + return anyType; + } + if (left.flags & 8192 /* Never */) { + return right; + } + if (right.flags & 8192 /* Never */) { + return left; + } + if (left.flags & 65536 /* Union */) { + return mapType(left, function (t) { return getSpreadType(t, right); }); + } + if (right.flags & 65536 /* Union */) { + return mapType(right, function (t) { return getSpreadType(left, t); }); + } + if (right.flags & 16777216 /* NonPrimitive */) { + return emptyObjectType; + } + var members = ts.createSymbolTable(); + var skippedPrivateMembers = ts.createUnderscoreEscapedMap(); + var stringIndexInfo; + var numberIndexInfo; + if (left === emptyObjectType) { + // for the first spread element, left === emptyObjectType, so take the right's string indexer + stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); + numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); + } + else { + stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); + numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); + } + for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { + 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 (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { + skippedPrivateMembers.set(rightProp.escapedName, true); + } + else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { + members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + } + } + for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { + var leftProp = _c[_b]; + if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) + || skippedPrivateMembers.has(leftProp.escapedName) + || isClassMethod(leftProp)) { + continue; + } + if (members.has(leftProp.escapedName)) { + var rightProp = members.get(leftProp.escapedName); + var rightType = getTypeOfSymbol(rightProp); + if (rightProp.flags & 16777216 /* Optional */) { + var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); + var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); + var result = createSymbol(flags, leftProp.escapedName); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); + result.leftSpread = leftProp; + result.rightSpread = rightProp; + result.declarations = declarations; + members.set(leftProp.escapedName, result); + } + } + else { + members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + } + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + } + function getNonReadonlySymbol(prop) { + if (!isReadonlySymbol(prop)) { + return prop; + } + var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */); + var result = createSymbol(flags, prop.escapedName); + result.type = getTypeOfSymbol(prop); + result.declarations = prop.declarations; + result.syntheticOrigin = prop; + return result; + } + function isClassMethod(prop) { + return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); + } + function createLiteralType(flags, value, symbol) { + var type = createType(flags); + 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.value, type.symbol); + freshType.regularType = type; + type.freshType = freshType; + } + return type.freshType; + } + return type; + } + function getRegularTypeOfLiteralType(type) { + return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; + } + 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) { + var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + literalTypes.set(key, type = createLiteralType(flags, value, symbol)); + } + return type; + } + function getTypeFromLiteralTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); + } + return links.resolvedType; + } + function getTypeFromJSDocVariadicType(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + var type = getTypeFromTypeNode(node.type); + links.resolvedType = type ? createArrayType(type) : unknownType; + } + return links.resolvedType; + } + function getThisType(node) { + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + var parent = container && container.parent; + if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { + if (!(ts.getModifierFlags(container) & 32 /* Static */) && + (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; + } + } + error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); + return unknownType; + } + function getTypeFromThisTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + links.resolvedType = getThisType(node); + } + return links.resolvedType; + } + function getTypeFromTypeNode(node) { + switch (node.kind) { + case 119 /* AnyKeyword */: + case 268 /* JSDocAllType */: + case 269 /* JSDocUnknownType */: + return anyType; + case 136 /* StringKeyword */: + return stringType; + case 133 /* NumberKeyword */: + return numberType; + case 122 /* BooleanKeyword */: + return booleanType; + case 137 /* SymbolKeyword */: + return esSymbolType; + case 105 /* VoidKeyword */: + return voidType; + case 139 /* UndefinedKeyword */: + return undefinedType; + case 95 /* NullKeyword */: + return nullType; + case 130 /* NeverKeyword */: + return neverType; + case 134 /* ObjectKeyword */: + return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; + case 169 /* ThisType */: + case 99 /* ThisKeyword */: + return getTypeFromThisTypeNode(node); + case 173 /* LiteralType */: + return getTypeFromLiteralTypeNode(node); + case 159 /* TypeReference */: + return getTypeFromTypeReference(node); + case 158 /* TypePredicate */: + return booleanType; + case 201 /* ExpressionWithTypeArguments */: + return getTypeFromTypeReference(node); + case 162 /* TypeQuery */: + return getTypeFromTypeQueryNode(node); + case 164 /* ArrayType */: + return getTypeFromArrayTypeNode(node); + case 165 /* TupleType */: + return getTypeFromTupleTypeNode(node); + case 166 /* UnionType */: + return getTypeFromUnionTypeNode(node); + case 167 /* IntersectionType */: + return getTypeFromIntersectionTypeNode(node); + case 270 /* JSDocNullableType */: + return getTypeFromJSDocNullableTypeNode(node); + case 168 /* ParenthesizedType */: + case 271 /* JSDocNonNullableType */: + case 272 /* JSDocOptionalType */: + case 267 /* JSDocTypeExpression */: + return getTypeFromTypeNode(node.type); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 163 /* TypeLiteral */: + case 285 /* JSDocTypeLiteral */: + case 273 /* JSDocFunctionType */: + return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + case 170 /* TypeOperator */: + return getTypeFromTypeOperatorNode(node); + case 171 /* IndexedAccessType */: + return getTypeFromIndexedAccessTypeNode(node); + case 172 /* MappedType */: + return getTypeFromMappedTypeNode(node); + // This function assumes that an identifier or qualified name is a type expression + // Callers should first ensure this by calling isTypeNode + case 71 /* Identifier */: + case 143 /* QualifiedName */: + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + case 274 /* JSDocVariadicType */: + return getTypeFromJSDocVariadicType(node); + default: + return unknownType; + } + } + function instantiateList(items, mapper, instantiator) { + if (items && items.length) { + var result = []; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; + result.push(instantiator(v, mapper)); + } + return result; + } + return items; + } + function instantiateTypes(types, mapper) { + return instantiateList(types, mapper, instantiateType); + } + function instantiateSignatures(signatures, mapper) { + return instantiateList(signatures, mapper, instantiateSignature); + } + function instantiateCached(type, mapper, instantiator) { + var instantiations = mapper.instantiations || (mapper.instantiations = []); + return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); + } + function makeUnaryTypeMapper(source, target) { + return function (t) { return t === source ? target : t; }; + } + function makeBinaryTypeMapper(source1, target1, source2, target2) { + return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; + } + function makeArrayTypeMapper(sources, targets) { + return function (t) { + for (var i = 0; i < sources.length; i++) { + if (t === sources[i]) { + return targets ? targets[i] : anyType; + } + } + return t; + }; + } + function createTypeMapper(sources, targets) { + ts.Debug.assert(targets === undefined || sources.length === targets.length); + var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : + sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : + makeArrayTypeMapper(sources, targets); + mapper.mappedTypes = sources; + return mapper; + } + function createTypeEraser(sources) { + return createTypeMapper(sources, /*targets*/ undefined); + } + /** + * Maps forward-references to later types parameters to the empty object type. + * This is used during inference when instantiating type parameter defaults. + */ + function createBackreferenceMapper(typeParameters, index) { + var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + mapper.mappedTypes = typeParameters; + return mapper; + } + function isInferenceContext(mapper) { + return !!mapper.signature; + } + function cloneTypeMapper(mapper) { + return mapper && isInferenceContext(mapper) ? + createInferenceContext(mapper.signature, mapper.flags | 2 /* NoDefault */, mapper.inferences) : + mapper; + } + function identityMapper(type) { + return type; + } + function combineTypeMappers(mapper1, mapper2) { + var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; + mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); + return mapper; + } + function createReplacementMapper(source, target, baseMapper) { + var mapper = function (t) { return t === source ? target : baseMapper(t); }; + mapper.mappedTypes = baseMapper.mappedTypes; + return mapper; + } + function cloneTypeParameter(typeParameter) { + var result = createType(16384 /* TypeParameter */); + result.symbol = typeParameter.symbol; + result.target = typeParameter; + return result; + } + function cloneTypePredicate(predicate, mapper) { + if (ts.isIdentifierTypePredicate(predicate)) { + return { + kind: 1 /* Identifier */, + parameterName: predicate.parameterName, + parameterIndex: predicate.parameterIndex, + type: instantiateType(predicate.type, mapper) + }; + } + else { + return { + kind: 0 /* This */, + type: instantiateType(predicate.type, mapper) + }; + } + } + function instantiateSignature(signature, mapper, eraseTypeParameters) { + var freshTypeParameters; + var freshTypePredicate; + if (signature.typeParameters && !eraseTypeParameters) { + // First create a fresh set of type parameters, then include a mapping from the old to the + // new type parameters in the mapper function. Finally store this mapper in the new type + // parameters such that we can use it when instantiating constraints. + freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); + mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); + for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { + var tp = freshTypeParameters_1[_i]; + tp.mapper = mapper; + } + } + if (signature.typePredicate) { + freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); + } + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), + /*resolvedReturnType*/ undefined, freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + result.target = signature; + result.mapper = mapper; + return result; + } + function instantiateSymbol(symbol, mapper) { + 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 + // always reference a non-aliases. + symbol = links.target; + mapper = combineTypeMappers(links.mapper, mapper); + } + // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and + // also transient so that we can just store data on it directly. + var result = createSymbol(symbol.flags, symbol.escapedName); + result.checkFlags = 1 /* Instantiated */; + result.declarations = symbol.declarations; + result.parent = symbol.parent; + result.target = symbol; + result.mapper = mapper; + if (symbol.valueDeclaration) { + result.valueDeclaration = symbol.valueDeclaration; + } + return result; + } + function instantiateAnonymousType(type, mapper) { + var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); + result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; + result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function instantiateMappedType(type, mapper) { + // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some + // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated + // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for + // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a + // union type A | undefined, we produce { [P in keyof A]: X } | undefined. + var constraintType = getConstraintTypeFromMappedType(type); + if (constraintType.flags & 262144 /* Index */) { + var typeVariable_1 = constraintType.type; + if (typeVariable_1.flags & 16384 /* TypeParameter */) { + var mappedTypeVariable = instantiateType(typeVariable_1, mapper); + if (typeVariable_1 !== mappedTypeVariable) { + return mapType(mappedTypeVariable, function (t) { + if (isMappableType(t)) { + return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); + } + return t; + }); + } + } + } + return instantiateMappedObjectType(type, mapper); + } + function isMappableType(type) { + return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); + } + function instantiateMappedObjectType(type, mapper) { + var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); + result.declaration = type.declaration; + result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; + result.aliasSymbol = type.aliasSymbol; + result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); + return result; + } + function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { + if (!(symbol.declarations && symbol.declarations.length)) { + return false; + } + var mappedTypes = mapper.mappedTypes; + // Starting with the parent of the symbol's declaration, check if the mapper maps any of + // the type parameters introduced by enclosing declarations. We just pick the first + // declaration since multiple declarations will all have the same parent anyway. + return !!ts.findAncestor(symbol.declarations[0], function (node) { + if (node.kind === 233 /* ModuleDeclaration */ || node.kind === 265 /* SourceFile */) { + return "quit"; + } + switch (node.kind) { + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 152 /* Constructor */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (typeParameters) { + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var d = typeParameters_1[_i]; + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { + return true; + } + } + } + if (ts.isClassLike(node) || node.kind === 230 /* InterfaceDeclaration */) { + var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; + if (thisType && ts.contains(mappedTypes, thisType)) { + return true; + } + } + break; + case 172 /* MappedType */: + if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { + return true; + } + break; + case 273 /* JSDocFunctionType */: + var func = node; + for (var _a = 0, _b = func.parameters; _a < _b.length; _a++) { + var p = _b[_a]; + if (ts.contains(mappedTypes, getTypeOfNode(p))) { + return true; + } + } + break; + } + }); + } + function isTopLevelTypeAlias(symbol) { + if (symbol.declarations && symbol.declarations.length) { + var parentKind = symbol.declarations[0].parent.kind; + return parentKind === 265 /* SourceFile */ || parentKind === 234 /* ModuleBlock */; + } + return false; + } + function instantiateType(type, mapper) { + if (type && mapper !== identityMapper) { + // If we are instantiating a type that has a top-level type alias, obtain the instantiation through + // the type alias instead in order to share instantiations for the same type arguments. This can + // dramatically reduce the number of structurally identical types we generate. Note that we can only + // perform this optimization for top-level type aliases. Consider: + // + // function f1(x: T) { + // type Foo = { x: X, t: T }; + // let obj: Foo = { x: x }; + // return obj; + // } + // function f2(x: U) { return f1(x); } + // let z = f2(42); + // + // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo + // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's + // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been + // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. + if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { + if (type.aliasTypeArguments) { + return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + return type; + } + return instantiateTypeNoAlias(type, mapper); + } + return type; + } + function instantiateTypeNoAlias(type, mapper) { + if (type.flags & 16384 /* TypeParameter */) { + return mapper(type); + } + if (type.flags & 32768 /* Object */) { + if (type.objectFlags & 16 /* Anonymous */) { + // If the anonymous type originates in a declaration of a function, method, class, or + // interface, in an object type literal, or in an object literal expression, we may need + // to instantiate the type because it might reference a type parameter. We skip instantiation + // if none of the type parameters that are in scope in the type's declaration are mapped by + // the given mapper, however we can only do that analysis if the type isn't itself an + // instantiation. + return type.symbol && + type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && + (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? + instantiateCached(type, mapper, instantiateAnonymousType) : type; + } + if (type.objectFlags & 32 /* Mapped */) { + return instantiateCached(type, mapper, instantiateMappedType); + } + if (type.objectFlags & 4 /* Reference */) { + return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); + } + } + if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { + return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); + } + if (type.flags & 262144 /* Index */) { + return getIndexType(instantiateType(type.type, mapper)); + } + if (type.flags & 524288 /* IndexedAccess */) { + return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); + } + return type; + } + function instantiateIndexInfo(info, mapper) { + return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); + } + // Returns true if the given expression contains (at any level of nesting) a function or arrow expression + // that is subject to contextual typing. + function isContextSensitive(node) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + switch (node.kind) { + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 178 /* ObjectLiteralExpression */: + return ts.forEach(node.properties, isContextSensitive); + case 177 /* ArrayLiteralExpression */: + return ts.forEach(node.elements, isContextSensitive); + case 195 /* ConditionalExpression */: + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); + case 194 /* BinaryExpression */: + return node.operatorToken.kind === 54 /* BarBarToken */ && + (isContextSensitive(node.left) || isContextSensitive(node.right)); + case 261 /* PropertyAssignment */: + return isContextSensitive(node.initializer); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + return isContextSensitiveFunctionLikeDeclaration(node); + case 185 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); + case 254 /* JsxAttributes */: + return ts.forEach(node.properties, isContextSensitive); + case 253 /* JsxAttribute */: + // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. + return node.initializer && isContextSensitive(node.initializer); + case 256 /* JsxExpression */: + // It is possible to that node.expression is undefined (e.g
) + return node.expression && isContextSensitive(node.expression); + } + return false; + } + function isContextSensitiveFunctionLikeDeclaration(node) { + // Functions with type parameters are not context sensitive. + if (node.typeParameters) { + return false; + } + // Functions with any parameters that lack type annotations are context sensitive. + if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + return true; + } + // For arrow functions we now know we're not context sensitive. + if (node.kind === 187 /* ArrowFunction */) { + return false; + } + // If the first parameter is not an explicit 'this' parameter, then the function has + // an implicit 'this' parameter which is subject to contextual typing. Otherwise we + // know that all parameters (including 'this') have type annotations and nothing is + // subject to contextual typing. + var parameter = ts.firstOrUndefined(node.parameters); + return !(parameter && ts.parameterIsThisKeyword(parameter)); + } + function isContextSensitiveFunctionOrObjectLiteralMethod(func) { + return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + } + function getTypeWithoutSignatures(type) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.constructSignatures.length) { + var result = createObjectType(16 /* Anonymous */, type.symbol); + result.members = resolved.members; + result.properties = resolved.properties; + result.callSignatures = ts.emptyArray; + result.constructSignatures = ts.emptyArray; + return result; + } + } + else if (type.flags & 131072 /* Intersection */) { + return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); + } + return type; + } + // TYPE CHECKING + function isTypeIdenticalTo(source, target) { + return isTypeRelatedTo(source, target, identityRelation); + } + function compareTypesIdentical(source, target) { + return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; + } + function compareTypesAssignable(source, target) { + return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; + } + function isTypeSubtypeOf(source, target) { + return isTypeRelatedTo(source, target, subtypeRelation); + } + function isTypeAssignableTo(source, target) { + return isTypeRelatedTo(source, target, assignableRelation); + } + // A type S is considered to be an instance of a type T if S and T are the same type or if S is a + // subtype of T but not structurally identical to T. This specifically means that two distinct but + // structurally identical types (such as two classes) are not considered instances of each other. + function isTypeInstanceOf(source, target) { + return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. + * + * A type S is comparable to a type T if some (but not necessarily all) of the possible values of S are also possible values of T. + * It is used to check following cases: + * - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`). + * - the types of `case` clause expressions and their respective `switch` expressions. + * - the type of an expression in a type assertion with the type being asserted. + */ + function isTypeComparableTo(source, target) { + return isTypeRelatedTo(source, target, comparableRelation); + } + function areTypesComparable(type1, type2) { + return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); + } + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + /** + * This is *not* a bi-directional relationship. + * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. + */ + function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { + return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); + } + function isSignatureAssignableTo(source, target, ignoreReturnTypes) { + return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, + /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + return 0 /* False */; + } + if (source.typeParameters) { + source = instantiateSignatureInContextOf(source, target); + } + var result = -1 /* True */; + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType && sourceThisType !== voidType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + // void sources are assignable to anything. + var related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) + || compareTypes(targetThisType, sourceThisType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); + } + return 0 /* False */; + } + result &= related; + } + } + var sourceMax = getNumNonRestParameters(source); + var targetMax = getNumNonRestParameters(target); + var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); + var sourceParams = source.parameters; + var targetParams = target.parameters; + for (var i = 0; i < checkCount; i++) { + var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); + var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); + var targetSig = getSingleCallSignature(getNonNullableType(targetType)); + // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter + // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, + // they naturally relate only contra-variantly). However, if the source and target parameters both have + // function types with a single call signature, we known we are relating two callback parameters. In + // that case it is sufficient to only relate the parameters of the signatures co-variantly because, + // similar to return values, callback parameters are output positions. This means that a Promise, + // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) + // with respect to T. + var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && + (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); + var related = callbacks ? + compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : + !checkAsCallback && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); + if (!related) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), ts.unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); + } + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) { + return result; + } + var sourceReturnType = getReturnTypeOfSignature(source); + // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions + if (target.typePredicate) { + if (source.typePredicate) { + result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); + } + else if (ts.isIdentifierTypePredicate(target.typePredicate)) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source)); + } + return 0 /* False */; + } + } + else { + // When relating callback signatures, we still need to relate return types bi-variantly as otherwise + // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } + // wouldn't be co-variant for T without this rule. + result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || + compareTypes(sourceReturnType, targetReturnType, reportErrors); + } + } + return result; + } + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { + if (source.kind !== target.kind) { + if (reportErrors) { + errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + if (source.kind === 1 /* Identifier */) { + var sourceIdentifierPredicate = source; + var targetIdentifierPredicate = target; + if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { + if (reportErrors) { + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return 0 /* False */; + } + } + var related = compareTypes(source.type, target.type, reportErrors); + if (related === 0 /* False */ && reportErrors) { + errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); + } + return related; + } + function isImplementationCompatibleWithOverload(implementation, overload) { + var erasedSource = getErasedSignature(implementation); + var erasedTarget = getErasedSignature(overload); + // First see if the return types are compatible in either direction. + var sourceReturnType = getReturnTypeOfSignature(erasedSource); + var targetReturnType = getReturnTypeOfSignature(erasedTarget); + if (targetReturnType === voidType + || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) + || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { + return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); + } + return false; + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? + numParams - 1 : + numParams; + } + function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { + if (source.hasRestParameter === target.hasRestParameter) { + if (source.hasRestParameter) { + // If both have rest parameters, get the max and add 1 to + // compensate for the rest parameter. + return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; + } + else { + return Math.min(sourceNonRestParamCount, targetNonRestParamCount); + } + } + else { + // Return the count for whichever signature doesn't have rest parameters. + return source.hasRestParameter ? + targetNonRestParamCount : + sourceNonRestParamCount; + } + } + function isEmptyResolvedType(t) { + return t.properties.length === 0 && + t.callSignatures.length === 0 && + t.constructSignatures.length === 0 && + !t.stringIndexInfo && + !t.numberIndexInfo; + } + function isEmptyObjectType(type) { + return type.flags & 32768 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 16777216 /* NonPrimitive */ ? true : + type.flags & 65536 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : + type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + false; + } + function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { + if (sourceSymbol === targetSymbol) { + return true; + } + var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); + var relation = enumRelation.get(id); + if (relation !== undefined) { + return relation; + } + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { + enumRelation.set(id, false); + return false; + } + 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.escapedName); + if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { + if (errorReporter) { + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + } + enumRelation.set(id, false); + return false; + } + } + } + enumRelation.set(id, true); + return true; + } + function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { + var s = source.flags; + var t = target.flags; + if (t & 8192 /* Never */) + return false; + if (t & 1 /* Any */ || s & 8192 /* Never */) + return true; + if (s & 262178 /* StringLike */ && t & 2 /* String */) + return true; + if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && + t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 84 /* NumberLike */ && t & 4 /* Number */) + return true; + if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && + t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + source.value === target.value) + return true; + if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) + return true; + if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + return true; + 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 (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) + return true; + if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) + return true; + if (relation === assignableRelation || relation === comparableRelation) { + if (s & 1 /* 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 & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) + return true; + } + return false; + } + function isTypeRelatedTo(source, target, relation) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + target = target.regularType; + } + if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { + return true; + } + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + return related === 1 /* Succeeded */; + } + } + if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { + return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); + } + return false; + } + /** + * Checks if 'source' is related to 'target' (e.g.: is a assignable to). + * @param source The left-hand-side of the relation. + * @param target The right-hand-side of the relation. + * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. + * Used as both to determine which checks are performed and as a cache of previously computed results. + * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. + * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. + * @param containingMessageChain A chain of errors to prepend any new errors found. + */ + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + var errorInfo; + var maybeKeys; + var sourceStack; + var targetStack; + var maybeCount = 0; + var depth = 0; + var expandingFlags = 0; + var overflow = false; + var isIntersectionConstituent = false; + ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); + var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); + if (overflow) { + error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); + } + else if (errorInfo) { + if (containingMessageChain) { + errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + } + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); + } + return result !== 0 /* False */; + function reportError(message, arg0, arg1, arg2) { + ts.Debug.assert(!!errorNode); + errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); + } + function reportRelationError(message, source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + } + if (!message) { + if (relation === comparableRelation) { + message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; + } + else if (sourceType === targetType) { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; + } + else { + message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; + } + } + reportError(message, sourceType, targetType); + } + function tryElaborateErrorsForPrimitivesAndObjects(source, target) { + var sourceType = typeToString(source); + var targetType = typeToString(target); + if ((globalStringType === source && stringType === target) || + (globalNumberType === source && numberType === target) || + (globalBooleanType === source && booleanType === target) || + (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { + reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); + } + } + function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { + if (!(type.flags & 196608 /* UnionOrIntersection */)) { + return false; + } + // at this point we know that this is union or intersection type possibly with nullable constituents. + // check if we still will have compound type if we ignore nullable components. + var seenNonNullable = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 6144 /* Nullable */) { + continue; + } + if (seenNonNullable) { + return true; + } + seenNonNullable = true; + } + return false; + } + /** + * Compare two types and return + * * Ternary.True if they are related with no assumptions, + * * Ternary.Maybe if they are related with assumptions of other relationships, or + * * Ternary.False if they are not related. + */ + function isRelatedTo(source, target, reportErrors, headMessage) { + if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + source = source.regularType; + } + if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { + target = target.regularType; + } + // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases + if (source === target) + return -1 /* True */; + if (relation === identityRelation) { + return isIdenticalTo(source, target); + } + if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) + return -1 /* True */; + if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return 0 /* False */; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { + source = getRegularTypeOfObjectLiteral(source); + } + } + if (relation !== comparableRelation && + !(source.flags & 196608 /* UnionOrIntersection */) && + !(target.flags & 65536 /* Union */) && + !isIntersectionConstituent && + source !== globalObjectType && + getPropertiesOfType(source).length > 0 && + isWeakType(target) && + !hasCommonProperties(source, target)) { + if (reportErrors) { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var result = 0 /* False */; + var saveErrorInfo = errorInfo; + var saveIsIntersectionConstituent = isIntersectionConstituent; + isIntersectionConstituent = false; + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 65536 /* Union */) { + result = relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); + } + else { + if (target.flags & 65536 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */)); + } + else if (target.flags & 131072 /* Intersection */) { + isIntersectionConstituent = true; + result = typeRelatedToEachType(source, target, reportErrors); + } + else if (source.flags & 131072 /* Intersection */) { + // Check to see if any constituents of the intersection are immediately related to the target. + // + // Don't report errors though. Checking whether a constituent is related to the source is not actually + // useful and leads to some confusing error messages. Instead it is better to let the below checks + // take care of this, or to not elaborate at all. For instance, + // + // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. + // + // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection + // than to report that 'D' is not assignable to 'A' or 'B'. + // + // - For a primitive type or type parameter (such as 'number = A & B') there is no point in + // breaking the intersection apart. + result = someTypeRelatedToType(source, target, /*reportErrors*/ false); + } + if (!result && (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */)) { + if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { + errorInfo = saveErrorInfo; + } + } + } + isIntersectionConstituent = saveIsIntersectionConstituent; + if (!result && reportErrors) { + if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + reportRelationError(headMessage, source, target); + } + return result; + } + function isIdenticalTo(source, target) { + var result; + if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); + } + if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || + source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { + if (result = eachTypeRelatedToSomeType(source, target)) { + if (result &= eachTypeRelatedToSomeType(target, source)) { + return result; + } + } + } + return 0 /* False */; + } + function hasExcessProperties(source, target, reportErrors) { + if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + if ((relation === assignableRelation || relation === comparableRelation) && + (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { + return false; + } + var _loop_4 = function (prop) { + if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + if (reportErrors) { + // We know *exactly* where things went wrong when comparing the types. + // Use this property as the error node as this will be more helpful in + // reasoning about what went wrong. + ts.Debug.assert(!!errorNode); + if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { + // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. + // However, using an object-literal error message will be very confusing to the users so we give different a message. + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + } + else { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { + errorNode = prop.valueDeclaration; + } + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + } + return { value: true }; + } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; + } + } + return false; + } + function eachTypeRelatedToSomeType(source, target) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; + var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeRelatedToSomeType(source, target, reportErrors) { + var targetTypes = target.types; + if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { + return -1 /* True */; + } + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); + if (related) { + return related; + } + } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } + return 0 /* False */; + } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } + function typeRelatedToEachType(source, target, reportErrors) { + var result = -1 /* True */; + var targetTypes = target.types; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; + var related = isRelatedTo(source, targetType, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function someTypeRelatedToType(source, target, reportErrors) { + var sourceTypes = source.types; + if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { + return -1 /* True */; + } + var len = sourceTypes.length; + for (var i = 0; i < len; i++) { + var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + if (related) { + return related; + } + } + return 0 /* False */; + } + function eachTypeRelatedToType(source, target, reportErrors) { + var result = -1 /* True */; + var sourceTypes = source.types; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; + var related = isRelatedTo(sourceType, target, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function typeArgumentsRelatedTo(source, target, reportErrors) { + var sources = source.typeArguments || ts.emptyArray; + var targets = target.typeArguments || ts.emptyArray; + if (sources.length !== targets.length && relation === identityRelation) { + return 0 /* False */; + } + var length = sources.length <= targets.length ? sources.length : targets.length; + var result = -1 /* True */; + for (var i = 0; i < length; i++) { + var related = isRelatedTo(sources[i], targets[i], reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. + // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. + // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are + // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion + // and issue an error. Otherwise, actually compare the structure of the two types. + function recursiveTypeRelatedTo(source, target, reportErrors) { + if (overflow) { + return 0 /* False */; + } + var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; + var related = relation.get(id); + if (related !== undefined) { + if (reportErrors && related === 2 /* Failed */) { + // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported + // failure and continue computing the relation such that errors get reported. + relation.set(id, 3 /* FailedAndReported */); + } + else { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } + } + if (!maybeKeys) { + maybeKeys = []; + sourceStack = []; + targetStack = []; + } + else { + for (var i = 0; i < maybeCount; i++) { + // If source and target are already being compared, consider them related with assumptions + if (id === maybeKeys[i]) { + return 1 /* Maybe */; + } + } + if (depth === 100) { + overflow = true; + return 0 /* False */; + } + } + var maybeStart = maybeCount; + maybeKeys[maybeCount] = id; + maybeCount++; + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + var saveExpandingFlags = expandingFlags; + if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) + expandingFlags |= 1; + if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) + expandingFlags |= 2; + var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; + expandingFlags = saveExpandingFlags; + depth--; + if (result) { + if (result === -1 /* True */ || depth === 0) { + // If result is definitely true, record all maybe keys as having succeeded + for (var i = maybeStart; i < maybeCount; i++) { + relation.set(maybeKeys[i], 1 /* Succeeded */); + } + maybeCount = maybeStart; + } + } + else { + // A false result goes straight into global cache (when something is false under + // assumptions it will also be false without assumptions) + relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); + maybeCount = maybeStart; + } + return result; + } + function structuredTypeRelatedTo(source, target, reportErrors) { + var result; + var saveErrorInfo = errorInfo; + if (target.flags & 16384 /* TypeParameter */) { + // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. + if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { + if (!source.declaration.questionToken) { + var templateType = getTemplateTypeFromMappedType(source); + var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); + if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { + return result; + } + } + } + } + else if (target.flags & 262144 /* Index */) { + // A keyof S is related to a keyof T if T is related to S. + if (source.flags & 262144 /* Index */) { + if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { + return result; + } + } + // A type S is assignable to keyof T if S is assignable to keyof C, where C is the + // constraint of T. + var constraint = getConstraintOfType(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { + return result; + } + } + } + else if (target.flags & 524288 /* IndexedAccess */) { + // A type S is related to a type T[K] if S is related to A[K], where K is string-like and + // A is the apparent type of S. + var constraint = getConstraintOfType(target); + if (constraint) { + if (result = isRelatedTo(source, constraint, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + if (source.flags & 16384 /* TypeParameter */) { + // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. + if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { + var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + var constraint = getConstraintOfTypeParameter(source); + // A type parameter with no constraint is not related to the non-primitive object type. + if (constraint || !(target.flags & 16777216 /* NonPrimitive */)) { + if (!constraint || constraint.flags & 1 /* Any */) { + constraint = emptyObjectType; + } + // The constraint may need to be further instantiated with its 'this' type. + constraint = getTypeWithThisArgument(constraint, source); + // Report constraint errors only if the constraint is not the empty object type + var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + } + } + else if (source.flags & 524288 /* IndexedAccess */) { + // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and + // A is the apparent type of S. + var constraint = getConstraintOfType(source); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (target.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { + // if we have indexed access types with identical index types, see if relationship holds for + // the two object types. + if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + return result; + } + } + } + else { + if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // We have type references to same target type, see if relationship holds for all type arguments + if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { + return result; + } + } + // Even if relationship doesn't hold for unions, intersections, or generic type references, + // it may hold in a structural comparison. + var sourceIsPrimitive = !!(source.flags & 8190 /* Primitive */); + if (relation !== identityRelation) { + source = getApparentType(source); + } + // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates + // to X. Failing both of those we want to check if the aggregation of A and B's members structurally + // relates to X. Thus, we include intersection types on the source side here. + if (source.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { + // Report structural errors only if we haven't reported any errors yet + var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + result = -1 /* True */; + } + else if (isGenericMappedType(target)) { + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : 0 /* False */; + } + else { + result = propertiesRelatedTo(source, target, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); + if (result) { + result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); + if (result) { + result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); + } + } + } + } + } + if (result) { + errorInfo = saveErrorInfo; + return result; + } + } + } + return 0 /* False */; + } + // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is + // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice + // that S and T are contra-variant whereas X and Y are co-variant. + function mappedTypeRelatedTo(source, target, reportErrors) { + var sourceReadonly = !!source.declaration.readonlyToken; + var sourceOptional = !!source.declaration.questionToken; + var targetReadonly = !!target.declaration.readonlyToken; + var targetOptional = !!target.declaration.questionToken; + var modifiersRelated = relation === identityRelation ? + sourceReadonly === targetReadonly && sourceOptional === targetOptional : + relation === comparableRelation || !sourceOptional || targetOptional; + if (modifiersRelated) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + } + } + return 0 /* False */; + } + function propertiesRelatedTo(source, target, reportErrors) { + if (relation === identityRelation) { + return propertiesIdenticalTo(source, target); + } + var result = -1 /* True */; + var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var targetProp = properties_3[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp !== targetProp) { + if (!sourceProp) { + if (!(targetProp.flags & 16777216 /* Optional */) || requireOptionalProperties) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); + } + return 0 /* False */; + } + } + else if (!(targetProp.flags & 4194304 /* Prototype */)) { + var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); + var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); + if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + 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)); + } + return 0 /* False */; + } + if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (reportErrors) { + if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { + reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); + } + else { + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); + } + } + return 0 /* False */; + } + } + else if (targetPropFlags & 16 /* Protected */) { + if (!isValidOverrideOf(sourceProp, targetProp)) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); + } + return 0 /* False */; + } + } + else if (sourcePropFlags & 16 /* Protected */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); + } + return 0 /* False */; + } + result &= related; + // When checking for comparability, be more lenient with optional properties. + if (relation !== comparableRelation && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) { + // TypeScript 1.0 spec (April 2014): 3.8.3 + // S is a subtype of a type T, and T is a supertype of S if ... + // S' and T are object types and, for each member M in T.. + // M is a property and S' contains a property N where + // if M is a required property, N is also a required property + // (M - property in T) + // (N - property in S) + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); + } + return 0 /* False */; + } + } + } + } + return result; + } + /** + * A type is 'weak' if it is an object type with at least one optional property + * and no required properties, call/construct signatures or index signatures + */ + function isWeakType(type) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && + !resolved.stringIndexInfo && !resolved.numberIndexInfo && + resolved.properties.length > 0 && + ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); + } + if (type.flags & 131072 /* Intersection */) { + return ts.every(type.types, isWeakType); + } + return false; + } + function hasCommonProperties(source, target) { + var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { + return true; + } + } + return false; + } + function propertiesIdenticalTo(source, target) { + if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { + return 0 /* False */; + } + var sourceProperties = getPropertiesOfObjectType(source); + var targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; + var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); + if (!targetProp) { + return 0 /* False */; + } + var related = compareProperties(sourceProp, targetProp, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function signaturesRelatedTo(source, target, kind, reportErrors) { + if (relation === identityRelation) { + return signaturesIdenticalTo(source, target, kind); + } + if (target === anyFunctionType || source === anyFunctionType) { + return -1 /* True */; + } + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { + if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { + // An abstract constructor type is not assignable to a non-abstract constructor type + // as it would otherwise be possible to new an abstract class. Note that the assignability + // check we perform for an extends clause excludes construct signatures from the target, + // so this check never proceeds. + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { + return 0 /* False */; + } + } + var result = -1 /* True */; + var saveErrorInfo = errorInfo; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We have 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. We erase type parameters + // as they are known to always be the same. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + else if (sourceSignatures.length === 1 && targetSignatures.length === 1) { + // For simple functions (functions with a single signature) we only erase type parameters for + // the comparable relation. Otherwise, if the source signature is generic, we instantiate it + // in the context of the target signature before checking the relationship. Ideally we'd do + // this regardless of the number of signatures, but the potential costs are prohibitive due + // to the quadratic nature of the logic below. + var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); + } + 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, /*erase*/ true, 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 result; + } + /** + * See signatureAssignableTo, compareSignaturesIdentical + */ + function signatureRelatedTo(source, target, erase, reportErrors) { + return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, + /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); + } + function signaturesIdenticalTo(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + if (sourceSignatures.length !== targetSignatures.length) { + return 0 /* False */; + } + var result = -1 /* True */; + for (var i = 0; i < sourceSignatures.length; i++) { + var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + if (!related) { + return 0 /* False */; + } + result &= related; + } + return result; + } + function eachPropertyRelatedTo(source, target, kind, reportErrors) { + var result = -1 /* True */; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { + var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); + } + return 0 /* False */; + } + result &= related; + } + } + return result; + } + function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { + var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); + if (!related && reportErrors) { + reportError(ts.Diagnostics.Index_signatures_are_incompatible); + } + return related; + } + function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { + if (relation === identityRelation) { + return indexTypesIdenticalTo(source, target, kind); + } + var targetInfo = getIndexInfoOfType(target, kind); + if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) { + // Index signature of type any permits assignment from everything but primitives + return -1 /* True */; + } + var sourceInfo = getIndexInfoOfType(source, kind) || + kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); + if (sourceInfo) { + return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); + } + if (isObjectLiteralType(source)) { + var related = -1 /* True */; + if (kind === 0 /* String */) { + var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); + if (sourceNumberInfo) { + related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); + } + } + if (related) { + related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); + } + return related; + } + if (reportErrors) { + reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); + } + return 0 /* False */; + } + function indexTypesIdenticalTo(source, target, indexKind) { + var targetInfo = getIndexInfoOfType(target, indexKind); + var sourceInfo = getIndexInfoOfType(source, indexKind); + if (!sourceInfo && !targetInfo) { + return -1 /* True */; + } + if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { + return isRelatedTo(sourceInfo.type, targetInfo.type); + } + return 0 /* False */; + } + function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { + if (!sourceSignature.declaration || !targetSignature.declaration) { + return true; + } + var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; + // A public, protected and private signature is assignable to a private signature. + if (targetAccessibility === 8 /* Private */) { + return true; + } + // A public and protected signature is assignable to a protected signature. + if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { + return true; + } + // Only a public signature is assignable to public signature. + if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { + return true; + } + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); + } + return false; + } + } + // 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 (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.escapedName); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // 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 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 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 + function isAbstractConstructorType(type) { + if (getObjectFlags(type) & 16 /* Anonymous */) { + var symbol = type.symbol; + if (symbol && symbol.flags & 32 /* Class */) { + var declaration = getClassLikeDeclarationOfSymbol(symbol); + if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { + return true; + } + } + } + return false; + } + // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons + // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // levels, but unequal at some level beyond that. + function isDeeplyNestedType(type, stack, depth) { + // We track all object types that have an associated symbol (representing the origin of the type) + if (depth >= 5 && type.flags & 32768 /* Object */) { + var symbol = type.symbol; + if (symbol) { + var count = 0; + for (var i = 0; i < depth; i++) { + var t = stack[i]; + if (t.flags & 32768 /* Object */ && t.symbol === symbol) { + count++; + if (count >= 5) + return true; + } + } + } + } + return false; + } + function isPropertyIdenticalTo(sourceProp, targetProp) { + return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; + } + function compareProperties(sourceProp, targetProp, compareTypes) { + // Two members are considered identical when + // - they are public properties with identical names, optionality, and types, + // - they are private or protected properties originating in the same declaration and having identical types + if (sourceProp === targetProp) { + return -1 /* True */; + } + var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; + var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; + if (sourcePropAccessibility !== targetPropAccessibility) { + return 0 /* False */; + } + if (sourcePropAccessibility) { + if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { + return 0 /* False */; + } + } + else { + if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) { + return 0 /* False */; + } + } + if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { + return 0 /* False */; + } + return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + function isMatchingSignature(source, target, partialMatch) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). + var sourceRestCount = source.hasRestParameter ? 1 : 0; + var targetRestCount = target.hasRestParameter ? 1 : 0; + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + /** + * See signatureRelatedTo, compareSignaturesIdentical + */ + function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { + // TODO (drosen): De-duplicate code between related functions. + if (source === target) { + return -1 /* True */; + } + if (!(isMatchingSignature(source, target, partialMatch))) { + return 0 /* False */; + } + // Check that the two signatures have the same number of type parameters. We might consider + // also checking that any type parameter constraints match, but that would require instantiating + // the constraints with a common set of type arguments to get relatable entities in places where + // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, + // particularly as we're comparing erased versions of the signatures below. + if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { + return 0 /* False */; + } + // Spec 1.0 Section 3.8.3 & 3.8.4: + // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N + source = getErasedSignature(source); + target = getErasedSignature(target); + var result = -1 /* True */; + if (!ignoreThisTypes) { + var sourceThisType = getThisTypeOfSignature(source); + if (sourceThisType) { + var targetThisType = getThisTypeOfSignature(target); + if (targetThisType) { + var related = compareTypes(sourceThisType, targetThisType); + if (!related) { + return 0 /* False */; + } + result &= related; + } + } + } + var targetLen = target.parameters.length; + for (var i = 0; i < targetLen; i++) { + var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); + var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var related = compareTypes(s, t); + if (!related) { + return 0 /* False */; + } + result &= related; + } + if (!ignoreReturnTypes) { + result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + return result; + } + function isRestParameterIndex(signature, parameterIndex) { + return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; + } + function literalTypesWithSameBaseType(types) { + var commonBaseType; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; + var baseType = getBaseTypeOfLiteralType(t); + if (!commonBaseType) { + commonBaseType = baseType; + } + if (baseType === t || baseType !== commonBaseType) { + return false; + } + } + return true; + } + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. + function getSupertypeOrUnion(types) { + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); + } + function getCommonSupertype(types) { + if (!strictNullChecks) { + return getSupertypeOrUnion(types); + } + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144 /* Nullable */) : + getUnionType(types, /*subtypeReduction*/ true); + } + function isArrayType(type) { + return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + } + function isArrayLikeType(type) { + // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, + // or if it is not the undefined or null type and if it is assignable to ReadonlyArray + return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || + !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + } + function isTupleLikeType(type) { + return !!getPropertyOfType(type, "0"); + } + function isUnitType(type) { + 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 & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + isUnitType(type); + } + function getBaseTypeOfLiteralType(type) { + 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 & 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; + } + /** + * Check if a Type was written as a tuple type literal. + * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. + */ + function isTupleType(type) { + return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); + } + function getFalsyFlagsOfTypes(types) { + var result = 0; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; + result |= getFalsyFlags(t); + } + return result; + } + // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null + // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns + // 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.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 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; + } + /** + * Add undefined or null or both to a type if they are missing. + * @param type - type to add undefined and/or null to if not present + * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both + */ + 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; + } + /** + * Return true if type was inferred from an object literal or written as an object type literal + * with no call or construct signatures. + */ + function isObjectLiteralType(type) { + return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && + getSignaturesOfType(type, 0 /* Call */).length === 0 && + getSignaturesOfType(type, 1 /* Construct */).length === 0; + } + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.escapedName); + symbol.declarations = source.declarations; + symbol.parent = source.parent; + symbol.type = type; + symbol.target = source; + if (source.valueDeclaration) { + symbol.valueDeclaration = source.valueDeclaration; + } + return symbol; + } + function transformTypeOfMembers(type, f) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var property = _a[_i]; + var original = getTypeOfSymbol(property); + var updated = f(original); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); + } + return members; + } + /** + * If the the provided object literal is subject to the excess properties check, + * create a new that is exempt. Recursively mark object literal members as exempt. + * Leave signatures alone since they are not subject to the check. + */ + function getRegularTypeOfObjectLiteral(type) { + if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { + return type; + } + var regularType = type.regularType; + if (regularType) { + return regularType; + } + var resolved = type; + var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); + var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); + regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; + regularNew.objectFlags |= 128 /* ObjectLiteral */; + type.regularType = regularNew; + return regularNew; + } + function getWidenedProperty(prop) { + var original = getTypeOfSymbol(prop); + var widened = getWidenedType(original); + return widened === original ? prop : createSymbolWithType(prop, widened); + } + function getWidenedTypeOfObjectLiteral(type) { + var members = ts.createSymbolTable(); + for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { + var prop = _a[_i]; + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop) : prop); + } + var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); + } + function getWidenedConstituentType(type) { + return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); + } + function getWidenedType(type) { + if (type.flags & 6291456 /* RequiresWidening */) { + if (type.flags & 6144 /* Nullable */) { + return anyType; + } + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { + return getWidenedTypeOfObjectLiteral(type); + } + if (type.flags & 65536 /* Union */) { + return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); + } + if (isArrayType(type) || isTupleType(type)) { + return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); + } + } + return type; + } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ + function reportWideningErrorsInType(type) { + var errorReported = false; + if (type.flags & 65536 /* Union */) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (isArrayType(type) || isTupleType(type)) { + for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } + if (getObjectFlags(type) & 128 /* ObjectLiteral */) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; + var t = getTypeOfSymbol(p); + if (t.flags & 2097152 /* ContainsWideningType */) { + if (!reportWideningErrorsInType(t)) { + error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, ts.unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); + } + errorReported = true; + } + } + } + return errorReported; + } + function reportImplicitAnyError(declaration, type) { + var typeAsString = typeToString(getWidenedType(type)); + var diagnostic; + switch (declaration.kind) { + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; + break; + case 146 /* Parameter */: + diagnostic = declaration.dotDotDotToken ? + ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : + ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; + break; + case 176 /* BindingElement */: + diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + break; + case 228 /* FunctionDeclaration */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + if (!declaration.name) { + error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); + return; + } + diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; + break; + default: + diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; + } + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); + } + function reportErrorsFromWidening(declaration, type) { + if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { + // Report implicit any error within type if possible, otherwise report error on declaration + if (!reportWideningErrorsInType(type)) { + reportImplicitAnyError(declaration, type); + } + } + } + function forEachMatchingParameterType(source, target, callback) { + var sourceMax = source.parameters.length; + var targetMax = target.parameters.length; + var count; + if (source.hasRestParameter && target.hasRestParameter) { + count = Math.max(sourceMax, targetMax); + } + else if (source.hasRestParameter) { + count = targetMax; + } + else if (target.hasRestParameter) { + count = sourceMax; + } + else { + count = Math.min(sourceMax, targetMax); + } + for (var i = 0; i < count; i++) { + callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); + } + } + function createInferenceContext(signature, flags, baseInferences) { + var inferences = baseInferences ? ts.map(baseInferences, cloneInferenceInfo) : ts.map(signature.typeParameters, createInferenceInfo); + var context = mapper; + context.mappedTypes = signature.typeParameters; + context.signature = signature; + context.inferences = inferences; + context.flags = flags; + return context; + function mapper(t) { + for (var i = 0; i < inferences.length; i++) { + if (t === inferences[i].typeParameter) { + inferences[i].isFixed = true; + return getInferredType(context, i); + } + } + return t; + } + } + function createInferenceInfo(typeParameter) { + return { + typeParameter: typeParameter, + candidates: undefined, + inferredType: undefined, + priority: undefined, + topLevel: true, + isFixed: false + }; + } + function cloneInferenceInfo(inference) { + return { + typeParameter: inference.typeParameter, + candidates: inference.candidates && inference.candidates.slice(), + inferredType: inference.inferredType, + priority: inference.priority, + topLevel: inference.topLevel, + isFixed: inference.isFixed + }; + } + // Return true if the given type could possibly reference a type parameter for which + // we perform type inference (i.e. a type parameter of a generic function). We cache + // results for union and intersection types for performance reasons. + function couldContainTypeVariables(type) { + var objectFlags = getObjectFlags(type); + return !!(type.flags & 540672 /* TypeVariable */ || + objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || + objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || + objectFlags & 32 /* Mapped */ || + type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + } + function couldUnionOrIntersectionContainTypeVariables(type) { + if (type.couldContainTypeVariables === undefined) { + type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + } + return type.couldContainTypeVariables; + } + function isTypeParameterAtTopLevel(type, typeParameter) { + return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + } + // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct + // an object type with the same set of properties as the source type, where the type of each + // property is computed by inferring from the source property type to X for the type + // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). + function inferTypeForHomomorphicMappedType(source, target) { + var properties = getPropertiesOfType(source); + var indexInfo = getIndexInfoOfType(source, 0 /* String */); + if (properties.length === 0 && !indexInfo) { + return undefined; + } + var typeParameter = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); + var inference = createInferenceInfo(typeParameter); + var inferences = [inference]; + var templateType = getTemplateTypeFromMappedType(target); + var readonlyMask = target.declaration.readonlyToken ? false : true; + var optionalMask = target.declaration.questionToken ? 0 : 16777216 /* Optional */; + var members = ts.createSymbolTable(); + for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { + var prop = properties_4[_i]; + var inferredPropType = inferTargetType(getTypeOfSymbol(prop)); + if (!inferredPropType) { + return undefined; + } + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; + inferredProp.declarations = prop.declarations; + inferredProp.type = inferredPropType; + members.set(prop.escapedName, inferredProp); + } + if (indexInfo) { + var inferredIndexType = inferTargetType(indexInfo.type); + if (!inferredIndexType) { + return undefined; + } + indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); + } + return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); + function inferTargetType(sourceType) { + inference.candidates = undefined; + inferTypes(inferences, sourceType, templateType); + return inference.candidates && getUnionType(inference.candidates, /*subtypeReduction*/ true); + } + } + function inferTypes(inferences, originalSource, originalTarget, priority) { + if (priority === void 0) { priority = 0; } + var symbolStack; + var visited; + inferFromTypes(originalSource, originalTarget); + function inferFromTypes(source, target) { + if (!couldContainTypeVariables(target)) { + return; + } + if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { + // Source and target are types originating in the same generic type alias declaration. + // Simply infer from source type arguments to target type arguments. + var sourceTypes = source.aliasTypeArguments; + var targetTypes = target.aliasTypeArguments; + for (var i = 0; i < sourceTypes.length; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + return; + } + 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. + if (source === target) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + inferFromTypes(t, t); + } + return; + } + // Find each source constituent type that has an identically matching target constituent + // type, and for each such type infer from the type to itself. When inferring from a + // type to itself we effectively find all type parameter occurrences within that type + // and infer themselves as their type arguments. We have special handling for numeric + // and string literals because the number and string types are not represented as unions + // of all their possible values. + var matchingTypes = void 0; + for (var _b = 0, _c = source.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (typeIdenticalToSomeType(t, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t); + inferFromTypes(t, t); + } + else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { + var b = getBaseTypeOfLiteralType(t); + if (typeIdenticalToSomeType(b, target.types)) { + (matchingTypes || (matchingTypes = [])).push(t, b); + } + } + } + // Next, to improve the quality of inferences, reduce the source and target types by + // removing the identically matched constituents. For example, when inferring from + // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. + if (matchingTypes) { + source = removeTypesFromUnionOrIntersection(source, matchingTypes); + target = removeTypesFromUnionOrIntersection(target, matchingTypes); + } + } + if (target.flags & 540672 /* TypeVariable */) { + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. Also, we exclude inferences for silentNeverType which is used as a wildcard + // when constructing types from type parameters that had no inference candidates. + if (source.flags & 8388608 /* ContainsAnyFunctionType */ || source === silentNeverType) { + return; + } + var inference = getInferenceInfoForType(target); + if (inference) { + if (!inference.isFixed) { + if (!inference.candidates || priority < inference.priority) { + inference.candidates = [source]; + inference.priority = priority; + } + else if (priority === inference.priority) { + inference.candidates.push(source); + } + if (!(priority & 4 /* ReturnType */) && target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + inference.topLevel = false; + } + } + return; + } + } + else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { + // If source and target are references to the same generic type, infer from type arguments + var sourceTypes = source.typeArguments || ts.emptyArray; + var targetTypes = target.typeArguments || ts.emptyArray; + var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + for (var i = 0; i < count; i++) { + inferFromTypes(sourceTypes[i], targetTypes[i]); + } + } + else if (target.flags & 196608 /* UnionOrIntersection */) { + var targetTypes = target.types; + var typeVariableCount = 0; + var typeVariable = void 0; + // First infer to each type in union or intersection that isn't a type variable + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; + if (getInferenceInfoForType(t)) { + typeVariable = t; + typeVariableCount++; + } + else { + inferFromTypes(source, t); + } + } + // Next, if target containings a single naked type variable, make a secondary inference to that type + // variable. This gives meaningful results for union types in co-variant positions and intersection + // types in contra-variant positions (such as callback parameters). + if (typeVariableCount === 1) { + var savePriority = priority; + priority |= 1 /* NakedTypeVariable */; + inferFromTypes(source, typeVariable); + priority = savePriority; + } + } + else if (source.flags & 196608 /* UnionOrIntersection */) { + // Source is a union or intersection type, infer from each constituent type + var sourceTypes = source.types; + for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { + var sourceType = sourceTypes_3[_e]; + inferFromTypes(sourceType, target); + } + } + else { + source = getApparentType(source); + if (source.flags & 32768 /* Object */) { + var key = source.id + "," + target.id; + if (visited && visited.get(key)) { + return; + } + (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); + } + } + } + } + function getInferenceInfoForType(type) { + if (type.flags & 540672 /* TypeVariable */) { + for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { + var inference = inferences_1[_i]; + if (type === inference.typeParameter) { + return inference; + } + } + } + return undefined; + } + function inferFromObjectTypes(source, target) { + if (getObjectFlags(target) & 32 /* Mapped */) { + var constraintType = getConstraintTypeFromMappedType(target); + if (constraintType.flags & 262144 /* Index */) { + // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, + // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source + // type and then make a secondary inference from that type to T. We make a secondary inference + // such that direct inferences to T get priority over inferences to Partial, for example. + var inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + var inferredType = inferTypeForHomomorphicMappedType(source, target); + if (inferredType) { + var savePriority = priority; + priority |= 2 /* MappedType */; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + return; + } + if (constraintType.flags & 16384 /* TypeParameter */) { + // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type + // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + inferFromTypes(getIndexType(source), constraintType); + inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); + return; + } + } + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target); + } + function inferFromProperties(source, target) { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { + var targetProp = properties_5[_i]; + var sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } + } + } + function inferFromSignatures(source, target, kind) { + var sourceSignatures = getSignaturesOfType(source, kind); + var targetSignatures = getSignaturesOfType(target, kind); + var sourceLen = sourceSignatures.length; + var targetLen = targetSignatures.length; + var len = sourceLen < targetLen ? sourceLen : targetLen; + for (var i = 0; i < len; i++) { + inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); + } + } + function inferFromSignature(source, target) { + forEachMatchingParameterType(source, target, inferFromTypes); + if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { + inferFromTypes(source.typePredicate.type, target.typePredicate.type); + } + else { + inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } + function inferFromIndexTypes(source, target) { + var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); + if (targetStringIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 0 /* String */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetStringIndexType); + } + } + var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); + if (targetNumberIndexType) { + var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || + getIndexTypeOfType(source, 0 /* String */) || + getImplicitIndexTypeOfType(source, 1 /* Number */); + if (sourceIndexType) { + inferFromTypes(sourceIndexType, targetNumberIndexType); + } + } + } + } + function typeIdenticalToSomeType(type, types) { + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; + if (isTypeIdenticalTo(t, type)) { + return true; + } + } + return false; + } + /** + * Return a new union or intersection type computed by removing a given set of types + * from a given union or intersection type. + */ + function removeTypesFromUnionOrIntersection(type, typesToRemove) { + var reducedTypes = []; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!typeIdenticalToSomeType(t, typesToRemove)) { + reducedTypes.push(t); + } + } + return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + } + function hasPrimitiveConstraint(type) { + var constraint = getConstraintOfTypeParameter(type); + return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); + } + function getInferredType(context, index) { + var inference = context.inferences[index]; + var inferredType = inference.inferredType; + if (!inferredType) { + if (inference.candidates) { + // We widen inferred literal types if + // all inferences were made to top-level ocurrences of the type parameter, and + // the type parameter has no constraint or its constraint includes no primitive or literal types, and + // the type parameter was fixed during inference or does not occur at top-level in the return type. + var signature = context.signature; + var widenLiteralTypes = inference.topLevel && + !hasPrimitiveConstraint(inference.typeParameter) && + (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); + var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; + // Infer widened union or supertype, or the unknown type for no common supertype. We infer union types + // for inferences coming from return types in order to avoid common supertype failures. + var unionOrSuperType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, /*subtypeReduction*/ true) : getCommonSupertype(baseCandidates); + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; + } + else { + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); + } + else { + inferredType = getDefaultTypeArgumentType(!!(context.flags & 4 /* AnyDefault */)); + } + } + inference.inferredType = inferredType; + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; + } + } + } + return inferredType; + } + function getDefaultTypeArgumentType(isInJavaScriptFile) { + return isInJavaScriptFile ? anyType : emptyObjectType; + } + function getInferredTypes(context) { + var result = []; + for (var i = 0; i < context.inferences.length; i++) { + result.push(getInferredType(context, i)); + } + return result; + } + // EXPRESSION TYPE CHECKING + function getResolvedSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + links.resolvedSymbol = !ts.nodeIsMissing(node) && resolveName(node, node.escapedText, 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; + } + function isInTypeQuery(node) { + // TypeScript 1.0 spec (April 2014): 3.6.3 + // A type query consists of the keyword typeof followed by an expression. + // The expression is restricted to a single identifier or a sequence of identifiers separated by periods + return !!ts.findAncestor(node, function (n) { return n.kind === 162 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 143 /* QualifiedName */ ? false : "quit"; }); + } + // 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. 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 ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + } + if (node.kind === 99 /* ThisKeyword */) { + return "0"; + } + if (node.kind === 179 /* PropertyAccessExpression */) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + ts.unescapeLeadingUnderscores(node.name.escapedText); + } + if (node.kind === 176 /* BindingElement */) { + var container = node.parent.parent; + var key = container.kind === 176 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var text = getBindingElementNameText(node); + var result = key && text && (key + "." + text); + return result; + } + return undefined; + } + function getLeftmostIdentifierOrThis(node) { + switch (node.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + return node; + case 179 /* PropertyAccessExpression */: + return getLeftmostIdentifierOrThis(node.expression); + } + return undefined; + } + function getBindingElementNameText(element) { + if (element.parent.kind === 174 /* ObjectBindingPattern */) { + var name = element.propertyName || element.name; + switch (name.kind) { + case 71 /* Identifier */: + return ts.unescapeLeadingUnderscores(name.escapedText); + case 144 /* ComputedPropertyName */: + return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + return name.text; + default: + // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined + ts.Debug.fail("Unexpected name kind for binding element name"); + } + } + else { + return "" + element.parent.elements.indexOf(element); + } + } + function isMatchingReference(source, target) { + switch (source.kind) { + case 71 /* Identifier */: + return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || + (target.kind === 226 /* VariableDeclaration */ || target.kind === 176 /* BindingElement */) && + getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); + case 99 /* ThisKeyword */: + return target.kind === 99 /* ThisKeyword */; + case 97 /* SuperKeyword */: + return target.kind === 97 /* SuperKeyword */; + case 179 /* PropertyAccessExpression */: + return target.kind === 179 /* PropertyAccessExpression */ && + source.name.escapedText === target.name.escapedText && + isMatchingReference(source.expression, target.expression); + case 176 /* BindingElement */: + if (target.kind !== 179 /* PropertyAccessExpression */) + return false; + var t = target; + if (t.name.escapedText !== getBindingElementNameText(source)) + return false; + if (source.parent.parent.kind === 176 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + return true; + } + if (source.parent.parent.kind === 226 /* VariableDeclaration */) { + var maybeId = source.parent.parent.initializer; + return maybeId && isMatchingReference(maybeId, t.expression); + } + } + return false; + } + function containsMatchingReference(source, target) { + while (source.kind === 179 /* PropertyAccessExpression */) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared + // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property + // a possible discriminant if its type differs in the constituents of containing union type, and if every + // choice is a unit type or a union of unit types. + function containsMatchingReferenceDiscriminant(source, target) { + return target.kind === 179 /* PropertyAccessExpression */ && + containsMatchingReference(source, target.expression) && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + } + function getDeclaredTypeOfReference(expr) { + if (expr.kind === 71 /* Identifier */) { + return getTypeOfSymbol(getResolvedSymbol(expr)); + } + if (expr.kind === 179 /* PropertyAccessExpression */) { + var type = getDeclaredTypeOfReference(expr.expression); + return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + } + return undefined; + } + function isDiscriminantProperty(type, name) { + if (type && type.flags & 65536 /* Union */) { + var prop = getUnionOrIntersectionProperty(type, name); + if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { + if (prop.isDiscriminantProperty === undefined) { + prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); + } + return prop.isDiscriminantProperty; + } + } + return false; + } + function isOrContainsMatchingReference(source, target) { + return isMatchingReference(source, target) || containsMatchingReference(source, target); + } + function hasMatchingArgument(callExpression, reference) { + if (callExpression.arguments) { + for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isOrContainsMatchingReference(reference, argument)) { + return true; + } + } + } + if (callExpression.expression.kind === 179 /* PropertyAccessExpression */ && + isOrContainsMatchingReference(reference, callExpression.expression.expression)) { + return true; + } + return false; + } + function getFlowNodeId(flow) { + if (!flow.id) { + flow.id = nextFlowId; + nextFlowId++; + } + return flow.id; + } + function typeMaybeAssignableTo(source, target) { + if (!(source.flags & 65536 /* Union */)) { + return isTypeAssignableTo(source, target); + } + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isTypeAssignableTo(t, target)) { + return true; + } + } + return false; + } + // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. + // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, + // we remove type string. + function getAssignmentReducedType(declaredType, assignedType) { + if (declaredType !== assignedType) { + if (assignedType.flags & 8192 /* Never */) { + return assignedType; + } + var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); + if (!(reducedType.flags & 8192 /* Never */)) { + return reducedType; + } + } + return declaredType; + } + function getTypeFactsOfTypes(types) { + var result = 0 /* None */; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; + result |= getTypeFacts(t); + } + return result; + } + function isFunctionObjectType(type) { + // We do a quick check for a "bind" property before performing the more expensive subtype + // check. This gives us a quicker out in the common case where an object type is not a function. + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.callSignatures.length || resolved.constructSignatures.length || + resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); + } + function getTypeFacts(type) { + var flags = type.flags; + if (flags & 2 /* String */) { + return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; + } + if (flags & 32 /* StringLiteral */) { + var isEmpty = type.value === ""; + return strictNullChecks ? + 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 */) { + var isZero = type.value === 0; + return strictNullChecks ? + isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : + isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; + } + if (flags & 8 /* Boolean */) { + return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; + } + if (flags & 136 /* BooleanLike */) { + return strictNullChecks ? + type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : + type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; + } + if (flags & 32768 /* Object */) { + return isFunctionObjectType(type) ? + strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : + strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + } + if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { + return 2457472 /* UndefinedFacts */; + } + if (flags & 4096 /* Null */) { + return 2340752 /* NullFacts */; + } + if (flags & 512 /* ESSymbol */) { + return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; + } + if (flags & 16777216 /* NonPrimitive */) { + return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; + } + if (flags & 540672 /* TypeVariable */) { + return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); + } + if (flags & 196608 /* UnionOrIntersection */) { + return getTypeFactsOfTypes(type.types); + } + return 8388607 /* All */; + } + function getTypeWithFacts(type, include) { + return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); + } + function getTypeWithDefault(type, defaultExpression) { + if (defaultExpression) { + var defaultType = getTypeOfExpression(defaultExpression); + return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); + } + return type; + } + function getTypeOfDestructuredProperty(type, name) { + var text = ts.getTextOfPropertyName(name); + return getTypeOfPropertyOfType(type, text) || + isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || + getIndexTypeOfType(type, 0 /* String */) || + unknownType; + } + function getTypeOfDestructuredArrayElement(type, index) { + return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || + unknownType; + } + function getTypeOfDestructuredSpreadExpression(type) { + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType); + } + function getAssignedTypeOfBinaryExpression(node) { + var isDestructuringDefaultAssignment = node.parent.kind === 177 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 261 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? + getTypeWithDefault(getAssignedType(node), node.right) : + getTypeOfExpression(node.right); + } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 194 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 216 /* ForOfStatement */ && parent.parent.initializer === parent; + } + function getAssignedTypeOfArrayLiteralElement(node, element) { + return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + } + function getAssignedTypeOfSpreadExpression(node) { + return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); + } + function getAssignedTypeOfPropertyAssignment(node) { + return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); + } + function getAssignedTypeOfShorthandPropertyAssignment(node) { + return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); + } + function getAssignedType(node) { + var parent = node.parent; + switch (parent.kind) { + case 215 /* ForInStatement */: + return stringType; + case 216 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; + case 194 /* BinaryExpression */: + return getAssignedTypeOfBinaryExpression(parent); + case 188 /* DeleteExpression */: + return undefinedType; + case 177 /* ArrayLiteralExpression */: + return getAssignedTypeOfArrayLiteralElement(parent, node); + case 198 /* SpreadElement */: + return getAssignedTypeOfSpreadExpression(parent); + case 261 /* PropertyAssignment */: + return getAssignedTypeOfPropertyAssignment(parent); + case 262 /* ShorthandPropertyAssignment */: + return getAssignedTypeOfShorthandPropertyAssignment(parent); + } + return unknownType; + } + function getInitialTypeOfBindingElement(node) { + var pattern = node.parent; + var parentType = getInitialType(pattern.parent); + var type = pattern.kind === 174 /* ObjectBindingPattern */ ? + getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : + !node.dotDotDotToken ? + getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredSpreadExpression(parentType); + return getTypeWithDefault(type, node.initializer); + } + function getTypeOfInitializer(node) { + // Return the cached type if one is available. If the type of the variable was inferred + // from its initializer, we'll already have cached the type. Otherwise we compute it now + // without caching such that transient types are reflected. + var links = getNodeLinks(node); + return links.resolvedType || getTypeOfExpression(node); + } + function getInitialTypeOfVariableDeclaration(node) { + if (node.initializer) { + return getTypeOfInitializer(node.initializer); + } + if (node.parent.parent.kind === 215 /* ForInStatement */) { + return stringType; + } + if (node.parent.parent.kind === 216 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; + } + return unknownType; + } + function getInitialType(node) { + return node.kind === 226 /* VariableDeclaration */ ? + getInitialTypeOfVariableDeclaration(node) : + getInitialTypeOfBindingElement(node); + } + function getInitialOrAssignedType(node) { + return node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */ ? + getInitialType(node) : + getAssignedType(node); + } + function isEmptyArrayAssignment(node) { + return node.kind === 226 /* VariableDeclaration */ && node.initializer && + isEmptyArrayLiteral(node.initializer) || + node.kind !== 176 /* BindingElement */ && node.parent.kind === 194 /* BinaryExpression */ && + isEmptyArrayLiteral(node.parent.right); + } + function getReferenceCandidate(node) { + switch (node.kind) { + case 185 /* ParenthesizedExpression */: + return getReferenceCandidate(node.expression); + case 194 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 58 /* EqualsToken */: + return getReferenceCandidate(node.left); + case 26 /* CommaToken */: + return getReferenceCandidate(node.right); + } + } + return node; + } + function getReferenceRoot(node) { + var parent = node.parent; + return parent.kind === 185 /* ParenthesizedExpression */ || + parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + getReferenceRoot(parent) : node; + } + function getTypeOfSwitchClause(clause) { + if (clause.kind === 257 /* CaseClause */) { + var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); + return isUnitType(caseType) ? caseType : undefined; + } + return neverType; + } + function getSwitchClauseTypes(switchStatement) { + var links = getNodeLinks(switchStatement); + if (!links.switchTypes) { + // If all case clauses specify expressions that have unit types, we return an array + // of those unit types. Otherwise we return an empty array. + links.switchTypes = []; + for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + var type = getTypeOfSwitchClause(clause); + if (type === undefined) { + return links.switchTypes = ts.emptyArray; + } + links.switchTypes.push(type); + } + } + return links.switchTypes; + } + function eachTypeContainedIn(source, types) { + return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + } + function isTypeSubsetOf(source, target) { + return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); + } + function isTypeSubsetOfUnion(source, target) { + if (source.flags & 65536 /* Union */) { + for (var _i = 0, _a = source.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (!containsType(target.types, t)) { + return false; + } + } + return true; + } + if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + return true; + } + return containsType(target.types, source); + } + function forEachType(type, f) { + return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); + } + function filterType(type, f) { + if (type.flags & 65536 /* Union */) { + var types = type.types; + var filtered = ts.filter(types, f); + return filtered === types ? type : getUnionTypeFromSortedList(filtered); + } + return f(type) ? type : neverType; + } + // Apply a mapping function to a type and return the resulting type. If the source type + // is a union type, the mapping function is applied to each constituent type and a union + // of the resulting types is returned. + function mapType(type, mapper) { + if (!(type.flags & 65536 /* Union */)) { + return mapper(type); + } + var types = type.types; + var mappedType; + var mappedTypes; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; + var t = mapper(current); + if (t) { + if (!mappedType) { + mappedType = t; + } + else if (!mappedTypes) { + mappedTypes = [mappedType, t]; + } + else { + mappedTypes.push(t); + } + } + } + return mappedTypes ? getUnionType(mappedTypes) : mappedType; + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } + function isIncomplete(flowType) { + return flowType.flags === 0; + } + function getTypeFromFlowType(flowType) { + return flowType.flags === 0 ? flowType.type : flowType; + } + function createFlowType(type, incomplete) { + return incomplete ? { flags: 0, type: type } : type; + } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType) { + var result = createObjectType(256 /* EvolvingArray */); + result.elementType = elementType; + return result; + } + function getEvolvingArrayType(elementType) { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType, node) { + var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + function createFinalArrayType(elementType) { + return elementType.flags & 8192 /* Never */ ? + autoArrayType : + createArrayType(elementType.flags & 65536 /* Union */ ? + getUnionType(elementType.types, /*subtypeReduction*/ true) : + elementType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType) { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); + } + function finalizeEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; + } + function getElementTypeOfEvolvingArrayType(type) { + return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; + } + function isEvolvingArrayTypeList(types) { + var hasEvolvingArrayType = false; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; + if (!(t.flags & 8192 /* Never */)) { + if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; + } + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types, subtypeReduction) { + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); + } + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node) { + var root = getReferenceRoot(node); + var parent = root.parent; + var isLengthPushOrUnshift = parent.kind === 179 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 181 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 180 /* ElementAccessExpression */ && + parent.expression === root && + parent.parent.kind === 194 /* BinaryExpression */ && + parent.parent.operatorToken.kind === 58 /* EqualsToken */ && + parent.parent.left === parent && + !ts.isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); + return isLengthPushOrUnshift || isElementAssignment; + } + function maybeTypePredicateCall(node) { + var links = getNodeLinks(node); + if (links.maybeTypePredicate === undefined) { + links.maybeTypePredicate = getMaybeTypePredicate(node); + } + return links.maybeTypePredicate; + } + function getMaybeTypePredicate(node) { + if (node.expression.kind !== 97 /* SuperKeyword */) { + var funcType = checkNonNullExpression(node.expression); + if (funcType !== silentNeverType) { + var apparentType = getApparentType(funcType); + if (apparentType !== unknownType) { + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); + } + } + } + return false; + } + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { + if (initialType === void 0) { initialType = declaredType; } + var key; + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { + return declaredType; + } + var visitedFlowStart = visitedFlowCount; + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + visitedFlowCount = visitedFlowStart; + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === 203 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { + return declaredType; + } + return resultType; + function getTypeAtFlowNode(flow) { + while (true) { + if (flow.flags & 1024 /* Shared */) { + // We cache results of flow type resolution for shared nodes that were previously visited in + // the same getFlowTypeOfReference invocation. A node is considered shared when it is the + // antecedent of more than one node. + for (var i = visitedFlowStart; i < visitedFlowCount; i++) { + if (visitedFlowNodes[i] === flow) { + return visitedFlowTypes[i]; + } + } + } + var type = void 0; + if (flow.flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16 /* Assignment */) { + type = getTypeAtFlowAssignment(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 96 /* Condition */) { + type = getTypeAtFlowCondition(flow); + } + else if (flow.flags & 128 /* SwitchClause */) { + type = getTypeAtSwitchClause(flow); + } + else if (flow.flags & 12 /* Label */) { + if (flow.antecedents.length === 1) { + flow = flow.antecedents[0]; + continue; + } + type = flow.flags & 4 /* BranchLabel */ ? + getTypeAtFlowBranchLabel(flow) : + getTypeAtFlowLoopLabel(flow); + } + else if (flow.flags & 256 /* ArrayMutation */) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = flow.antecedent; + continue; + } + } + else if (flow.flags & 2 /* Start */) { + // Check if we should continue with the control flow of the containing function. + var container = flow.container; + if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + flow = container.flowNode; + continue; + } + // At the top of the flow we have the initial type. + type = initialType; + } + else { + // Unreachable code errors are reported in the binding phase. Here we + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); + } + if (flow.flags & 1024 /* Shared */) { + // Record visited node and the associated type in the cache. + visitedFlowNodes[visitedFlowCount] = flow; + visitedFlowTypes[visitedFlowCount] = type; + visitedFlowCount++; + } + return type; + } + } + function getTypeAtFlowAssignment(flow) { + var node = flow.node; + // Assignments only narrow the computed type if the declared type is a union type. Thus, we + // only need to evaluate the assigned type if the declared type is a union type. + if (isMatchingReference(reference, node)) { + if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & 65536 /* Union */) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; + } + // We didn't have a direct match. However, if the reference is a dotted name, this + // may be an assignment to a left hand part of the reference. For example, for a + // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, + // return the declared type. + if (containsMatchingReference(reference, node)) { + return declaredType; + } + // Assignment doesn't affect reference + return undefined; + } + function getTypeAtFlowArrayMutation(flow) { + var node = flow.node; + var expr = node.kind === 181 /* CallExpression */ ? + node.expression.expression : + node.left.expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + var evolvedType_1 = type; + if (node.kind === 181 /* CallExpression */) { + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var arg = _a[_i]; + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); + } + } + else { + var indexType = getTypeOfExpression(node.left.argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { + evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); + } + } + return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } + function getTypeAtFlowCondition(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + if (type.flags & 8192 /* Never */) { + return flowType; + } + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; + var nonEvolvingType = finalizeEvolvingArrayType(type); + var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + var incomplete = isIncomplete(flowType); + var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); + } + function getTypeAtSwitchClause(flow) { + var flowType = getTypeAtFlowNode(flow.antecedent); + var type = getTypeFromFlowType(flowType); + var expr = flow.switchStatement.expression; + if (isMatchingReference(reference, expr)) { + type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } + else if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + return createFlowType(type, isIncomplete(flowType)); + } + function getTypeAtFlowBranchLabel(flow) { + var antecedentTypes = []; + var subtypeReduction = false; + var seenIncomplete = false; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } + var flowType = getTypeAtFlowNode(antecedent); + var type = getTypeFromFlowType(flowType); + // If the type at a particular antecedent path is the declared type and the + // reference is known to always be assigned (i.e. when declared and initial types + // are the same), there is no reason to process more antecedents since the only + // possible outcome is subtypes that will be removed in the final union type anyway. + if (type === declaredType && declaredType === initialType) { + return type; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + if (isIncomplete(flowType)) { + seenIncomplete = true; + } + } + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); + } + function getTypeAtFlowLoopLabel(flow) { + // If we have previously computed the control flow type for the reference at + // this flow loop junction, return the cached type. + var id = getFlowNodeId(flow); + var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); + if (!key) { + key = getFlowCacheKey(reference); + // No cache key is generated when binding patterns are in unnarrowable situations + if (!key) { + return declaredType; + } + } + var cached = cache.get(key); + if (cached) { + return cached; + } + // If this flow loop junction and reference are already being processed, return + // the union of the types computed for each branch so far, marked as incomplete. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. + for (var i = flowLoopStart; i < flowLoopCount; i++) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); + } + } + // Add the flow loop junction and reference to the in-process stack and analyze + // each antecedent code path. + var antecedentTypes = []; + var subtypeReduction = false; + var firstAntecedentType; + flowLoopNodes[flowLoopCount] = flow; + flowLoopKeys[flowLoopCount] = key; + flowLoopTypes[flowLoopCount] = antecedentTypes; + for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { + var antecedent = _a[_i]; + flowLoopCount++; + var flowType = getTypeAtFlowNode(antecedent); + flowLoopCount--; + if (!firstAntecedentType) { + firstAntecedentType = flowType; + } + var type = getTypeFromFlowType(flowType); + // If we see a value appear in the cache it is a sign that control flow analysis + // was restarted and completed by checkExpressionCached. We can simply pick up + // the resulting type and bail out. + var cached_1 = cache.get(key); + if (cached_1) { + return cached_1; + } + if (!ts.contains(antecedentTypes, type)) { + antecedentTypes.push(type); + } + // If an antecedent type is not a subset of the declared type, we need to perform + // subtype reduction. This happens when a "foreign" type is injected into the control + // flow using the instanceof operator or a user defined type predicate. + if (!isTypeSubsetOf(type, declaredType)) { + subtypeReduction = true; + } + // If the type at a particular antecedent path is the declared type there is no + // reason to process more antecedents since the only possible outcome is subtypes + // that will be removed in the final union type anyway. + if (type === declaredType) { + break; + } + } + // The result is incomplete if the first antecedent (the non-looping control flow path) + // is incomplete. + var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); + if (isIncomplete(firstAntecedentType)) { + return createFlowType(result, /*incomplete*/ true); + } + cache.set(key, result); + return result; + } + function isMatchingReferenceDiscriminant(expr, computedType) { + return expr.kind === 179 /* PropertyAccessExpression */ && + computedType.flags & 65536 /* Union */ && + isMatchingReference(reference, expr.expression) && + isDiscriminantProperty(computedType, expr.name.escapedText); + } + function narrowTypeByDiscriminant(type, propAccess, narrowType) { + var propName = propAccess.name.escapedText; + var propType = getTypeOfPropertyOfType(type, propName); + var narrowedPropType = propType && narrowType(propType); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + } + function narrowTypeByTruthiness(type, expr, assumeTrue) { + if (isMatchingReference(reference, expr)) { + return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); + } + if (isMatchingReferenceDiscriminant(expr, declaredType)) { + return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); + } + if (containsMatchingReferenceDiscriminant(reference, expr)) { + return declaredType; + } + return type; + } + function narrowTypeByBinaryExpression(type, expr, assumeTrue) { + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return narrowTypeByTruthiness(type, expr.left, assumeTrue); + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + var operator_1 = expr.operatorToken.kind; + var left_1 = getReferenceCandidate(expr.left); + var right_1 = getReferenceCandidate(expr.right); + if (left_1.kind === 189 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); + } + if (right_1.kind === 189 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); + } + if (isMatchingReference(reference, left_1)) { + return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); + } + if (isMatchingReference(reference, right_1)) { + return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); + } + if (isMatchingReferenceDiscriminant(left_1, declaredType)) { + return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); + } + if (isMatchingReferenceDiscriminant(right_1, declaredType)) { + return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); + } + if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { + return declaredType; + } + break; + case 93 /* InstanceOfKeyword */: + return narrowTypeByInstanceof(type, expr, assumeTrue); + case 26 /* CommaToken */: + return narrowType(type, expr.right, assumeTrue); + } + return type; + } + function narrowTypeByEquality(type, operator, value, assumeTrue) { + if (type.flags & 1 /* Any */) { + return type; + } + if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + var valueType = getTypeOfExpression(value); + if (valueType.flags & 6144 /* Nullable */) { + if (!strictNullChecks) { + return type; + } + var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; + var facts = doubleEquals ? + assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : + value.kind === 95 /* NullKeyword */ ? + assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : + assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; + return getTypeWithFacts(type, facts); + } + if (type.flags & 16810497 /* NotUnionOrUnit */) { + return type; + } + if (assumeTrue) { + var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + } + if (isUnitType(valueType)) { + var regularType_1 = getRegularTypeOfLiteralType(valueType); + return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); + } + return type; + } + function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands + var target = getReferenceCandidate(typeOfExpr.expression); + if (!isMatchingReference(reference, target)) { + // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the + // narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, target)) { + return declaredType; + } + return type; + } + if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } + if (assumeTrue && !(type.flags & 65536 /* Union */)) { + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + var targetType = typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 540672 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + } + var facts = assumeTrue ? + typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : + typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; + return getTypeWithFacts(type, facts); + } + function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { + // We only narrow if all case expressions specify values with unit types + var switchTypes = getSwitchClauseTypes(switchStatement); + if (!switchTypes.length) { + return type; + } + var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); + var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); + var discriminantType = getUnionType(clauseTypes); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); + if (!hasDefaultClause) { + return caseType; + } + var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); + return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + } + function narrowTypeByInstanceof(type, expr, assumeTrue) { + var left = getReferenceCandidate(expr.left); + if (!isMatchingReference(reference, left)) { + // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the + // narrowed type of 'y' to its declared type. + if (containsMatchingReference(reference, left)) { + return declaredType; + } + return type; + } + // Check that right operand is a function type with a prototype property + var rightType = getTypeOfExpression(expr.right); + if (!isTypeSubtypeOf(rightType, globalFunctionType)) { + return type; + } + var targetType; + var prototypeProperty = getPropertyOfType(rightType, "prototype"); + if (prototypeProperty) { + // Target type is type of the prototype property + var prototypePropertyType = getTypeOfSymbol(prototypeProperty); + if (!isTypeAny(prototypePropertyType)) { + targetType = prototypePropertyType; + } + } + // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { + return type; + } + if (!targetType) { + // Target type is type of construct signature + var constructSignatures = void 0; + if (getObjectFlags(rightType) & 2 /* Interface */) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; + } + else if (getObjectFlags(rightType) & 16 /* Anonymous */) { + constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + } + if (constructSignatures && constructSignatures.length) { + targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + } + } + if (targetType) { + return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); + } + return type; + } + function getNarrowedType(type, candidate, assumeTrue, isRelated) { + if (!assumeTrue) { + return filterType(type, function (t) { return !isRelated(t, candidate); }); + } + // If the current type is a union type, remove all constituents that couldn't be instances of + // the candidate type. If one or more constituents remain, return a union of those. + if (type.flags & 65536 /* Union */) { + var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); + if (!(assignableType.flags & 8192 /* Never */)) { + return assignableType; + } + } + // If the candidate type is a subtype of the target type, narrow to the candidate type. + // Otherwise, if the target type is assignable to the candidate type, keep the target type. + // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate + // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the + // two types. + return isTypeSubtypeOf(candidate, type) ? candidate : + isTypeAssignableTo(type, candidate) ? type : + isTypeAssignableTo(candidate, type) ? candidate : + getIntersectionType([type, candidate]); + } + function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { + if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { + return type; + } + var signature = getResolvedSignature(callExpression); + var predicate = signature.typePredicate; + if (!predicate) { + return type; + } + // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' + if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { + return type; + } + if (ts.isIdentifierTypePredicate(predicate)) { + var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + if (predicateArgument) { + if (isMatchingReference(reference, predicateArgument)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, predicateArgument)) { + return declaredType; + } + } + } + else { + var invokedExpression = ts.skipParentheses(callExpression.expression); + if (invokedExpression.kind === 180 /* ElementAccessExpression */ || invokedExpression.kind === 179 /* PropertyAccessExpression */) { + var accessExpression = invokedExpression; + var possibleReference = ts.skipParentheses(accessExpression.expression); + if (isMatchingReference(reference, possibleReference)) { + return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); + } + if (containsMatchingReference(reference, possibleReference)) { + return declaredType; + } + } + } + return type; + } + // Narrow the given type based on the given expression having the assumed boolean value. The returned type + // will be a subtype or the same type as the argument. + function narrowType(type, expr, assumeTrue) { + switch (expr.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 179 /* PropertyAccessExpression */: + return narrowTypeByTruthiness(type, expr, assumeTrue); + case 181 /* CallExpression */: + return narrowTypeByTypePredicate(type, expr, assumeTrue); + case 185 /* ParenthesizedExpression */: + return narrowType(type, expr.expression, assumeTrue); + case 194 /* BinaryExpression */: + return narrowTypeByBinaryExpression(type, expr, assumeTrue); + case 192 /* PrefixUnaryExpression */: + if (expr.operator === 51 /* ExclamationToken */) { + return narrowType(type, expr.operand, !assumeTrue); + } + break; + } + return type; + } + } + function getTypeOfSymbolAtLocation(symbol, location) { + symbol = symbol.exportSymbol || symbol; + // If we have an identifier or a property access at the given location, if the location is + // an dotted name expression, and if the location is not an assignment target, obtain the type + // of the expression (which will reflect control flow analysis). If the expression indeed + // resolved to the given symbol, return the narrowed type. + if (location.kind === 71 /* Identifier */) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { + location = location.parent; + } + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { + var type = getTypeOfExpression(location); + if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { + return type; + } + } + } + // The location isn't a reference to the given symbol, meaning we're being asked + // a hypothetical question of what type the symbol would have if there was a reference + // to it at the given location. Since we have no control flow information for the + // hypothetical reference (control flow information is created and attached by the + // binder), we simply return the declared type of the symbol. + return getTypeOfSymbol(symbol); + } + function getControlFlowContainer(node) { + return ts.findAncestor(node.parent, function (node) { + return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || + node.kind === 234 /* ModuleBlock */ || + node.kind === 265 /* SourceFile */ || + node.kind === 149 /* PropertyDeclaration */; + }); + } + // Check if a parameter is assigned anywhere within its declaring function. + function isParameterAssigned(symbol) { + var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; + var links = getNodeLinks(func); + if (!(links.flags & 4194304 /* AssignmentsMarked */)) { + links.flags |= 4194304 /* AssignmentsMarked */; + if (!hasParentWithAssignmentsMarked(func)) { + markParameterAssignments(func); + } + } + return symbol.isAssigned || false; + } + function hasParentWithAssignmentsMarked(node) { + return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); + } + function markParameterAssignments(node) { + if (node.kind === 71 /* Identifier */) { + if (ts.isAssignmentTarget(node)) { + var symbol = getResolvedSymbol(node); + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146 /* Parameter */) { + symbol.isAssigned = true; + } + } + } + else { + ts.forEachChild(node, markParameterAssignments); + } + } + function isConstVariable(symbol) { + return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromDeclaredType(declaredType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 146 /* Parameter */ && + declaration.initializer && + getFalsyFlags(declaredType) & 2048 /* Undefined */ && + !(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) { + return unknownType; + } + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol) { + var container = ts.getContainingFunction(node); + if (languageVersion < 2 /* ES2015 */) { + if (container.kind === 187 /* ArrowFunction */) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); + } + else if (ts.hasModifier(container, 256 /* Async */)) { + error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); + } + } + getNodeLinks(container).flags |= 8192 /* CaptureArguments */; + return getTypeOfSymbol(symbol); + } + // We should only mark aliases as referenced if there isn't a local value declaration + // for the symbol. + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */) && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { + markAliasSymbolAsReferenced(symbol); + } + var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + var declaration = localOrExportSymbol.valueDeclaration; + if (localOrExportSymbol.flags & 32 /* Class */) { + // Due to the emit for class decorators, any reference to the class from inside of the class body + // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind + // behavior of class names in ES6. + if (declaration.kind === 229 /* ClassDeclaration */ + && ts.nodeIsDecorated(declaration)) { + var container = ts.getContainingClass(node); + while (container !== undefined) { + if (container === declaration && container.name !== node) { + getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + break; + } + container = ts.getContainingClass(container); + } + } + else if (declaration.kind === 199 /* ClassExpression */) { + // When we emit a class expression with static members that contain a reference + // to the constructor in the initializer, we will need to substitute that + // binding with an alias as the class name is not in scope. + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + while (container !== undefined) { + if (container.parent === declaration) { + if (container.kind === 149 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; + getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; + } + break; + } + container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); + } + } + } + checkCollisionWithCapturedSuperVariable(node, node); + checkCollisionWithCapturedThisVariable(node, node); + checkCollisionWithCapturedNewTargetVariable(node, node); + checkNestedBlockScopedBinding(node, symbol); + var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (!(localOrExportSymbol.flags & 3 /* Variable */)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); + return unknownType; + } + if (isReadonlySymbol(localOrExportSymbol)) { + error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); + return unknownType; + } + } + var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; + // We only narrow variables and parameters occurring in a non-assignment position. For all other + // entities we simply return the declared type. + if (localOrExportSymbol.flags & 3 /* Variable */) { + if (assignmentKind === 1 /* Definite */) { + return type; + } + } + else if (isAlias) { + declaration = ts.find(symbol.declarations, isSomeImportDeclaration); + } + else { + return type; + } + if (!declaration) { + return type; + } + // The declaration container is the innermost function that encloses the declaration of the variable + // or parameter. The flow container is the innermost function starting with which we analyze the control + // flow graph to determine the control flow based type. + var isParameter = ts.getRootDeclaration(declaration).kind === 146 /* Parameter */; + var declarationContainer = getControlFlowContainer(declaration); + var flowContainer = getControlFlowContainer(node); + var isOuterVariable = flowContainer !== declarationContainer; + // When the control flow originates in a function expression or arrow function and we are referencing + // a const variable or parameter from an outer function, we extend the origin of the control flow + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === 186 /* FunctionExpression */ || + flowContainer.kind === 187 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze + // the entire control flow graph from the variable's declaration (i.e. when the flow container and + // declaration container are the same). + var assumeInitialized = isParameter || isAlias || isOuterVariable || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 246 /* ExportSpecifier */) || + node.parent.kind === 203 /* NonNullExpression */ || + ts.isInAmbientContext(declaration); + var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : + type === autoType || type === autoArrayType ? undefinedType : + 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 + // control flow based type does include undefined. + if (type === autoType || type === autoArrayType) { + if (flowType === autoType || flowType === autoArrayType) { + if (noImplicitAny) { + 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); + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); + // Return the declared type to reduce follow-on errors + return type; + } + return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; + } + function isInsideFunction(node, threshold) { + return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); + } + function checkNestedBlockScopedBinding(node, symbol) { + if (languageVersion >= 2 /* ES2015 */ || + (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || + symbol.valueDeclaration.parent.kind === 260 /* CatchClause */) { + return; + } + // 1. walk from the use site up to the declaration and check + // if there is anything function like between declaration and use-site (is binding/class is captured in function). + // 2. walk from the declaration up to the boundary of lexical environment and check + // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + var usedInFunction = isInsideFunction(node.parent, container); + var current = container; + var containedInIterationStatement = false; + while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { + if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { + containedInIterationStatement = true; + break; + } + current = current.parent; + } + if (containedInIterationStatement) { + if (usedInFunction) { + // mark iteration statement as containing block-scoped binding captured in some function + getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; + } + // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. + // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. + if (container.kind === 214 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 227 /* VariableDeclarationList */).parent === container && + isAssignedInBodyOfForStatement(node, container)) { + getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; + } + // set 'declared inside loop' bit on the block-scoped binding + getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; + } + if (usedInFunction) { + getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; + } + } + function isAssignedInBodyOfForStatement(node, container) { + // skip parenthesized nodes + var current = node; + while (current.parent.kind === 185 /* ParenthesizedExpression */) { + current = current.parent; + } + // check if node is used as LHS in some assignment expression + var isAssigned = false; + if (ts.isAssignmentTarget(current)) { + isAssigned = true; + } + else if ((current.parent.kind === 192 /* PrefixUnaryExpression */ || current.parent.kind === 193 /* PostfixUnaryExpression */)) { + var expr = current.parent; + isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; + } + if (!isAssigned) { + return false; + } + // at this point we know that node is the target of assignment + // now check that modification happens inside the statement part of the ForStatement + return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); + } + function captureLexicalThis(node, container) { + getNodeLinks(node).flags |= 2 /* LexicalThis */; + if (container.kind === 149 /* PropertyDeclaration */ || container.kind === 152 /* Constructor */) { + var classNode = container.parent; + getNodeLinks(classNode).flags |= 4 /* CaptureThis */; + } + else { + getNodeLinks(container).flags |= 4 /* CaptureThis */; + } + } + function findFirstSuperCall(n) { + if (ts.isSuperCall(n)) { + return n; + } + else if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findFirstSuperCall); + } + /** + * Return a cached result if super-statement is already found. + * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor + * + * @param constructor constructor-function to look for super statement + */ + function getSuperCallInConstructor(constructor) { + var links = getNodeLinks(constructor); + // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result + if (links.hasSuperCall === undefined) { + links.superCall = findFirstSuperCall(constructor.body); + links.hasSuperCall = links.superCall ? true : false; + } + return links.superCall; + } + /** + * Check if the given class-declaration extends null then return true. + * Otherwise, return false + * @param classDecl a class declaration to check if it extends null + */ + function classDeclarationExtendsNull(classDecl) { + var classSymbol = getSymbolOfNode(classDecl); + var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); + var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); + return baseConstructorType === nullWideningType; + } + function checkThisBeforeSuper(node, container, diagnosticMessage) { + var containingClassDecl = container.parent; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + // If a containing class does not have extends clause or the class extends null + // skip checking whether super statement is called before "this" accessing. + if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { + var superCall = getSuperCallInConstructor(container); + // We should give an error in the following cases: + // - No super-call + // - "this" is accessing before super-call. + // i.e super(this) + // this.x; super(); + // We want to make sure that super-call is done before accessing "this" so that + // "this" is not accessed as a parameter of the super-call. + if (!superCall || superCall.end > node.pos) { + // In ES6, super inside constructor of class-declaration has to precede "this" accessing + error(node, diagnosticMessage); + } + } + } + function checkThisExpression(node) { + // Stop at the first arrow function so that we can + // tell whether 'this' needs to be captured. + var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); + var needToCaptureLexicalThis = false; + if (container.kind === 152 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); + } + // Now skip arrow functions to get the "real" owner of 'this'. + if (container.kind === 187 /* ArrowFunction */) { + container = ts.getThisContainer(container, /* includeArrowFunctions */ false); + // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code + needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); + } + switch (container.kind) { + case 233 /* ModuleDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 232 /* EnumDeclaration */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + break; + case 152 /* Constructor */: + if (isInConstructorArgumentInitializer(node, container)) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + if (ts.getModifierFlags(container) & 32 /* Static */) { + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks + } + break; + case 144 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; + } + if (needToCaptureLexicalThis) { + captureLexicalThis(node, container); + } + if (ts.isFunctionLike(container) && + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { + // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. + // If this is a function in a JS file, it might be a class method. Check if it's the RHS + // of a x.prototype.y = function [name]() { .... } + if (container.kind === 186 /* FunctionExpression */ && + container.parent.kind === 194 /* BinaryExpression */ && + ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { + // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') + var className = container.parent // x.prototype.y = f + .left // x.prototype.y + .expression // x.prototype + .expression; // x + var classSymbol = checkExpression(className).symbol; + if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { + return getInferredClassType(classSymbol); + } + } + var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); + if (thisType) { + return thisType; + } + } + if (ts.isClassLike(container.parent)) { + var symbol = getSymbolOfNode(container.parent); + var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return getFlowTypeOfReference(node, type); + } + if (ts.isInJavaScriptFile(node)) { + var type = getTypeForThisExpressionFromJSDoc(container); + if (type && type !== unknownType) { + return type; + } + } + if (noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return anyType; + } + function getTypeForThisExpressionFromJSDoc(node) { + var jsdocType = ts.getJSDocType(node); + if (jsdocType && jsdocType.kind === 273 /* JSDocFunctionType */) { + var jsDocFunctionType = jsdocType; + if (jsDocFunctionType.parameters.length > 0 && + jsDocFunctionType.parameters[0].name && + jsDocFunctionType.parameters[0].name.escapedText === "this") { + return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); + } + } + } + function isInConstructorArgumentInitializer(node, constructorDecl) { + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146 /* Parameter */; }); + } + function checkSuperExpression(node) { + var isCallExpression = node.parent.kind === 181 /* CallExpression */ && node.parent.expression === node; + var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); + var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting + if (!isCallExpression) { + while (container && container.kind === 187 /* ArrowFunction */) { + container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); + needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; + } + } + var canUseSuperExpression = isLegalUsageOfSuperExpression(container); + var nodeCheckFlag = 0; + if (!canUseSuperExpression) { + // issue more specific error if super is used in computed property name + // class A { foo() { return "1" }} + // class B { + // [super.foo()]() {} + // } + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144 /* ComputedPropertyName */; }); + if (current && current.kind === 144 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { + error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); + } + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); + } + else { + error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); + } + return unknownType; + } + if (!isCallExpression && container.kind === 152 /* Constructor */) { + checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); + } + if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { + nodeCheckFlag = 512 /* SuperStatic */; + } + else { + nodeCheckFlag = 256 /* SuperInstance */; + } + getNodeLinks(node).flags |= nodeCheckFlag; + // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. + // This is due to the fact that we emit the body of an async function inside of a generator function. As generator + // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper + // uses an arrow function, which is permitted to reference `super`. + // + // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property + // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value + // of a property or indexed access, either as part of an assignment expression or destructuring assignment. + // + // The simplest case is reading a value, in which case we will emit something like the following: + // + // // ts + // ... + // async asyncMethod() { + // let x = await super.asyncMethod(); + // return x; + // } + // ... + // + // // js + // ... + // asyncMethod() { + // const _super = name => super[name]; + // return __awaiter(this, arguments, Promise, function *() { + // let x = yield _super("asyncMethod").call(this); + // return x; + // }); + // } + // ... + // + // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases + // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: + // + // // ts + // ... + // async asyncMethod(ar: Promise) { + // [super.a, super.b] = await ar; + // } + // ... + // + // // js + // ... + // asyncMethod(ar) { + // const _super = (function (geti, seti) { + // const cache = Object.create(null); + // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); + // })(name => super[name], (name, value) => super[name] = value); + // return __awaiter(this, arguments, Promise, function *() { + // [_super("a").value, _super("b").value] = yield ar; + // }); + // } + // ... + // + // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. + // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment + // while a property access can. + if (container.kind === 151 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { + if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { + getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; + } + else { + getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; + } + } + if (needToCaptureLexicalThis) { + // call expressions are allowed only in constructors so they should always capture correct 'this' + // super property access expressions can also appear in arrow functions - + // in this case they should also use correct lexical this + captureLexicalThis(node.parent, container); + } + if (container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (languageVersion < 2 /* ES2015 */) { + error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); + return unknownType; + } + else { + // for object literal assume that type of 'super' is 'any' + return anyType; + } + } + // at this point the only legal case for parent is ClassLikeDeclaration + var classLikeDeclaration = container.parent; + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (!baseClassType) { + if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); + } + return unknownType; + } + if (container.kind === 152 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) + error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); + return unknownType; + } + return nodeCheckFlag === 512 /* SuperStatic */ + ? getBaseConstructorTypeOfClass(classType) + : getTypeWithThisArgument(baseClassType, classType.thisType); + function isLegalUsageOfSuperExpression(container) { + if (!container) { + return false; + } + if (isCallExpression) { + // TS 1.0 SPEC (April 2014): 4.8.1 + // Super calls are only permitted in constructors of derived classes + return container.kind === 152 /* Constructor */; + } + else { + // TS 1.0 SPEC (April 2014) + // 'super' property access is allowed + // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance + // - In a static member function or static member accessor + // topmost container must be something that is directly nested in the class declaration\object literal expression + if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { + if (ts.getModifierFlags(container) & 32 /* Static */) { + return container.kind === 151 /* MethodDeclaration */ || + container.kind === 150 /* MethodSignature */ || + container.kind === 153 /* GetAccessor */ || + container.kind === 154 /* SetAccessor */; + } + else { + return container.kind === 151 /* MethodDeclaration */ || + container.kind === 150 /* MethodSignature */ || + container.kind === 153 /* GetAccessor */ || + container.kind === 154 /* SetAccessor */ || + container.kind === 149 /* PropertyDeclaration */ || + container.kind === 148 /* PropertySignature */ || + container.kind === 152 /* Constructor */; + } + } + } + return false; + } + } + function getContainingObjectLiteral(func) { + return (func.kind === 151 /* MethodDeclaration */ || + func.kind === 153 /* GetAccessor */ || + func.kind === 154 /* SetAccessor */) && func.parent.kind === 178 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 186 /* FunctionExpression */ && func.parent.kind === 261 /* PropertyAssignment */ ? func.parent.parent : + undefined; + } + function getThisTypeArgument(type) { + return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; + } + function getThisTypeFromContextualType(type) { + return mapType(type, function (t) { + return t.flags & 131072 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + }); + } + function getContextualThisParameterType(func) { + if (func.kind === 187 /* ArrowFunction */) { + return undefined; + } + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var thisParameter = contextualSignature.thisParameter; + if (thisParameter) { + return getTypeOfSymbol(thisParameter); + } + } + } + if (noImplicitThis || ts.isInJavaScriptFile(func)) { + var containingLiteral = getContainingObjectLiteral(func); + if (containingLiteral) { + // We have an object literal method. Check if the containing object literal has a contextual type + // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in + // any directly enclosing object literals. + var contextualType = getApparentTypeOfContextualType(containingLiteral); + var literal = containingLiteral; + var type = contextualType; + while (type) { + var thisType = getThisTypeFromContextualType(type); + if (thisType) { + return instantiateType(thisType, getContextualMapper(containingLiteral)); + } + if (literal.parent.kind !== 261 /* PropertyAssignment */) { + break; + } + literal = literal.parent.parent; + type = getApparentTypeOfContextualType(literal); + } + // There was no contextual ThisType for the containing object literal, so the contextual type + // for 'this' is the non-null form of the contextual type for the containing object literal or + // the type of the object literal itself. + return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); + } + // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the + // contextual type for 'this' is 'obj'. + if (func.parent.kind === 194 /* BinaryExpression */ && func.parent.operatorToken.kind === 58 /* EqualsToken */) { + var target = func.parent.left; + if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { + return checkExpressionCached(target.expression); + } + } + } + return undefined; + } + // Return contextual type of parameter or undefined if no contextual type is available + function getContextuallyTypedParameterType(parameter) { + var func = parameter.parent; + if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (parameter.dotDotDotToken) { + var restTypes = []; + for (var i = indexOfParameter; i < iife.arguments.length; i++) { + restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); + } + return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; + } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < iife.arguments.length ? + getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameters = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + var indexOfParameter = ts.indexOf(func.parameters, parameter); + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + // If last parameter is contextually rest parameter get its type + if (funcHasRestParameters && + indexOfParameter === (func.parameters.length - 1) && + isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); + } + } + } + return undefined; + } + // In a variable, parameter or property declaration with a type annotation, + // the contextual type of an initializer expression is the type of the variable, parameter or property. + // Otherwise, in a parameter declaration of a contextually typed function expression, + // the contextual type of an initializer expression is the contextual type of the parameter. + // Otherwise, in a variable or parameter declaration with a binding pattern name, + // the contextual type of an initializer expression is the type implied by the binding pattern. + // Otherwise, in a binding pattern inside a variable or parameter declaration, + // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. + function getContextualTypeForInitializerExpression(node) { + var declaration = node.parent; + if (node === declaration.initializer) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + if (declaration.kind === 146 /* Parameter */) { + var type = getContextuallyTypedParameterType(declaration); + if (type) { + return type; + } + } + if (ts.isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); + } + if (ts.isBindingPattern(declaration.parent)) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + if (parentDeclaration.kind !== 176 /* BindingElement */) { + var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); + if (parentTypeNode && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text) { + return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); + } + } + } + } + } + return undefined; + } + function getContextualTypeForReturnExpression(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + return undefined; + } + var contextualReturnType = getContextualReturnType(func); + return functionFlags & 2 /* Async */ + ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function + : contextualReturnType; // Regular function + } + return undefined; + } + function getContextualTypeForYieldOperand(node) { + var func = ts.getContainingFunction(node); + if (func) { + var functionFlags = ts.getFunctionFlags(func); + var contextualReturnType = getContextualReturnType(func); + if (contextualReturnType) { + return node.asteriskToken + ? contextualReturnType + : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); + } + } + return undefined; + } + function isInParameterInitializerBeforeContainingFunction(node) { + while (node.parent && !ts.isFunctionLike(node.parent)) { + if (node.parent.kind === 146 /* Parameter */ && node.parent.initializer === node) { + return true; + } + node = node.parent; + } + return false; + } + function getContextualReturnType(functionDecl) { + // If the containing function has a return type annotation, is a constructor, or is a get accessor whose + // corresponding set accessor has a type annotation, return statements in the function are contextually typed + if (functionDecl.kind === 152 /* Constructor */ || + ts.getEffectiveReturnTypeNode(functionDecl) || + isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { + return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); + } + // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature + // and that call signature is non-generic, return statements are contextually typed by the return type of the signature + var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + if (signature) { + return getReturnTypeOfSignature(signature); + } + return undefined; + } + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); + if (argIndex >= 0) { + // If we're already in the process of resolving the given signature, don't resolve again as + // that could cause infinite recursion. Instead, return anySignature. + var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); + return getTypeAtPosition(signature, argIndex); + } + return undefined; + } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 183 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } + function getContextualTypeForBinaryOperand(node) { + var binaryExpression = node.parent; + var operator = binaryExpression.operatorToken.kind; + if (ts.isAssignmentOperator(operator)) { + // Don't do this for special property assignments to avoid circularity + if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { + return undefined; + } + // In an assignment expression, the right operand is contextually typed by the type of the left operand. + if (node === binaryExpression.right) { + return getTypeOfExpression(binaryExpression.left); + } + } + else if (operator === 54 /* BarBarToken */) { + // When an || expression has a contextual type, the operands are contextually typed by that type. When an || + // expression has no contextual type, the right operand is contextually typed by the type of the left operand. + var type = getContextualType(binaryExpression); + if (!type && node === binaryExpression.right) { + type = getTypeOfExpression(binaryExpression.left); + } + return type; + } + else if (operator === 53 /* AmpersandAmpersandToken */ || operator === 26 /* CommaToken */) { + if (node === binaryExpression.right) { + return getContextualType(binaryExpression); + } + } + return undefined; + } + function getTypeOfPropertyOfContextualType(type, name) { + return mapType(type, function (t) { + var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; + return prop ? getTypeOfSymbol(prop) : undefined; + }); + } + function getIndexTypeOfContextualType(type, kind) { + return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); + } + // Return true if the given contextual type is a tuple-like type + function contextualTypeIsTupleLikeType(type) { + return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + } + // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of + // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one + // exists. Otherwise, it is the type of the string index signature in T, if one exists. + function getContextualTypeForObjectLiteralMethod(node) { + ts.Debug.assert(ts.isObjectLiteralMethod(node)); + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + return getContextualTypeForObjectLiteralElement(node); + } + function getContextualTypeForObjectLiteralElement(element) { + var objectLiteral = element.parent; + var type = getApparentTypeOfContextualType(objectLiteral); + if (type) { + if (!ts.hasDynamicName(element)) { + // For a (non-symbol) computed property, there is no reason to look up the name + // in the type. It will just be "__computed", which does not appear in any + // SymbolTable. + var symbolName = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || + getIndexTypeOfContextualType(type, 0 /* String */); + } + return undefined; + } + // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is + // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, + // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated + // type of T. + function getContextualTypeForElementExpression(node) { + var arrayLiteral = node.parent; + var type = getApparentTypeOfContextualType(arrayLiteral); + if (type) { + var index = ts.indexOf(arrayLiteral.elements, node); + return getTypeOfPropertyOfContextualType(type, "" + index) + || getIndexTypeOfContextualType(type, 1 /* Number */) + || getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + } + return undefined; + } + // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. + function getContextualTypeForConditionalOperand(node) { + var conditional = node.parent; + return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; + } + function getContextualTypeForJsxExpression(node) { + // JSX expression can appear in two position : JSX Element's children or JSX attribute + var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? + node.parent.parent : + node.parent.openingElement.attributes; // node.parent is JsxElement + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + var attributesType = getContextualType(jsxAttributes); + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + if (ts.isJsxAttribute(node.parent)) { + // JSX expression is in JSX attribute + return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); + } + else if (node.parent.kind === 249 /* JsxElement */) { + // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; + } + else { + // JSX expression is in JSX spread attribute + return attributesType; + } + } + function getContextualTypeForJsxAttribute(attribute) { + // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type + // which is a type of the parameter of the signature we are trying out. + // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName + var attributesType = getContextualType(attribute.parent); + if (ts.isJsxAttribute(attribute)) { + if (!attributesType || isTypeAny(attributesType)) { + return undefined; + } + return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); + } + else { + return attributesType; + } + } + // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily + // be "pushed" onto a node using the contextualType property. + function getApparentTypeOfContextualType(node) { + var type = getContextualType(node); + return type && getApparentType(type); + } + /** + * Woah! Do you really want to use this function? + * + * Unless you're trying to get the *non-apparent* type for a + * value-literal type or you're authoring relevant portions of this algorithm, + * you probably meant to use 'getApparentTypeOfContextualType'. + * Otherwise this may not be very useful. + * + * In cases where you *are* working on this function, you should understand + * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. + * + * - Use 'getContextualType' when you are simply going to propagate the result to the expression. + * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. + * + * @param node the expression whose contextual type will be returned. + * @returns the contextual type of an expression. + */ + function getContextualType(node) { + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (node.contextualType) { + return node.contextualType; + } + var parent = node.parent; + switch (parent.kind) { + case 226 /* VariableDeclaration */: + case 146 /* Parameter */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 176 /* BindingElement */: + return getContextualTypeForInitializerExpression(node); + case 187 /* ArrowFunction */: + case 219 /* ReturnStatement */: + return getContextualTypeForReturnExpression(node); + case 197 /* YieldExpression */: + return getContextualTypeForYieldOperand(parent); + case 181 /* CallExpression */: + case 182 /* NewExpression */: + return getContextualTypeForArgument(parent, node); + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + return getTypeFromTypeNode(parent.type); + case 194 /* BinaryExpression */: + return getContextualTypeForBinaryOperand(node); + case 261 /* PropertyAssignment */: + case 262 /* ShorthandPropertyAssignment */: + return getContextualTypeForObjectLiteralElement(parent); + case 263 /* SpreadAssignment */: + return getApparentTypeOfContextualType(parent.parent); + case 177 /* ArrayLiteralExpression */: + return getContextualTypeForElementExpression(node); + case 195 /* ConditionalExpression */: + return getContextualTypeForConditionalOperand(node); + case 205 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 185 /* ParenthesizedExpression */: + return getContextualType(parent); + case 256 /* JsxExpression */: + return getContextualTypeForJsxExpression(parent); + case 253 /* JsxAttribute */: + case 255 /* JsxSpreadAttribute */: + return getContextualTypeForJsxAttribute(parent); + case 251 /* JsxOpeningElement */: + case 250 /* JsxSelfClosingElement */: + return getAttributesTypeFromJsxOpeningLikeElement(parent); + } + return undefined; + } + function getContextualMapper(node) { + node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return node ? node.contextualMapper : identityMapper; + } + // If the given type is an object or union type with a single signature, and if that signature has at + // least as many parameters as the given function, return the signature. Otherwise return undefined. + function getContextualCallSignature(type, node) { + var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + if (signatures.length === 1) { + var signature = signatures[0]; + if (!isAritySmaller(signature, node)) { + return signature; + } + } + } + /** If the contextual signature has fewer parameters than the function expression, do not use it */ + function isAritySmaller(signature, target) { + var targetParameterCount = 0; + for (; targetParameterCount < target.parameters.length; targetParameterCount++) { + var param = target.parameters[targetParameterCount]; + if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { + break; + } + } + if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { + targetParameterCount--; + } + var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; + return sourceLength < targetParameterCount; + } + function isFunctionExpressionOrArrowFunction(node) { + return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */; + } + function getContextualSignatureForFunctionLikeDeclaration(node) { + // Only function expressions, arrow functions, and object literal methods are contextually typed. + return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) + ? getContextualSignature(node) + : undefined; + } + function getContextualTypeForFunctionLikeDeclaration(node) { + return ts.isObjectLiteralMethod(node) ? + getContextualTypeForObjectLiteralMethod(node) : + getApparentTypeOfContextualType(node); + } + // Return the contextual signature for a given expression node. A contextual type provides a + // contextual signature if it has a single call signature and if that call signature is non-generic. + // If the contextual type is a union type, get the signature from each type possible and if they are + // all identical ignoring their return type, the result is same signature but with return type as + // union type of return types from these signatures + function getContextualSignature(node) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var type = getContextualTypeForFunctionLikeDeclaration(node); + if (!type) { + return undefined; + } + if (!(type.flags & 65536 /* Union */)) { + return getContextualCallSignature(type, node); + } + var signatureList; + var types = type.types; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; + var signature = getContextualCallSignature(current, node); + if (signature) { + if (!signatureList) { + // This signature will contribute to contextual union signature + signatureList = [signature]; + } + else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { + // Signatures aren't identical, do not use + return undefined; + } + else { + // Use this signature for contextual union signature + signatureList.push(signature); + } + } + } + // Result is union of signatures collected (return type is union of return types of this signature set) + var result; + if (signatureList) { + result = cloneSignature(signatureList[0]); + // Clear resolved return type we possibly got from cloneSignature + result.resolvedReturnType = undefined; + result.unionSignatures = signatureList; + } + return result; + } + function checkSpreadExpression(node, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); + } + var arrayOrIterableType = checkExpression(node.expression, checkMode); + return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + } + function hasDefaultValue(node) { + return (node.kind === 176 /* BindingElement */ && !!node.initializer) || + (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + } + function checkArrayLiteral(node, checkMode) { + var elements = node.elements; + var hasSpreadElement = false; + var elementTypes = []; + var inDestructuringPattern = ts.isAssignmentTarget(node); + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; + if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { + // Given the following situation: + // var c: {}; + // [...c] = ["", 0]; + // + // c is represented in the tree as a spread element in an array literal. + // But c really functions as a rest element, and its purpose is to provide + // a contextual type for the right hand side of the assignment. Therefore, + // instead of calling checkExpression on "...c", which will give an error + // if c is not iterable/array-like, we need to act as if we are trying to + // get the contextual element type from it. So we do something similar to + // getContextualTypeForElementExpression, which will crucially not error + // if there is no index type / iterated type. + var restArrayType = checkExpression(e.expression, checkMode); + var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || + getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false, /*checkAssignability*/ false); + if (restElementType) { + elementTypes.push(restElementType); + } + } + else { + var type = checkExpressionForMutableLocation(e, checkMode); + elementTypes.push(type); + } + hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; + } + if (!hasSpreadElement) { + // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such + // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". + if (inDestructuringPattern && elementTypes.length) { + var type = cloneTypeReference(createTupleType(elementTypes)); + type.pattern = node; + return type; + } + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { + var pattern = contextualType.pattern; + // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting + // tuple type with the corresponding binding or assignment element types to make the lengths equal. + if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { + var patternElements = pattern.elements; + for (var i = elementTypes.length; i < patternElements.length; i++) { + var patternElement = patternElements[i]; + if (hasDefaultValue(patternElement)) { + elementTypes.push(contextualType.typeArguments[i]); + } + else { + if (patternElement.kind !== 200 /* OmittedExpression */) { + error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + elementTypes.push(unknownType); + } + } + } + if (elementTypes.length) { + return createTupleType(elementTypes); + } + } + } + return createArrayType(elementTypes.length ? + getUnionType(elementTypes, /*subtypeReduction*/ true) : + strictNullChecks ? neverType : undefinedWideningType); + } + function isNumericName(name) { + switch (name.kind) { + case 144 /* ComputedPropertyName */: + return isNumericComputedName(name); + case 71 /* Identifier */: + return isNumericLiteralName(name.escapedText); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return isNumericLiteralName(name.text); + default: + return false; + } + } + 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), 84 /* NumberLike */); + } + function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { + return isTypeAny(type) || isTypeOfKind(type, kind); + } + function isInfinityOrNaNString(name) { + return name === "Infinity" || name === "-Infinity" || name === "NaN"; + } + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + 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, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); + } + else { + checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); + } + } + return links.resolvedType; + } + function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { + var propTypes = []; + for (var i = 0; i < properties.length; i++) { + if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { + propTypes.push(getTypeOfSymbol(properties[i])); + } + } + var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; + return createIndexInfo(unionType, /*isReadonly*/ false); + } + function checkObjectLiteral(node, checkMode) { + var inDestructuringPattern = ts.isAssignmentTarget(node); + // Grammar checking + checkGrammarObjectLiteralExpression(node, inDestructuringPattern); + var propertiesTable = ts.createSymbolTable(); + var propertiesArray = []; + var spread = emptyObjectType; + var propagatedFlags = 0; + var contextualType = getApparentTypeOfContextualType(node); + var contextualTypeHasPattern = contextualType && contextualType.pattern && + (contextualType.pattern.kind === 174 /* ObjectBindingPattern */ || contextualType.pattern.kind === 178 /* ObjectLiteralExpression */); + var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); + var typeFlags = 0; + var patternWithComputedProperties = false; + var hasComputedStringProperty = false; + var hasComputedNumberProperty = false; + var isInJSFile = ts.isInJavaScriptFile(node); + var offset = 0; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 261 /* PropertyAssignment */ || + memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || + ts.isObjectLiteralMethod(memberDecl)) { + var jsdocType = void 0; + if (isInJSFile) { + jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); + } + var type = void 0; + if (memberDecl.kind === 261 /* PropertyAssignment */) { + type = checkPropertyAssignment(memberDecl, checkMode); + } + else if (memberDecl.kind === 151 /* MethodDeclaration */) { + type = checkObjectLiteralMethod(memberDecl, checkMode); + } + else { + ts.Debug.assert(memberDecl.kind === 262 /* ShorthandPropertyAssignment */); + type = checkExpressionForMutableLocation(memberDecl.name, checkMode); + } + if (jsdocType) { + checkTypeAssignableTo(type, jsdocType, memberDecl); + type = jsdocType; + } + typeFlags |= type.flags; + var prop = createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (inDestructuringPattern) { + // If object literal is an assignment pattern and if the assignment pattern specifies a default value + // for the property, make the property optional. + var isOptional = (memberDecl.kind === 261 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 262 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + if (isOptional) { + prop.flags |= 16777216 /* Optional */; + } + if (ts.hasDynamicName(memberDecl)) { + patternWithComputedProperties = true; + } + } + else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + // If object literal is contextually typed by the implied type of a binding pattern, and if the + // binding pattern specifies a default value for the property, make the property optional. + var impliedProp = getPropertyOfType(contextualType, member.escapedName); + if (impliedProp) { + prop.flags |= impliedProp.flags & 16777216 /* Optional */; + } + else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { + error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); + } + } + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; + } + else if (memberDecl.kind === 263 /* SpreadAssignment */) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(memberDecl, 2 /* Assign */); + } + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + propertiesArray = []; + propertiesTable = ts.createSymbolTable(); + hasComputedStringProperty = false; + hasComputedNumberProperty = false; + typeFlags = 0; + } + var type = checkExpression(memberDecl.expression); + if (!isValidSpreadType(type)) { + error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); + return unknownType; + } + spread = getSpreadType(spread, type); + offset = i + 1; + continue; + } + else { + // TypeScript 1.0 spec (April 2014) + // A get accessor declaration is processed in the same manner as + // an ordinary function declaration(section 6.1) with no parameters. + // A set accessor declaration is processed in the same manner + // as an ordinary function declaration with a single parameter and a Void return type. + ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); + checkNodeDeferred(memberDecl); + } + if (ts.hasDynamicName(memberDecl)) { + if (isNumericName(memberDecl.name)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + } + else { + propertiesTable.set(member.escapedName, member); + } + propertiesArray.push(member); + } + // If object literal is contextually typed by the implied type of a binding pattern, augment the result + // type with those properties for which the binding pattern specifies a default value. + if (contextualTypeHasPattern) { + for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { + var prop = _a[_i]; + if (!propertiesTable.get(prop.escapedName)) { + if (!(prop.flags & 16777216 /* Optional */)) { + error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + } + propertiesTable.set(prop.escapedName, prop); + propertiesArray.push(prop); + } + } + } + if (spread !== emptyObjectType) { + if (propertiesArray.length > 0) { + spread = getSpreadType(spread, createObjectLiteralType()); + } + if (spread.flags & 32768 /* Object */) { + // only set the symbol and flags if this is a (fresh) object type + spread.flags |= propagatedFlags; + spread.flags |= 1048576 /* FreshLiteral */; + spread.objectFlags |= 128 /* ObjectLiteral */; + spread.symbol = node.symbol; + } + return spread; + } + return createObjectLiteralType(); + function createObjectLiteralType() { + var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; + var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; + var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; + result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); + result.objectFlags |= 128 /* ObjectLiteral */; + if (patternWithComputedProperties) { + result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; + } + if (inDestructuringPattern) { + result.pattern = node; + } + if (!(result.flags & 6144 /* Nullable */)) { + propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); + } + return result; + } + } + function isValidSpreadType(type) { + return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */ | 16777216 /* NonPrimitive */) || + type.flags & 32768 /* Object */ && !isGenericMappedType(type) || + type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + } + function checkJsxSelfClosingElement(node) { + checkJsxOpeningLikeElement(node); + return getJsxGlobalElementType() || anyType; + } + function checkJsxElement(node) { + // Check attributes + checkJsxOpeningLikeElement(node.openingElement); + // Perform resolution on the closing tag so that rename/go to definition/etc work + if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { + getIntrinsicTagSymbol(node.closingElement); + } + else { + checkExpression(node.closingElement.tagName); + } + return getJsxGlobalElementType() || anyType; + } + /** + * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers + */ + function isUnhyphenatedJsxName(name) { + // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers + return name.indexOf("-") < 0; + } + /** + * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name + */ + function isJsxIntrinsicIdentifier(tagName) { + // TODO (yuisu): comment + switch (tagName.kind) { + case 179 /* PropertyAccessExpression */: + case 99 /* ThisKeyword */: + return false; + case 71 /* Identifier */: + return ts.isIntrinsicJsxName(tagName.escapedText); + default: + ts.Debug.fail(); + } + } + /** + * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. + * + * @param openingLikeElement a JSX opening-like element + * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable + * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. + * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, + * which also calls getSpreadType. + */ + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { + var attributes = openingLikeElement.attributes; + var attributesTable = ts.createSymbolTable(); + 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; + if (ts.isJsxAttribute(attributeDecl)) { + var exprType = attributeDecl.initializer ? + checkExpression(attributeDecl.initializer, checkMode) : + trueType; // is sugar for + var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.type = exprType; + attributeSymbol.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + attributesArray.push(attributeSymbol); + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + } + else { + ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createSymbolTable(); + } + var exprType = checkExpression(attributeDecl.expression); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; + } + } + } + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + } + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createSymbolTable(); + for (var _b = 0, attributesArray_1 = attributesArray; _b < attributesArray_1.length; _b++) { + var attr = attributesArray_1[_b]; + if (!filter || filter(attr)) { + attributesTable.set(attr.escapedName, 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 _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 */) { + if (!child.containsOnlyWhiteSpaces) { + childrenTypes.push(stringType); + } + } + else { + childrenTypes.push(checkExpression(child, checkMode)); + } + } + 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, ts.unescapeLeadingUnderscores(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 + var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName); + childrenPropSymbol.type = childrenTypes.length === 1 ? + childrenTypes[0] : + createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); + attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); + } + } + 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 + * @param attributesTable a symbol table of attributes property + */ + function createJsxAttributesType(symbol, attributesTable) { + var result = createAnonymousType(symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; + result.objectFlags |= 128 /* ObjectLiteral */; + return result; + } + } + /** + * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. + * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) + * @param node a JSXAttributes to be resolved of its type + */ + function checkJsxAttributes(node, checkMode) { + return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); + } + function getJsxType(name) { + var jsxType = jsxTypes.get(name); + if (jsxType === undefined) { + jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); + } + return jsxType; + } + /** + * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic + * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic + * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). + * May also return unknownSymbol if both of these lookups fail. + */ + function getIntrinsicTagSymbol(node) { + var links = getNodeLinks(node); + if (!links.resolvedSymbol) { + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + // Property case + if (!ts.isIdentifier(node.tagName)) + throw ts.Debug.fail(); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); + if (intrinsicProp) { + links.jsxFlags |= 1 /* IntrinsicNamedElement */; + return links.resolvedSymbol = intrinsicProp; + } + // Intrinsic string indexer case + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + links.jsxFlags |= 2 /* IntrinsicIndexedElement */; + return links.resolvedSymbol = intrinsicElementsType.symbol; + } + // Wasn't found + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); + return links.resolvedSymbol = unknownSymbol; + } + else { + if (noImplicitAny) { + error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements)); + } + return links.resolvedSymbol = unknownSymbol; + } + } + return links.resolvedSymbol; + } + /** + * Given a JSX element that is a class element, finds the Element Instance Type. If the + * element is not a class element, or the class element type cannot be determined, returns 'undefined'. + * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). + */ + function getJsxElementInstanceType(node, valueType) { + ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); + if (isTypeAny(valueType)) { + // Short-circuit if the class tag is using an element type 'any' + return anyType; + } + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(valueType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(valueType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); + return unknownType; + } + } + 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. + * Get a single property from that container if existed. Report an error if there are more than one property. + * + * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer + * if other string is given or the container doesn't exist, return undefined. + */ + function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { + // JSX + var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] + var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); + // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] + var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); + // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute + var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); + if (propertiesOfJsxElementAttribPropInterface) { + // Element Attributes has zero properties, so the element attributes type will be the class instance type + if (propertiesOfJsxElementAttribPropInterface.length === 0) { + return ""; + } + else if (propertiesOfJsxElementAttribPropInterface.length === 1) { + return propertiesOfJsxElementAttribPropInterface[0].escapedName; + } + else if (propertiesOfJsxElementAttribPropInterface.length > 1) { + // More than one property on ElementAttributesProperty is an error + error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer)); + } + } + return undefined; + } + /// e.g. "props" for React.d.ts, + /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all + /// non-intrinsic elements' attributes type is 'any'), + /// or '' if it has 0 properties (which means every + /// non-intrinsic elements' attributes type is the element instance type) + function getJsxElementPropertiesName() { + if (!_hasComputedJsxElementPropertiesName) { + _hasComputedJsxElementPropertiesName = true; + _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); + } + return _jsxElementPropertiesName; + } + function getJsxElementChildrenPropertyname() { + if (!_hasComputedJsxElementChildrenPropertyName) { + _hasComputedJsxElementChildrenPropertyName = true; + _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); + } + 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. + * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) + * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. + * @param openingLikeElement a JSX opening-like element to find attributes type + * @param elementType a type of the opening-like element. This elementType can't be an union type + * @param elemInstanceType an element instance type (the result of newing or invoking this tag) + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global + */ + function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { + ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. + var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); + 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); + if (intrinsicAttributes !== unknownType) { + paramType = intersectTypes(intrinsicAttributes, paramType); + } + return paramType; + } + } + } + } + return undefined; + } + /** + * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. + * Return all attributes type of resolved call signature including candidate signatures. + * This function assumes that the caller handled other possible element type of the JSX element. + * This function is a behavior used by language service when looking up completion in JSX element. + * @param openingLikeElement a JSX opening-like element to find attributes type + * @param elementType a type of the opening-like element. This elementType can't be an union type + * @param elemInstanceType an element instance type (the result of newing or invoking this tag) + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global + */ + function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { + ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { + // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type + var jsxStatelessElementType = getJsxGlobalStatelessElementType(); + if (jsxStatelessElementType) { + // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. + var candidatesOutArray = []; + getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); + var result = void 0; + var allMatchingAttributesType = void 0; + for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { + 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++) { + var attribute = _b[_a]; + if (ts.isJsxAttribute(attribute) && + isUnhyphenatedJsxName(attribute.name.escapedText) && + !getPropertyOfType(paramType, attribute.name.escapedText)) { + shouldBeCandidate = false; + break; + } + } + if (shouldBeCandidate) { + result = intersectTypes(result, paramType); + } + allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); + } + } + // If we can't find any matching, just return everything. + if (!result) { + result = allMatchingAttributesType; + } + // Intersect in JSX.IntrinsicAttributes if it exists + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttributes !== unknownType) { + result = intersectTypes(intrinsicAttributes, result); + } + return result; + } + } + return undefined; + } + /** + * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. + * For instance: + * declare function Foo(attr: { p1: string}): JSX.Element; + * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" + * + * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. + * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component + * + * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement + * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature + * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. + * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) + * @return attributes type if able to resolve the type of node + * anyType if there is no type ElementAttributesProperty or there is an error + * emptyObjectType if there is no "prop" in the element instance type + */ + function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { + if (!elementType) { + elementType = checkExpression(openingLikeElement.tagName); + } + if (elementType.flags & 65536 /* Union */) { + var types = elementType.types; + return getUnionType(types.map(function (type) { + return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); + }), /*subtypeReduction*/ true); + } + // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type + if (elementType.flags & 2 /* String */) { + return anyType; + } + else if (elementType.flags & 32 /* StringLiteral */) { + // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type + // For example: + // var CustomTag: "h1" = "h1"; + // Hello World + var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); + if (intrinsicElementsType !== unknownType) { + var stringLiteralTypeName = ts.escapeLeadingUnderscores(elementType.value); + var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); + if (intrinsicProp) { + return getTypeOfSymbol(intrinsicProp); + } + var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); + if (indexSignatureType) { + return indexSignatureType; + } + error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(stringLiteralTypeName), "JSX." + JsxNames.IntrinsicElements); + } + // If we need to report an error, we already done so here. So just return any to prevent any more error downstream + return anyType; + } + // Get the element instance type (the result of newing or invoking this tag) + var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. + // Otherwise get only attributes type from the signature picked by choose-overload logic. + var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? + tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : + defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); + if (statelessAttributesType) { + return statelessAttributesType; + } + // Issue an error if this return type isn't assignable to JSX.ElementClass + if (elementClassType) { + checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); + } + if (isTypeAny(elemInstanceType)) { + return elemInstanceType; + } + var propsName = getJsxElementPropertiesName(); + if (propsName === undefined) { + // There is no type ElementAttributesProperty, return 'any' + return anyType; + } + else if (propsName === "") { + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + return elemInstanceType; + } + else { + var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + if (!attributesType) { + // There is no property named 'props' on this instance type + return emptyObjectType; + } + else if (isTypeAny(attributesType) || (attributesType === unknownType)) { + // Props is of type 'any' or unknown + return attributesType; + } + else { + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); + if (intrinsicClassAttribs !== unknownType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + if (typeParams) { + if (typeParams.length === 1) { + apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); + } + } + else { + apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); + } + } + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); + if (intrinsicAttribs !== unknownType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); + } + return apparentAttributesType; + } + } + } + /** + * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. + * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. + * @param node an intrinsic JSX opening-like element + */ + function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { + ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var symbol = getIntrinsicTagSymbol(node); + if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { + return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); + } + else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { + return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; + } + else { + return links.resolvedJsxElementAttributesType = unknownType; + } + } + return links.resolvedJsxElementAttributesType; + } + /** + * Get attributes type of the given custom opening-like JSX element. + * This function is intended to be called from a caller that handles intrinsic JSX element already. + * @param node a custom JSX opening-like element + * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component + */ + function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { + var links = getNodeLinks(node); + if (!links.resolvedJsxElementAttributesType) { + var elemClassType = getJsxGlobalElementClassType(); + return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); + } + return links.resolvedJsxElementAttributesType; + } + /** + * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. + * This function is called by language service (see: completions-tryGetGlobalSymbols). + * @param node a JSX opening-like element to get attributes type for + */ + function getAllAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + // Because in language service, the given JSX opening-like element may be incomplete and therefore, + // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); + } + } + /** + * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. + * @param node a JSXOpeningLikeElement node + * @return an attributes type of the given node + */ + function getAttributesTypeFromJsxOpeningLikeElement(node) { + if (isJsxIntrinsicIdentifier(node.tagName)) { + return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + } + else { + return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); + } + } + /** + * Given a JSX attribute, returns the symbol for the corresponds property + * of the element attributes type. Will return unknownSymbol for attributes + * that have no matching element attributes type property. + */ + function getJsxAttributePropertySymbol(attrib) { + var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); + var prop = getPropertyOfType(attributesType, attrib.name.escapedText); + return prop || unknownSymbol; + } + function getJsxGlobalElementClassType() { + if (!deferredJsxElementClassType) { + deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); + } + return deferredJsxElementClassType; + } + function getJsxGlobalElementType() { + if (!deferredJsxElementType) { + deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); + } + return deferredJsxElementType; + } + function getJsxGlobalStatelessElementType() { + if (!deferredJsxStatelessElementType) { + var jsxElementType = getJsxGlobalElementType(); + if (jsxElementType) { + deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); + } + } + return deferredJsxStatelessElementType; + } + /** + * Returns all the properties of the Jsx.IntrinsicElements interface + */ + function getJsxIntrinsicTagNames() { + var intrinsics = getJsxType(JsxNames.IntrinsicElements); + return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray; + } + function checkJsxPreconditions(errorNode) { + // Preconditions for using JSX + if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { + error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); + } + if (getJsxGlobalElementType() === undefined) { + if (noImplicitAny) { + error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); + } + } + } + function checkJsxOpeningLikeElement(node) { + checkGrammarJsxElement(node); + checkJsxPreconditions(node); + // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. + // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. + var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; + var reactNamespace = getJsxNamespace(); + var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); + if (reactSym) { + // Mark local symbol as referenced here because it might not have been marked + // if jsx emit was not react as there wont be error being emitted + reactSym.isReferenced = true; + // If react symbol is alias, mark it as refereced + if (reactSym.flags & 2097152 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { + markAliasSymbolAsReferenced(reactSym); + } + } + 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 + * 1. the object type is empty and the check is for assignability, or + * 2. if the object type has index signatures, or + * 3. if the property is actually declared in the object type + * (this means that 'toString', for example, is not usually a known property). + * 4. 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) || + getPropertyOfObjectType(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" + * Check assignablity between given attributes property, "source attributes", and the "target attributes" + * @param openingLikeElement an opening-like JSX element to check its JSXAttributes + */ + function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { + // The function involves following steps: + // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. + // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) + // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. + // 3. Check if the two are assignable to each other + // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. + var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? + getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : + getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); + // sourceAttributesType is a type of an attributes properties. + // i.e
+ // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". + var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { + return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); + }); + // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. + // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. + if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { + error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName())); + } + else { + // 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.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } + } + } + function checkJsxExpression(node, checkMode) { + if (node.expression) { + var type = checkExpression(node.expression, checkMode); + if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { + error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); + } + return type; + } + else { + return unknownType; + } + } + // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized + // '.prototype' property as well as synthesized tuple index properties. + function getDeclarationKindFromSymbol(s) { + return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; + } + function getDeclarationNodeFlagsFromSymbol(s) { + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; + } + function isMethodLike(symbol) { + return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + } + /** + * Check whether the requested property access is valid. + * Returns true if node is a valid property access, and false otherwise. + * @param node The node to be checked. + * @param left The left hand side of the property access (e.g.: the super in `super.foo`). + * @param type The type of left. + * @param prop The symbol for the right hand side of the property access. + */ + function checkPropertyAccessibility(node, left, type, prop) { + var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); + var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? + node.name : + node.right; + 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; + } + if (left.kind === 97 /* SuperKeyword */) { + // TS 1.0 spec (April 2014): 4.8.2 + // - In a constructor, instance member function, instance member accessor, or + // instance member variable initializer where this references a derived class instance, + // a super property access is permitted and must specify a public instance member function of the base class. + // - In a static member function or static member accessor + // where this references the constructor function object of a derived class, + // a super property access is permitted and must specify a public static member function of the base class. + if (languageVersion < 2 /* ES2015 */) { + var hasNonMethodDeclaration = forEachProperty(prop, function (p) { + var propKind = getDeclarationKindFromSymbol(p); + return propKind !== 151 /* MethodDeclaration */ && propKind !== 150 /* MethodSignature */; + }); + if (hasNonMethodDeclaration) { + error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); + return false; + } + } + if (flags & 128 /* Abstract */) { + // A method cannot be accessed in a super property access if the method is abstract. + // This error could mask a private property access error. But, a member + // cannot simultaneously be private and abstract, so this will trigger an + // additional error elsewhere. + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + } + // Public properties are otherwise accessible. + if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + // Property is known to be private or protected at this point + // Private property is accessible if the property is within the declaring class + if (flags & 8 /* Private */) { + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); + return false; + } + return true; + } + // Property is known to be protected at this point + // All protected properties of a supertype are accessible in a super access + if (left.kind === 97 /* SuperKeyword */) { + return true; + } + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes + var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { + var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; + }); + // A protected property is accessible if the property is within the declaring class or classes derived from it + if (!enclosingClass) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + // No further restrictions for static properties + if (flags & 32 /* Static */) { + return true; + } + // An instance property must be accessed through an instance of the enclosing class + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { + // get the original type -- represented as the type constraint of the 'this' type + type = getConstraintOfTypeParameter(type); + } + if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); + return false; + } + return true; + } + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); + } + function checkNonNullType(type, errorNode) { + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144 /* Nullable */; + if (kind) { + error(errorNode, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + var t = getNonNullableType(type); + return t.flags & (6144 /* Nullable */ | 8192 /* Never */) ? unknownType : t; + } + return type; + } + function checkPropertyAccessExpression(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + } + function checkQualifiedName(node) { + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + } + function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { + var type = checkNonNullExpression(left); + if (isTypeAny(type) || type === silentNeverType) { + return type; + } + var apparentType = getApparentType(getWidenedType(type)); + if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { + // handle cases when type is Type parameter with invalid or any constraint + return apparentType; + } + var prop = getPropertyOfType(apparentType, right.escapedText); + if (!prop) { + var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); + if (stringIndexType) { + return stringIndexType; + } + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); + } + return unknownType; + } + if (prop.valueDeclaration) { + if (isInPropertyInitializer(node) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && + node.parent && node.parent.kind !== 159 /* TypeReference */ && + !ts.isInAmbientContext(prop.valueDeclaration) && + !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { + error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.unescapeLeadingUnderscores(right.escapedText)); + } + } + markPropertyAsReferenced(prop); + getNodeLinks(node).resolvedSymbol = prop; + checkPropertyAccessibility(node, left, apparentType, prop); + var propType = getDeclaredOrApparentType(prop, node); + var assignmentKind = ts.getAssignmentTargetKind(node); + if (assignmentKind) { + if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { + error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.unescapeLeadingUnderscores(right.escapedText)); + return unknownType; + } + } + // Only compute control flow type if this is a property access expression that isn't an + // assignment target, and the referenced property was declared as a variable, property, + // accessor, or optional method. + if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || + !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && + !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { + return propType; + } + 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.escapedText)) { + 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(ts.unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), 107455 /* Value */); + return suggestion && suggestion.escapedName; + } + 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(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); + }); + if (result) { + return result.escapedName; + } + } + /** + * 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; + var justCheckExactMatches = false; + 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]; + var candidateName = ts.unescapeLeadingUnderscores(candidate.escapedName); + if (candidate.flags & meaning && + candidateName && + Math.abs(candidateName.length - name.length) < maximumLengthDifference) { + candidateName = candidateName.toLowerCase(); + if (candidateName === name) { + return candidate; + } + if (justCheckExactMatches) { + continue; + } + 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) { + justCheckExactMatches = true; + bestCandidate = 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 + : node.left; + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { + if (type !== unknownType && !isTypeAny(type)) { + var prop = getPropertyOfType(type, propertyName); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); + } + // In js files properties of unions are allowed in completion + if (ts.isInJavaScriptFile(left) && (type.flags & 65536 /* Union */)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; + } + return true; + } + /** + * Return the symbol of the for-in variable declared or referenced by the given for-in statement. + */ + function getForInVariableSymbol(node) { + var initializer = node.initializer; + if (initializer.kind === 227 /* VariableDeclarationList */) { + var variable = initializer.declarations[0]; + if (variable && !ts.isBindingPattern(variable.name)) { + return getSymbolOfNode(variable); + } + } + else if (initializer.kind === 71 /* Identifier */) { + return getResolvedSymbol(initializer); + } + return undefined; + } + /** + * Return true if the given type is considered to have numeric property names. + */ + function hasNumericPropertyNames(type) { + return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); + } + /** + * Return true if given node is an expression consisting of an identifier (possibly parenthesized) + * that references a for-in variable for an object with numeric property names. + */ + function isForInVariableForNumericPropertyNames(expr) { + var e = ts.skipParentheses(expr); + if (e.kind === 71 /* Identifier */) { + var symbol = getResolvedSymbol(e); + if (symbol.flags & 3 /* Variable */) { + var child = expr; + var node = expr.parent; + while (node) { + if (node.kind === 215 /* ForInStatement */ && + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression))) { + return true; + } + child = node; + node = node.parent; + } + } + } + return false; + } + function checkIndexedAccess(node) { + var objectType = checkNonNullExpression(node.expression); + var indexExpression = node.argumentExpression; + if (!indexExpression) { + var sourceFile = ts.getSourceFileOfNode(node); + if (node.parent.kind === 182 /* NewExpression */ && node.parent.expression === node) { + var start = ts.skipTrivia(sourceFile.text, node.expression.end); + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); + } + else { + var start = node.end - "]".length; + var end = node.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); + } + return unknownType; + } + var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); + if (objectType === unknownType || objectType === silentNeverType) { + return objectType; + } + if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { + error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; + } + return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); + } + function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { + if (expressionType === unknownType) { + // There is already an error, so no need to report one. + return false; + } + if (!ts.isWellKnownSymbolSyntactically(expression)) { + return false; + } + // Make sure the property type is the primitive symbol type + if ((expressionType.flags & 512 /* ESSymbol */) === 0) { + if (reportError) { + error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); + } + return false; + } + // The name is Symbol., so make sure Symbol actually resolves to the + // global Symbol object + var leftHandSide = expression.expression; + var leftHandSideSymbol = getResolvedSymbol(leftHandSide); + if (!leftHandSideSymbol) { + return false; + } + var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); + if (!globalESSymbol) { + // Already errored when we tried to look up the symbol + return false; + } + if (leftHandSideSymbol !== globalESSymbol) { + if (reportError) { + error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); + } + return false; + } + 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); + } + else if (node.kind !== 147 /* Decorator */) { + ts.forEach(node.arguments, function (argument) { + checkExpression(argument); + }); + } + return anySignature; + } + function resolveErrorCall(node) { + resolveUntypedCall(node); + return unknownSignature; + } + // Re-order candidate signatures into the result array. Assumes the result array to be empty. + // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order + // A nit here is that we reorder only signatures that belong to the same symbol, + // so order how inherited signatures are processed is still preserved. + // interface A { (x: string): void } + // interface B extends A { (x: 'foo'): string } + // const b: B; + // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] + function reorderCandidates(signatures, result) { + var lastParent; + var lastSymbol; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; + ts.Debug.assert(!result.length); + 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) { + if (lastParent && parent === lastParent) { + index++; + } + else { + lastParent = parent; + index = cutoffIndex; + } + } + else { + // current declaration belongs to a different symbol + // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex + index = cutoffIndex = result.length; + lastParent = parent; + } + lastSymbol = symbol; + // specialized signatures always need to be placed before non-specialized signatures regardless + // of the cutoff position; see GH#1133 + if (signature.hasLiteralTypes) { + specializedIndex++; + spliceIndex = specializedIndex; + // The cutoff index always needs to be greater than or equal to the specialized signature index + // in order to prevent non-specialized signatures from being added before a specialized + // signature. + cutoffIndex++; + } + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); + } + } + function getSpreadArgumentIndex(args) { + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + if (arg && arg.kind === 198 /* SpreadElement */) { + return i; + } + } + return -1; + } + function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + var argCount; // Apparent number of arguments we will have in this call + var typeArguments; // Type arguments (undefined if none) + var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var isDecorator; + var spreadArgIndex = -1; + if (ts.isJsxOpeningLikeElement(node)) { + // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". + return true; + } + if (node.kind === 183 /* TaggedTemplateExpression */) { + var tagExpression = node; + // Even if the call is incomplete, we'll have a missing expression as our last argument, + // so we can say the count is just the arg list length + argCount = args.length; + typeArguments = undefined; + if (tagExpression.template.kind === 196 /* TemplateExpression */) { + // If a tagged template expression lacks a tail literal, the call is incomplete. + // Specifically, a template only can end in a TemplateTail or a Missing literal. + var templateExpression = tagExpression.template; + var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); + ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; + } + else { + // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, + // then this might actually turn out to be a TemplateHead in the future; + // so we consider the call to be incomplete. + var templateLiteral = tagExpression.template; + ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); + callIsIncomplete = !!templateLiteral.isUnterminated; + } + } + else if (node.kind === 147 /* Decorator */) { + isDecorator = true; + typeArguments = undefined; + argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); + } + else { + var callExpression = node; + if (!callExpression.arguments) { + // This only happens when we have something of the form: 'new C' + ts.Debug.assert(callExpression.kind === 182 /* NewExpression */); + return signature.minArgumentCount === 0; + } + argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; + // If we are missing the close parenthesis, the call is incomplete. + callIsIncomplete = callExpression.arguments.end === callExpression.end; + typeArguments = callExpression.typeArguments; + spreadArgIndex = getSpreadArgumentIndex(args); + } + // If the user supplied type arguments, but the number of type arguments does not match + // the declared number of type parameters, the call has an incorrect arity. + var numTypeParameters = ts.length(signature.typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); + var hasRightNumberOfTypeArgs = !typeArguments || + (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); + if (!hasRightNumberOfTypeArgs) { + return false; + } + // 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) || spreadArgIndex >= signature.minArgumentCount; + } + // Too many arguments implies incorrect arity. + if (!signature.hasRestParameter && argCount > signature.parameters.length) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + var hasEnoughArguments = argCount >= signature.minArgumentCount; + return callIsIncomplete || hasEnoughArguments; + } + // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. + function getSingleCallSignature(type) { + if (type.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(type); + if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && + resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { + return resolved.callSignatures[0]; + } + } + return undefined; + } + // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) + function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { + var context = createInferenceContext(signature, 1 /* InferUnionTypes */); + forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + // Type parameters from outer context referenced by source type are fixed by instantiation of the source type + inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + }); + if (!contextualMapper) { + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); + } + return getSignatureInstantiation(signature, getInferredTypes(context)); + } + function inferTypeArguments(node, signature, args, excludeArgument, context) { + // Clear out all the inference results from the last time inferTypeArguments was called on this context + for (var _i = 0, _a = context.inferences; _i < _a.length; _i++) { + var inference = _a[_i]; + // As an optimization, we don't have to clear (and later recompute) inferred types + // for type parameters that have already been fixed on the previous call to inferTypeArguments. + // It would be just as correct to reset all of them. But then we'd be repeating the same work + // for the type parameters that were fixed, namely the work done by getInferredType. + if (!inference.isFixed) { + inference.inferredType = undefined; + } + } + // If a contextual type is available, infer from that type to the return type of the call expression. For + // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression + // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the + // return type of 'wrap'. + if (ts.isExpression(node)) { + var contextualType = getContextualType(node); + if (contextualType) { + // We clone the contextual mapper to avoid disturbing a resolution in progress for an + // outer call expression. Effectively we just want a snapshot of whatever has been + // inferred for any outer call expression so far. + var instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + // If the contextual type is a generic function type with a single call signature, we + // instantiate the type with its own type parameters and type arguments. This ensures that + // the type parameters are not erased to type any during type inference such that they can + // be inferred as actual types from the contextual type. For example: + // declare function arrayMap(f: (x: T) => U): (a: T[]) => U[]; + // const boxElements: (a: A[]) => { value: A }[] = arrayMap(value => ({ value })); + // Above, the type of the 'value' parameter is inferred to be 'A'. + var contextualSignature = getSingleCallSignature(instantiatedType); + var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? + getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters)) : + instantiatedType; + var inferenceTargetType = getReturnTypeOfSignature(signature); + // Inferences made from return types have lower priority than all other inferences. + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); + } + } + var thisType = getThisTypeOfSignature(signature); + if (thisType) { + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + inferTypes(context.inferences, thisArgumentType, thisType); + } + // We perform two passes over the arguments. In the first pass we infer from all arguments, but use + // wildcards for all context sensitive function expressions. + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + var paramType = getTypeAtPosition(signature, i); + var argType = getEffectiveArgumentType(node, i); + // If the effective argument type is 'undefined', there is no synthetic type + // for the argument. In that case, we should check the argument. + if (argType === undefined) { + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : context; + argType = checkExpressionWithContextualType(arg, paramType, mapper); + } + inferTypes(context.inferences, argType, paramType); + } + } + // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this + // time treating function expressions normally (which may cause previously inferred type arguments to be fixed + // as we construct types for contextually typed parameters) + // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. + // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. + if (excludeArgument) { + for (var i = 0; i < argCount; i++) { + // No need to check for omitted args and template expressions, their exclusion value is always undefined + if (excludeArgument[i] === false) { + var arg = args[i]; + var paramType = getTypeAtPosition(signature, i); + inferTypes(context.inferences, checkExpressionWithContextualType(arg, paramType, context), paramType); + } + } + } + return getInferredTypes(context); + } + function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { + var typeParameters = signature.typeParameters; + var typeArgumentsAreAssignable = true; + var mapper; + for (var i = 0; i < typeArgumentNodes.length; i++) { + if (typeArgumentsAreAssignable /* so far */) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + var errorInfo = void 0; + var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; + if (reportErrors && headMessage) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); + typeArgumentHeadMessage = headMessage; + } + if (!mapper) { + mapper = createTypeMapper(typeParameters, typeArgumentTypes); + } + var typeArgument = typeArgumentTypes[i]; + typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); + } + } + } + return typeArgumentsAreAssignable; + } + /** + * Check if the given signature can possibly be a signature called by the JSX opening-like element. + * @param node a JSX opening-like element we are trying to figure its call signature + * @param signature a candidate signature we are trying whether it is a call signature + * @param relation a relationship to check parameter and argument type + * @param excludeArgument + */ + function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { + // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: + // 1. callIsIncomplete + // 2. attributes property has same number of properties as the parameter object type. + // We can figure that out by resolving attributes property and check number of properties in the resolved type + // If the call has correct arity, we will then check if the argument type and parameter type is assignable + var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete + if (callIsIncomplete) { + return true; + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + // Stateless function components can have maximum of three arguments: "props", "context", and "updater". + // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, + // can be specified by users through attributes property. + var paramType = getTypeAtPosition(signature, 0); + var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); + var argProperties = getPropertiesOfType(attributesType); + for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { + var arg = argProperties_1[_i]; + if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { + return false; + } + } + return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); + } + function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { + if (ts.isJsxOpeningLikeElement(node)) { + return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); + } + var thisType = getThisTypeOfSignature(signature); + if (thisType && thisType !== voidType && node.kind !== 182 /* NewExpression */) { + // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType + // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. + // If the expression is a new expression, then the check is skipped. + var thisArgumentNode = getThisArgumentOfCall(node); + var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; + var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; + if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + return false; + } + } + var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + var argCount = getEffectiveArgumentCount(node, args, signature); + for (var i = 0; i < argCount; i++) { + var arg = getEffectiveArgument(node, args, i); + // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. + if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { + // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) + var paramType = getTypeAtPosition(signature, i); + // If the effective argument type is undefined, there is no synthetic type for the argument. + // In that case, we should check the argument. + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + // Use argument expression as error location when reporting errors + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } + } + } + return true; + } + /** + * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. + */ + function getThisArgumentOfCall(node) { + if (node.kind === 181 /* CallExpression */) { + var callee = node.expression; + if (callee.kind === 179 /* PropertyAccessExpression */) { + return callee.expression; + } + else if (callee.kind === 180 /* ElementAccessExpression */) { + return callee.expression; + } + } + } + /** + * Returns the effective arguments for an expression that works like a function invocation. + * + * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. + * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution + * expressions, where the first element of the list is `undefined`. + * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types + * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. + */ + function getEffectiveCallArguments(node) { + if (node.kind === 183 /* TaggedTemplateExpression */) { + var template = node.template; + var args_4 = [undefined]; + if (template.kind === 196 /* TemplateExpression */) { + ts.forEach(template.templateSpans, function (span) { + args_4.push(span.expression); + }); + } + return args_4; + } + else if (node.kind === 147 /* Decorator */) { + // For a decorator, we return undefined as we will determine + // the number and types of arguments for a decorator using + // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. + return undefined; + } + else if (ts.isJsxOpeningLikeElement(node)) { + return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; + } + else { + return node.arguments || ts.emptyArray; + } + } + /** + * Returns the effective argument count for a node that works like a function invocation. + * If 'node' is a Decorator, the number of arguments is derived from the decoration + * target and the signature: + * If 'node.target' is a class declaration or class expression, the effective argument + * count is 1. + * If 'node.target' is a parameter declaration, the effective argument count is 3. + * If 'node.target' is a property declaration, the effective argument count is 2. + * If 'node.target' is a method or accessor declaration, the effective argument count + * is 3, although it can be 2 if the signature only accepts two arguments, allowing + * us to match a property decorator. + * Otherwise, the argument count is the length of the 'args' array. + */ + function getEffectiveArgumentCount(node, args, signature) { + if (node.kind === 147 /* Decorator */) { + switch (node.parent.kind) { + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) + return 1; + case 149 /* PropertyDeclaration */: + // A property declaration decorator will have two arguments (see + // `PropertyDecorator` in core.d.ts) + return 2; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + // A method or accessor declaration decorator will have two or three arguments (see + // `PropertyDecorator` and `MethodDecorator` in core.d.ts) + // If we are emitting decorators for ES3, we will only pass two arguments. + if (languageVersion === 0 /* ES3 */) { + return 2; + } + // If the method decorator signature only accepts a target and a key, we will only + // type check those arguments. + return signature.parameters.length >= 3 ? 3 : 2; + case 146 /* Parameter */: + // A parameter declaration decorator will have three arguments (see + // `ParameterDecorator` in core.d.ts) + return 3; + } + } + else { + return args.length; + } + } + /** + * Returns the effective type of the first argument to a decorator. + * If 'node' is a class declaration or class expression, the effective argument type + * is the type of the static side of the class. + * If 'node' is a parameter declaration, the effective argument type is either the type + * of the static or instance side of the class for the parameter's parent method, + * depending on whether the method is declared static. + * For a constructor, the type is always the type of the static side of the class. + * If 'node' is a property, method, or accessor declaration, the effective argument + * type is the type of the static or instance side of the parent class for class + * element, depending on whether the element is declared static. + */ + function getEffectiveDecoratorFirstArgumentType(node) { + // The first argument to a decorator is its `target`. + if (node.kind === 229 /* ClassDeclaration */) { + // For a class decorator, the `target` is the type of the class (e.g. the + // "static" or "constructor" side of the class) + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + if (node.kind === 146 /* Parameter */) { + // For a parameter decorator, the `target` is the parent type of the + // parameter's containing method. + node = node.parent; + if (node.kind === 152 /* Constructor */) { + var classSymbol = getSymbolOfNode(node); + return getTypeOfSymbol(classSymbol); + } + } + if (node.kind === 149 /* PropertyDeclaration */ || + node.kind === 151 /* MethodDeclaration */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // For a property or method decorator, the `target` is the + // "static"-side type of the parent of the member if the member is + // declared "static"; otherwise, it is the "instance"-side type of the + // parent of the member. + return getParentTypeOfClassElement(node); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective type for the second argument to a decorator. + * If 'node' is a parameter, its effective argument type is one of the following: + * If 'node.parent' is a constructor, the effective argument type is 'any', as we + * will emit `undefined`. + * If 'node.parent' is a member with an identifier, numeric, or string literal name, + * the effective argument type will be a string literal type for the member name. + * If 'node.parent' is a computed property name, the effective argument type will + * either be a symbol type or the string type. + * If 'node' is a member with an identifier, numeric, or string literal name, the + * effective argument type will be a string literal type for the member name. + * If 'node' is a computed property name, the effective argument type will either + * be a symbol type or the string type. + * A class decorator does not have a second argument type. + */ + function getEffectiveDecoratorSecondArgumentType(node) { + // The second argument to a decorator is its `propertyKey` + if (node.kind === 229 /* ClassDeclaration */) { + ts.Debug.fail("Class decorators should not have a second synthetic argument."); + return unknownType; + } + if (node.kind === 146 /* Parameter */) { + node = node.parent; + if (node.kind === 152 /* Constructor */) { + // For a constructor parameter decorator, the `propertyKey` will be `undefined`. + return anyType; + } + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. + } + if (node.kind === 149 /* PropertyDeclaration */ || + node.kind === 151 /* MethodDeclaration */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // The `propertyKey` for a property or method decorator will be a + // string literal type if the member name is an identifier, number, or string; + // otherwise, if the member name is a computed property name it will + // be either string or symbol. + var element = node; + switch (element.name.kind) { + case 71 /* Identifier */: + return getLiteralType(ts.unescapeLeadingUnderscores(element.name.escapedText)); + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + return getLiteralType(element.name.text); + case 144 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(element.name); + if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { + return nameType; + } + else { + return stringType; + } + default: + ts.Debug.fail("Unsupported property name."); + return unknownType; + } + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective argument type for the third argument to a decorator. + * If 'node' is a parameter, the effective argument type is the number type. + * If 'node' is a method or accessor, the effective argument type is a + * `TypedPropertyDescriptor` instantiated with the type of the member. + * Class and property decorators do not have a third effective argument. + */ + function getEffectiveDecoratorThirdArgumentType(node) { + // The third argument to a decorator is either its `descriptor` for a method decorator + // or its `parameterIndex` for a parameter decorator + if (node.kind === 229 /* ClassDeclaration */) { + ts.Debug.fail("Class decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 146 /* Parameter */) { + // The `parameterIndex` for a parameter decorator is always a number + return numberType; + } + if (node.kind === 149 /* PropertyDeclaration */) { + ts.Debug.fail("Property decorators should not have a third synthetic argument."); + return unknownType; + } + if (node.kind === 151 /* MethodDeclaration */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` + // for the type of the member. + var propertyType = getTypeOfNode(node); + return createTypedPropertyDescriptorType(propertyType); + } + ts.Debug.fail("Unsupported decorator target."); + return unknownType; + } + /** + * Returns the effective argument type for the provided argument to a decorator. + */ + function getEffectiveDecoratorArgumentType(node, argIndex) { + if (argIndex === 0) { + return getEffectiveDecoratorFirstArgumentType(node.parent); + } + else if (argIndex === 1) { + return getEffectiveDecoratorSecondArgumentType(node.parent); + } + else if (argIndex === 2) { + return getEffectiveDecoratorThirdArgumentType(node.parent); + } + ts.Debug.fail("Decorators should not have a fourth synthetic argument."); + return unknownType; + } + /** + * Gets the effective argument type for an argument in a call expression. + */ + function getEffectiveArgumentType(node, argIndex) { + // Decorators provide special arguments, a tagged template expression provides + // a special first argument, and string literals get string literal types + // unless we're reporting errors + if (node.kind === 147 /* Decorator */) { + return getEffectiveDecoratorArgumentType(node, argIndex); + } + else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + return getGlobalTemplateStringsArrayType(); + } + // This is not a synthetic argument, so we return 'undefined' + // to signal that the caller needs to check the argument. + return undefined; + } + /** + * Gets the effective argument expression for an argument in a call expression. + */ + function getEffectiveArgument(node, args, argIndex) { + // For a decorator or the first argument of a tagged template expression we return undefined. + if (node.kind === 147 /* Decorator */ || + (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */)) { + return undefined; + } + return args[argIndex]; + } + /** + * Gets the error node to use when reporting errors for an effective argument. + */ + function getEffectiveArgumentErrorNode(node, argIndex, arg) { + if (node.kind === 147 /* Decorator */) { + // For a decorator, we use the expression of the decorator for error reporting. + return node.expression; + } + else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { + // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. + return node.template; + } + else { + return arg; + } + } + function resolveCall(node, signatures, candidatesOutArray, fallbackError) { + var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 147 /* Decorator */; + var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); + var typeArguments; + if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { + typeArguments = node.typeArguments; + // We already perform checking on the type arguments on the class declaration itself. + if (node.expression.kind !== 97 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } + var candidates = candidatesOutArray || []; + // reorderCandidates fills up the candidates array directly + reorderCandidates(signatures, candidates); + if (!candidates.length) { + diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); + return resolveErrorCall(node); + } + var args = getEffectiveCallArguments(node); + // The following applies to any value of 'excludeArgument[i]': + // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. + // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. + // - false: the argument at 'i' *was* and *has been* permanently contextually typed. + // + // The idea is that we will perform type argument inference & assignability checking once + // without using the susceptible parameters that are functions, and once more for each of those + // parameters, contextually typing each as we go along. + // + // For a tagged template, then the first argument be 'undefined' if necessary + // because it represents a TemplateStringsArray. + // + // For a decorator, no arguments are susceptible to contextual typing due to the fact + // decorators are applied to a declaration by the emitter, and not to an expression. + var excludeArgument; + var excludeCount = 0; + if (!isDecorator) { + // We do not need to call `getEffectiveArgumentCount` here as it only + // applies when calculating the number of arguments for a decorator. + for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { + if (isContextSensitive(args[i])) { + if (!excludeArgument) { + excludeArgument = new Array(args.length); + } + excludeArgument[i] = true; + excludeCount++; + } + } + } + // The following variables are captured and modified by calls to chooseOverload. + // If overload resolution or type argument inference fails, we want to report the + // best error possible. The best error is one which says that an argument was not + // assignable to a parameter. This implies that everything else about the overload + // was fine. So if there is any overload that is only incorrect because of an + // argument, we will report an error on that one. + // + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; + // foo(true); + // + // If none of the overloads even made it that far, there are two possibilities. + // There was a problem with type arguments for some overload, in which case + // report an error on that. Or none of the overloads even had correct arity, + // in which case give an arity error. + // + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); + // + var candidateForArgumentError; + var candidateForTypeArgumentError; + var result; + // If we are in signature help, a trailing comma indicates that we intend to provide another argument, + // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 /* CallExpression */ && node.arguments.hasTrailingComma; + // Section 4.12.1: + // if the candidate list contains one or more signatures for which the type of each argument + // expression is a subtype of each corresponding parameter type, the return type of the first + // of those signatures becomes the return type of the function call. + // Otherwise, the return type of the first signature in the candidate list becomes the return + // type of the function call. + // + // Whether the call is an error is determined by assignability of the arguments. The subtype pass + // is just important for choosing the best signature. So in the case where there is only one + // signature, the subtype pass is useless. So skipping it is an optimization. + if (candidates.length > 1) { + result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); + } + if (!result) { + result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); + } + if (result) { + return result; + } + // No signatures were applicable. Now report errors based on the last applicable signature with + // no arguments excluded from assignability checks. + // If candidate is undefined, it means that no candidates had a suitable arity. In that case, + // skip the checkApplicableSignature check. + if (candidateForArgumentError) { + if (isJsxOpeningOrSelfClosingElement) { + // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". + return candidateForArgumentError; + } + // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] + // The importance of excludeArgument is to prevent us from typing function expression parameters + // in arguments too early. If possible, we'd like to only type them once we know the correct + // overload. However, this matters for the case where the call is correct. When the call is + // an error, we don't need to exclude any arguments, although it would cause no harm to do so. + checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); + } + else if (candidateForTypeArgumentError) { + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); + } + 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 than anySignature. + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + if (!produceDiagnostics) { + ts.Debug.assert(candidates.length > 0); // Else would have exited above. + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { + var typeArguments_2 = node.typeArguments.map(getTypeOfNode); + while (typeArguments_2.length > typeParameters.length) { + typeArguments_2.pop(); + } + while (typeArguments_2.length < typeParameters.length) { + typeArguments_2.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments_2); + candidates[bestIndex] = instantiated; + return instantiated; + } + return candidate; + } + return resolveErrorCall(node); + function chooseOverload(candidates, relation, signatureHelpTrailingComma) { + if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; + for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { + var originalCandidate = candidates[candidateIndex]; + if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + continue; + } + var candidate = void 0; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : + undefined; + while (true) { + candidate = originalCandidate; + if (candidate.typeParameters) { + var typeArgumentTypes = void 0; + if (typeArguments) { + typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } + } + else { + typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); + } + candidate = getSignatureInstantiation(candidate, typeArgumentTypes); + } + if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; + break; + } + if (excludeCount === 0) { + candidates[candidateIndex] = candidate; + return candidate; + } + excludeCount--; + if (excludeCount > 0) { + excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + } + else { + excludeArgument = undefined; + } + } + } + return undefined; + } + } + function getLongestCandidateIndex(candidates, argsCount) { + var maxParamsIndex = -1; + var maxParams = -1; + for (var i = 0; i < candidates.length; i++) { + var candidate = candidates[i]; + if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + return i; + } + if (candidate.parameters.length > maxParams) { + maxParams = candidate.parameters.length; + maxParamsIndex = i; + } + } + return maxParamsIndex; + } + function resolveCallExpression(node, candidatesOutArray) { + if (node.expression.kind === 97 /* SuperKeyword */) { + var superType = checkSuperExpression(node.expression); + if (superType !== unknownType) { + // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated + // with the type arguments specified in the extends clause. + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + if (baseTypeNode) { + var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); + return resolveCall(node, baseConstructors, candidatesOutArray); + } + } + return resolveUntypedCall(node); + } + var funcType = checkNonNullExpression(node.expression); + if (funcType === silentNeverType) { + return silentNeverSignature; + } + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including call signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + // TS 1.0 Spec: 4.12 + // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual + // types are provided for the argument expressions, and the result is always of type Any. + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + // The unknownType indicates that an error already occurred (and was reported). No + // need to report another error in this case. + if (funcType !== unknownType && node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. + // TypeScript employs overload resolution in typed function calls in order to support functions + // with multiple call signatures. + if (!callSignatures.length) { + if (constructSignatures.length) { + error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); + } + else { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + } + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + /** + * TS 1.0 spec: 4.12 + * If FuncExpr is of type Any, or of an object type that has no call or construct signatures + * but is a subtype of the Function interface, the call is an untyped function call. + */ + function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { + if (isTypeAny(funcType)) { + return true; + } + if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { + return true; + } + if (!numCallSignatures && !numConstructSignatures) { + // We exclude union types because we may have a union of function types that happen to have + // no common signatures. + if (funcType.flags & 65536 /* Union */) { + return false; + } + return isTypeAssignableTo(funcType, globalFunctionType); + } + return false; + } + function resolveNewExpression(node, candidatesOutArray) { + if (node.arguments && languageVersion < 1 /* ES5 */) { + var spreadIndex = getSpreadArgumentIndex(node.arguments); + if (spreadIndex >= 0) { + error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); + } + } + var expressionType = checkNonNullExpression(node.expression); + if (expressionType === silentNeverType) { + return silentNeverSignature; + } + // If expressionType's apparent type(section 3.8.1) is an object type with one or + // more construct signatures, the expression is processed in the same manner as a + // function call, but using the construct signatures as the initial set of candidate + // signatures for overload resolution. The result type of the function call becomes + // the result type of the operation. + expressionType = getApparentType(expressionType); + if (expressionType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + // If the expression is a class of abstract type, then it cannot be instantiated. + // Note, only class declarations can be declared abstract. + // In the case of a merged class-module or class-interface declaration, + // 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(ts.getNameOfDeclaration(valueDecl))); + return resolveErrorCall(node); + } + // TS 1.0 spec: 4.11 + // If expressionType is of type Any, Args can be any argument + // list and the result of the operation is of type Any. + if (isTypeAny(expressionType)) { + if (node.typeArguments) { + error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); + } + return resolveUntypedCall(node); + } + // Technically, this signatures list may be incomplete. We are taking the apparent type, + // but we are not including construct signatures that may have been added to the Object or + // Function interface, since they have none by default. This is a bit of a leap of faith + // that the user will not add any. + var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); + if (constructSignatures.length) { + if (!isConstructorAccessible(node, constructSignatures[0])) { + return resolveErrorCall(node); + } + return resolveCall(node, constructSignatures, candidatesOutArray); + } + // If expressionType's apparent type is an object type with no construct signatures but + // one or more call signatures, the expression is processed as a function call. A compile-time + // error occurs if the result of the function call is not Void. The type of the result of the + // operation is Any. It is an error to have a Void this type. + var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); + if (callSignatures.length) { + var signature = resolveCall(node, callSignatures, candidatesOutArray); + if (!isJavaScriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); + } + if (getThisTypeOfSignature(signature) === voidType) { + error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); + } + return signature; + } + error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + return resolveErrorCall(node); + } + function isConstructorAccessible(node, signature) { + if (!signature || !signature.declaration) { + return true; + } + var declaration = signature.declaration; + var modifiers = ts.getModifierFlags(declaration); + // Public constructor is accessible. + if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { + return true; + } + var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); + var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); + // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) + if (!isNodeWithinClass(node, declaringClassDeclaration)) { + var containingClass = ts.getContainingClass(node); + if (containingClass) { + var containingType = getTypeOfNode(containingClass); + var baseTypes = getBaseTypes(containingType); + while (baseTypes.length) { + var baseType = baseTypes[0]; + if (modifiers & 16 /* Protected */ && + baseType.symbol === declaration.parent.symbol) { + return true; + } + baseTypes = getBaseTypes(baseType); + } + } + if (modifiers & 8 /* Private */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + if (modifiers & 16 /* Protected */) { + error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); + } + return false; + } + return true; + } + function resolveTaggedTemplateExpression(node, candidatesOutArray) { + var tagType = checkExpression(node.tag); + var apparentType = getApparentType(tagType); + if (apparentType === unknownType) { + // Another error has already been reported + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + if (!callSignatures.length) { + error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray); + } + /** + * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. + */ + function getDiagnosticHeadMessageForDecoratorResolution(node) { + switch (node.parent.kind) { + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; + case 146 /* Parameter */: + return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; + case 149 /* PropertyDeclaration */: + return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + } + } + /** + * Resolves a decorator as if it were a call expression. + */ + function resolveDecorator(node, candidatesOutArray) { + var funcType = checkExpression(node.expression); + var apparentType = getApparentType(funcType); + if (apparentType === unknownType) { + return resolveErrorCall(node); + } + var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); + var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); + if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { + return resolveUntypedCall(node); + } + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + if (!callSignatures.length) { + var errorInfo = void 0; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + return resolveErrorCall(node); + } + return resolveCall(node, callSignatures, candidatesOutArray, headMessage); + } + /** + * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. + * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName + * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) + * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. + * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function + * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + */ + function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { + ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); + var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); + return callSignature; + } + /** + * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. + * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible + * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. + * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures + */ + function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { + // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) + if (elementType.flags & 65536 /* Union */) { + var types = elementType.types; + var result = void 0; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; + result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); + } + return result; + } + var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); + if (callSignatures && callSignatures.length > 0) { + return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); + } + return undefined; + } + function resolveSignature(node, candidatesOutArray) { + switch (node.kind) { + case 181 /* CallExpression */: + return resolveCallExpression(node, candidatesOutArray); + case 182 /* NewExpression */: + return resolveNewExpression(node, candidatesOutArray); + case 183 /* TaggedTemplateExpression */: + return resolveTaggedTemplateExpression(node, candidatesOutArray); + case 147 /* Decorator */: + return resolveDecorator(node, candidatesOutArray); + case 251 /* JsxOpeningElement */: + case 250 /* JsxSelfClosingElement */: + // This code-path is called by language service + return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); + } + ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); + } + /** + * Resolve a signature of a given call-like expression. + * @param node a call-like expression to try resolve a signature for + * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; + * the function will fill it up with appropriate candidate signatures + * @return a signature of the call-like expression or undefined if one can't be found + */ + function getResolvedSignature(node, candidatesOutArray) { + var links = getNodeLinks(node); + // If getResolvedSignature has already been called, we will have cached the resolvedSignature. + // However, it is possible that either candidatesOutArray was not passed in the first time, + // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work + // to correctly fill the candidatesOutArray. + var cached = links.resolvedSignature; + if (cached && cached !== resolvingSignature && !candidatesOutArray) { + return cached; + } + links.resolvedSignature = resolvingSignature; + var result = resolveSignature(node, candidatesOutArray); + // If signature resolution originated in control flow type analysis (for example to compute the + // assigned type in a flow assignment) we don't cache the result as it may be based on temporary + // types from the control flow analysis. + links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; + return result; + } + /** + * Indicates whether a declaration can be treated as a constructor in a JavaScript + * file. + */ + function isJavaScriptConstructor(node) { + if (ts.isInJavaScriptFile(node)) { + // If the node has a @class tag, treat it like a constructor. + if (ts.getJSDocClassTag(node)) + return true; + // If the symbol of the node has members, treat it like a constructor. + var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : + ts.isVariableDeclaration(node) && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : + undefined; + return symbol && symbol.members !== undefined; + } + return false; + } + function getInferredClassType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.inferredClassType) { + links.inferredClassType = createAnonymousType(symbol, symbol.members || emptySymbols, ts.emptyArray, ts.emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); + } + return links.inferredClassType; + } + function isInferredClassType(type) { + return type.symbol + && getObjectFlags(type) & 16 /* Anonymous */ + && getSymbolLinks(type.symbol).inferredClassType === type; + } + /** + * Syntactically and semantically checks a call or new expression. + * @param node The call/new expression to be checked. + * @returns On success, the expression's signature's return type. On failure, anyType. + */ + function checkCallExpression(node) { + // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true + checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); + var signature = getResolvedSignature(node); + if (node.expression.kind === 97 /* SuperKeyword */) { + return voidType; + } + if (node.kind === 182 /* NewExpression */) { + var declaration = signature.declaration; + if (declaration && + declaration.kind !== 152 /* Constructor */ && + declaration.kind !== 156 /* ConstructSignature */ && + declaration.kind !== 161 /* ConstructorType */ && + !ts.isJSDocConstructSignature(declaration)) { + // When resolved signature is a call signature (and not a construct signature) the result type is any, unless + // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations + // in a JS file + // Note:JS inferred classes might come from a variable declaration instead of a function declaration. + // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. + var funcSymbol = node.expression.kind === 71 /* Identifier */ ? + getResolvedSymbol(node.expression) : + checkExpression(node.expression).symbol; + if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { + funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); + } + if (funcSymbol && funcSymbol.flags & 16 /* Function */ && (funcSymbol.members || ts.getJSDocClassTag(funcSymbol.valueDeclaration))) { + return getInferredClassType(funcSymbol); + } + else if (noImplicitAny) { + error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); + } + return anyType; + } + } + // In JavaScript files, calls to any identifier 'require' are treated as external module imports + if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { + return resolveExternalModuleTypeByLiteral(node.arguments[0]); + } + return getReturnTypeOfSignature(signature); + } + function checkImportCallExpression(node) { + // Check grammar of dynamic import + checkGrammarArguments(node, node.arguments) || checkGrammarImportCallExpression(node); + if (node.arguments.length === 0) { + return createPromiseReturnType(node, anyType); + } + var specifier = node.arguments[0]; + var specifierType = checkExpressionCached(specifier); + // Even though multiple arugments is grammatically incorrect, type-check extra arguments for completion + for (var i = 1; i < node.arguments.length; ++i) { + checkExpressionCached(node.arguments[i]); + } + if (specifierType.flags & 2048 /* Undefined */ || specifierType.flags & 4096 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); + } + // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal + var moduleSymbol = resolveExternalModuleName(node, specifier); + if (moduleSymbol) { + var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); + if (esModuleSymbol) { + return createPromiseReturnType(node, getTypeOfSymbol(esModuleSymbol)); + } + } + return createPromiseReturnType(node, anyType); + } + function isCommonJsRequire(node) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + return false; + } + // Make sure require is not a local function + if (!ts.isIdentifier(node.expression)) + throw ts.Debug.fail(); + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!resolvedRequire) { + // project does not contain symbol named 'require' - assume commonjs require + return true; + } + // project includes symbol named 'require' - make sure that it it ambient and local non-alias + if (resolvedRequire.flags & 2097152 /* Alias */) { + return false; + } + var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ + ? 228 /* FunctionDeclaration */ + : resolvedRequire.flags & 3 /* Variable */ + ? 226 /* VariableDeclaration */ + : 0 /* Unknown */; + if (targetDeclarationKind !== 0 /* Unknown */) { + var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); + // function/variable declaration should be ambient + return ts.isInAmbientContext(decl); + } + return false; + } + function checkTaggedTemplateExpression(node) { + return getReturnTypeOfSignature(getResolvedSignature(node)); + } + function checkAssertion(node) { + return checkAssertionWorker(node, node.type, node.expression); + } + function checkAssertionWorker(errNode, type, expression, checkMode) { + var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); + checkSourceElement(type); + var targetType = getTypeFromTypeNode(type); + if (produceDiagnostics && targetType !== unknownType) { + var widenedType = getWidenedType(exprType); + if (!isTypeComparableTo(targetType, widenedType)) { + checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); + } + } + return targetType; + } + function checkNonNullAssertion(node) { + return getNonNullableType(checkExpression(node.expression)); + } + function checkMetaProperty(node) { + checkGrammarMetaProperty(node); + var container = ts.getNewTargetContainer(node); + if (!container) { + error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); + return unknownType; + } + else if (container.kind === 152 /* Constructor */) { + var symbol = getSymbolOfNode(container.parent); + return getTypeOfSymbol(symbol); + } + else { + var symbol = getSymbolOfNode(container); + return getTypeOfSymbol(symbol); + } + } + function getTypeOfParameter(symbol) { + var type = getTypeOfSymbol(symbol); + if (strictNullChecks) { + var declaration = symbol.valueDeclaration; + if (declaration && declaration.initializer) { + return getNullableType(type, 2048 /* Undefined */); + } + } + return type; + } + function getTypeAtPosition(signature, pos) { + return signature.hasRestParameter ? + pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : + pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + } + function getTypeOfFirstParameterOfSignature(signature) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; + } + function inferFromAnnotatedParameters(signature, context, mapper) { + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var declaration = signature.parameters[i].valueDeclaration; + if (declaration.type) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + inferTypes(mapper.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i)); + } + } + } + } + function assignContextualParameterTypes(signature, context) { + signature.typeParameters = context.typeParameters; + if (context.thisParameter) { + var parameter = signature.thisParameter; + if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { + if (!parameter) { + signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); + } + assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); + } + } + var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + for (var i = 0; i < len; i++) { + var parameter = signature.parameters[i]; + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + var parameter = ts.lastOrUndefined(signature.parameters); + if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { + var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); + } + } + } + // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push + // the destructured type into the contained binding elements. + function assignBindingElementTypes(node) { + if (ts.isBindingPattern(node.name)) { + for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + if (element.name.kind === 71 /* Identifier */) { + getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + } + assignBindingElementTypes(element); + } + } + } + } + function assignTypeToParameterAndFixTypeParameters(parameter, contextualType) { + var links = getSymbolLinks(parameter); + if (!links.type) { + links.type = contextualType; + 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 && + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); + } + assignBindingElementTypes(parameter.valueDeclaration); + } + } + function createPromiseType(promisedType) { + // creates a `Promise` type where `T` is the promisedType argument + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType) { + // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type + promisedType = getAwaitedType(promisedType) || emptyObjectType; + return createTypeReference(globalPromiseType, [promisedType]); + } + return emptyObjectType; + } + function createPromiseReturnType(func, promisedType) { + var promiseType = createPromiseType(promisedType); + if (promiseType === emptyObjectType) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); + return unknownType; + } + else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { + error(func, ts.isImportCall(func) ? + ts.Diagnostics.A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : + ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + return promiseType; + } + function getReturnTypeFromBody(func, checkMode) { + var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!func.body) { + return unknownType; + } + var functionFlags = ts.getFunctionFlags(func); + var type; + if (func.body.kind !== 207 /* Block */) { + type = checkExpressionCached(func.body, checkMode); + if (functionFlags & 2 /* Async */) { + // 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 should be unwrapped to its awaited type, which we will wrap in + // the native Promise type later in this function. + type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + } + else { + var types = void 0; + if (functionFlags & 1 /* Generator */) { + types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); + if (!types || types.length === 0) { + var iterableIteratorAny = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function + : createIterableIteratorType(anyType); // Generator function + if (noImplicitAny) { + error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); + } + return iterableIteratorAny; + } + } + else { + types = checkAndAggregateReturnExpressionTypes(func, checkMode); + if (!types) { + // For an async function, the return type will not be never, but rather a Promise for never. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, neverType) // Async function + : neverType; // Normal function + } + if (types.length === 0) { + // For an async function, the return type will not be void, but rather a Promise for void. + return functionFlags & 2 /* Async */ + ? createPromiseReturnType(func, voidType) // Async function + : voidType; // Normal function + } + } + // Return a union of the return expression types. + type = getUnionType(types, /*subtypeReduction*/ true); + if (functionFlags & 1 /* Generator */) { + type = functionFlags & 2 /* Async */ + ? createAsyncIterableIteratorType(type) // AsyncGenerator function + : createIterableIteratorType(type); // Generator function + } + } + if (!contextualSignature) { + reportErrorsFromWidening(func, type); + } + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { + type = getWidenedLiteralType(type); + } + var widenedType = getWidenedType(type); + // 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 /* AsyncGenerator */) === 2 /* Async */ + ? createPromiseReturnType(func, widenedType) // Async function + : widenedType; // Generator function, AsyncGenerator function, or normal function + } + function checkAndAggregateYieldOperandTypes(func, checkMode) { + var aggregatedTypes = []; + var functionFlags = ts.getFunctionFlags(func); + ts.forEachYieldExpression(func.body, function (yieldExpression) { + var expr = yieldExpression.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (yieldExpression.asteriskToken) { + // A yield* expression effectively yields everything that its operand yields + type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); + } + if (functionFlags & 2 /* Async */) { + type = checkAwaitedType(type, expr, yieldExpression.asteriskToken + ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member + : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + }); + return aggregatedTypes; + } + function isExhaustiveSwitchStatement(node) { + if (!node.possiblyExhaustive) { + return false; + } + var type = getTypeOfExpression(node.expression); + if (!isLiteralType(type)) { + return false; + } + var switchTypes = getSwitchClauseTypes(node); + if (!switchTypes.length) { + return false; + } + return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); + } + function functionHasImplicitReturn(func) { + if (!(func.flags & 128 /* HasImplicitReturn */)) { + return false; + } + var lastStatement = ts.lastOrUndefined(func.body.statements); + if (lastStatement && lastStatement.kind === 221 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { + return false; + } + return true; + } + function checkAndAggregateReturnExpressionTypes(func, checkMode) { + var functionFlags = ts.getFunctionFlags(func); + var aggregatedTypes = []; + var hasReturnWithNoExpression = functionHasImplicitReturn(func); + var hasReturnOfTypeNever = false; + ts.forEachReturnStatement(func.body, function (returnStatement) { + var expr = returnStatement.expression; + if (expr) { + var type = checkExpressionCached(expr, checkMode); + if (functionFlags & 2 /* Async */) { + // 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 should be unwrapped to its awaited type, which should be wrapped in + // the native Promise type by the caller. + type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + if (type.flags & 8192 /* Never */) { + hasReturnOfTypeNever = true; + } + else if (!ts.contains(aggregatedTypes, type)) { + aggregatedTypes.push(type); + } + } + else { + hasReturnWithNoExpression = true; + } + }); + if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || + func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */)) { + return undefined; + } + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (!ts.contains(aggregatedTypes, undefinedType)) { + aggregatedTypes.push(undefinedType); + } + } + return aggregatedTypes; + } + /** + * TypeScript Specification 1.0 (6.3) - July 2014 + * An explicitly typed function whose return type isn't the Void type, + * the Any type, or a union type containing the Void or Any type as a constituent + * must have at least one return statement somewhere in its body. + * An exception to this rule is if the function implementation consists of a single 'throw' statement. + * + * @param returnType - return type of the function, can be undefined if return type is not explicitly specified + */ + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { + if (!produceDiagnostics) { + return; + } + // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. + if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { + return; + } + // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. + // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 /* Block */ || !functionHasImplicitReturn(func)) { + return; + } + var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; + if (returnType && returnType.flags & 8192 /* Never */) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); + } + else if (returnType && !hasExplicitReturn) { + // minimal check: function has syntactic return type annotation and no explicit return statements in the body + // this function does not conform to the specification. + // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); + } + else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { + error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); + } + else if (compilerOptions.noImplicitReturns) { + if (!returnType) { + // If return type annotation is omitted check if function has any explicit return statements. + // If it does not have any - its inferred return type is void - don't do any checks. + // Otherwise get inferred return type from function body and report error only if it is not void / anytype + if (!hasExplicitReturn) { + return; + } + var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); + if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { + return; + } + } + error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + // Grammar checking + var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { + checkGrammarForGenerator(node); + } + // The identityMapper object is used to indicate that function expressions are wildcards + if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { + checkNodeDeferred(node); + return anyFunctionType; + } + var links = getNodeLinks(node); + var type = getTypeOfSymbol(node.symbol); + // Check if function expression is contextually typed and assign parameter types if so. + if (!(links.flags & 1024 /* ContextChecked */)) { + var contextualSignature = getContextualSignature(node); + // If a type check is started at a function expression that is an argument of a function call, obtaining the + // contextual type may recursively get back to here during overload resolution of the call. If so, we will have + // already assigned contextual types. + if (!(links.flags & 1024 /* ContextChecked */)) { + links.flags |= 1024 /* ContextChecked */; + if (contextualSignature) { + var signature = getSignaturesOfType(type, 0 /* Call */)[0]; + if (isContextSensitive(node)) { + var contextualMapper = getContextualMapper(node); + if (checkMode === 2 /* Inferential */) { + inferFromAnnotatedParameters(signature, contextualSignature, contextualMapper); + } + var instantiatedContextualSignature = contextualMapper === identityMapper ? + contextualSignature : instantiateSignature(contextualSignature, contextualMapper); + assignContextualParameterTypes(signature, instantiatedContextualSignature); + } + if (!ts.getEffectiveReturnTypeNode(node) && !signature.resolvedReturnType) { + var returnType = getReturnTypeFromBody(node, checkMode); + if (!signature.resolvedReturnType) { + signature.resolvedReturnType = returnType; + } + } + } + checkSignatureDeclaration(node); + checkNodeDeferred(node); + } + } + if (produceDiagnostics && node.kind !== 151 /* MethodDeclaration */) { + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + } + return type; + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnOrPromisedType = returnTypeNode && + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? + checkAsyncFunctionReturnType(node) : + getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + if ((functionFlags & 1 /* Generator */) === 0) { + // return is not necessary in the body of generators + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (node.body) { + if (!returnTypeNode) { + // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors + // we need. An example is the noImplicitAny errors resulting from widening the return expression + // of a function. Because checking of function expression bodies is deferred, there was never an + // appropriate time to do this during the main walk of the file (see the comment at the top of + // checkFunctionExpressionBodies). So it must be done now. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + if (node.body.kind === 207 /* Block */) { + checkSourceElement(node.body); + } + else { + // 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 we + // should not be checking assignability of a promise to the return type. Instead, we need to + // check assignability of the awaited type of the expression body against the promised type of + // its return type annotation. + var exprType = checkExpression(node.body); + if (returnOrPromisedType) { + 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); + } + else { + checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + } + } + } + registerForUnusedIdentifiersCheck(node); + } + } + function checkArithmeticOperandType(operand, type, diagnostic) { + if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { + error(operand, diagnostic); + return false; + } + return true; + } + function isReadonlySymbol(symbol) { + // The following symbols are considered read-only: + // Properties with a 'readonly' modifier + // Variables declared with 'const' + // Get accessors without matching set accessors + // Enum members + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + 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 */); + } + function isReferenceToReadonlyEntity(expr, symbol) { + if (isReadonlySymbol(symbol)) { + // Allow assignments to readonly properties within constructors of the same class declaration. + if (symbol.flags & 4 /* Property */ && + (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) && + expr.expression.kind === 99 /* ThisKeyword */) { + // Look for if this is the constructor for the class that `symbol` is a property of. + var func = ts.getContainingFunction(expr); + if (!(func && func.kind === 152 /* Constructor */)) { + return true; + } + // If func.parent is a class and symbol is a (readonly) property of that class, or + // if func is a constructor and symbol is a (readonly) parameter property declared in it, + // then symbol is writeable here. + return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); + } + return true; + } + return false; + } + function isReferenceThroughNamespaceImport(expr) { + if (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) { + var node = ts.skipParentheses(expr.expression); + if (node.kind === 71 /* Identifier */) { + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol.flags & 2097152 /* Alias */) { + var declaration = getDeclarationOfAliasSymbol(symbol); + return declaration && declaration.kind === 240 /* NamespaceImport */; + } + } + } + return false; + } + function checkReferenceExpression(expr, invalidReferenceMessage) { + // References are combinations of identifiers, parentheses, and property accesses. + var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); + if (node.kind !== 71 /* Identifier */ && node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { + error(expr, invalidReferenceMessage); + return false; + } + return true; + } + function checkDeleteExpression(node) { + checkExpression(node.expression); + var expr = ts.skipParentheses(node.expression); + if (expr.kind !== 179 /* PropertyAccessExpression */ && expr.kind !== 180 /* ElementAccessExpression */) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); + return booleanType; + } + var links = getNodeLinks(expr); + var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); + if (symbol && isReadonlySymbol(symbol)) { + error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); + } + return booleanType; + } + function checkTypeOfExpression(node) { + checkExpression(node.expression); + return typeofType; + } + function checkVoidExpression(node) { + checkExpression(node.expression); + return undefinedWideningType; + } + function checkAwaitExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 16384 /* AwaitContext */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + var operandType = checkExpression(node.expression); + return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + function checkPrefixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { + return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); + } + switch (node.operator) { + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + checkNonNullType(operandType, node.operand); + if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { + error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); + } + return numberType; + case 51 /* ExclamationToken */: + var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); + return facts === 1048576 /* Truthy */ ? falseType : + facts === 2097152 /* Falsy */ ? trueType : + booleanType; + case 43 /* PlusPlusToken */: + case 44 /* MinusMinusToken */: + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + return unknownType; + } + function checkPostfixUnaryExpression(node) { + var operandType = checkExpression(node.operand); + if (operandType === silentNeverType) { + return silentNeverType; + } + var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + if (ok) { + // run check only if former checks succeeded to avoid reporting cascading errors + checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); + } + return numberType; + } + // Return true if type might be of the given kind. A union or intersection type might be of a given + // kind if at least one constituent type is of the given kind. + function maybeTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 196608 /* UnionOrIntersection */) { + var types = type.types; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; + if (maybeTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + // Return true if type is of the given kind. A union type is of a given kind if all constituent types + // are of the given kind. An intersection type is of a given kind if at least one constituent type is + // of the given kind. + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; + } + if (type.flags & 65536 /* Union */) { + var types = type.types; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; + if (!isTypeOfKind(t, kind)) { + return false; + } + } + return true; + } + if (type.flags & 131072 /* Intersection */) { + var types = type.types; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; + if (isTypeOfKind(t, kind)) { + return true; + } + } + } + return false; + } + function isConstEnumObjectType(type) { + return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + } + function isConstEnumSymbol(symbol) { + return (symbol.flags & 128 /* ConstEnum */) !== 0; + } + function checkInstanceOfExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + // TypeScript 1.0 spec (April 2014): 4.15.4 + // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, + // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. + // The result is always of the Boolean primitive type. + // NOTE: do not raise error if leftType is unknown as related error was already reported + if (isTypeOfKind(leftType, 8190 /* Primitive */)) { + error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + // NOTE: do not raise error if right is unknown as related error was already reported + if (!(isTypeAny(rightType) || + getSignaturesOfType(rightType, 0 /* Call */).length || + getSignaturesOfType(rightType, 1 /* Construct */).length || + isTypeSubtypeOf(rightType, globalFunctionType))) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); + } + return booleanType; + } + function checkInExpression(left, right, leftType, rightType) { + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + // TypeScript 1.0 spec (April 2014): 4.15.5 + // 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, 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 */)) { + error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + return booleanType; + } + function checkObjectLiteralAssignment(node, sourceType) { + var properties = node.properties; + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var p = properties_6[_i]; + checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); + } + return sourceType; + } + /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ + function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { + if (property.kind === 261 /* PropertyAssignment */ || property.kind === 262 /* ShorthandPropertyAssignment */) { + var name = property.name; + if (name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(name); + } + if (isComputedNonLiteralName(name)) { + return undefined; + } + var text = ts.getTextOfPropertyName(name); + var type = isTypeAny(objectLiteralType) + ? objectLiteralType + : getTypeOfPropertyOfType(objectLiteralType, text) || + isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || + getIndexTypeOfType(objectLiteralType, 0 /* String */); + if (type) { + if (property.kind === 262 /* ShorthandPropertyAssignment */) { + return checkDestructuringAssignment(property, type); + } + else { + // non-shorthand property assignments should always have initializers + return checkDestructuringAssignment(property.initializer, type); + } + } + else { + error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + } + } + else if (property.kind === 263 /* SpreadAssignment */) { + if (languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(property, 4 /* Rest */); + } + var nonRestNames = []; + if (allProperties) { + for (var i = 0; i < allProperties.length - 1; i++) { + nonRestNames.push(allProperties[i].name); + } + } + var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + return checkDestructuringAssignment(property.expression, type); + } + else { + error(property, ts.Diagnostics.Property_assignment_expected); + } + } + function checkArrayLiteralAssignment(node, sourceType, checkMode) { + if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + // This elementType will be used if the specific property corresponding to this index is not + // present (aka the tuple element property). This call also checks that the parentType is in + // fact an iterable or array (depending on target language). + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; + var elements = node.elements; + for (var i = 0; i < elements.length; i++) { + checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); + } + return sourceType; + } + function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { + var elements = node.elements; + var element = elements[elementIndex]; + if (element.kind !== 200 /* OmittedExpression */) { + if (element.kind !== 198 /* SpreadElement */) { + var propName = "" + elementIndex; + var type = isTypeAny(sourceType) + ? sourceType + : isTupleLikeType(sourceType) + ? getTypeOfPropertyOfType(sourceType, propName) + : elementType; + if (type) { + return checkDestructuringAssignment(element, type, checkMode); + } + else { + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } + else { + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } + } + } + else { + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + else { + var restExpression = element.expression; + if (restExpression.kind === 194 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + else { + return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + } + } + } + } + return undefined; + } + function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { + var target; + if (exprOrAssignment.kind === 262 /* ShorthandPropertyAssignment */) { + var prop = exprOrAssignment; + if (prop.objectAssignmentInitializer) { + // In strict null checking mode, if a default value of a non-undefined type is specified, remove + // undefined from the final type. + if (strictNullChecks && + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { + sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); + } + checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); + } + target = exprOrAssignment.name; + } + else { + target = exprOrAssignment; + } + if (target.kind === 194 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + checkBinaryExpression(target, checkMode); + target = target.left; + } + if (target.kind === 178 /* ObjectLiteralExpression */) { + return checkObjectLiteralAssignment(target, sourceType); + } + if (target.kind === 177 /* ArrayLiteralExpression */) { + return checkArrayLiteralAssignment(target, sourceType, checkMode); + } + return checkReferenceAssignment(target, sourceType, checkMode); + } + function checkReferenceAssignment(target, sourceType, checkMode) { + var targetType = checkExpression(target, checkMode); + var error = target.parent.kind === 263 /* SpreadAssignment */ ? + ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : + ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; + if (checkReferenceExpression(target, error)) { + checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); + } + return sourceType; + } + /** + * This is a *shallow* check: An expression is side-effect-free if the + * evaluation of the expression *itself* cannot produce side effects. + * For example, x++ / 3 is side-effect free because the / operator + * does not have side effects. + * The intent is to "smell test" an expression for correctness in positions where + * its value is discarded (e.g. the left side of the comma operator). + */ + function isSideEffectFree(node) { + node = ts.skipParentheses(node); + switch (node.kind) { + case 71 /* Identifier */: + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 183 /* TaggedTemplateExpression */: + case 196 /* TemplateExpression */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 139 /* UndefinedKeyword */: + case 186 /* FunctionExpression */: + case 199 /* ClassExpression */: + case 187 /* ArrowFunction */: + case 177 /* ArrayLiteralExpression */: + case 178 /* ObjectLiteralExpression */: + case 189 /* TypeOfExpression */: + case 203 /* NonNullExpression */: + case 250 /* JsxSelfClosingElement */: + case 249 /* JsxElement */: + return true; + case 195 /* ConditionalExpression */: + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); + case 194 /* BinaryExpression */: + if (ts.isAssignmentOperator(node.operatorToken.kind)) { + return false; + } + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); + case 192 /* PrefixUnaryExpression */: + case 193 /* PostfixUnaryExpression */: + // Unary operators ~, !, +, and - have no side effects. + // The rest do. + switch (node.operator) { + case 51 /* ExclamationToken */: + case 37 /* PlusToken */: + case 38 /* MinusToken */: + case 52 /* TildeToken */: + return true; + } + return false; + // Some forms listed here for clarity + case 190 /* VoidExpression */: // Explicit opt-out + case 184 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 202 /* AsExpression */: // Not SEF, but can produce useful type warnings + default: + return false; + } + } + function isTypeEqualityComparableTo(source, target) { + return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + } + function getBestChoiceType(type1, type2) { + var firstAssignableToSecond = isTypeAssignableTo(type1, type2); + var secondAssignableToFirst = isTypeAssignableTo(type2, type1); + return secondAssignableToFirst && !firstAssignableToSecond ? type1 : + firstAssignableToSecond && !secondAssignableToFirst ? type2 : + getUnionType([type1, type2], /*subtypeReduction*/ true); + } + function checkBinaryExpression(node, checkMode) { + return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); + } + function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { + var operator = operatorToken.kind; + if (operator === 58 /* EqualsToken */ && (left.kind === 178 /* ObjectLiteralExpression */ || left.kind === 177 /* ArrayLiteralExpression */)) { + return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); + } + var leftType = checkExpression(left, checkMode); + var rightType = checkExpression(right, checkMode); + switch (operator) { + case 39 /* AsteriskToken */: + case 40 /* AsteriskAsteriskToken */: + case 61 /* AsteriskEqualsToken */: + case 62 /* AsteriskAsteriskEqualsToken */: + case 41 /* SlashToken */: + case 63 /* SlashEqualsToken */: + case 42 /* PercentToken */: + case 64 /* PercentEqualsToken */: + case 38 /* MinusToken */: + case 60 /* MinusEqualsToken */: + case 45 /* LessThanLessThanToken */: + case 65 /* LessThanLessThanEqualsToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 66 /* GreaterThanGreaterThanEqualsToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + case 49 /* BarToken */: + case 69 /* BarEqualsToken */: + case 50 /* CaretToken */: + case 70 /* CaretEqualsToken */: + case 48 /* AmpersandToken */: + case 68 /* AmpersandEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + var suggestedOperator = void 0; + // if a user tries to apply a bitwise operator to 2 boolean operands + // try and return them a helpful suggestion + if ((leftType.flags & 136 /* BooleanLike */) && + (rightType.flags & 136 /* BooleanLike */) && + (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { + error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); + } + else { + // otherwise just check each operand separately and report errors as normal + var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + if (leftOk && rightOk) { + checkAssignmentOperator(numberType); + } + } + return numberType; + case 37 /* PlusToken */: + case 59 /* PlusEqualsToken */: + if (leftType === silentNeverType || rightType === silentNeverType) { + return silentNeverType; + } + if (!isTypeOfKind(leftType, 1 /* Any */ | 262178 /* StringLike */) && !isTypeOfKind(rightType, 1 /* Any */ | 262178 /* StringLike */)) { + leftType = checkNonNullType(leftType, left); + rightType = checkNonNullType(rightType, right); + } + var resultType = void 0; + 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; + } + else { + if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { + // If one or both operands are of the String primitive type, the result is of the String primitive type. + resultType = stringType; + } + else if (isTypeAny(leftType) || isTypeAny(rightType)) { + // Otherwise, the result is of type Any. + // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. + resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; + } + // Symbols are not allowed at all in arithmetic expressions + if (resultType && !checkForDisallowedESSymbolOperand(operator)) { + return resultType; + } + } + if (!resultType) { + reportOperatorError(); + return anyType; + } + if (operator === 59 /* PlusEqualsToken */) { + checkAssignmentOperator(resultType); + } + return resultType; + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + if (checkForDisallowedESSymbolOperand(operator)) { + leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); + rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); + if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { + reportOperatorError(); + } + } + return booleanType; + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + var leftIsLiteral = isLiteralType(leftType); + var rightIsLiteral = isLiteralType(rightType); + if (!leftIsLiteral || !rightIsLiteral) { + leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; + rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; + } + if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { + reportOperatorError(); + } + return booleanType; + case 93 /* InstanceOfKeyword */: + return checkInstanceOfExpression(left, right, leftType, rightType); + case 92 /* InKeyword */: + return checkInExpression(left, right, leftType, rightType); + case 53 /* AmpersandAmpersandToken */: + return getTypeFacts(leftType) & 1048576 /* Truthy */ ? + getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : + leftType; + case 54 /* BarBarToken */: + return getTypeFacts(leftType) & 2097152 /* Falsy */ ? + getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : + leftType; + case 58 /* EqualsToken */: + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + case 26 /* CommaToken */: + if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { + error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + } + return rightType; + } + function isEvalNode(node) { + return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; + } + // Return true if there was no error, false if there was an error. + function checkForDisallowedESSymbolOperand(operator) { + var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : + maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : + undefined; + if (offendingSymbolOperand) { + error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); + return false; + } + return true; + } + function getSuggestedBooleanOperator(operator) { + switch (operator) { + case 49 /* BarToken */: + case 69 /* BarEqualsToken */: + return 54 /* BarBarToken */; + case 50 /* CaretToken */: + case 70 /* CaretEqualsToken */: + return 35 /* ExclamationEqualsEqualsToken */; + case 48 /* AmpersandToken */: + case 68 /* AmpersandEqualsToken */: + return 53 /* AmpersandAmpersandToken */; + default: + return undefined; + } + } + function checkAssignmentOperator(valueType) { + if (produceDiagnostics && ts.isAssignmentOperator(operator)) { + // TypeScript 1.0 spec (April 2014): 4.17 + // An assignment of the form + // VarExpr = ValueExpr + // requires VarExpr to be classified as a reference + // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) + // and the type of the non - compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { + // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported + checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); + } + } + } + function reportOperatorError() { + error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + } + } + function isYieldExpressionInClass(node) { + var current = node; + var parent = node.parent; + while (parent) { + if (ts.isFunctionLike(parent) && current === parent.body) { + return false; + } + else if (ts.isClassLike(current)) { + return true; + } + current = parent; + parent = parent.parent; + } + return false; + } + function checkYieldExpression(node) { + // Grammar checking + if (produceDiagnostics) { + if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); + } + if (isInParameterInitializerBeforeContainingFunction(node)) { + error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); + } + } + if (node.expression) { + var func = ts.getContainingFunction(node); + // If the user's code is syntactically correct, the func should always have a star. After all, + // we are in a yield context. + var functionFlags = func && ts.getFunctionFlags(func); + if (node.asteriskToken) { + // 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 */); + } + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 256 /* Values */); + } + } + if (functionFlags & 1 /* Generator */) { + var expressionType = checkExpressionCached(node.expression); + var expressionElementType = void 0; + var nodeIsYieldStar = !!node.asteriskToken; + if (nodeIsYieldStar) { + expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); + } + // There is no point in doing an assignability check if the function + // has no explicit return type because the return type is directly computed + // from the yield expressions. + var returnType = ts.getEffectiveReturnTypeNode(func); + if (returnType) { + var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), (functionFlags & 2 /* Async */) !== 0) || anyType; + if (nodeIsYieldStar) { + checkTypeAssignableTo(functionFlags & 2 /* Async */ + ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionElementType, signatureElementType, node.expression, + /*headMessage*/ undefined); + } + else { + checkTypeAssignableTo(functionFlags & 2 /* Async */ + ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) + : expressionType, signatureElementType, node.expression, + /*headMessage*/ undefined); + } + } + } + } + // Both yield and yield* expressions have type 'any' + return anyType; + } + function checkConditionalExpression(node, checkMode) { + checkExpression(node.condition); + var type1 = checkExpression(node.whenTrue, checkMode); + var type2 = checkExpression(node.whenFalse, checkMode); + return getBestChoiceType(type1, type2); + } + function checkLiteralExpression(node) { + if (node.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(node); + } + switch (node.kind) { + case 9 /* StringLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(node.text)); + case 8 /* NumericLiteral */: + return getFreshTypeOfLiteralType(getLiteralType(+node.text)); + case 101 /* TrueKeyword */: + return trueType; + case 86 /* FalseKeyword */: + return falseType; + } + } + function checkTemplateExpression(node) { + // We just want to check each expressions, but we are unconcerned with + // the type of each expression, as any value may be coerced into a string. + // It is worth asking whether this is what we really want though. + // A place where we actually *are* concerned with the expressions' types are + // in tagged templates. + ts.forEach(node.templateSpans, function (templateSpan) { + checkExpression(templateSpan.expression); + }); + return stringType; + } + function checkExpressionWithContextualType(node, contextualType, contextualMapper) { + var saveContextualType = node.contextualType; + var saveContextualMapper = node.contextualMapper; + node.contextualType = contextualType; + node.contextualMapper = contextualMapper; + var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : + contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; + var result = checkExpression(node, checkMode); + node.contextualType = saveContextualType; + node.contextualMapper = saveContextualMapper; + return result; + } + function checkExpressionCached(node, checkMode) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + // When computing a type that we're going to cache, we need to ignore any ongoing control flow + // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart + // to the top of the stack ensures all transient types are computed from a known point. + var saveFlowLoopStart = flowLoopStart; + flowLoopStart = flowLoopCount; + links.resolvedType = checkExpression(node, checkMode); + flowLoopStart = saveFlowLoopStart; + } + return links.resolvedType; + } + function isTypeAssertion(node) { + node = ts.skipParentheses(node); + return node.kind === 184 /* TypeAssertionExpression */ || node.kind === 202 /* AsExpression */; + } + function checkDeclarationInitializer(declaration) { + var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); + return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || + isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); + } + function isLiteralContextualType(contextualType) { + if (contextualType) { + if (contextualType.flags & 540672 /* TypeVariable */) { + var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; + // If the type parameter is constrained to the base primitive type we're checking for, + // consider this a literal context. For example, given a type parameter 'T extends string', + // this causes us to infer string literal types for T. + if (constraint.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { + return true; + } + contextualType = constraint; + } + return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); + } + return false; + } + function checkExpressionForMutableLocation(node, checkMode) { + var type = checkExpression(node, checkMode); + return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); + } + function checkPropertyAssignment(node, checkMode) { + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + return checkExpressionForMutableLocation(node.initializer, checkMode); + } + function checkObjectLiteralMethod(node, checkMode) { + // Grammar checking + checkGrammarMethod(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { + if (checkMode === 2 /* Inferential */) { + var signature = getSingleCallSignature(type); + if (signature && signature.typeParameters) { + var contextualType = getApparentTypeOfContextualType(node); + if (contextualType) { + var contextualSignature = getSingleCallSignature(getNonNullableType(contextualType)); + if (contextualSignature && !contextualSignature.typeParameters) { + return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); + } + } + } + } + return type; + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * A cache argument of true indicates that if the function performs a full type check, it is ok + * to cache the result. + */ + function getTypeOfExpression(node, cache) { + // Optimize for the common case of a call to a function with a single non-generic call + // signature where we can just fetch the return type without checking the arguments. + if (node.kind === 181 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + var funcType = checkNonNullExpression(node.expression); + var signature = getSingleCallSignature(funcType); + if (signature && !signature.typeParameters) { + return getReturnTypeOfSignature(signature); + } + } + // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions + // should have a parameter that indicates whether full error checking is required such that + // we can perform the optimizations locally. + return cache ? checkExpressionCached(node) : checkExpression(node); + } + /** + * Returns the type of an expression. Unlike checkExpression, this function is simply concerned + * with computing the type and may not fully check all contained sub-expressions for errors. + * It is intended for uses where you know there is no contextual type, + * and requesting the contextual type might cause a circularity or other bad behaviour. + * It sets the contextual type of the node to any before calling getTypeOfExpression. + */ + function getContextFreeTypeOfExpression(node) { + var saveContextualType = node.contextualType; + node.contextualType = anyType; + var type = getTypeOfExpression(node); + node.contextualType = saveContextualType; + return type; + } + // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When + // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the + // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in + // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function + // object, it serves as an indicator that all contained function and arrow expressions should be considered to + // have the wildcard function type; this form of type check is used during overload resolution to exclude + // contextually typed function and arrow expressions in the initial phase. + function checkExpression(node, checkMode) { + var type; + if (node.kind === 143 /* QualifiedName */) { + type = checkQualifiedName(node); + } + else { + var uninstantiatedType = checkExpressionWorker(node, checkMode); + type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); + } + if (isConstEnumObjectType(type)) { + // enum object type for const enums are only permitted in: + // - 'left' in property access + // - 'object' in indexed access + // - target in rhs of import statement + var ok = (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + if (!ok) { + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + } + } + return type; + } + function checkParenthesizedExpression(node, checkMode) { + if (ts.isInJavaScriptFile(node) && node.jsDoc) { + var typecasts = ts.flatMap(node.jsDoc, function (doc) { return ts.filter(doc.tags, function (tag) { return tag.kind === 281 /* JSDocTypeTag */; }); }); + if (typecasts && typecasts.length) { + // We should have already issued an error if there were multiple type jsdocs + var cast_1 = typecasts[0]; + return checkAssertionWorker(cast_1, cast_1.typeExpression.type, node.expression, checkMode); + } + } + return checkExpression(node.expression, checkMode); + } + function checkExpressionWorker(node, checkMode) { + switch (node.kind) { + case 71 /* Identifier */: + return checkIdentifier(node); + case 99 /* ThisKeyword */: + return checkThisExpression(node); + case 97 /* SuperKeyword */: + return checkSuperExpression(node); + case 95 /* NullKeyword */: + return nullWideningType; + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + return checkLiteralExpression(node); + case 196 /* TemplateExpression */: + return checkTemplateExpression(node); + case 13 /* NoSubstitutionTemplateLiteral */: + return stringType; + case 12 /* RegularExpressionLiteral */: + return globalRegExpType; + case 177 /* ArrayLiteralExpression */: + return checkArrayLiteral(node, checkMode); + case 178 /* ObjectLiteralExpression */: + return checkObjectLiteral(node, checkMode); + case 179 /* PropertyAccessExpression */: + return checkPropertyAccessExpression(node); + case 180 /* ElementAccessExpression */: + return checkIndexedAccess(node); + case 181 /* CallExpression */: + if (node.expression.kind === 91 /* ImportKeyword */) { + return checkImportCallExpression(node); + } + /* falls through */ + case 182 /* NewExpression */: + return checkCallExpression(node); + case 183 /* TaggedTemplateExpression */: + return checkTaggedTemplateExpression(node); + case 185 /* ParenthesizedExpression */: + return checkParenthesizedExpression(node, checkMode); + case 199 /* ClassExpression */: + return checkClassExpression(node); + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); + case 189 /* TypeOfExpression */: + return checkTypeOfExpression(node); + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + return checkAssertion(node); + case 203 /* NonNullExpression */: + return checkNonNullAssertion(node); + case 204 /* MetaProperty */: + return checkMetaProperty(node); + case 188 /* DeleteExpression */: + return checkDeleteExpression(node); + case 190 /* VoidExpression */: + return checkVoidExpression(node); + case 191 /* AwaitExpression */: + return checkAwaitExpression(node); + case 192 /* PrefixUnaryExpression */: + return checkPrefixUnaryExpression(node); + case 193 /* PostfixUnaryExpression */: + return checkPostfixUnaryExpression(node); + case 194 /* BinaryExpression */: + return checkBinaryExpression(node, checkMode); + case 195 /* ConditionalExpression */: + return checkConditionalExpression(node, checkMode); + case 198 /* SpreadElement */: + return checkSpreadExpression(node, checkMode); + case 200 /* OmittedExpression */: + return undefinedWideningType; + case 197 /* YieldExpression */: + return checkYieldExpression(node); + case 256 /* JsxExpression */: + return checkJsxExpression(node, checkMode); + case 249 /* JsxElement */: + return checkJsxElement(node); + case 250 /* JsxSelfClosingElement */: + return checkJsxSelfClosingElement(node); + case 254 /* JsxAttributes */: + return checkJsxAttributes(node, checkMode); + case 251 /* JsxOpeningElement */: + ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); + } + return unknownType; + } + // DECLARATION AND STATEMENT TYPE CHECKING + function checkTypeParameter(node) { + // Grammar Checking + if (node.expression) { + grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); + } + checkSourceElement(node.constraint); + checkSourceElement(node.default); + var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); + if (!hasNonCircularBaseConstraint(typeParameter)) { + error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); + } + var constraintType = getConstraintOfTypeParameter(typeParameter); + var defaultType = getDefaultFromTypeParameter(typeParameter); + if (constraintType && defaultType) { + checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); + } + } + function checkParameter(node) { + // Grammar checking + // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the + // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code + // or if its FunctionBody is strict code(11.1.5). + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkVariableLikeDeclaration(node); + var func = ts.getContainingFunction(node); + if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { + func = ts.getContainingFunction(node); + if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { + error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); + } + } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } + if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { + if (ts.indexOf(func.parameters, node) !== 0) { + error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); + } + if (func.kind === 152 /* Constructor */ || func.kind === 156 /* ConstructSignature */ || func.kind === 161 /* ConstructorType */) { + error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); + } + } + // Only check rest parameter type if it's not a binding pattern. Since binding patterns are + // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); + } + } + function getTypePredicateParameterIndex(parameterList, parameter) { + if (parameterList) { + for (var i = 0; i < parameterList.length; i++) { + var param = parameterList[i]; + if (param.name.kind === 71 /* Identifier */ && param.name.escapedText === parameter.escapedText) { + return i; + } + } + } + return -1; + } + function checkTypePredicate(node) { + var parent = getTypePredicateParent(node); + if (!parent) { + // The parent must not be valid. + error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + return; + } + var typePredicate = getSignatureFromDeclaration(parent).typePredicate; + if (!typePredicate) { + return; + } + checkSourceElement(node.type); + var parameterName = node.parameterName; + if (ts.isThisTypePredicate(typePredicate)) { + getTypeFromThisTypeNode(parameterName); + } + else { + if (typePredicate.parameterIndex >= 0) { + if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); + } + else { + var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + /*headMessage*/ undefined, leadingError); + } + } + else if (parameterName) { + var hasReportedError = false; + for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { + var name = _a[_i].name; + if (ts.isBindingPattern(name) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { + hasReportedError = true; + break; + } + } + if (!hasReportedError) { + error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); + } + } + } + } + function getTypePredicateParent(node) { + switch (node.parent.kind) { + case 187 /* ArrowFunction */: + case 155 /* CallSignature */: + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + case 160 /* FunctionType */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + var parent = node.parent; + if (node === parent.type) { + return parent; + } + } + } + function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isOmittedExpression(element)) { + continue; + } + var name = element.name; + if (name.kind === 71 /* Identifier */ && name.escapedText === predicateVariableName) { + error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); + return true; + } + else if (name.kind === 175 /* ArrayBindingPattern */ || name.kind === 174 /* ObjectBindingPattern */) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { + return true; + } + } + } + } + function checkSignatureDeclaration(node) { + // Grammar checking + if (node.kind === 157 /* IndexSignature */) { + checkGrammarIndexSignature(node); + } + else if (node.kind === 160 /* FunctionType */ || node.kind === 228 /* FunctionDeclaration */ || node.kind === 161 /* ConstructorType */ || + node.kind === 155 /* CallSignature */ || node.kind === 152 /* Constructor */ || + node.kind === 156 /* ConstructSignature */) { + checkGrammarFunctionLikeDeclaration(node); + } + var functionFlags = ts.getFunctionFlags(node); + 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 */); + } + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); + } + // 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 */); + } + } + checkTypeParameters(node.typeParameters); + ts.forEach(node.parameters, checkParameter); + // TODO(rbuckton): Should we start checking JSDoc types? + if (node.type) { + checkSourceElement(node.type); + } + if (produceDiagnostics) { + checkCollisionWithArgumentsInGeneratedCode(node); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if (noImplicitAny && !returnTypeNode) { + switch (node.kind) { + case 156 /* ConstructSignature */: + error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + case 155 /* CallSignature */: + error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); + break; + } + } + if (returnTypeNode) { + var functionFlags_1 = ts.getFunctionFlags(node); + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { + var returnType = getTypeFromTypeNode(returnTypeNode); + if (returnType === voidType) { + error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); + } + else { + var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; + var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ + ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function + : createIterableIteratorType(generatorElementType); // Generator function + // Naively, one could check that IterableIterator is assignable to the return type annotation. + // However, that would not catch the error in the following case. + // + // interface BadGenerator extends Iterable, Iterator { } + // function* g(): BadGenerator { } // Iterable and Iterator have different types! + // + checkTypeAssignableTo(iterableIteratorInstantiation, returnType, returnTypeNode); + } + } + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { + checkAsyncFunctionReturnType(node); + } + } + if (noUnusedIdentifiers && !node.body) { + checkUnusedTypeParameters(node); + } + } + } + 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.createUnderscoreEscapedMap(); + var staticNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 152 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var param = _c[_b]; + if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, 3 /* Property */); + } + } + } + else { + var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + var names = isStatic ? staticNames : instanceNames; + var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); + if (memberName) { + switch (member.kind) { + case 153 /* GetAccessor */: + addName(names, member.name, memberName, 1 /* Getter */); + break; + case 154 /* SetAccessor */: + addName(names, member.name, memberName, 2 /* Setter */); + break; + case 149 /* PropertyDeclaration */: + addName(names, member.name, memberName, 3 /* Property */); + break; + case 151 /* MethodDeclaration */: + addName(names, member.name, memberName, 4 /* Method */); + break; + } + } + } + } + function addName(names, location, name, meaning) { + var prev = names.get(name); + if (prev) { + if (prev & 4 /* Method */) { + if (meaning !== 4 /* Method */) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + } + else if (prev & meaning) { + error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); + } + else { + names.set(name, prev | meaning); + } + } + else { + names.set(name, meaning); + } + } + } + /** + * Static members being set on a constructor function may conflict with built-in properties + * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable + * built-in properties. This check issues a transpile error when a class has a static + * member with the same name as a non-writable built-in property. + * + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 + * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor + * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances + */ + function checkClassForStaticPropertyNameConflicts(node) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var memberNameNode = member.name; + var isStatic = ts.getModifierFlags(member) & 32 /* Static */; + if (isStatic && memberNameNode) { + var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); + switch (memberName) { + case "name": + case "length": + case "caller": + case "arguments": + case "prototype": + var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; + var className = getNameOfSymbol(getSymbolOfNode(node)); + error(memberNameNode, message, memberName, className); + break; + } + } + } + } + function checkObjectTypeForDuplicateDeclarations(node) { + var names = ts.createMap(); + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 148 /* PropertySignature */) { + var memberName = void 0; + switch (member.name.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + memberName = member.name.text; + break; + case 71 /* Identifier */: + memberName = ts.unescapeLeadingUnderscores(member.name.escapedText); + break; + default: + continue; + } + if (names.get(memberName)) { + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); + error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + } + else { + names.set(memberName, true); + } + } + } + } + function checkTypeForDuplicateIndexSignatures(node) { + if (node.kind === 230 /* InterfaceDeclaration */) { + var nodeSymbol = getSymbolOfNode(node); + // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration + // to prevent this run check only for the first declaration of a given kind + if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { + return; + } + } + // TypeScript 1.0 spec (April 2014) + // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. + // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration + var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + if (indexSymbol) { + var seenNumericIndexer = false; + var seenStringIndexer = false; + for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var declaration = decl; + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + switch (declaration.parameters[0].type.kind) { + case 136 /* StringKeyword */: + if (!seenStringIndexer) { + seenStringIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_string_index_signature); + } + break; + case 133 /* NumberKeyword */: + if (!seenNumericIndexer) { + seenNumericIndexer = true; + } + else { + error(declaration, ts.Diagnostics.Duplicate_number_index_signature); + } + break; + } + } + } + } + } + function checkPropertyDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); + checkVariableLikeDeclaration(node); + } + function checkMethodDeclaration(node) { + // Grammar checking + checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); + // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration + checkFunctionOrMethodDeclaration(node); + // Abstract methods cannot have an implementation. + // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. + if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { + error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); + } + } + function checkConstructorDeclaration(node) { + // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. + checkSignatureDeclaration(node); + // Grammar check for checking only related to constructorDeclaration + checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + var symbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(symbol); + } + // exit early in the case of signature - super checks are not relevant to them + if (ts.nodeIsMissing(node.body)) { + return; + } + if (!produceDiagnostics) { + return; + } + function containsSuperCallAsComputedPropertyName(n) { + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); + } + function containsSuperCall(n) { + if (ts.isSuperCall(n)) { + return true; + } + else if (ts.isFunctionLike(n)) { + return false; + } + else if (ts.isClassLike(n)) { + return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); + } + return ts.forEachChild(n, containsSuperCall); + } + function markThisReferencesAsErrors(n) { + if (n.kind === 99 /* ThisKeyword */) { + error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); + } + else if (n.kind !== 186 /* FunctionExpression */ && n.kind !== 228 /* FunctionDeclaration */) { + ts.forEachChild(n, markThisReferencesAsErrors); + } + } + function isInstancePropertyWithInitializer(n) { + return n.kind === 149 /* PropertyDeclaration */ && + !(ts.getModifierFlags(n) & 32 /* Static */) && + !!n.initializer; + } + // TS 1.0 spec (April 2014): 8.3.2 + // Constructors of classes with no extends clause may not contain super calls, whereas + // constructors of derived classes must contain at least one super call somewhere in their function body. + var containingClassDecl = node.parent; + if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); + var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); + var superCall = getSuperCallInConstructor(node); + if (superCall) { + if (classExtendsNull) { + error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: + // - The containing class is a derived class. + // - The constructor declares parameter properties + // or the containing class declares instance member variables with initializers. + var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || + ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. + if (superCallShouldBeFirst) { + var statements = node.body.statements; + var superCallStatement = void 0; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; + if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement)) { + break; + } + } + if (!superCallStatement) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } + } + } + else if (!classExtendsNull) { + error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); + } + } + } + function checkAccessorDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking accessors + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + checkDecorators(node); + checkSignatureDeclaration(node); + if (node.kind === 153 /* GetAccessor */) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (!(node.flags & 256 /* HasExplicitReturn */)) { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } + } + } + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + // TypeScript 1.0 spec (April 2014): 8.4.3 + // Accessors for the same member name must specify the same accessibility. + var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); + if (otherAccessor) { + if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { + error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); + } + if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { + error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); + } + // TypeScript 1.0 spec (April 2014): 4.5 + // If both accessors include type annotations, the specified types must be identical. + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); + checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); + } + } + var returnType = getTypeOfAccessors(getSymbolOfNode(node)); + if (node.kind === 153 /* GetAccessor */) { + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); + } + } + checkSourceElement(node.body); + registerForUnusedIdentifiersCheck(node); + } + function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { + var firstType = getAnnotatedType(first); + var secondType = getAnnotatedType(second); + if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { + error(first, message); + } + } + function checkMissingDeclaration(node) { + checkDecorators(node); + } + function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + var typeArguments; + var mapper; + var result = true; + for (var i = 0; i < typeParameters.length; i++) { + var constraint = getConstraintOfTypeParameter(typeParameters[i]); + if (constraint) { + if (!typeArguments) { + typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); + mapper = createTypeMapper(typeParameters, typeArguments); + } + var typeArgument = typeArguments[i]; + result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + } + } + return result; + } + function checkTypeReferenceNode(node) { + checkGrammarTypeArguments(node, node.typeArguments); + if (node.kind === 159 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + var type = getTypeFromTypeReference(node); + if (type !== unknownType) { + if (node.typeArguments) { + // Do type argument local checks only if referenced type is successfully resolved + ts.forEach(node.typeArguments, checkSourceElement); + if (produceDiagnostics) { + var symbol = getNodeLinks(node).resolvedSymbol; + var typeParameters = symbol.flags & 524288 /* TypeAlias */ ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; + checkTypeArgumentConstraints(typeParameters, node.typeArguments); + } + } + 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)); + } + } + } + function checkTypeQuery(node) { + getTypeFromTypeQueryNode(node); + } + function checkTypeLiteral(node) { + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + checkObjectTypeForDuplicateDeclarations(node); + } + } + function checkArrayType(node) { + checkSourceElement(node.elementType); + } + function checkTupleType(node) { + // Grammar checking + var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { + grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + } + ts.forEach(node.elementTypes, checkSourceElement); + } + function checkUnionOrIntersectionType(node) { + ts.forEach(node.types, checkSourceElement); + } + function checkIndexedAccessIndexType(type, accessNode) { + if (!(type.flags & 524288 /* IndexedAccess */)) { + return type; + } + // Check if the index type is assignable to 'keyof T' for the object type. + var objectType = type.objectType; + var indexType = type.indexType; + if (isTypeAssignableTo(indexType, getIndexType(objectType))) { + return type; + } + // 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, 84 /* NumberLike */)) { + var constraint = getBaseConstraintOfType(objectType); + if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { + return type; + } + } + error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); + return type; + } + function checkIndexedAccessType(node) { + checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); + } + function checkMappedType(node) { + checkSourceElement(node.typeParameter); + checkSourceElement(node.type); + var type = getTypeFromMappedTypeNode(node); + var constraintType = getConstraintTypeFromMappedType(type); + checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); + } + function isPrivateWithinAmbient(node) { + return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); + } + function getEffectiveDeclarationFlags(n, flagsToCheck) { + var flags = ts.getCombinedModifierFlags(n); + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. + if (n.parent.kind !== 230 /* InterfaceDeclaration */ && + n.parent.kind !== 229 /* ClassDeclaration */ && + n.parent.kind !== 199 /* ClassExpression */ && + ts.isInAmbientContext(n)) { + if (!(flags & 2 /* Ambient */)) { + // It is nested in an ambient context, which means it is automatically exported + flags |= 1 /* Export */; + } + flags |= 2 /* Ambient */; + } + return flags & flagsToCheck; + } + function checkFunctionOrConstructorSymbol(symbol) { + if (!produceDiagnostics) { + return; + } + function getCanonicalOverload(overloads, implementation) { + // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration + // Error on all deviations from this canonical set of flags + // The caveat is that if some overloads are defined in lib.d.ts, we don't want to + // report the errors on those. To achieve this, we will say that the implementation is + // the canonical signature only if it is in the same container as the first overload + var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; + } + function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { + // Error if some overloads have a flag that is not shared by all overloads. To find the + // deviations, we XOR someOverloadFlags with allOverloadFlags + var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + if (someButNotAllOverloadFlags !== 0) { + var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + ts.forEach(overloads, function (o) { + var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; + if (deviation & 1 /* Export */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } + else if (deviation & 2 /* Ambient */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } + else if (deviation & (8 /* Private */ | 16 /* Protected */)) { + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } + else if (deviation & 128 /* Abstract */) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } + }); + } + } + function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { + if (someHaveQuestionToken !== allHaveQuestionToken) { + var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); + ts.forEach(overloads, function (o) { + var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; + if (deviation) { + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + } + }); + } + } + var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; + var someNodeFlags = 0 /* None */; + var allNodeFlags = flagsToCheck; + var someHaveQuestionToken = false; + var allHaveQuestionToken = true; + var hasOverloads = false; + var bodyDeclaration; + var lastSeenNonAmbientDeclaration; + var previousDeclaration; + var declarations = symbol.declarations; + var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; + function reportImplementationExpectedError(node) { + if (node.name && ts.nodeIsMissing(node.name)) { + return; + } + var seen = false; + var subsequentNode = ts.forEachChild(node.parent, function (c) { + if (seen) { + return c; + } + else { + seen = c === node; + } + }); + // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. + // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. + if (subsequentNode && subsequentNode.pos === node.end) { + if (subsequentNode.kind === node.kind) { + var errorNode_1 = subsequentNode.name || subsequentNode; + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + var subsequentName = subsequentNode.name; + if (node.name && subsequentName && + (ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) || + !ts.isComputedPropertyName(node.name) && !ts.isComputedPropertyName(subsequentName) && ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) { + var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && + (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); + // we can get here in two cases + // 1. mixed static and instance class members + // 2. something with the same name was defined before the set of overloads that prevents them from merging + // here we'll report error only for the first case since for second we should already report error in binder + if (reportError) { + var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + error(errorNode_1, diagnostic); + } + return; + } + else if (ts.nodeIsPresent(subsequentNode.body)) { + error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); + return; + } + } + } + var errorNode = node.name || node; + if (isConstructor) { + error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); + } + else { + // Report different errors regarding non-consecutive blocks of declarations depending on whether + // the node in question is abstract. + if (ts.getModifierFlags(node) & 128 /* Abstract */) { + error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); + } + else { + error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); + } + } + } + var duplicateFunctionDeclaration = false; + var multipleConstructorImplementation = false; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var current = declarations_5[_i]; + var node = current; + var inAmbientContext = ts.isInAmbientContext(node); + var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; + if (inAmbientContextOrInterface) { + // check if declarations are consecutive only if they are non-ambient + // 1. ambient declarations can be interleaved + // i.e. this is legal + // declare function foo(); + // declare function bar(); + // declare function foo(); + // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one + previousDeclaration = undefined; + } + if (node.kind === 228 /* FunctionDeclaration */ || node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */ || node.kind === 152 /* Constructor */) { + var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + someNodeFlags |= currentNodeFlags; + allNodeFlags &= currentNodeFlags; + someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); + allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { + if (isConstructor) { + multipleConstructorImplementation = true; + } + else { + duplicateFunctionDeclaration = true; + } + } + else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { + reportImplementationExpectedError(previousDeclaration); + } + if (ts.nodeIsPresent(node.body)) { + if (!bodyDeclaration) { + bodyDeclaration = node; + } + } + else { + hasOverloads = true; + } + previousDeclaration = node; + if (!inAmbientContextOrInterface) { + lastSeenNonAmbientDeclaration = node; + } + } + } + if (multipleConstructorImplementation) { + ts.forEach(declarations, function (declaration) { + error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); + }); + } + if (duplicateFunctionDeclaration) { + ts.forEach(declarations, function (declaration) { + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); + }); + } + // Abstract methods can't have an implementation -- in particular, they don't need one. + if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && + !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { + reportImplementationExpectedError(lastSeenNonAmbientDeclaration); + } + if (hasOverloads) { + checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); + checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); + if (bodyDeclaration) { + var signatures = getSignaturesOfSymbol(symbol); + var bodySignature = getSignatureFromDeclaration(bodyDeclaration); + 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; + } + } + } + } + } + function checkExportsOnMergedDeclarations(node) { + if (!produceDiagnostics) { + return; + } + // if localSymbol is defined on node then node itself is exported - check is required + var symbol = node.localSymbol; + if (!symbol) { + // local symbol is undefined => this declaration is non-exported. + // however symbol might contain other declarations that are exported + symbol = getSymbolOfNode(node); + if (!symbol.exportSymbol) { + // this is a pure local symbol (all declarations are non-exported) - no need to check anything + return; + } + } + // run the check only for the first declaration in the list + if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { + return; + } + var exportedDeclarationSpaces = 0 /* None */; + var nonExportedDeclarationSpaces = 0 /* None */; + var defaultExportedDeclarationSpaces = 0 /* None */; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var d = _a[_i]; + var declarationSpaces = getDeclarationSpaces(d); + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 1 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } + } + else { + nonExportedDeclarationSpaces |= declarationSpaces; + } + } + // Spaces for anything not declared a 'default export'. + var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { + // declaration spaces for exported and non-exported declarations intersect + 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); + } + } + } + var DeclarationSpaces; + (function (DeclarationSpaces) { + DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None"; + DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue"; + DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; + DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; + })(DeclarationSpaces || (DeclarationSpaces = {})); + function getDeclarationSpaces(d) { + switch (d.kind) { + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + return 2 /* ExportType */; + case 233 /* ModuleDeclaration */: + return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ + ? 4 /* ExportNamespace */ | 1 /* ExportValue */ + : 4 /* ExportNamespace */; + case 229 /* ClassDeclaration */: + case 232 /* EnumDeclaration */: + return 2 /* ExportType */ | 1 /* ExportValue */; + case 237 /* ImportEqualsDeclaration */: + var result_3 = 0 /* None */; + var target = resolveAlias(getSymbolOfNode(d)); + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 226 /* VariableDeclaration */: + case 176 /* BindingElement */: + case 228 /* FunctionDeclaration */: + case 242 /* ImportSpecifier */:// https://github.com/Microsoft/TypeScript/pull/7591 + return 1 /* ExportValue */; + default: + ts.Debug.fail(ts.SyntaxKind[d.kind]); + } + } + } + function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { + var promisedType = getPromisedTypeOfPromise(type, errorNode); + return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); + } + /** + * Gets the "promised type" of a promise. + * @param type The type of the promise. + * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. + */ + function getPromisedTypeOfPromise(promise, errorNode) { + // + // { // promise + // then( // thenFunction + // onfulfilled: ( // onfulfilledParameterType + // value: T // valueParameterType + // ) => any + // ): any; + // } + // + if (isTypeAny(promise)) { + return undefined; + } + var typeAsPromise = promise; + if (typeAsPromise.promisedTypeOfPromise) { + return typeAsPromise.promisedTypeOfPromise; + } + if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { + return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; + } + var thenFunction = getTypeOfPropertyOfType(promise, "then"); + if (isTypeAny(thenFunction)) { + return undefined; + } + var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray; + if (thenSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); + } + return undefined; + } + var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); + if (isTypeAny(onfulfilledParameterType)) { + return undefined; + } + var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); + if (onfulfilledParameterSignatures.length === 0) { + if (errorNode) { + error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); + } + return undefined; + } + return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); + } + /** + * Gets the "awaited type" of a type. + * @param type The type to await. + * @remarks The "awaited type" of an expression is its "promised type" if the expression is a + * Promise-like type; otherwise, it is the type of the expression. This is used to reflect + * The runtime behavior of the `await` keyword. + */ + function checkAwaitedType(type, errorNode, diagnosticMessage) { + return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; + } + function getAwaitedType(type, errorNode, diagnosticMessage) { + var typeAsAwaitable = type; + if (typeAsAwaitable.awaitedTypeOfType) { + return typeAsAwaitable.awaitedTypeOfType; + } + if (isTypeAny(type)) { + return typeAsAwaitable.awaitedTypeOfType = type; + } + if (type.flags & 65536 /* Union */) { + var types = void 0; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var constituentType = _a[_i]; + types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); + } + if (!types) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true); + } + var promisedType = getPromisedTypeOfPromise(type); + if (promisedType) { + if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + // Verify that we don't have a bad actor in the form of a promise whose + // promised type is the same as the promise type, or a mutually recursive + // promise. If so, we return undefined as we cannot guess the shape. If this + // were the actual case in the JavaScript, this Promise would never resolve. + // + // An example of a bad actor with a singly-recursive promise type might + // be: + // + // interface BadPromise { + // then( + // onfulfilled: (value: BadPromise) => any, + // onrejected: (error: any) => any): BadPromise; + // } + // The above interface will pass the PromiseLike check, and return a + // promised type of `BadPromise`. Since this is a self reference, we + // don't want to keep recursing ad infinitum. + // + // An example of a bad actor in the form of a mutually-recursive + // promise type might be: + // + // interface BadPromiseA { + // then( + // onfulfilled: (value: BadPromiseB) => any, + // onrejected: (error: any) => any): BadPromiseB; + // } + // + // interface BadPromiseB { + // then( + // onfulfilled: (value: BadPromiseA) => any, + // onrejected: (error: any) => any): BadPromiseA; + // } + // + if (errorNode) { + error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); + } + return undefined; + } + // Keep track of the type we're about to unwrap to avoid bad recursive promise types. + // See the comments above for more information. + awaitedTypeStack.push(type.id); + var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); + awaitedTypeStack.pop(); + if (!awaitedType) { + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = awaitedType; + } + // The type was not a promise, so it could not be unwrapped any further. + // As long as the type does not have a callable "then" property, it is + // safe to return the type; otherwise, an error will be reported in + // the call to getNonThenableType and we will return undefined. + // + // An example of a non-promise "thenable" might be: + // + // await { then(): void {} } + // + // The "thenable" does not match the minimal definition for a promise. When + // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise + // will never settle. We treat this as an error to help flag an early indicator + // of a runtime problem. If the user wants to return this value from an async + // function, they would need to wrap it in some other value. If they want it to + // be treated as a promise, they can cast to . + var thenFunction = getTypeOfPropertyOfType(type, "then"); + if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { + if (errorNode) { + ts.Debug.assert(!!diagnosticMessage); + error(errorNode, diagnosticMessage); + } + return undefined; + } + return typeAsAwaitable.awaitedTypeOfType = type; + } + /** + * Checks the return type of an async function to ensure it is a compatible + * Promise implementation. + * + * This checks that an async function has a valid Promise-compatible return type, + * and returns the *awaited type* of the promise. An async function has a valid + * Promise-compatible return type if the resolved value of the return type has a + * construct signature that takes in an `initializer` function that in turn supplies + * a `resolve` function as one of its arguments and results in an object with a + * callable `then` signature. + * + * @param node The signature to check + */ + function checkAsyncFunctionReturnType(node) { + // As part of our emit for an async function, we will need to emit the entity name of + // the return type annotation as an expression. To meet the necessary runtime semantics + // for __awaiter, we must also check that the type of the declaration (e.g. the static + // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. + // + // An example might be (from lib.es6.d.ts): + // + // interface Promise { ... } + // interface PromiseConstructor { + // new (...): Promise; + // } + // declare var Promise: PromiseConstructor; + // + // When an async function declares a return type annotation of `Promise`, we + // need to get the type of the `Promise` variable declaration above, which would + // be `PromiseConstructor`. + // + // The same case applies to a class: + // + // declare class Promise { + // constructor(...); + // then(...): Promise; + // } + // + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + var returnType = getTypeFromTypeNode(returnTypeNode); + if (languageVersion >= 2 /* ES2015 */) { + if (returnType === unknownType) { + return unknownType; + } + var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); + if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { + // The promise type was not a valid type reference to the global promise type, so we + // report an error and return the unknown type. + error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); + return unknownType; + } + } + else { + // Always mark the type node as referenced if it points to a value + markTypeNodeAsReferenced(returnTypeNode); + if (returnType === unknownType) { + return unknownType; + } + var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); + if (promiseConstructorName === undefined) { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); + return unknownType; + } + var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true); + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; + if (promiseConstructorType === unknownType) { + if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); + } + else { + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + } + return unknownType; + } + var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); + if (globalPromiseConstructorLikeType === emptyObjectType) { + // If we couldn't resolve the global PromiseConstructorLike type we cannot verify + // compatibility with __awaiter. + error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { + return unknownType; + } + // Verify there is no local declaration that could collide with the promise constructor. + var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 107455 /* Value */); + if (collidingSymbol) { + error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.unescapeLeadingUnderscores(rootName.escapedText), ts.entityNameToString(promiseConstructorName)); + return unknownType; + } + } + // Get and return the awaited type of the return type. + return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + } + /** Check a decorator */ + function checkDecorator(node) { + var signature = getResolvedSignature(node); + var returnType = getReturnTypeOfSignature(signature); + if (returnType.flags & 1 /* Any */) { + return; + } + var expectedReturnType; + var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + var errorInfo; + switch (node.parent.kind) { + case 229 /* ClassDeclaration */: + var classSymbol = getSymbolOfNode(node.parent); + var classConstructorType = getTypeOfSymbol(classSymbol); + expectedReturnType = getUnionType([classConstructorType, voidType]); + break; + case 146 /* Parameter */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + break; + case 149 /* PropertyDeclaration */: + expectedReturnType = voidType; + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + break; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + var methodType = getTypeOfNode(node.parent); + var descriptorType = createTypedPropertyDescriptorType(methodType); + expectedReturnType = getUnionType([descriptorType, voidType]); + break; + } + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + } + /** + * If a TypeNode can be resolved to a value symbol imported from an external module, it is + * marked as referenced to prevent import elision. + */ + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); + } + function markEntityNameOrEntityExpressionAsReference(typeName) { + var rootName = typeName && getFirstIdentifier(typeName); + var rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === 71 /* Identifier */ ? 793064 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (rootSymbol + && rootSymbol.flags & 2097152 /* Alias */ + && symbolIsValue(rootSymbol) + && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { + 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.escapedText !== individualEntityName.escapedText) { + return undefined; + } + } + else { + commonEntityName = individualEntityName; + } + } + return commonEntityName; + case 168 /* ParenthesizedType */: + return getEntityNameForDecoratorMetadata(node.type); + case 159 /* TypeReference */: + return node.typeName; + } + } + } + function getParameterTypeNodeForDecoratorCheck(node) { + var typeNode = ts.getEffectiveTypeAnnotationNode(node); + return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode; + } + /** Check the decorators of a node */ + function checkDecorators(node) { + if (!node.decorators) { + return; + } + // skip this check for nodes that cannot have decorators. These should have already had an error reported by + // checkGrammarDecorators. + if (!ts.nodeCanBeDecorated(node)) { + return; + } + if (!compilerOptions.experimentalDecorators) { + error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); + } + var firstDecorator = node.decorators[0]; + checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); + if (node.kind === 146 /* Parameter */) { + checkExternalEmitHelpers(firstDecorator, 32 /* Param */); + } + if (compilerOptions.emitDecoratorMetadata) { + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. + switch (node.kind) { + case 229 /* ClassDeclaration */: + var constructor = ts.getFirstConstructorWithBody(node); + if (constructor) { + for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); + break; + case 149 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); + break; + case 146 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + break; + } + } + ts.forEach(node.decorators, checkDecorator); + } + function checkFunctionDeclaration(node) { + if (produceDiagnostics) { + checkFunctionOrMethodDeclaration(node); + checkGrammarForGenerator(node); + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function checkJSDoc(node) { + if (!ts.isInJavaScriptFile(node)) { + return; + } + ts.forEach(node.jsDoc, checkSourceElement); + } + function checkJSDocComment(node) { + if (node.tags) { + for (var _i = 0, _a = node.tags; _i < _a.length; _i++) { + var tag = _a[_i]; + checkSourceElement(tag); + } + } + } + function checkFunctionOrMethodDeclaration(node) { + checkJSDoc(node); + checkDecorators(node); + checkSignatureDeclaration(node); + var functionFlags = ts.getFunctionFlags(node); + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name && node.name.kind === 144 /* ComputedPropertyName */) { + // This check will account for methods in class/interface declarations, + // as well as accessors in classes/object literals + checkComputedPropertyName(node.name); + } + if (!ts.hasDynamicName(node)) { + // first we want to check the local symbol that contain this declaration + // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol + // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode + var symbol = getSymbolOfNode(node); + var localSymbol = node.localSymbol || symbol; + // Since the javascript won't do semantic analysis like typescript, + // if the javascript file comes before the typescript file and both contain same name functions, + // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. + var firstDeclaration = ts.find(localSymbol.declarations, + // Get first non javascript function declaration + function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)); }); + // Only type check the symbol once + if (node === firstDeclaration) { + checkFunctionOrConstructorSymbol(localSymbol); + } + if (symbol.parent) { + // run check once for the first declaration + if (ts.getDeclarationOfKind(symbol, node.kind) === node) { + // run check on export symbol to check that modifiers agree across all exported declarations + checkFunctionOrConstructorSymbol(symbol); + } + } + } + checkSourceElement(node.body); + var returnTypeNode = ts.getEffectiveReturnTypeNode(node); + if ((functionFlags & 1 /* Generator */) === 0) { + var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ + ? checkAsyncFunctionReturnType(node) // Async function + : getTypeFromTypeNode(returnTypeNode)); // normal function + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); + } + if (produceDiagnostics && !returnTypeNode) { + // Report an implicit any error if there is no body, no explicit return type, and node is not a private method + // in an ambient context + if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { + reportImplicitAnyError(node, anyType); + } + if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(node.body)) { + // A generator with a body and no type annotation can still cause errors. It can error if the + // yielded values have no common supertype, or it can give an implicit any error if it has no + // yielded values. The only way to trigger these errors is to try checking its return type. + getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } + } + registerForUnusedIdentifiersCheck(node); + } + function registerForUnusedIdentifiersCheck(node) { + if (deferredUnusedIdentifierNodes) { + deferredUnusedIdentifierNodes.push(node); + } + } + function checkUnusedIdentifiers() { + if (deferredUnusedIdentifierNodes) { + for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { + var node = deferredUnusedIdentifierNodes_1[_i]; + switch (node.kind) { + case 265 /* SourceFile */: + case 233 /* ModuleDeclaration */: + checkUnusedModuleMembers(node); + break; + case 229 /* ClassDeclaration */: + case 199 /* ClassExpression */: + checkUnusedClassMembers(node); + checkUnusedTypeParameters(node); + break; + case 230 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node); + break; + case 207 /* Block */: + case 235 /* CaseBlock */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node); + break; + case 152 /* Constructor */: + case 186 /* FunctionExpression */: + case 228 /* FunctionDeclaration */: + case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + if (node.body) { + checkUnusedLocalsAndParameters(node); + } + checkUnusedTypeParameters(node); + break; + case 150 /* MethodSignature */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + case 157 /* IndexSignature */: + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + checkUnusedTypeParameters(node); + break; + case 231 /* TypeAliasDeclaration */: + checkUnusedTypeParameters(node); + break; + } + } + } + } + function checkUnusedLocalsAndParameters(node) { + if (node.parent.kind !== 230 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + 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(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + else if (compilerOptions.noUnusedLocals) { + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, ts.unescapeLeadingUnderscores(local.escapedName)); }); + } + } + }); + } + } + function isRemovedPropertyFromObjectSpread(node) { + if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { + var lastElement = ts.lastOrUndefined(node.parent.elements); + return lastElement !== node && !!lastElement.dotDotDotToken; + } + return false; + } + function errorUnusedLocal(node, name) { + if (isIdentifierThatStartsWithUnderScore(node)) { + var declaration = ts.getRootDeclaration(node.parent); + if (declaration.kind === 226 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration.parent.parent)) { + return; + } + } + if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { + error(node, ts.Diagnostics._0_is_declared_but_never_used, name); + } + } + function parameterNameStartsWithUnderscore(parameterName) { + return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); + } + function isIdentifierThatStartsWithUnderScore(node) { + return node.kind === 71 /* Identifier */ && ts.unescapeLeadingUnderscores(node.escapedText).charCodeAt(0) === 95 /* _ */; + } + function checkUnusedClassMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.members) { + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { + if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { + error(member.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(member.symbol.escapedName)); + } + } + else if (member.kind === 152 /* Constructor */) { + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(parameter.symbol.escapedName)); + } + } + } + } + } + } + } + function checkUnusedTypeParameters(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + if (node.typeParameters) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + var symbol = getSymbolOfNode(node); + var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); + if (lastDeclaration !== node) { + return; + } + for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { + var typeParameter = _a[_i]; + if (!getMergedSymbol(typeParameter.symbol).isReferenced) { + error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, ts.unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); + } + } + } + } + } + function checkUnusedModuleMembers(node) { + if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { + node.locals.forEach(function (local) { + if (!local.isReferenced && !local.exportSymbol) { + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (!ts.isAmbientModule(declaration)) { + errorUnusedLocal(ts.getNameOfDeclaration(declaration), ts.unescapeLeadingUnderscores(local.escapedName)); + } + } + } + }); + } + } + function checkBlock(node) { + // Grammar checking for SyntaxKind.Block + if (node.kind === 207 /* Block */) { + checkGrammarStatementInAmbientContext(node); + } + ts.forEach(node.statements, checkSourceElement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkCollisionWithArgumentsInGeneratedCode(node) { + // no rest parameters \ declaration context \ overload - no codegen impact + if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { + return; + } + ts.forEach(node.parameters, function (p) { + if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { + error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); + } + }); + } + function needCollisionCheckForIdentifier(node, identifier, name) { + if (!(identifier && identifier.escapedText === name)) { + return false; + } + if (node.kind === 149 /* PropertyDeclaration */ || + node.kind === 148 /* PropertySignature */ || + node.kind === 151 /* MethodDeclaration */ || + node.kind === 150 /* MethodSignature */ || + node.kind === 153 /* GetAccessor */ || + node.kind === 154 /* SetAccessor */) { + // it is ok to have member named '_super' or '_this' - member access is always qualified + return false; + } + if (ts.isInAmbientContext(node)) { + // ambient context - no codegen impact + return false; + } + var root = ts.getRootDeclaration(node); + if (root.kind === 146 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + // just an overload - no codegen impact + return false; + } + return true; + } + function checkCollisionWithCapturedThisVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_this")) { + potentialThisCollisions.push(node); + } + } + function checkCollisionWithCapturedNewTargetVariable(node, name) { + if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { + potentialNewTargetCollisions.push(node); + } + } + // this function will run after checking the source file so 'CaptureThis' is correct for all nodes + function checkIfThisIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { + var isDeclaration_1 = node.kind !== 71 /* Identifier */; + if (isDeclaration_1) { + 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); + } + return true; + } + }); + } + function checkIfNewTargetIsCapturedInEnclosingScope(node) { + ts.findAncestor(node, function (current) { + if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { + var isDeclaration_2 = node.kind !== 71 /* Identifier */; + if (isDeclaration_2) { + 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); + } + return true; + } + }); + } + function checkCollisionWithCapturedSuperVariable(node, name) { + if (!needCollisionCheckForIdentifier(node, name, "_super")) { + return; + } + // bubble up and find containing type + var enclosingClass = ts.getContainingClass(node); + // if containing type was not found or it is ambient - exit (no codegen) + if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { + return; + } + if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { + var isDeclaration_3 = node.kind !== 71 /* Identifier */; + if (isDeclaration_3) { + error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); + } + else { + error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); + } + } + } + function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES2015) { + return; + } + if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + // If the declaration happens to be in external module, report error that require and exports are reserved keywords + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { + if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + return; + } + // Uninstantiated modules shouldnt do this check + if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { + return; + } + // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent + var parent = getDeclarationContainer(node); + if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + // If the declaration happens to be in external module, report error that Promise is a reserved identifier. + error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); + } + } + function checkVarDeclaredNamesNotShadowed(node) { + // - ScriptBody : StatementList + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // - Block : { StatementList } + // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList + // also occurs in the VarDeclaredNames of StatementList. + // Variable declarations are hoisted to the top of their function scope. They can shadow + // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition + // by the binder as the declaration scope is different. + // A non-initialized declaration is a no-op as the block declaration will resolve before the var + // declaration. the problem is if the declaration has an initializer. this will act as a write to the + // block declared value. this is fine for let, but not const. + // Only consider declarations with initializers, uninitialized const declarations will not + // step on a let/const variable. + // Do not consider const and const declarations, as duplicate block-scoped declarations + // are handled by the binder. + // We are only looking for const declarations that step on let\const declarations from a + // different scope. e.g.: + // { + // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration + // const x = 0; // symbol for this declaration will be 'symbol' + // } + // skip block-scoped variables and parameters + if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + return; + } + // skip variable declarations that don't have initializers + // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern + // so we'll always treat binding elements as initialized + if (node.kind === 226 /* VariableDeclaration */ && !node.initializer) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol.flags & 1 /* FunctionScopedVariable */) { + if (!ts.isIdentifier(node.name)) + throw ts.Debug.fail(); + var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + if (localDeclarationSymbol && + localDeclarationSymbol !== symbol && + localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { + if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 208 /* VariableStatement */ && varDeclList.parent.parent + ? varDeclList.parent.parent + : undefined; + // names of block-scoped and function scoped variables can collide only + // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) + var namesShareScope = container && + (container.kind === 207 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 234 /* ModuleBlock */ || + container.kind === 233 /* ModuleDeclaration */ || + container.kind === 265 /* SourceFile */); + // here we know that function scoped variable is shadowed by block scoped one + // if they are defined in the same scope - binder has already reported redeclaration error + // otherwise if variable has an initializer - show error that initialization will fail + // since LHS will be block scoped name instead of function scoped + if (!namesShareScope) { + var name = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); + } + } + } + } + } + // Check that a parameter initializer contains no references to parameters declared to the right of itself + function checkParameterInitializer(node) { + if (ts.getRootDeclaration(node).kind !== 146 /* Parameter */) { + return; + } + var func = ts.getContainingFunction(node); + visit(node.initializer); + function visit(n) { + if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { + // do not dive in types + // skip declaration names (i.e. in object literal expressions) + return; + } + if (n.kind === 179 /* PropertyAccessExpression */) { + // skip property names in property access expression + return visit(n.expression); + } + else if (n.kind === 71 /* Identifier */) { + // check FunctionLikeDeclaration.locals (stores parameters\function local variable) + // if it contains entry with a specified name + var symbol = resolveName(n, n.escapedText, 107455 /* Value */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { + return; + } + if (symbol.valueDeclaration === node) { + error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); + return; + } + // locals map for function contain both parameters and function locals + // so we need to do a bit of extra work to check if reference is legal + var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (enclosingContainer === func) { + if (symbol.valueDeclaration.kind === 146 /* Parameter */ || + symbol.valueDeclaration.kind === 176 /* BindingElement */) { + // it is ok to reference parameter in initializer if either + // - parameter is located strictly on the left of current parameter declaration + if (symbol.valueDeclaration.pos < node.pos) { + return; + } + // - parameter is wrapped in function-like entity + if (ts.findAncestor(n, function (current) { + if (current === node.initializer) { + return "quit"; + } + return ts.isFunctionLike(current.parent) || + // computed property names/initializers in instance property declaration of class like entities + // are executed in constructor and thus deferred + (current.parent.kind === 149 /* PropertyDeclaration */ && + !(ts.hasModifier(current.parent, 32 /* Static */)) && + ts.isClassLike(current.parent.parent)); + })) { + return; + } + // fall through to report error + } + error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); + } + } + else { + return ts.forEachChild(n, visit); + } + } + } + function convertAutoToAny(type) { + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; + } + // Check variable, parameter, or property declaration + function checkVariableLikeDeclaration(node) { + checkDecorators(node); + checkSourceElement(node.type); + // JSDoc `function(string, string): string` syntax results in parameters with no name + if (!node.name) { + return; + } + // For a computed property, just check the initializer and exit + // Do not use hasDynamicName here, because that returns false for well known symbols. + // We want to perform checkComputedPropertyName for all computed properties, including + // well known symbols. + if (node.name.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.name); + if (node.initializer) { + checkExpressionCached(node.initializer); + } + } + if (node.kind === 176 /* BindingElement */) { + if (node.parent.kind === 174 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 4 /* Rest */); + } + // check computed properties inside property names of binding elements + if (node.propertyName && node.propertyName.kind === 144 /* ComputedPropertyName */) { + checkComputedPropertyName(node.propertyName); + } + // check private/protected variable access + var parent = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent); + var name = node.propertyName || node.name; + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + markPropertyAsReferenced(property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); + } + } + // For a binding pattern, check contained binding elements + if (ts.isBindingPattern(node.name)) { + if (node.name.kind === 175 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + checkExternalEmitHelpers(node, 512 /* Read */); + } + ts.forEach(node.name.elements, checkSourceElement); + } + // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body + if (node.initializer && ts.getRootDeclaration(node).kind === 146 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); + return; + } + // For a binding pattern, validate the initializer and exit + if (ts.isBindingPattern(node.name)) { + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + return; + } + var symbol = getSymbolOfNode(node); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); + if (node === symbol.valueDeclaration) { + // Node is the primary declaration of the symbol, just validate the initializer + // Don't validate for-in initializer as it is already an error + if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); + checkParameterInitializer(node); + } + } + else { + // Node is a secondary declaration, check that type is identical to primary declaration and check that + // initializer is consistent with type associated with the node + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); + if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { + error(node.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(node.name), typeToString(type), typeToString(declarationType)); + } + if (node.initializer) { + checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); + } + if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { + 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)); + } + } + if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */) { + // We know we don't have a binding pattern or computed name here + checkExportsOnMergedDeclarations(node); + if (node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */) { + checkVarDeclaredNamesNotShadowed(node); + } + checkCollisionWithCapturedSuperVariable(node, node.name); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + } + function areDeclarationFlagsIdentical(left, right) { + if ((left.kind === 146 /* Parameter */ && right.kind === 226 /* VariableDeclaration */) || + (left.kind === 226 /* VariableDeclaration */ && right.kind === 146 /* Parameter */)) { + // Differences in optionality between parameters and variables are allowed. + return true; + } + if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { + return false; + } + var interestingFlags = 8 /* Private */ | + 16 /* Protected */ | + 256 /* Async */ | + 128 /* Abstract */ | + 64 /* Readonly */ | + 32 /* Static */; + return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); + } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } + function checkVariableStatement(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { + // We only disallow modifier on a method declaration if it is a property of object-literal-expression + if (node.modifiers && node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (ts.getFunctionFlags(node) & 2 /* Async */) { + if (node.modifiers.length > 1) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function checkExpressionStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + } + function checkIfStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 209 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } + checkSourceElement(node.elseStatement); + } + function checkDoStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkSourceElement(node.statement); + checkExpression(node.expression); + } + function checkWhileStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkExpression(node.expression); + checkSourceElement(node.statement); + } + function checkForStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind === 227 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 227 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } + if (node.condition) + checkExpression(node.condition); + if (node.incrementor) + checkExpression(node.incrementor); + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForOfStatement(node) { + checkGrammarForInOrForOfStatement(node); + if (node.kind === 216 /* ForOfStatement */) { + if (node.awaitModifier) { + 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 (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } + } + // Check the LHS and RHS + // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS + // via checkRightHandSideOfForOf. + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === 227 /* VariableDeclarationList */) { + checkForInOrForOfVariableDeclaration(node); + } + else { + var varExpr = node.initializer; + var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); + // There may be a destructuring assignment on the left side + if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + // iteratedType may be undefined. In this case, we still want to check the structure of + // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like + // to short circuit the type relation checking as much as possible, so we pass the unknownType. + checkDestructuringAssignment(varExpr, iteratedType || unknownType); + } + else { + var leftType = checkExpression(varExpr); + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); + // iteratedType will be undefined if the rightType was missing properties/signatures + // required to get its iteratedType (like [Symbol.iterator] or next). This may be + // because we accessed properties from anyType, or it may have led to an error inside + // getElementTypeOfIterable. + if (iteratedType) { + checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); + } + } + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInStatement(node) { + // Grammar checking + checkGrammarForInOrForOfStatement(node); + var rightType = checkNonNullExpression(node.expression); + // TypeScript 1.0 spec (April 2014): 5.4 + // In a 'for-in' statement of the form + // for (let VarDecl in Expr) Statement + // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + if (node.initializer.kind === 227 /* VariableDeclarationList */) { + var variable = node.initializer.declarations[0]; + if (variable && ts.isBindingPattern(variable.name)) { + error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + checkForInOrForOfVariableDeclaration(node); + } + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var leftType = checkExpression(varExpr); + if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } + else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + } + else { + // run check only former check succeeded to avoid cascading errors + checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); + } + } + // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved + // in this case error about missing name is already reported - do not report extra one + if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { + error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); + } + checkSourceElement(node.statement); + if (node.locals) { + registerForUnusedIdentifiersCheck(node); + } + } + function checkForInOrForOfVariableDeclaration(iterationStatement) { + var variableDeclarationList = iterationStatement.initializer; + // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); + } + } + function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { + var expressionType = checkNonNullExpression(rhsExpression); + return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); + } + function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables) { + if (isTypeAny(inputType)) { + return inputType; + } + return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, /*checkAssignability*/ true) || anyType; + } + /** + * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment + * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type + * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. + */ + function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + var uplevelIteration = languageVersion >= 2 /* ES2015 */; + var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; + // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 + // or higher, when inside of an async generator or for-await-if, or when + // downlevelIteration is requested. + if (uplevelIteration || downlevelIteration || allowAsyncIterables) { + // We only report errors for an invalid iterable type in ES2015 or higher. + var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); + if (iteratedType || uplevelIteration) { + return iteratedType; + } + } + var arrayType = inputType; + var reportedError = false; + var hasStringConstituent = false; + // If strings are permitted, remove any string-like constituents from the array type. + // This allows us to find other non-string element types from an array unioned with + // a string. + if (allowStringInput) { + if (arrayType.flags & 65536 /* Union */) { + // After we remove all types that are StringLike, we will know if there was a string constituent + // based on whether the result of filter is a new array. + var arrayTypes = inputType.types; + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); + if (filteredTypes !== arrayTypes) { + arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); + } + } + else if (arrayType.flags & 262178 /* StringLike */) { + arrayType = neverType; + } + hasStringConstituent = arrayType !== inputType; + if (hasStringConstituent) { + if (languageVersion < 1 /* ES5 */) { + if (errorNode) { + error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); + reportedError = true; + } + } + // Now that we've removed all the StringLike types, if no constituents remain, then the entire + // arrayOrStringType was a string. + if (arrayType.flags & 8192 /* Never */) { + return stringType; + } + } + } + if (!isArrayLikeType(arrayType)) { + if (errorNode && !reportedError) { + // Which error we report depends on whether we allow strings or if there was a + // string constituent. For example, if the input type is number | string, we + // want to say that number is not an array type. But if the input was just + // number and string input is allowed, we want to say that number is not an + // array type or a string type. + var diagnostic = !allowStringInput || hasStringConstituent + ? downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type + : downlevelIteration + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + error(errorNode, diagnostic, typeToString(arrayType)); + } + return hasStringConstituent ? stringType : undefined; + } + var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); + if (hasStringConstituent && arrayElementType) { + // This is just an optimization for the case where arrayOrStringType is string | string[] + if (arrayElementType.flags & 262178 /* StringLike */) { + return stringType; + } + return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); + } + return arrayElementType; + } + /** + * We want to treat type as an iterable, and get the type it is an iterable of. The iterable + * must have the following structure (annotated with the names of the variables below): + * + * { // iterable + * [Symbol.iterator]: { // iteratorMethod + * (): Iterator + * } + * } + * + * For an async iterable, we expect the following structure: + * + * { // iterable + * [Symbol.asyncIterator]: { // iteratorMethod + * (): AsyncIterator + * } + * } + * + * T is the type we are after. At every level that involves analyzing return types + * of signatures, we union the return types of all the signatures. + * + * Another thing to note is that at any step of this process, we could run into a dead end, + * meaning either the property is missing, or we run into the anyType. If either of these things + * happens, we return undefined to signal that we could not find the iterated type. If a property + * is missing, and the previous step did not result in 'any', then we also give an error if the + * caller requested it. Then the caller can decide what to do in the case where there is no iterated + * type. This is different from returning anyType, because that would signify that we have matched the + * whole pattern and that T (above) is 'any'. + * + * For a **for-of** statement, `yield*` (in a normal generator), spread, array + * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` + * method. + * + * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. + * + * For a **for-await-of** statement or a `yield*` in an async generator we will look for + * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. + */ + function getIteratedTypeOfIterable(type, errorNode, allowAsyncIterables, allowSyncIterables, checkAssignability) { + if (isTypeAny(type)) { + return undefined; + } + return mapType(type, getIteratedType); + function getIteratedType(type) { + var typeAsIterable = type; + if (allowAsyncIterables) { + if (typeAsIterable.iteratedTypeOfAsyncIterable) { + return typeAsIterable.iteratedTypeOfAsyncIterable; + } + // As an optimization, if the type is an instantiation of the global `AsyncIterable` + // or the global `AsyncIterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; + } + } + if (allowSyncIterables) { + if (typeAsIterable.iteratedTypeOfIterable) { + return typeAsIterable.iteratedTypeOfIterable; + } + // As an optimization, if the type is an instantiation of the global `Iterable` or + // `IterableIterator` then just grab its type argument. + if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || + isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { + return typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; + } + } + var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); + var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + if (isTypeAny(methodType)) { + return undefined; + } + var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); + if (!ts.some(signatures)) { + if (errorNode) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); + // only report on the first error + errorNode = undefined; + } + return undefined; + } + var returnType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var iteratedType = getIteratedTypeOfIterator(returnType, errorNode, /*isAsyncIterator*/ !!asyncMethodType); + if (checkAssignability && errorNode && iteratedType) { + // If `checkAssignability` was specified, we were called from + // `checkIteratedTypeOrElementType`. As such, we need to validate that + // the type passed in is actually an Iterable. + checkTypeAssignableTo(type, asyncMethodType + ? createAsyncIterableType(iteratedType) + : createIterableType(iteratedType), errorNode); + } + return asyncMethodType + ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType + : typeAsIterable.iteratedTypeOfIterable = iteratedType; + } + } + /** + * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on + * Iterators instead of Iterables. Here is the structure: + * + * { // iterator + * next: { // nextMethod + * (): { // nextResult + * value: T // nextValue + * } + * } + * } + * + * For an async iterator, we expect the following structure: + * + * { // iterator + * next: { // nextMethod + * (): PromiseLike<{ // nextResult + * value: T // nextValue + * }> + * } + * } + */ + function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { + if (isTypeAny(type)) { + return undefined; + } + var typeAsIterator = type; + if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { + return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; + } + // As an optimization, if the type is an instantiation of the global `Iterator` (for + // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then + // just grab its type argument. + var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; + if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] + : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; + } + // Both async and non-async iterators must have a `next` method. + var nextMethod = getTypeOfPropertyOfType(type, "next"); + if (isTypeAny(nextMethod)) { + return undefined; + } + var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : ts.emptyArray; + if (nextMethodSignatures.length === 0) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.An_async_iterator_must_have_a_next_method + : ts.Diagnostics.An_iterator_must_have_a_next_method); + } + return undefined; + } + var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + if (isTypeAny(nextResult)) { + return undefined; + } + // For an async iterator, we must get the awaited type of the return type. + if (isAsyncIterator) { + nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); + if (isTypeAny(nextResult)) { + return undefined; + } + } + var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); + if (!nextValue) { + if (errorNode) { + error(errorNode, isAsyncIterator + ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property + : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); + } + return undefined; + } + return isAsyncIterator + ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue + : typeAsIterator.iteratedTypeOfIterator = nextValue; + } + /** + * A generator may have a return type of `Iterator`, `Iterable`, or + * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, + * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract + * the iterated type from this return type for contextual typing and verifying signatures. + */ + function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { + if (isTypeAny(returnType)) { + return undefined; + } + return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, /*allowAsyncIterables*/ isAsyncGenerator, /*allowSyncIterables*/ !isAsyncGenerator, /*checkAssignability*/ false) + || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); + } + function checkBreakOrContinueStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); + // TODO: Check that target label is valid + } + function isGetAccessorWithAnnotatedSetAccessor(node) { + return node.kind === 153 /* GetAccessor */ + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */)) !== undefined; + } + function isUnwrappedReturnTypeVoidOrAny(func, returnType) { + 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 */); + } + function checkReturnStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + var functionBlock = ts.getContainingFunction(node); + if (!functionBlock) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); + } + } + var func = ts.getContainingFunction(node); + if (func) { + var signature = getSignatureFromDeclaration(func); + var returnType = getReturnTypeOfSignature(signature); + if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { + var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; + var functionFlags = ts.getFunctionFlags(func); + if (functionFlags & 1 /* Generator */) { + // A generator does not need its return expressions checked against its return type. + // Instead, the yield expressions are checked against the element type. + // TODO: Check return expressions of generators when return type tracking is added + // for generators. + return; + } + if (func.kind === 154 /* SetAccessor */) { + if (node.expression) { + error(node, ts.Diagnostics.Setters_cannot_return_a_value); + } + } + else if (func.kind === 152 /* Constructor */) { + if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); + } + } + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + if (functionFlags & 2 /* Async */) { + var promisedType = getPromisedTypeOfPromise(returnType); + var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); + if (promisedType) { + // If the function has a return type, but promisedType is + // undefined, an error will be reported in checkAsyncFunctionReturnType + // so we don't need to report one here. + checkTypeAssignableTo(awaitedType, promisedType, node); + } + } + else { + checkTypeAssignableTo(exprType, returnType, node); + } + } + } + else if (func.kind !== 152 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { + // The function has a return type, but the return statement doesn't have an expression. + error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + } + function checkWithStatement(node) { + // Grammar checking for withStatement + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.flags & 16384 /* AwaitContext */) { + grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); + } + } + checkExpression(node.expression); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } + } + function checkSwitchStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + var firstDefaultClause; + var hasDuplicateDefaultClause = false; + var expressionType = checkExpression(node.expression); + var expressionIsLiteral = isLiteralType(expressionType); + ts.forEach(node.caseBlock.clauses, function (clause) { + // Grammar check for duplicate default clauses, skip if we already report duplicate default clause + if (clause.kind === 258 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (firstDefaultClause === undefined) { + firstDefaultClause = clause; + } + else { + var sourceFile = ts.getSourceFileOfNode(node); + var start = ts.skipTrivia(sourceFile.text, clause.pos); + var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + hasDuplicateDefaultClause = true; + } + } + if (produceDiagnostics && clause.kind === 257 /* CaseClause */) { + var caseClause = clause; + // TypeScript 1.0 spec (April 2014): 5.9 + // In a 'switch' statement, each 'case' expression must be of a type that is comparable + // to or from the type of the 'switch' expression. + var caseType = checkExpression(caseClause.expression); + var caseIsLiteral = isLiteralType(caseType); + var comparedExpressionType = expressionType; + if (!caseIsLiteral || !expressionIsLiteral) { + caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; + comparedExpressionType = getBaseTypeOfLiteralType(expressionType); + } + if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { + // expressionType is not comparable to caseType, try the reversed check and report errors if it fails + checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); + } + } + ts.forEach(clause.statements, checkSourceElement); + }); + if (node.caseBlock.locals) { + registerForUnusedIdentifiersCheck(node.caseBlock); + } + } + function checkLabeledStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + ts.findAncestor(node.parent, function (current) { + if (ts.isFunctionLike(current)) { + return "quit"; + } + if (current.kind === 222 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + var sourceFile = ts.getSourceFileOfNode(node); + grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); + return true; + } + }); + } + // ensure that label is unique + checkSourceElement(node.statement); + } + function checkThrowStatement(node) { + // Grammar checking + if (!checkGrammarStatementInAmbientContext(node)) { + if (node.expression === undefined) { + grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); + } + } + if (node.expression) { + checkExpression(node.expression); + } + } + function checkTryStatement(node) { + // Grammar checking + checkGrammarStatementInAmbientContext(node); + checkBlock(node.tryBlock); + var catchClause = node.catchClause; + if (catchClause) { + // Grammar checking + if (catchClause.variableDeclaration) { + if (catchClause.variableDeclaration.type) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); + } + else if (catchClause.variableDeclaration.initializer) { + grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); + } + else { + var blockLocals_1 = catchClause.block.locals; + if (blockLocals_1) { + ts.forEachKey(catchClause.locals, function (caughtName) { + var blockLocal = blockLocals_1.get(caughtName); + if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { + grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); + } + }); + } + } + } + checkBlock(catchClause.block); + } + if (node.finallyBlock) { + checkBlock(node.finallyBlock); + } + } + function checkIndexConstraints(type) { + var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); + var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); + var stringIndexType = getIndexTypeOfType(type, 0 /* String */); + var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); + if (stringIndexType || numberIndexType) { + ts.forEach(getPropertiesOfObjectType(type), function (prop) { + var propType = getTypeOfSymbol(prop); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + }); + if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { + var classDeclaration = type.symbol.valueDeclaration; + for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { + var member = _a[_i]; + // Only process instance properties with computed names here. + // Static properties cannot be in conflict with indexers, + // and properties with literal names were already checked. + if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } + } + var errorNode; + if (stringIndexType && numberIndexType) { + errorNode = declaredNumberIndexer || declaredStringIndexer; + // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer + if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { + var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); + errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; + } + } + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); + } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + var propDeclaration = prop.valueDeclaration; + // index is numeric and property name is not valid numeric literal + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + return; + } + // perform property check if property or indexer is declared in 'type' + // this allows us to rule out cases when both property and indexer are inherited from the base class + var errorNode; + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { + errorNode = propDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (getObjectFlags(containingType) & 2 /* Interface */) { + // for interfaces property and indexer might be inherited from different bases + // check if any base class already has both property and indexer. + // check should be performed only if 'type' is the first type that brings property\indexer together + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ + ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 + : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } + } + function checkTypeNameIsReserved(name, message) { + // TS 1.0 spec (April 2014): 3.6.1 + // The predefined type keywords are reserved and cannot be used as names of user defined types. + switch (name.escapedText) { + case "any": + case "number": + case "boolean": + case "string": + case "symbol": + case "void": + case "object": + error(name, message, name.escapedText); + } + } + /** + * Check each type parameter and check that type parameters have no duplicate type parameter declarations + */ + function checkTypeParameters(typeParameterDeclarations) { + if (typeParameterDeclarations) { + var seenDefault = false; + for (var i = 0; i < typeParameterDeclarations.length; i++) { + var node = typeParameterDeclarations[i]; + checkTypeParameter(node); + if (produceDiagnostics) { + if (node.default) { + seenDefault = true; + } + else if (seenDefault) { + error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); + } + for (var j = 0; j < i; j++) { + if (typeParameterDeclarations[j].symbol === node.symbol) { + error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); + } + } + } + } + } + } + /** Check that type parameter lists are identical across multiple declarations */ + function checkTypeParameterListsIdentical(symbol) { + if (symbol.declarations.length === 1) { + return; + } + var links = getSymbolLinks(symbol); + if (!links.typeParametersChecked) { + links.typeParametersChecked = true; + var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); + if (declarations.length <= 1) { + return; + } + var type = getDeclaredTypeOfSymbol(symbol); + if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { + // Report an error on every conflicting declaration. + var name = symbolToString(symbol); + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); + } + } + } + } + function areTypeParametersIdentical(declarations, typeParameters) { + var maxTypeArgumentCount = ts.length(typeParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + // If this declaration has too few or too many type parameters, we report an error + var numTypeParameters = ts.length(declaration.typeParameters); + if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { + return false; + } + for (var i = 0; i < numTypeParameters; i++) { + var source = declaration.typeParameters[i]; + var target = typeParameters[i]; + // If the type parameter node does not have the same as the resolved type + // parameter at this position, we report an error. + if (source.name.escapedText !== target.symbol.escapedName) { + return false; + } + // If the type parameter node does not have an identical constraint as the resolved + // type parameter at this position, we report an error. + var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); + var targetConstraint = getConstraintFromTypeParameter(target); + if ((sourceConstraint || targetConstraint) && + (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { + return false; + } + // If the type parameter node has a default and it is not identical to the default + // for the type parameter at this position, we report an error. + var sourceDefault = source.default && getTypeFromTypeNode(source.default); + var targetDefault = getDefaultFromTypeParameter(target); + if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { + return false; + } + } + } + return true; + } + function checkClassExpression(node) { + checkClassLikeDeclaration(node); + checkNodeDeferred(node); + return getTypeOfSymbol(getSymbolOfNode(node)); + } + function checkClassExpressionDeferred(node) { + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassDeclaration(node) { + if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { + grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); + } + checkClassLikeDeclaration(node); + ts.forEach(node.members, checkSourceElement); + registerForUnusedIdentifiersCheck(node); + } + function checkClassLikeDeclaration(node) { + checkGrammarClassLikeDeclaration(node); + checkDecorators(node); + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkTypeParameters(node.typeParameters); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + var staticType = getTypeOfSymbol(symbol); + checkTypeParameterListsIdentical(symbol); + checkClassForDuplicateDeclarations(node); + // Only check for reserved static identifiers on non-ambient context. + if (!ts.isInAmbientContext(node)) { + checkClassForStaticPropertyNameConflicts(node); + } + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + if (baseTypeNode) { + if (languageVersion < 2 /* ES2015 */) { + checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); + } + var baseTypes = getBaseTypes(type); + if (baseTypes.length && produceDiagnostics) { + var baseType_1 = baseTypes[0]; + var baseConstructorType = getBaseConstructorTypeOfClass(type); + var staticBaseType = getApparentType(baseConstructorType); + checkBaseTypeAccessibility(staticBaseType, baseTypeNode); + checkSourceElement(baseTypeNode.expression); + if (ts.some(baseTypeNode.typeArguments)) { + ts.forEach(baseTypeNode.typeArguments, checkSourceElement); + for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { + var constructor = _a[_i]; + if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { + break; + } + } + } + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); + if (baseConstructorType.flags & 540672 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); + } + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 540672 /* TypeVariable */)) { + // When the static base type is a "class-like" constructor function (but not actually a class), we verify + // that all instantiated base constructor signatures return the same type. We can simply compare the type + // references (as opposed to checking the structure of the types) because elsewhere we have already checked + // that the base type is a class or interface type (and not, for example, an anonymous object type). + var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); + if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { + error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); + } + } + checkKindsOfPropertyMemberOverrides(type, baseType_1); + } + } + var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); + if (implementedTypeNodes) { + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; + if (!ts.isEntityNameExpression(typeRefNode.expression)) { + error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(typeRefNode); + if (produceDiagnostics) { + var t = getTypeFromTypeNode(typeRefNode); + if (t !== unknownType) { + if (isValidBaseType(t)) { + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + } + else { + error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); + } + } + } + } + } + if (produceDiagnostics) { + checkIndexConstraints(type); + checkTypeForDuplicateIndexSignatures(node); + } + } + function checkBaseTypeAccessibility(type, node) { + var signatures = getSignaturesOfType(type, 1 /* Construct */); + if (signatures.length) { + var declaration = signatures[0].declaration; + if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { + var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); + if (!isNodeWithinClass(node, typeClassDeclaration)) { + error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); + } + } + } + } + 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 ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; + } + function getClassLikeDeclarationOfSymbol(symbol) { + return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); + } + function getClassOrInterfaceDeclarationsOfSymbol(symbol) { + return ts.filter(symbol.declarations, function (d) { + return d.kind === 229 /* ClassDeclaration */ || d.kind === 230 /* InterfaceDeclaration */; + }); + } + function checkKindsOfPropertyMemberOverrides(type, baseType) { + // TypeScript 1.0 spec (April 2014): 8.2.3 + // A derived class inherits all members from its base class it doesn't override. + // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. + // Both public and private property members are inherited, but only public property members can be overridden. + // A property member in a derived class is said to override a property member in a base class + // when the derived class property member has the same name and kind(instance or static) + // as the base class property member. + // The type of an overriding property member must be assignable(section 3.8.4) + // to the type of the overridden property member, or otherwise a compile - time error occurs. + // Base class instance member functions can be overridden by derived class instance member functions, + // but not by other kinds of members. + // Base class instance member variables and accessors can be overridden by + // derived class instance member variables and accessors, but not by other kinds of members. + // NOTE: assignability is checked in checkClassDeclaration + var baseProperties = getPropertiesOfType(baseType); + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; + var base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + 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, + // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* + // type declaration, derived and base resolve to the same symbol even in the case of generic classes. + if (derived === base) { + // derived class inherits base without override/redeclaration + var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + // It is an error to inherit an abstract member without implementing it or being declared abstract. + // If there is no declaration for the derived class (as in the case of class expressions), + // then the class cannot be declared abstract. + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { + if (derivedClassDecl.kind === 199 /* ClassExpression */) { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); + } + else { + error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); + } + } + } + else { + // derived overrides base. + 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 (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; + } + var errorMessage = void 0; + if (isMethodLike(base)) { + if (derived.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + } + } + else if (base.flags & 4 /* Property */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + } + else { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } + } + } + } + function checkInheritedPropertiesAreIdentical(type, typeNode) { + var baseTypes = getBaseTypes(type); + if (baseTypes.length < 2) { + return true; + } + var seen = ts.createUnderscoreEscapedMap(); + ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); }); + var ok = true; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; + var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); + for (var _a = 0, properties_7 = properties; _a < properties_7.length; _a++) { + var prop = properties_7[_a]; + var existing = seen.get(prop.escapedName); + if (!existing) { + seen.set(prop.escapedName, { prop: prop, containingType: base }); + } + else { + var isInheritedProperty = existing.containingType !== type; + if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { + ok = false; + var typeName1 = typeToString(existing.containingType); + var typeName2 = typeToString(base); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); + diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); + } + } + } + } + return ok; + } + function checkInterfaceDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); + checkTypeParameters(node.typeParameters); + if (produceDiagnostics) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + checkTypeParameterListsIdentical(symbol); + // Only check this symbol once + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); + if (node === firstInterfaceDecl) { + var type = getDeclaredTypeOfSymbol(symbol); + var typeWithThis = getTypeWithThisArgument(type); + // run subsequent checks only if first set succeeded + if (checkInheritedPropertiesAreIdentical(type, node.name)) { + for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { + var baseType = _a[_i]; + checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); + } + checkIndexConstraints(type); + } + } + checkObjectTypeForDuplicateDeclarations(node); + } + ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { + if (!ts.isEntityNameExpression(heritageElement.expression)) { + error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); + } + checkTypeReferenceNode(heritageElement); + }); + ts.forEach(node.members, checkSourceElement); + if (produceDiagnostics) { + checkTypeForDuplicateIndexSignatures(node); + registerForUnusedIdentifiersCheck(node); + } + } + function checkTypeAliasDeclaration(node) { + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + checkTypeParameters(node.typeParameters); + checkSourceElement(node.type); + registerForUnusedIdentifiersCheck(node); + } + function computeEnumMemberValues(node) { + var nodeLinks = getNodeLinks(node); + if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { + nodeLinks.flags |= 16384 /* EnumValuesComputed */; + var autoValue = 0; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + var value = computeMemberValue(member, autoValue); + getNodeLinks(member).enumMemberValue = value; + autoValue = typeof value === "number" ? value + 1 : undefined; + } + } + } + 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); + } + } + 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; + } + } + 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; + case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; + case 45 /* LessThanLessThanToken */: return left << right; + case 50 /* CaretToken */: return left ^ right; + case 39 /* AsteriskToken */: return left * right; + case 41 /* SlashToken */: return left / right; + case 37 /* PlusToken */: return left + right; + case 38 /* MinusToken */: return left - right; + case 42 /* PercentToken */: return left % right; + } + } + 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.escapedText); + case 180 /* ElementAccessExpression */: + case 179 /* PropertyAccessExpression */: + var ex = expr; + if (isConstantMemberAccess(ex)) { + var type = getTypeOfExpression(ex.expression); + if (type.symbol && type.symbol.flags & 384 /* Enum */) { + var name = void 0; + if (ex.kind === 179 /* PropertyAccessExpression */) { + name = ex.name.escapedText; + } + else { + var argument = ex.argumentExpression; + ts.Debug.assert(ts.isLiteralExpression(argument)); + name = ts.escapeLeadingUnderscores(argument.text); + } + return evaluateEnumMember(expr, type.symbol, name); + } + } + 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; + } + // Grammar checking + checkGrammarDecorators(node) || checkGrammarModifiers(node); + checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithCapturedNewTargetVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkExportsOnMergedDeclarations(node); + computeEnumMemberValues(node); + var enumIsConst = ts.isConst(node); + if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { + error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); + } + // Spec 2014 - Section 9.3: + // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, + // and when an enum type has multiple declarations, only one declaration is permitted to omit a value + // for the first member. + // + // Only perform this check once per symbol + var enumSymbol = getSymbolOfNode(node); + var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); + if (node === firstDeclaration) { + if (enumSymbol.declarations.length > 1) { + // check that const is placed\omitted on all enum declarations + ts.forEach(enumSymbol.declarations, function (decl) { + if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + } + }); + } + var seenEnumMissingInitialInitializer_1 = false; + ts.forEach(enumSymbol.declarations, function (declaration) { + // return true if we hit a violation of the rule, false otherwise + if (declaration.kind !== 232 /* EnumDeclaration */) { + return false; + } + var enumDeclaration = declaration; + if (!enumDeclaration.members.length) { + return false; + } + var firstEnumMember = enumDeclaration.members[0]; + if (!firstEnumMember.initializer) { + if (seenEnumMissingInitialInitializer_1) { + error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); + } + else { + seenEnumMissingInitialInitializer_1 = true; + } + } + }); + } + } + function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { + var declarations = symbol.declarations; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 229 /* ClassDeclaration */ || + (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !ts.isInAmbientContext(declaration)) { + return declaration; + } + } + return undefined; + } + function inSameLexicalScope(node1, node2) { + var container1 = ts.getEnclosingBlockScopeContainer(node1); + var container2 = ts.getEnclosingBlockScopeContainer(node2); + if (isGlobalSourceFile(container1)) { + return isGlobalSourceFile(container2); + } + else if (isGlobalSourceFile(container2)) { + return false; + } + else { + return container1 === container2; + } + } + function checkModuleDeclaration(node) { + if (produceDiagnostics) { + // Grammar checking + var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); + var inAmbientContext = ts.isInAmbientContext(node); + if (isGlobalAugmentation && !inAmbientContext) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); + } + var isAmbientExternalModule = ts.isAmbientModule(node); + var contextErrorMessage = isAmbientExternalModule + ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + if (checkGrammarModuleElementContext(node, contextErrorMessage)) { + // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { + if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + } + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } + checkExportsOnMergedDeclarations(node); + var symbol = getSymbolOfNode(node); + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & 512 /* ValueModule */ + && symbol.declarations.length > 1 + && !inAmbientContext + && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + if (firstNonAmbientClassOrFunc) { + if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); + } + else if (node.pos < firstNonAmbientClassOrFunc.pos) { + error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); + } + } + // if the module merges with a class declaration in the same lexical scope, + // we need to track this to ensure the correct emit. + var mergedClass = ts.getDeclarationOfKind(symbol, 229 /* ClassDeclaration */); + if (mergedClass && + inSameLexicalScope(node, mergedClass)) { + getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; + } + } + if (isAmbientExternalModule) { + if (ts.isExternalModuleAugmentation(node)) { + // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) + // otherwise we'll be swamped in cascading errors. + // We can detect if augmentation was applied using following rules: + // - augmentation for a global scope is always applied + // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */); + if (checkBody && node.body) { + // body of ambient external module is always a module block + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + checkModuleAugmentationElement(statement, isGlobalAugmentation); + } + } + } + else if (isGlobalSourceFile(node.parent)) { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) { + error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); + } + } + else { + if (isGlobalAugmentation) { + error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); + } + else { + // Node is not an augmentation and is not located on the script level. + // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. + error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); + } + } + } + } + if (node.body) { + checkSourceElement(node.body); + if (!ts.isGlobalScopeAugmentation(node)) { + registerForUnusedIdentifiersCheck(node); + } + } + } + function checkModuleAugmentationElement(node, isGlobalAugmentation) { + switch (node.kind) { + case 208 /* VariableStatement */: + // error each individual name in variable statement instead of marking the entire variable statement + for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + checkModuleAugmentationElement(decl, isGlobalAugmentation); + } + break; + case 243 /* ExportAssignment */: + case 244 /* ExportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); + break; + case 237 /* ImportEqualsDeclaration */: + case 238 /* ImportDeclaration */: + grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); + break; + case 176 /* BindingElement */: + case 226 /* VariableDeclaration */: + var name = node.name; + if (ts.isBindingPattern(name)) { + for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { + var el = _c[_b]; + // mark individual names in binding pattern + checkModuleAugmentationElement(el, isGlobalAugmentation); + } + break; + } + // falls through + case 229 /* ClassDeclaration */: + case 232 /* EnumDeclaration */: + case 228 /* FunctionDeclaration */: + case 230 /* InterfaceDeclaration */: + case 233 /* ModuleDeclaration */: + case 231 /* TypeAliasDeclaration */: + if (isGlobalAugmentation) { + return; + } + var symbol = getSymbolOfNode(node); + if (symbol) { + // module augmentations cannot introduce new names on the top level scope of the module + // this is done it two steps + // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error + // 2. main check - report error if value declaration of the parent symbol is module augmentation) + var reportError = !(symbol.flags & 33554432 /* Transient */); + if (!reportError) { + // symbol should not originate in augmentation + reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); + } + } + break; + } + } + function getFirstIdentifier(node) { + switch (node.kind) { + case 71 /* Identifier */: + return node; + case 143 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 71 /* Identifier */); + return node; + case 179 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 71 /* Identifier */); + return node; + } + } + function checkExternalImportOrExportDeclaration(node) { + var moduleName = ts.getExternalModuleName(node); + if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { + error(moduleName, ts.Diagnostics.String_literal_expected); + return false; + } + var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 244 /* ExportDeclaration */ ? + ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : + ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); + return false; + } + if (inAmbientExternalModule && ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(moduleName))) { + // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration + // no need to do this again. + if (!isTopLevelInExternalModuleAugmentation(node)) { + // TypeScript 1.0 spec (April 2013): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference + // other external modules only through top - level external module names. + // Relative external module names are not permitted. + error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); + return false; + } + } + return true; + } + function checkAliasSymbol(node) { + var symbol = getSymbolOfNode(node); + var target = resolveAlias(symbol); + if (target !== unknownSymbol) { + // For external modules symbol represent local symbol for an alias. + // This local symbol will merge any other local declarations (excluding other aliases) + // and symbol.flags will contains combined representation for all merged declaration. + // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, + // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* + // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). + var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | + (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | + (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); + if (target.flags & excludedMeanings) { + var message = node.kind === 246 /* ExportSpecifier */ ? + ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : + 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 (compilerOptions.isolatedModules + && node.kind === 246 /* ExportSpecifier */ + && !(target.flags & 107455 /* Value */) + && !ts.isInAmbientContext(node)) { + error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); + } + } + } + function checkImportBinding(node) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + checkAliasSymbol(node); + } + function checkImportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); + } + if (checkExternalImportOrExportDeclaration(node)) { + var importClause = node.importClause; + if (importClause) { + if (importClause.name) { + checkImportBinding(importClause); + } + if (importClause.namedBindings) { + if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { + checkImportBinding(importClause.namedBindings); + } + else { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } + } + } + } + } + function checkImportEqualsDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. + return; + } + checkGrammarDecorators(node) || checkGrammarModifiers(node); + if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { + checkImportBinding(node); + if (ts.getModifierFlags(node) & 1 /* Export */) { + markExportAsReferenced(node); + } + if (ts.isInternalModuleImportEqualsDeclaration(node)) { + var target = resolveAlias(getSymbolOfNode(node)); + if (target !== unknownSymbol) { + if (target.flags & 107455 /* Value */) { + // Target is a value symbol, check that it is not hidden by a local declaration with the same name + var moduleName = getFirstIdentifier(node.moduleReference); + if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { + error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); + } + } + if (target.flags & 793064 /* Type */) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); + } + } + } + else { + if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { + // Import equals declaration is deprecated in es6 or above + grammarErrorOnNode(node, ts.Diagnostics.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); + } + } + } + } + function checkExportDeclaration(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + // If we hit an export in an illegal context, just bail out to avoid cascading errors. + return; + } + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); + } + if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { + if (node.exportClause) { + // export { x, y } + // export { x, y } from "foo" + ts.forEach(node.exportClause.elements, checkExportSpecifier); + var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 /* ModuleBlock */ && + !node.moduleSpecifier && ts.isInAmbientContext(node); + if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); + } + } + else { + // export * from "foo" + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + } + if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015) { + checkExternalEmitHelpers(node, 32768 /* ExportStar */); + } + } + } + } + function checkGrammarModuleElementContext(node, errorMessage) { + var isInAppropriateContext = node.parent.kind === 265 /* SourceFile */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 233 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); + } + return !isInAppropriateContext; + } + function checkExportSpecifier(node) { + checkAliasSymbol(node); + if (!node.parent.parent.moduleSpecifier) { + var exportedName = node.propertyName || node.name; + // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) + var symbol = resolveName(exportedName, exportedName.escapedText, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.unescapeLeadingUnderscores(exportedName.escapedText)); + } + else { + markExportAsReferenced(node); + } + } + } + function checkExportAssignment(node) { + if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { + // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. + return; + } + var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + if (node.isExportEquals) { + error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); + } + else { + error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + return; + } + // Grammar checking + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { + grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); + } + if (node.expression.kind === 71 /* Identifier */) { + markExportAsReferenced(node); + } + else { + checkExpressionCached(node.expression); + } + checkExternalModuleExports(container); + if (node.isExportEquals && !ts.isInAmbientContext(node)) { + if (modulekind === ts.ModuleKind.ES2015) { + // export assignment is not supported in es6 modules + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); + } + else if (modulekind === ts.ModuleKind.System) { + // system modules does not support export assignment + grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); + } + } + } + function hasExportedMembers(moduleSymbol) { + return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); + } + function checkExternalModuleExports(node) { + var moduleSymbol = getSymbolOfNode(node); + var links = getSymbolLinks(moduleSymbol); + if (!links.exportsChecked) { + var exportEqualsSymbol = moduleSymbol.exports.get("export="); + if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { + var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + if (!isTopLevelInExternalModuleAugmentation(declaration)) { + error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); + } + } + // Checks for export * conflicts + var exports = getExportsOfModule(moduleSymbol); + exports && exports.forEach(function (_a, id) { + var declarations = _a.declarations, flags = _a.flags; + if (id === "__export") { + return; + } + // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. + // (TS Exceptions: namespaces, function overloads, enums, and interfaces) + if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { + return; + } + var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); + if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { + // it is legal to merge type alias with other values + // so count should be either 1 (just type alias) or 2 (type alias + merged value) + return; + } + if (exportedDeclarationsCount > 1) { + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; + if (isNotOverload(declaration)) { + diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); + } + } + } + }); + links.exportsChecked = true; + } + function isNotOverload(declaration) { + return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || + !!declaration.body; + } + } + function checkSourceElement(node) { + if (!node) { + return; + } + var kind = node.kind; + if (cancellationToken) { + // Only bother checking on a few construct kinds. We don't want to be excessively + // hitting the cancellation token on every node we check. + switch (kind) { + case 233 /* ModuleDeclaration */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 228 /* FunctionDeclaration */: + cancellationToken.throwIfCancellationRequested(); + } + } + switch (kind) { + case 145 /* TypeParameter */: + return checkTypeParameter(node); + case 146 /* Parameter */: + return checkParameter(node); + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + return checkPropertyDeclaration(node); + case 160 /* FunctionType */: + case 161 /* ConstructorType */: + case 155 /* CallSignature */: + case 156 /* ConstructSignature */: + return checkSignatureDeclaration(node); + case 157 /* IndexSignature */: + return checkSignatureDeclaration(node); + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + return checkMethodDeclaration(node); + case 152 /* Constructor */: + return checkConstructorDeclaration(node); + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + return checkAccessorDeclaration(node); + case 159 /* TypeReference */: + return checkTypeReferenceNode(node); + case 158 /* TypePredicate */: + return checkTypePredicate(node); + case 162 /* TypeQuery */: + return checkTypeQuery(node); + case 163 /* TypeLiteral */: + return checkTypeLiteral(node); + case 164 /* ArrayType */: + return checkArrayType(node); + case 165 /* TupleType */: + return checkTupleType(node); + case 166 /* UnionType */: + case 167 /* IntersectionType */: + return checkUnionOrIntersectionType(node); + case 168 /* ParenthesizedType */: + case 170 /* TypeOperator */: + return checkSourceElement(node.type); + case 275 /* JSDocComment */: + return checkJSDocComment(node); + case 279 /* JSDocParameterTag */: + return checkSourceElement(node.typeExpression); + case 273 /* JSDocFunctionType */: + checkSignatureDeclaration(node); + // falls through + case 274 /* JSDocVariadicType */: + case 271 /* JSDocNonNullableType */: + case 270 /* JSDocNullableType */: + case 268 /* JSDocAllType */: + case 269 /* JSDocUnknownType */: + if (!ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); + } + return; + case 267 /* JSDocTypeExpression */: + return checkSourceElement(node.type); + case 171 /* IndexedAccessType */: + return checkIndexedAccessType(node); + case 172 /* MappedType */: + return checkMappedType(node); + case 228 /* FunctionDeclaration */: + return checkFunctionDeclaration(node); + case 207 /* Block */: + case 234 /* ModuleBlock */: + return checkBlock(node); + case 208 /* VariableStatement */: + return checkVariableStatement(node); + case 210 /* ExpressionStatement */: + return checkExpressionStatement(node); + case 211 /* IfStatement */: + return checkIfStatement(node); + case 212 /* DoStatement */: + return checkDoStatement(node); + case 213 /* WhileStatement */: + return checkWhileStatement(node); + case 214 /* ForStatement */: + return checkForStatement(node); + case 215 /* ForInStatement */: + return checkForInStatement(node); + case 216 /* ForOfStatement */: + return checkForOfStatement(node); + case 217 /* ContinueStatement */: + case 218 /* BreakStatement */: + return checkBreakOrContinueStatement(node); + case 219 /* ReturnStatement */: + return checkReturnStatement(node); + case 220 /* WithStatement */: + return checkWithStatement(node); + case 221 /* SwitchStatement */: + return checkSwitchStatement(node); + case 222 /* LabeledStatement */: + return checkLabeledStatement(node); + case 223 /* ThrowStatement */: + return checkThrowStatement(node); + case 224 /* TryStatement */: + return checkTryStatement(node); + case 226 /* VariableDeclaration */: + return checkVariableDeclaration(node); + case 176 /* BindingElement */: + return checkBindingElement(node); + case 229 /* ClassDeclaration */: + return checkClassDeclaration(node); + case 230 /* InterfaceDeclaration */: + return checkInterfaceDeclaration(node); + case 231 /* TypeAliasDeclaration */: + return checkTypeAliasDeclaration(node); + case 232 /* EnumDeclaration */: + return checkEnumDeclaration(node); + case 233 /* ModuleDeclaration */: + return checkModuleDeclaration(node); + case 238 /* ImportDeclaration */: + return checkImportDeclaration(node); + case 237 /* ImportEqualsDeclaration */: + return checkImportEqualsDeclaration(node); + case 244 /* ExportDeclaration */: + return checkExportDeclaration(node); + case 243 /* ExportAssignment */: + return checkExportAssignment(node); + case 209 /* EmptyStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 225 /* DebuggerStatement */: + checkGrammarStatementInAmbientContext(node); + return; + case 247 /* MissingDeclaration */: + return checkMissingDeclaration(node); + } + } + // Function and class expression bodies are checked after all statements in the enclosing body. This is + // to ensure constructs like the following are permitted: + // const foo = function () { + // const s = foo(); + // return "hello"; + // } + // Here, performing a full type check of the body of the function expression whilst in the process of + // determining the type of foo would cause foo to be given type any because of the recursive reference. + // Delaying the type check of the body ensures foo has been assigned a type. + function checkNodeDeferred(node) { + if (deferredNodes) { + deferredNodes.push(node); + } + } + function checkDeferredNodes() { + for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { + var node = deferredNodes_1[_i]; + switch (node.kind) { + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + checkFunctionExpressionOrObjectLiteralMethodDeferred(node); + break; + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + checkAccessorDeclaration(node); + break; + case 199 /* ClassExpression */: + checkClassExpressionDeferred(node); + break; + } + } + } + function checkSourceFile(node) { + ts.performance.mark("beforeCheck"); + checkSourceFileWorker(node); + ts.performance.mark("afterCheck"); + ts.performance.measure("Check", "beforeCheck", "afterCheck"); + } + // Fully type check a source file and collect the relevant diagnostics. + function checkSourceFileWorker(node) { + var links = getNodeLinks(node); + if (!(links.flags & 1 /* TypeChecked */)) { + // If skipLibCheck is enabled, skip type checking if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip type checking if file contains a + // '/// ' directive. + if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { + return; + } + // Grammar checking + checkGrammarSourceFile(node); + ts.clear(potentialThisCollisions); + ts.clear(potentialNewTargetCollisions); + deferredNodes = []; + deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; + ts.forEach(node.statements, checkSourceElement); + checkDeferredNodes(); + if (ts.isExternalModule(node)) { + registerForUnusedIdentifiersCheck(node); + } + if (!node.isDeclarationFile) { + checkUnusedIdentifiers(); + } + deferredNodes = undefined; + deferredUnusedIdentifierNodes = undefined; + if (ts.isExternalOrCommonJsModule(node)) { + checkExternalModuleExports(node); + } + if (potentialThisCollisions.length) { + ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); + ts.clear(potentialThisCollisions); + } + if (potentialNewTargetCollisions.length) { + ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); + ts.clear(potentialNewTargetCollisions); + } + links.flags |= 1 /* TypeChecked */; + } + } + function getDiagnostics(sourceFile, ct) { + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + return getDiagnosticsWorker(sourceFile); + } + finally { + cancellationToken = undefined; + } + } + function getDiagnosticsWorker(sourceFile) { + throwIfNonDiagnosticsProducing(); + if (sourceFile) { + // Some global diagnostics are deferred until they are needed and + // may not be reported in the firt call to getGlobalDiagnostics. + // We should catch these changes and report them. + var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; + checkSourceFile(sourceFile); + var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); + if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { + // If the arrays are not the same reference, new diagnostics were added. + var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); + return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); + } + else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { + // If the arrays are the same reference, but the length has changed, a single + // new diagnostic was added as DiagnosticCollection attempts to reuse the + // same array. + return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); + } + return semanticDiagnostics; + } + // Global diagnostics are always added when a file is not provided to + // getDiagnostics + ts.forEach(host.getSourceFiles(), checkSourceFile); + return diagnostics.getDiagnostics(); + } + function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); + return diagnostics.getGlobalDiagnostics(); + } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } + // Language service support + function isInsideWithStatementBody(node) { + if (node) { + while (node.parent) { + if (node.parent.kind === 220 /* WithStatement */ && node.parent.statement === node) { + return true; + } + node = node.parent; + } + } + return false; + } + function getSymbolsInScope(location, meaning) { + if (isInsideWithStatementBody(location)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return []; + } + var symbols = ts.createSymbolTable(); + var memberFlags = 0 /* None */; + populateSymbols(); + return symbolsToArray(symbols); + function populateSymbols() { + while (location) { + if (location.locals && !isGlobalSourceFile(location)) { + copySymbols(location.locals, meaning); + } + switch (location.kind) { + case 233 /* ModuleDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); + break; + case 232 /* EnumDeclaration */: + copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); + break; + case 199 /* ClassExpression */: + var className = location.name; + if (className) { + copySymbol(location.symbol, meaning); + } + // falls through + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + // If we didn't come from static member of class or interface, + // add the type parameters into the symbol table + // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. + // Note: that the memberFlags come from previous iteration. + if (!(memberFlags & 32 /* Static */)) { + copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); + } + break; + case 186 /* FunctionExpression */: + var funcName = location.name; + if (funcName) { + copySymbol(location.symbol, meaning); + } + break; + } + if (ts.introducesArgumentsExoticObject(location)) { + copySymbol(argumentsSymbol, meaning); + } + memberFlags = ts.getModifierFlags(location); + location = location.parent; + } + copySymbols(globals, meaning); + } + /** + * Copy the given symbol into symbol tables if the symbol has the given meaning + * and it doesn't already existed in the symbol table + * @param key a key for storing in symbol table; if undefined, use symbol.name + * @param symbol the symbol to be added into symbol table + * @param meaning meaning of symbol to filter by before adding to symbol table + */ + function copySymbol(symbol, meaning) { + if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { + var id = symbol.escapedName; + // We will copy all symbol regardless of its reserved name because + // symbolsToArray will check whether the key is a reserved name and + // it will not copy symbol with reserved name to the array + if (!symbols.has(id)) { + symbols.set(id, symbol); + } + } + } + function copySymbols(source, meaning) { + if (meaning) { + source.forEach(function (symbol) { + copySymbol(symbol, meaning); + }); + } + } + } + function isTypeDeclarationName(name) { + return name.kind === 71 /* Identifier */ && + isTypeDeclaration(name.parent) && + name.parent.name === name; + } + function isTypeDeclaration(node) { + switch (node.kind) { + case 145 /* TypeParameter */: + case 229 /* ClassDeclaration */: + case 230 /* InterfaceDeclaration */: + case 231 /* TypeAliasDeclaration */: + case 232 /* EnumDeclaration */: + return true; + } + } + // True if the given identifier is part of a type reference + function isTypeReferenceIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 143 /* QualifiedName */) { + node = node.parent; + } + return node.parent && node.parent.kind === 159 /* TypeReference */; + } + function isHeritageClauseElementIdentifier(entityName) { + var node = entityName; + while (node.parent && node.parent.kind === 179 /* PropertyAccessExpression */) { + node = node.parent; + } + return node.parent && node.parent.kind === 201 /* ExpressionWithTypeArguments */; + } + function forEachEnclosingClass(node, callback) { + var result; + while (true) { + node = ts.getContainingClass(node); + if (!node) + break; + if (result = callback(node)) + break; + } + return result; + } + function isNodeWithinClass(node, classDeclaration) { + return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); + } + function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { + while (nodeOnRightSide.parent.kind === 143 /* QualifiedName */) { + nodeOnRightSide = nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 237 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + } + if (nodeOnRightSide.parent.kind === 243 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + } + return undefined; + } + function isInRightSideOfImportOrExportAssignment(node) { + return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; + } + function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { + var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); + switch (specialPropertyAssignmentKind) { + case 1 /* ExportsProperty */: + case 3 /* PrototypeProperty */: + return getSymbolOfNode(entityName.parent); + case 4 /* ThisProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + return getSymbolOfNode(entityName.parent.parent); + } + } + function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { + if (ts.isDeclarationName(entityName)) { + return getSymbolOfNode(entityName.parent); + } + if (ts.isInJavaScriptFile(entityName) && + entityName.parent.kind === 179 /* PropertyAccessExpression */ && + entityName.parent === entityName.parent.parent.left) { + // Check if this is a special property assignment + var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); + if (specialPropertyAssignmentSymbol) { + return specialPropertyAssignmentSymbol; + } + } + if (entityName.parent.kind === 243 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + return resolveEntityName(entityName, + /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + if (entityName.kind !== 179 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + // Since we already checked for ExportAssignment, this really could only be an Import + var importEqualsDeclaration = ts.getAncestor(entityName, 237 /* ImportEqualsDeclaration */); + ts.Debug.assert(importEqualsDeclaration !== undefined); + return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); + } + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + entityName = entityName.parent; + } + if (isHeritageClauseElementIdentifier(entityName)) { + var meaning = 0 /* None */; + // In an interface or class, we're definitely interested in a type. + if (entityName.parent.kind === 201 /* ExpressionWithTypeArguments */) { + meaning = 793064 /* Type */; + // In a class 'extends' clause we are also looking for a value. + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { + meaning |= 107455 /* Value */; + } + } + else { + meaning = 1920 /* Namespace */; + } + meaning |= 2097152 /* Alias */; + var entityNameSymbol = resolveEntityName(entityName, meaning); + if (entityNameSymbol) { + return entityNameSymbol; + } + } + if (entityName.parent.kind === 279 /* JSDocParameterTag */) { + return ts.getParameterSymbolFromJSDoc(entityName.parent); + } + if (entityName.parent.kind === 145 /* TypeParameter */ && entityName.parent.parent.kind === 282 /* JSDocTemplateTag */) { + ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); + return typeParameter && typeParameter.symbol; + } + if (ts.isPartOfExpression(entityName)) { + if (ts.nodeIsMissing(entityName)) { + // Missing entity name. + return undefined; + } + if (entityName.kind === 71 /* Identifier */) { + if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { + return getIntrinsicTagSymbol(entityName.parent); + } + return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.kind === 179 /* PropertyAccessExpression */ || entityName.kind === 143 /* QualifiedName */) { + var links = getNodeLinks(entityName); + if (links.resolvedSymbol) { + return links.resolvedSymbol; + } + if (entityName.kind === 179 /* PropertyAccessExpression */) { + checkPropertyAccessExpression(entityName); + } + else { + checkQualifiedName(entityName); + } + return links.resolvedSymbol; + } + } + else if (isTypeReferenceIdentifier(entityName)) { + var meaning = entityName.parent.kind === 159 /* TypeReference */ ? 793064 /* Type */ : 1920 /* Namespace */; + return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + } + else if (entityName.parent.kind === 253 /* JsxAttribute */) { + return getJsxAttributePropertySymbol(entityName.parent); + } + if (entityName.parent.kind === 158 /* TypePredicate */) { + return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); + } + // Do we want to return undefined here? + return undefined; + } + function getSymbolAtLocation(node) { + if (node.kind === 265 /* SourceFile */) { + return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; + } + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return undefined; + } + if (isDeclarationNameOrImportPropertyName(node)) { + // This is a declaration, call getSymbolOfNode + return getSymbolOfNode(node.parent); + } + else if (ts.isLiteralComputedPropertyDeclarationName(node)) { + return getSymbolOfNode(node.parent.parent); + } + if (node.kind === 71 /* Identifier */) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + } + else if (node.parent.kind === 176 /* BindingElement */ && + node.parent.parent.kind === 174 /* ObjectBindingPattern */ && + node === node.parent.propertyName) { + var typeOfPattern = getTypeOfNode(node.parent.parent); + var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); + if (propertyDeclaration) { + return propertyDeclaration; + } + } + } + switch (node.kind) { + case 71 /* Identifier */: + case 179 /* PropertyAccessExpression */: + case 143 /* QualifiedName */: + return getSymbolOfEntityNameOrPropertyAccessExpression(node); + case 99 /* ThisKeyword */: + var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + if (ts.isFunctionLike(container)) { + var sig = getSignatureFromDeclaration(container); + if (sig.thisParameter) { + return sig.thisParameter; + } + } + // falls through + case 97 /* SuperKeyword */: + var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); + return type.symbol; + case 169 /* ThisType */: + return getTypeFromTypeNode(node).symbol; + case 123 /* ConstructorKeyword */: + // constructor keyword for an overload, should take us to the definition if it exist + var constructorDeclaration = node.parent; + if (constructorDeclaration && constructorDeclaration.kind === 152 /* Constructor */) { + return constructorDeclaration.parent.symbol; + } + return undefined; + case 9 /* StringLiteral */: + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { + return resolveExternalModuleName(node, node); + } + // falls through + case 8 /* NumericLiteral */: + // index access + if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { + var objectType = getTypeOfExpression(node.parent.expression); + if (objectType === unknownType) + return undefined; + var apparentType = getApparentType(objectType); + if (apparentType === unknownType) + return undefined; + return getPropertyOfType(apparentType, node.text); + } + break; + } + return undefined; + } + function getShorthandAssignmentValueSymbol(location) { + // The function returns a value symbol of an identifier in the short-hand property assignment. + // This is necessary as an identifier in short-hand property assignment can contains two meaning: + // property name and property value. + if (location && location.kind === 262 /* ShorthandPropertyAssignment */) { + return resolveEntityName(location.name, 107455 /* Value */ | 2097152 /* Alias */); + } + return undefined; + } + /** Returns the target of an export specifier without following aliases */ + function getExportSpecifierLocalTargetSymbol(node) { + return node.parent.parent.moduleSpecifier ? + getExternalModuleMember(node.parent.parent, node) : + resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + } + function getTypeOfNode(node) { + if (isInsideWithStatementBody(node)) { + // We cannot answer semantic questions within a with block, do not proceed any further + return unknownType; + } + if (ts.isPartOfTypeNode(node)) { + var typeFromTypeNode = getTypeFromTypeNode(node); + if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { + var containingClass = ts.getContainingClass(node); + var classType = getTypeOfNode(containingClass); + typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); + } + return typeFromTypeNode; + } + if (ts.isPartOfExpression(node)) { + return getRegularTypeOfExpression(node); + } + if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { + // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the + // extends clause of a class. We handle that case here. + var classNode = ts.getContainingClass(node); + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); + var baseType = getBaseTypes(classType)[0]; + return baseType && getTypeWithThisArgument(baseType, classType.thisType); + } + if (isTypeDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getDeclaredTypeOfSymbol(symbol); + } + if (isTypeDeclarationName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getDeclaredTypeOfSymbol(symbol); + } + if (ts.isDeclaration(node)) { + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration + var symbol = getSymbolOfNode(node); + return getTypeOfSymbol(symbol); + } + if (isDeclarationNameOrImportPropertyName(node)) { + var symbol = getSymbolAtLocation(node); + return symbol && getTypeOfSymbol(symbol); + } + if (ts.isBindingPattern(node)) { + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + } + if (isInRightSideOfImportOrExportAssignment(node)) { + var symbol = getSymbolAtLocation(node); + var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + } + return unknownType; + } + // Gets the type of object literal or array literal of destructuring assignment. + // { a } from + // for ( { a } of elems) { + // } + // [ a ] from + // [a] = [ some array ...] + function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { + ts.Debug.assert(expr.kind === 178 /* ObjectLiteralExpression */ || expr.kind === 177 /* ArrayLiteralExpression */); + // If this is from "for of" + // for ( { a } of elems) { + // } + if (expr.parent.kind === 216 /* ForOfStatement */) { + var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + // If this is from "for" initializer + // for ({a } = elems[0];.....) { } + if (expr.parent.kind === 194 /* BinaryExpression */) { + var iteratedType = getTypeOfExpression(expr.parent.right); + return checkDestructuringAssignment(expr, iteratedType || unknownType); + } + // If this is from nested object binding pattern + // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { + if (expr.parent.kind === 261 /* PropertyAssignment */) { + var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + } + // Array literal assignment - array destructuring pattern + ts.Debug.assert(expr.parent.kind === 177 /* ArrayLiteralExpression */); + // [{ property1: p1, property2 }] = elems; + var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + } + // Gets the property symbol corresponding to the property in destructuring assignment + // 'property1' from + // for ( { property1: a } of elems) { + // } + // 'property1' at location 'a' from: + // [a] = [ property1, property2 ] + function getPropertySymbolOfDestructuringAssignment(location) { + // Get the type of the object or array literal and then look for property of given name in the type + var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); + } + function getRegularTypeOfExpression(expr) { + if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { + expr = expr.parent; + } + return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); + } + /** + * Gets either the static or instance type of a class element, based on + * whether the element is declared as "static". + */ + function getParentTypeOfClassElement(node) { + var classSymbol = getSymbolOfNode(node.parent); + return ts.getModifierFlags(node) & 32 /* Static */ + ? getTypeOfSymbol(classSymbol) + : getDeclaredTypeOfSymbol(classSymbol); + } + // Return the list of properties of the given type, augmented with properties from Function + // if the type has call or construct signatures + function getAugmentedPropertiesOfType(type) { + type = getApparentType(type); + var propsByName = ts.createSymbolTable(getPropertiesOfType(type)); + if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { + ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); + } + }); + } + return getNamedMembers(propsByName); + } + function getRootSymbols(symbol) { + if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) { + var symbols_4 = []; + var name_2 = symbol.escapedName; + ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { + var symbol = getPropertyOfType(t, name_2); + if (symbol) { + symbols_4.push(symbol); + } + }); + return symbols_4; + } + else if (symbol.flags & 33554432 /* Transient */) { + var transient = symbol; + if (transient.leftSpread) { + return getRootSymbols(transient.leftSpread).concat(getRootSymbols(transient.rightSpread)); + } + if (transient.syntheticOrigin) { + return getRootSymbols(transient.syntheticOrigin); + } + var target = void 0; + var next = symbol; + while (next = getSymbolLinks(next).target) { + target = next; + } + if (target) { + return [target]; + } + } + return [symbol]; + } + // Emitter support + function isArgumentsLocalBinding(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var isPropertyName_1 = node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; + return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; + } + } + return false; + } + function moduleExportsSomeValue(moduleReferenceExpression) { + var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); + if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { + // If the module is not found or is shorthand, assume that it may export a value. + return true; + } + var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); + // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment + // otherwise it will return moduleSymbol itself + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + var symbolLinks = getSymbolLinks(moduleSymbol); + if (symbolLinks.exportsSomeValue === undefined) { + // for export assignments - check if resolved symbol for RHS is itself a value + // otherwise - check if at least one export is value + symbolLinks.exportsSomeValue = hasExportAssignment + ? !!(moduleSymbol.flags & 107455 /* Value */) + : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); + } + return symbolLinks.exportsSomeValue; + function isValue(s) { + s = resolveSymbol(s); + return s && !!(s.flags & 107455 /* Value */); + } + } + function isNameOfModuleOrEnumDeclaration(node) { + var parent = node.parent; + return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + } + // When resolved as an expression identifier, if the given node references an exported entity, return the declaration + // node of the exported entity's container. Otherwise, return undefined. + function getReferencedExportContainer(node, prefixLocals) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + // When resolving the export container for the name of a module or enum + // declaration, we need to start resolution at the declaration's container. + // Otherwise, we could incorrectly resolve the export container as the + // declaration if it contains an exported member with the same name. + var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); + if (symbol) { + if (symbol.flags & 1048576 /* ExportValue */) { + // If we reference an exported entity within the same module declaration, then whether + // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the + // kinds that we do NOT prefix. + var exportSymbol = getMergedSymbol(symbol.exportSymbol); + if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { + return undefined; + } + symbol = exportSymbol; + } + var parentSymbol_1 = getParentOfSymbol(symbol); + if (parentSymbol_1) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 265 /* SourceFile */) { + var symbolFile = parentSymbol_1.valueDeclaration; + var referenceFile = ts.getSourceFileOfNode(node); + // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. + var symbolIsUmdExport = symbolFile !== referenceFile; + return symbolIsUmdExport ? undefined : symbolFile; + } + return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); + } + } + } + } + // When resolved as an expression identifier, if the given node references an import, return the declaration of + // that import. Otherwise, return undefined. + function getReferencedImportDeclaration(node) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + // We should only get the declaration of an alias if there isn't a local value + // declaration for the symbol + if (isNonLocalAlias(symbol, /*excludes*/ 107455 /* Value */)) { + return getDeclarationOfAliasSymbol(symbol); + } + } + return undefined; + } + function isSymbolOfDeclarationWithCollidingName(symbol) { + if (symbol.flags & 418 /* BlockScoped */) { + var links = getSymbolLinks(symbol); + if (links.isDeclarationWithCollidingName === undefined) { + var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); + if (ts.isStatementWithLocals(container)) { + var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); + if (!!resolveName(container.parent, symbol.escapedName, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + // redeclaration - always should be renamed + links.isDeclarationWithCollidingName = true; + } + else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { + // binding is captured in the function + // should be renamed if: + // - binding is not top level - top level bindings never collide with anything + // AND + // - binding is not declared in loop, should be renamed to avoid name reuse across siblings + // let a, b + // { let x = 1; a = () => x; } + // { let x = 100; b = () => x; } + // console.log(a()); // should print '1' + // console.log(b()); // should print '100' + // OR + // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body + // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly + // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus + // they will not collide with anything + var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; + var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 207 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); + } + else { + links.isDeclarationWithCollidingName = false; + } + } + } + return links.isDeclarationWithCollidingName; + } + return false; + } + // When resolved as an expression identifier, if the given node references a nested block scoped entity with + // a name that either hides an existing name or might hide it when compiled downlevel, + // return the declaration of that entity. Otherwise, return undefined. + function getReferencedDeclarationWithCollidingName(node) { + if (!ts.isGeneratedIdentifier(node)) { + node = ts.getParseTreeNode(node, ts.isIdentifier); + if (node) { + var symbol = getReferencedValueSymbol(node); + if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { + return symbol.valueDeclaration; + } + } + } + return undefined; + } + // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an + // existing name or might hide a name when compiled downlevel + function isDeclarationWithCollidingName(node) { + node = ts.getParseTreeNode(node, ts.isDeclaration); + if (node) { + var symbol = getSymbolOfNode(node); + if (symbol) { + return isSymbolOfDeclarationWithCollidingName(symbol); + } + } + return false; + } + function isValueAliasDeclaration(node) { + switch (node.kind) { + case 237 /* ImportEqualsDeclaration */: + case 239 /* ImportClause */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */: + case 246 /* ExportSpecifier */: + return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); + case 244 /* ExportDeclaration */: + var exportClause = node.exportClause; + return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); + case 243 /* ExportAssignment */: + return node.expression + && node.expression.kind === 71 /* Identifier */ + ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) + : true; + } + return false; + } + function isTopLevelValueImportEqualsWithEntityName(node) { + node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 265 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + // parent is not source file or it is not reference to internal module + return false; + } + var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); + } + function isAliasResolvedToValue(symbol) { + var target = resolveAlias(symbol); + if (target === unknownSymbol) { + return true; + } + // const enums and modules that contain only const enums are not considered values from the emit perspective + // unless 'preserveConstEnums' option is set to true + return target.flags & 107455 /* Value */ && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); + } + function isConstEnumOrConstEnumOnlyModule(s) { + return isConstEnumSymbol(s) || s.constEnumOnlyModule; + } + function isReferencedAliasDeclaration(node, checkChildren) { + if (ts.isAliasSymbolDeclaration(node)) { + var symbol = getSymbolOfNode(node); + if (symbol && getSymbolLinks(symbol).referenced) { + return true; + } + } + if (checkChildren) { + return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + } + return false; + } + function isImplementationOfOverload(node) { + if (ts.nodeIsPresent(node.body)) { + var symbol = getSymbolOfNode(node); + var signaturesOfSymbol = getSignaturesOfSymbol(symbol); + // If this function body corresponds to function with multiple signature, it is implementation of overload + // e.g.: function foo(a: string): string; + // function foo(a: number): number; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + return signaturesOfSymbol.length > 1 || + // If there is single signature for the symbol, it is overload if that signature isn't coming from the node + // e.g.: function foo(a: string): string; + // function foo(a: any) { // This is implementation of the overloads + // return a; + // } + (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); + } + return false; + } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } + function getNodeCheckFlags(node) { + return getNodeLinks(node).flags; + } + function getEnumMemberValue(node) { + computeEnumMemberValues(node.parent); + return getNodeLinks(node).enumMemberValue; + } + function canHaveConstantValue(node) { + switch (node.kind) { + case 264 /* EnumMember */: + case 179 /* PropertyAccessExpression */: + case 180 /* ElementAccessExpression */: + return true; + } + return false; + } + function getConstantValue(node) { + if (node.kind === 264 /* EnumMember */) { + return getEnumMemberValue(node); + } + var symbol = getNodeLinks(node).resolvedSymbol; + if (symbol && (symbol.flags & 8 /* EnumMember */)) { + // inline property\index accesses only for const enums + if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { + return getEnumMemberValue(symbol.valueDeclaration); + } + } + return undefined; + } + function isFunctionType(type) { + return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + } + function getTypeReferenceSerializationKind(typeName, location) { + // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. + var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. + var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); + if (valueSymbol && valueSymbol === typeSymbol) { + var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); + if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { + return ts.TypeReferenceSerializationKind.Promise; + } + var constructorType = getTypeOfSymbol(valueSymbol); + if (constructorType && isConstructorType(constructorType)) { + return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; + } + } + // We might not be able to resolve type symbol so use unknown type in that case (eg error case) + if (!typeSymbol) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === unknownType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 1 /* Any */) { + return ts.TypeReferenceSerializationKind.ObjectType; + } + else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { + return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; + } + else if (isTypeOfKind(type, 136 /* BooleanLike */)) { + return ts.TypeReferenceSerializationKind.BooleanType; + } + else if (isTypeOfKind(type, 84 /* NumberLike */)) { + return ts.TypeReferenceSerializationKind.NumberLikeType; + } + else if (isTypeOfKind(type, 262178 /* StringLike */)) { + return ts.TypeReferenceSerializationKind.StringLikeType; + } + else if (isTupleType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else if (isTypeOfKind(type, 512 /* ESSymbol */)) { + return ts.TypeReferenceSerializationKind.ESSymbolType; + } + else if (isFunctionType(type)) { + return ts.TypeReferenceSerializationKind.TypeWithCallSignature; + } + else if (isArrayType(type)) { + return ts.TypeReferenceSerializationKind.ArrayLikeType; + } + else { + return ts.TypeReferenceSerializationKind.ObjectType; + } + } + function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + // Get type of the symbol if this is the valid symbol otherwise get type at location + var symbol = getSymbolOfNode(declaration); + var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) + ? getWidenedLiteralType(getTypeOfSymbol(symbol)) + : unknownType; + if (flags & 8192 /* AddUndefined */) { + type = getNullableType(type, 2048 /* Undefined */); + } + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + var signature = getSignatureFromDeclaration(signatureDeclaration); + getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + } + function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + var type = getWidenedType(getRegularTypeOfExpression(expr)); + getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + } + function hasGlobalName(name) { + return globals.has(ts.escapeLeadingUnderscores(name)); + } + function getReferencedValueSymbol(reference, startInDeclarationContainer) { + var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; + if (resolvedSymbol) { + return resolvedSymbol; + } + var location = reference; + if (startInDeclarationContainer) { + // When resolving the name of a declaration as a value, we need to start resolution + // at a point outside of the declaration. + var parent = reference.parent; + if (ts.isDeclaration(parent) && reference === parent.name) { + location = getDeclarationContainer(parent); + } + } + return resolveName(location, reference.escapedText, 107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + } + function getReferencedValueDeclaration(reference) { + if (!ts.isGeneratedIdentifier(reference)) { + reference = ts.getParseTreeNode(reference, ts.isIdentifier); + if (reference) { + var symbol = getReferencedValueSymbol(reference); + if (symbol) { + return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; + } + } + } + return undefined; + } + function isLiteralConstDeclaration(node) { + if (ts.isConst(node)) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); + } + return false; + } + function writeLiteralConstValue(node, writer) { + var type = getTypeOfSymbol(getSymbolOfNode(node)); + writer.writeStringLiteral(literalTypeToString(type)); + } + function createResolver() { + // this variable and functions that use it are deliberately moved here from the outer scope + // to avoid scope pollution + var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); + var fileToDirective; + if (resolvedTypeReferenceDirectives) { + // populate reverse mapping: file path -> type reference directive that was resolved to this file + fileToDirective = ts.createMap(); + resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { + if (!resolvedDirective) { + return; + } + var file = host.getSourceFile(resolvedDirective.resolvedFileName); + fileToDirective.set(file.path, key); + }); + } + return { + getReferencedExportContainer: getReferencedExportContainer, + getReferencedImportDeclaration: getReferencedImportDeclaration, + getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, + isDeclarationWithCollidingName: isDeclarationWithCollidingName, + isValueAliasDeclaration: function (node) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated like values. + return node ? isValueAliasDeclaration(node) : true; + }, + hasGlobalName: hasGlobalName, + isReferencedAliasDeclaration: function (node, checkChildren) { + node = ts.getParseTreeNode(node); + // Synthesized nodes are always treated as referenced. + return node ? isReferencedAliasDeclaration(node, checkChildren) : true; + }, + getNodeCheckFlags: function (node) { + node = ts.getParseTreeNode(node); + return node ? getNodeCheckFlags(node) : undefined; + }, + isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, + isDeclarationVisible: isDeclarationVisible, + isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + writeTypeOfDeclaration: writeTypeOfDeclaration, + writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, + writeTypeOfExpression: writeTypeOfExpression, + isSymbolAccessible: isSymbolAccessible, + isEntityNameVisible: isEntityNameVisible, + getConstantValue: function (node) { + node = ts.getParseTreeNode(node, canHaveConstantValue); + return node ? getConstantValue(node) : undefined; + }, + collectLinkedAliases: collectLinkedAliases, + getReferencedValueDeclaration: getReferencedValueDeclaration, + getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, + isOptionalParameter: isOptionalParameter, + moduleExportsSomeValue: moduleExportsSomeValue, + isArgumentsLocalBinding: isArgumentsLocalBinding, + getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, + getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, + getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, + isLiteralConstDeclaration: isLiteralConstDeclaration, + writeLiteralConstValue: writeLiteralConstValue, + getJsxFactoryEntity: function () { return _jsxFactoryEntity; } + }; + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForEntityName(node) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + // property access can only be used as values + // qualified names can only be used as types\namespaces + // identifiers are treated as values only if they appear in type queries + var meaning = (node.kind === 179 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) + ? 107455 /* Value */ | 1048576 /* ExportValue */ + : 793064 /* Type */ | 1920 /* Namespace */; + var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); + return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; + } + // defined here to avoid outer scope pollution + function getTypeReferenceDirectivesForSymbol(symbol, meaning) { + // program does not have any files with type reference directives - bail out + if (!fileToDirective) { + return undefined; + } + if (!isSymbolFromTypeDeclarationFile(symbol)) { + return undefined; + } + // check what declarations in the symbol can contribute to the target meaning + var typeReferenceDirectives; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + // check meaning of the local symbol to see if declaration needs to be analyzed further + if (decl.symbol && decl.symbol.flags & meaning) { + var file = ts.getSourceFileOfNode(decl); + var typeReferenceDirective = fileToDirective.get(file.path); + if (typeReferenceDirective) { + (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); + } + else { + // found at least one entry that does not originate from type reference directive + return undefined; + } + } + } + return typeReferenceDirectives; + } + function isSymbolFromTypeDeclarationFile(symbol) { + // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) + if (!symbol.declarations) { + return false; + } + // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope + // external modules cannot define or contribute to type declaration files + var current = symbol; + while (true) { + var parent = getParentOfSymbol(current); + if (parent) { + current = parent; + } + else { + break; + } + } + if (current.valueDeclaration && current.valueDeclaration.kind === 265 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + return false; + } + // check that at least one declaration of top level symbol originates from type declaration file + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var file = ts.getSourceFileOfNode(decl); + if (fileToDirective.has(file.path)) { + return true; + } + } + return false; + } + } + function getExternalModuleFileFromDeclaration(declaration) { + var specifier = ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + if (!moduleSymbol) { + return undefined; + } + return ts.getDeclarationOfKind(moduleSymbol, 265 /* SourceFile */); + } + function initializeTypeChecker() { + // Bind all source files and propagate errors + for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + ts.bindSourceFile(file, compilerOptions); + } + // Initialize global symbol table + var augmentations; + for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { + var file = _c[_b]; + if (!ts.isExternalOrCommonJsModule(file)) { + mergeSymbolTable(globals, file.locals); + } + if (file.patternAmbientModules && file.patternAmbientModules.length) { + patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); + } + if (file.moduleAugmentations.length) { + (augmentations || (augmentations = [])).push(file.moduleAugmentations); + } + if (file.symbol && file.symbol.globalExports) { + // Merge in UMD exports with first-in-wins semantics (see #9771) + var source = file.symbol.globalExports; + source.forEach(function (sourceSymbol, id) { + if (!globals.has(id)) { + globals.set(id, sourceSymbol); + } + }); + } + } + if (augmentations) { + // merge module augmentations. + // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed + for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { + var list = augmentations_1[_d]; + for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { + var augmentation = list_1[_e]; + mergeModuleAugmentation(augmentation); + } + } + } + // Setup global builtins + addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); + getSymbolLinks(undefinedSymbol).type = undefinedWideningType; + getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); + getSymbolLinks(unknownSymbol).type = unknownType; + // Initialize special types + globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); + globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); + globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); + globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); + globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); + globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); + globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); + anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); + globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); + anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; + globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); + } + function checkExternalEmitHelpers(location, helpers) { + if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + var sourceFile = ts.getSourceFileOfNode(location); + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { + var helpersModule = resolveHelpersModule(sourceFile, location); + if (helpersModule !== unknownSymbol) { + var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; + for (var helper = 1 /* FirstEmitHelper */; helper <= 32768 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + var name = getHelperName(helper); + var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 107455 /* Value */); + if (!symbol) { + error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); + } + } + } + } + requestedExternalEmitHelpers |= helpers; + } + } + } + function getHelperName(helper) { + switch (helper) { + case 1 /* Extends */: return "__extends"; + case 2 /* Assign */: return "__assign"; + case 4 /* Rest */: return "__rest"; + case 8 /* Decorate */: return "__decorate"; + case 16 /* Metadata */: return "__metadata"; + case 32 /* Param */: return "__param"; + case 64 /* Awaiter */: return "__awaiter"; + case 128 /* Generator */: return "__generator"; + case 256 /* Values */: return "__values"; + case 512 /* Read */: return "__read"; + case 1024 /* Spread */: return "__spread"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; + case 32768 /* ExportStar */: return "__exportStar"; + default: ts.Debug.fail("Unrecognized helper"); + } + } + function resolveHelpersModule(node, errorNode) { + if (!externalHelpersModule) { + externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + } + return externalHelpersModule; + } + // GRAMMAR CHECKING + function checkGrammarDecorators(node) { + if (!node.decorators) { + return false; + } + if (!ts.nodeCanBeDecorated(node)) { + if (node.kind === 151 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); + } + else { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); + } + } + else if (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */) { + var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); + if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); + } + } + return false; + } + function checkGrammarModifiers(node) { + var quickResult = reportObviousModifierErrors(node); + if (quickResult !== undefined) { + return quickResult; + } + var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; + var flags = 0 /* None */; + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 131 /* ReadonlyKeyword */) { + if (node.kind === 148 /* PropertySignature */ || node.kind === 150 /* MethodSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); + } + if (node.kind === 157 /* IndexSignature */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); + } + } + switch (modifier.kind) { + case 76 /* ConstKeyword */: + if (node.kind !== 232 /* EnumDeclaration */ && node.parent.kind === 229 /* ClassDeclaration */) { + return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); + } + break; + case 114 /* PublicKeyword */: + case 113 /* ProtectedKeyword */: + case 112 /* PrivateKeyword */: + var text = visibilityToString(ts.modifierToFlag(modifier.kind)); + if (modifier.kind === 113 /* ProtectedKeyword */) { + lastProtected = modifier; + } + else if (modifier.kind === 112 /* PrivateKeyword */) { + lastPrivate = modifier; + } + if (flags & 28 /* AccessibilityModifier */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); + } + else if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); + } + else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); + } + else if (flags & 128 /* Abstract */) { + if (modifier.kind === 112 /* PrivateKeyword */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); + } + else { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); + } + } + flags |= ts.modifierToFlag(modifier.kind); + break; + case 115 /* StaticKeyword */: + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); + } + else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + flags |= 32 /* Static */; + lastStatic = modifier; + break; + case 131 /* ReadonlyKeyword */: + if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); + } + else if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */ && node.kind !== 157 /* IndexSignature */ && node.kind !== 146 /* Parameter */) { + // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. + return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); + } + flags |= 64 /* Readonly */; + lastReadonly = modifier; + break; + case 84 /* ExportKeyword */: + if (flags & 1 /* Export */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); + } + else if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); + } + else if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); + } + else if (node.parent.kind === 229 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } + flags |= 1 /* Export */; + break; + case 79 /* DefaultKeyword */: + var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } + flags |= 512 /* Default */; + break; + case 124 /* DeclareKeyword */: + if (flags & 2 /* Ambient */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.parent.kind === 229 /* ClassDeclaration */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } + else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234 /* ModuleBlock */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } + flags |= 2 /* Ambient */; + lastDeclare = modifier; + break; + case 117 /* AbstractKeyword */: + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); + } + if (node.kind !== 229 /* ClassDeclaration */) { + if (node.kind !== 151 /* MethodDeclaration */ && + node.kind !== 149 /* PropertyDeclaration */ && + node.kind !== 153 /* GetAccessor */ && + node.kind !== 154 /* SetAccessor */) { + return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); + } + if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { + return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); + } + if (flags & 32 /* Static */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); + } + if (flags & 8 /* Private */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); + } + } + flags |= 128 /* Abstract */; + break; + case 120 /* AsyncKeyword */: + if (flags & 256 /* Async */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); + } + else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); + } + else if (node.kind === 146 /* Parameter */) { + return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); + } + flags |= 256 /* Async */; + lastAsync = modifier; + break; + } + } + if (node.kind === 152 /* Constructor */) { + if (flags & 32 /* Static */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); + } + if (flags & 128 /* Abstract */) { + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + } + else if (flags & 256 /* Async */) { + return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); + } + else if (flags & 64 /* Readonly */) { + return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); + } + return; + } + else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); + } + else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); + } + else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); + } + if (flags & 256 /* Async */) { + return checkGrammarAsyncModifier(node, lastAsync); + } + } + /** + * true | false: Early return this value from checkGrammarModifiers. + * undefined: Need to do full checking on the modifiers. + */ + function reportObviousModifierErrors(node) { + return !node.modifiers + ? false + : shouldReportBadModifier(node) + ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) + : undefined; + } + function shouldReportBadModifier(node) { + switch (node.kind) { + case 153 /* GetAccessor */: + case 154 /* SetAccessor */: + case 152 /* Constructor */: + case 149 /* PropertyDeclaration */: + case 148 /* PropertySignature */: + case 151 /* MethodDeclaration */: + case 150 /* MethodSignature */: + case 157 /* IndexSignature */: + case 233 /* ModuleDeclaration */: + case 238 /* ImportDeclaration */: + case 237 /* ImportEqualsDeclaration */: + case 244 /* ExportDeclaration */: + case 243 /* ExportAssignment */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + case 146 /* Parameter */: + return false; + default: + if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + return false; + } + switch (node.kind) { + case 228 /* FunctionDeclaration */: + return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); + case 229 /* ClassDeclaration */: + return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); + case 230 /* InterfaceDeclaration */: + case 208 /* VariableStatement */: + case 231 /* TypeAliasDeclaration */: + return true; + case 232 /* EnumDeclaration */: + return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); + default: + ts.Debug.fail(); + return false; + } + } + } + function nodeHasAnyModifiersExcept(node, allowedModifier) { + return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; + } + function checkGrammarAsyncModifier(node, asyncModifier) { + switch (node.kind) { + case 151 /* MethodDeclaration */: + case 228 /* FunctionDeclaration */: + case 186 /* FunctionExpression */: + case 187 /* ArrowFunction */: + return false; + } + return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); + } + function checkGrammarForDisallowedTrailingComma(list) { + if (list && list.hasTrailingComma) { + var start = list.end - ",".length; + var end = list.end; + var sourceFile = ts.getSourceFileOfNode(list[0]); + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + } + } + function checkGrammarTypeParameterList(typeParameters, file) { + if (checkGrammarForDisallowedTrailingComma(typeParameters)) { + return true; + } + if (typeParameters && typeParameters.length === 0) { + var start = typeParameters.pos - "<".length; + var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; + return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); + } + } + function checkGrammarParameterList(parameters) { + var seenOptionalParameter = false; + var parameterCount = parameters.length; + for (var i = 0; i < parameterCount; i++) { + var parameter = parameters[i]; + if (parameter.dotDotDotToken) { + if (i !== (parameterCount - 1)) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + if (ts.isBindingPattern(parameter.name)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); + } + } + else if (parameter.questionToken) { + seenOptionalParameter = true; + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); + } + } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); + } + } + } + function checkGrammarFunctionLikeDeclaration(node) { + // Prevent cascading error by short-circuit + var file = ts.getSourceFileOfNode(node); + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + } + function checkGrammarClassLikeDeclaration(node) { + var file = ts.getSourceFileOfNode(node); + return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); + } + function checkGrammarArrowFunction(node, file) { + if (node.kind === 187 /* ArrowFunction */) { + var arrowFunction = node; + var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + if (startLine !== endLine) { + return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); + } + } + return false; + } + function checkGrammarIndexSignatureParameters(node) { + var parameter = node.parameters[0]; + if (node.parameters.length !== 1) { + if (parameter) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + else { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); + } + } + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); + } + if (ts.getModifierFlags(parameter) !== 0) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); + } + if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); + } + if (parameter.initializer) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); + } + if (!parameter.type) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); + } + if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + } + if (!node.type) { + return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); + } + } + function checkGrammarIndexSignature(node) { + // Prevent cascading error by short-circuit + return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); + } + function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { + if (typeArguments && typeArguments.length === 0) { + var sourceFile = ts.getSourceFileOfNode(node); + var start = typeArguments.pos - "<".length; + var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); + } + } + function checkGrammarTypeArguments(node, typeArguments) { + return checkGrammarForDisallowedTrailingComma(typeArguments) || + checkGrammarForAtLeastOneTypeArgument(node, typeArguments); + } + function checkGrammarForOmittedArgument(node, args) { + if (args) { + var sourceFile = ts.getSourceFileOfNode(node); + for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { + var arg = args_5[_i]; + if (arg.kind === 200 /* OmittedExpression */) { + return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); + } + } + } + } + function checkGrammarArguments(node, args) { + return checkGrammarForOmittedArgument(node, args); + } + function checkGrammarHeritageClause(node) { + var types = node.types; + if (checkGrammarForDisallowedTrailingComma(types)) { + return true; + } + if (types && types.length === 0) { + var listType = ts.tokenToString(node.token); + var sourceFile = ts.getSourceFileOfNode(node); + return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); + } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); + } + function checkGrammarClassDeclarationHeritageClauses(node) { + var seenExtendsClause = false; + var seenImplementsClause = false; + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); + } + if (heritageClause.types.length > 1) { + return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + if (seenImplementsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); + } + seenImplementsClause = true; + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + } + function checkGrammarInterfaceDeclaration(node) { + var seenExtendsClause = false; + if (node.heritageClauses) { + for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { + var heritageClause = _a[_i]; + if (heritageClause.token === 85 /* ExtendsKeyword */) { + if (seenExtendsClause) { + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); + } + seenExtendsClause = true; + } + else { + ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); + return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); + } + // Grammar checking heritageClause inside class declaration + checkGrammarHeritageClause(heritageClause); + } + } + return false; + } + function checkGrammarComputedPropertyName(node) { + // If node is not a computedPropertyName, just skip the grammar checking + if (node.kind !== 144 /* ComputedPropertyName */) { + return false; + } + var computedPropertyName = node; + if (computedPropertyName.expression.kind === 194 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + } + } + function checkGrammarForGenerator(node) { + if (node.asteriskToken) { + ts.Debug.assert(node.kind === 228 /* FunctionDeclaration */ || + node.kind === 186 /* FunctionExpression */ || + node.kind === 151 /* MethodDeclaration */); + if (ts.isInAmbientContext(node)) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); + } + if (!node.body) { + return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); + } + } + } + function checkGrammarForInvalidQuestionMark(questionToken, message) { + if (questionToken) { + return grammarErrorOnNode(questionToken, message); + } + } + function checkGrammarObjectLiteralExpression(node, inDestructuring) { + var seen = ts.createUnderscoreEscapedMap(); + var Property = 1; + var GetAccessor = 2; + var SetAccessor = 4; + var GetOrSetAccessor = GetAccessor | SetAccessor; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var prop = _a[_i]; + if (prop.kind === 263 /* SpreadAssignment */) { + continue; + } + var name = prop.name; + if (name.kind === 144 /* ComputedPropertyName */) { + // If the name is not a ComputedPropertyName, the grammar checking will skip it + checkGrammarComputedPropertyName(name); + } + if (prop.kind === 262 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern + // outside of destructuring it is a syntax error + return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); + } + // Modifiers are never allowed on properties except for 'async' on a method declaration + if (prop.modifiers) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + var mod = _c[_b]; + if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 151 /* MethodDeclaration */) { + grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); + } + } + } + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = void 0; + if (prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */) { + // Grammar checking for computedPropertyName and shorthandPropertyAssignment + checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); + if (name.kind === 8 /* NumericLiteral */) { + checkGrammarNumericLiteral(name); + } + currentKind = Property; + } + else if (prop.kind === 151 /* MethodDeclaration */) { + currentKind = Property; + } + else if (prop.kind === 153 /* GetAccessor */) { + currentKind = GetAccessor; + } + else if (prop.kind === 154 /* SetAccessor */) { + currentKind = SetAccessor; + } + else { + ts.Debug.fail("Unexpected syntax kind:" + prop.kind); + } + var effectiveName = ts.getPropertyNameForPropertyNameNode(name); + if (effectiveName === undefined) { + continue; + } + var existingKind = seen.get(effectiveName); + if (!existingKind) { + seen.set(effectiveName, currentKind); + } + else { + if (currentKind === Property && existingKind === Property) { + grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); + } + else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { + if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { + seen.set(effectiveName, currentKind | existingKind); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + } + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + } + } + } + } + function checkGrammarJsxElement(node) { + var seen = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { + var attr = _a[_i]; + if (attr.kind === 255 /* JsxSpreadAttribute */) { + continue; + } + var jsxAttr = attr; + var name = jsxAttr.name; + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); + } + else { + return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + } + var initializer = jsxAttr.initializer; + if (initializer && initializer.kind === 256 /* JsxExpression */ && !initializer.expression) { + return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); + } + } + } + function checkGrammarForInOrForOfStatement(forInOrOfStatement) { + if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { + return true; + } + if (forInOrOfStatement.kind === 216 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { + return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); + } + } + if (forInOrOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { + var variableList = forInOrOfStatement.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + var declarations = variableList.declarations; + // declarations.length can be zero if there is an error in variable declaration in for-of or for-in + // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details + // For example: + // var let = 10; + // for (let of [1,2,3]) {} // this is invalid ES6 syntax + // for (let in [1,2,3]) {} // this is invalid ES6 syntax + // We will then want to skip on grammar checking on variableList declaration + if (!declarations.length) { + return false; + } + if (declarations.length > 1) { + var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement + : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; + return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); + } + var firstDeclaration = declarations[0]; + if (firstDeclaration.initializer) { + var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer + : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; + return grammarErrorOnNode(firstDeclaration.name, diagnostic); + } + if (firstDeclaration.type) { + var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ + ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation + : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; + return grammarErrorOnNode(firstDeclaration, diagnostic); + } + } + } + return false; + } + function checkGrammarAccessor(accessor) { + var kind = accessor.kind; + if (languageVersion < 1 /* ES5 */) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); + } + else if (ts.isInAmbientContext(accessor)) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); + } + else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { + return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { + return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); + } + else if (accessor.typeParameters) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); + } + else if (!doesAccessorHaveCorrectParameterCount(accessor)) { + return grammarErrorOnNode(accessor.name, kind === 153 /* GetAccessor */ ? + ts.Diagnostics.A_get_accessor_cannot_have_parameters : + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); + } + else if (kind === 154 /* SetAccessor */) { + if (accessor.type) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); + } + else { + var parameter = accessor.parameters[0]; + if (parameter.dotDotDotToken) { + return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); + } + else if (parameter.questionToken) { + return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); + } + else if (parameter.initializer) { + return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); + } + } + } + } + /** Does the accessor have the right number of parameters? + * A get accessor has no parameters or a single `this` parameter. + * A set accessor has one parameter or a `this` parameter and one more parameter. + */ + function doesAccessorHaveCorrectParameterCount(accessor) { + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 0 : 1); + } + function getAccessorThisParameter(accessor) { + if (accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); + } + } + function checkGrammarForNonSymbolComputedProperty(node, message) { + if (ts.isDynamicName(node)) { + return grammarErrorOnNode(node, message); + } + } + function checkGrammarMethod(node) { + if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || + checkGrammarFunctionLikeDeclaration(node) || + checkGrammarForGenerator(node)) { + return true; + } + if (node.parent.kind === 178 /* ObjectLiteralExpression */) { + if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } + if (ts.isClassLike(node.parent)) { + // Technically, computed properties in ambient contexts is disallowed + // for property declarations and accessors too, not just methods. + // However, property declarations disallow computed names in general, + // and accessors are not allowed in ambient contexts in general, + // so this error only really matters for methods. + if (ts.isInAmbientContext(node)) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); + } + else if (!node.body) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); + } + } + else if (node.parent.kind === 230 /* InterfaceDeclaration */) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); + } + else if (node.parent.kind === 163 /* TypeLiteral */) { + return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); + } + } + function checkGrammarBreakOrContinueStatement(node) { + var current = node; + while (current) { + if (ts.isFunctionLike(current)) { + return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); + } + switch (current.kind) { + case 222 /* LabeledStatement */: + if (node.label && current.label.escapedText === node.label.escapedText) { + // found matching label - verify that label usage is correct + // continue can only target labels that are on iteration statements + var isMisplacedContinueLabel = node.kind === 217 /* ContinueStatement */ + && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); + if (isMisplacedContinueLabel) { + return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); + } + return false; + } + break; + case 221 /* SwitchStatement */: + if (node.kind === 218 /* BreakStatement */ && !node.label) { + // unlabeled break within switch statement - ok + return false; + } + break; + default: + if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { + // unlabeled break or continue within iteration statement - ok + return false; + } + break; + } + current = current.parent; + } + if (node.label) { + var message = node.kind === 218 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement + : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + else { + var message = node.kind === 218 /* BreakStatement */ + ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement + : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + return grammarErrorOnNode(node, message); + } + } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== ts.lastOrUndefined(elements)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + } + if (node.name.kind === 175 /* ArrayBindingPattern */ || node.name.kind === 174 /* ObjectBindingPattern */) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); + } + if (node.initializer) { + // Error on equals token which immediately precedes the initializer + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + } + function isStringOrNumberLiteralExpression(expr) { + return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || + expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.operand.kind === 8 /* NumericLiteral */; + } + function checkGrammarVariableDeclaration(node) { + if (node.parent.parent.kind !== 215 /* ForInStatement */ && node.parent.parent.kind !== 216 /* ForOfStatement */) { + if (ts.isInAmbientContext(node)) { + if (node.initializer) { + if (ts.isConst(node) && !node.type) { + if (!isStringOrNumberLiteralExpression(node.initializer)) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + } + } + else { + // Error on equals token which immediate precedes the initializer + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { + // Error on equals token which immediate precedes the initializer + var equalsTokenLength = "=".length; + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + else if (!node.initializer) { + if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } + if (ts.isConst(node)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); + } + } + } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } + var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding + // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments + return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); + } + function checkESModuleMarker(name) { + if (name.kind === 71 /* Identifier */) { + if (ts.unescapeLeadingUnderscores(name.escapedText) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } + function checkGrammarNameInLetOrConstDeclarations(name) { + if (name.kind === 71 /* Identifier */) { + if (name.originalKeywordKind === 110 /* LetKeyword */) { + return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (!ts.isOmittedExpression(element)) { + checkGrammarNameInLetOrConstDeclarations(element.name); + } + } + } + } + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + } + function allowLetAndConstDeclarations(parent) { + switch (parent.kind) { + case 211 /* IfStatement */: + case 212 /* DoStatement */: + case 213 /* WhileStatement */: + case 220 /* WithStatement */: + case 214 /* ForStatement */: + case 215 /* ForInStatement */: + case 216 /* ForOfStatement */: + return false; + case 222 /* LabeledStatement */: + return allowLetAndConstDeclarations(parent.parent); + } + return true; + } + function checkGrammarForDisallowedLetOrConstStatement(node) { + if (!allowLetAndConstDeclarations(node.parent)) { + if (ts.isLet(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); + } + else if (ts.isConst(node.declarationList)) { + return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); + } + } + } + function checkGrammarMetaProperty(node) { + if (node.keywordToken === 94 /* NewKeyword */) { + if (node.name.escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + } + } + function hasParseDiagnostics(sourceFile) { + return sourceFile.parseDiagnostics.length > 0; + } + function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); + return true; + } + } + function grammarErrorOnNode(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); + return true; + } + } + function checkGrammarConstructorTypeParameters(node) { + if (node.typeParameters) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarConstructorTypeAnnotation(node) { + if (node.type) { + return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); + } + } + function checkGrammarProperty(node) { + if (ts.isClassLike(node.parent)) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + } + else if (node.parent.kind === 230 /* InterfaceDeclaration */) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); + } + } + else if (node.parent.kind === 163 /* TypeLiteral */) { + if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { + return true; + } + if (node.initializer) { + return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); + } + } + if (ts.isInAmbientContext(node) && node.initializer) { + return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); + } + } + function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { + // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace + // interfaces and imports categories: + // + // DeclarationElement: + // ExportAssignment + // export_opt InterfaceDeclaration + // export_opt TypeAliasDeclaration + // export_opt ImportDeclaration + // export_opt ExternalImportDeclaration + // export_opt AmbientDeclaration + // + // TODO: The spec needs to be amended to reflect this grammar. + if (node.kind === 230 /* InterfaceDeclaration */ || + node.kind === 231 /* TypeAliasDeclaration */ || + node.kind === 238 /* ImportDeclaration */ || + node.kind === 237 /* ImportEqualsDeclaration */ || + node.kind === 244 /* ExportDeclaration */ || + node.kind === 243 /* ExportAssignment */ || + node.kind === 236 /* NamespaceExportDeclaration */ || + ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { + return false; + } + return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); + } + function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isDeclaration(decl) || decl.kind === 208 /* VariableStatement */) { + if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { + return true; + } + } + } + } + function checkGrammarSourceFile(node) { + return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + } + function checkGrammarStatementInAmbientContext(node) { + if (ts.isInAmbientContext(node)) { + // An accessors is already reported about the ambient context + if (ts.isAccessor(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = true; + } + // Find containing block which is either Block, ModuleBlock, SourceFile + var links = getNodeLinks(node); + if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { + return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); + } + // We are either parented by another statement, or some sort of block. + // If we're in a block, we only want to really report an error once + // to prevent noisiness. So use a bit on the block to indicate if + // this has already been reported, and don't report if it has. + // + if (node.parent.kind === 207 /* Block */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { + var links_1 = getNodeLinks(node.parent); + // Check if the containing block ever report this error + if (!links_1.hasReportedStatementInAmbientContext) { + return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); + } + } + else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); + } + } + } + function checkGrammarNumericLiteral(node) { + // Grammar checking + if (node.numericLiteralFlags & 4 /* Octal */) { + var diagnosticMessage = void 0; + if (languageVersion >= 1 /* ES5 */) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 173 /* LiteralType */)) { + diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; + } + else if (ts.isChildOfNodeWithKind(node, 264 /* EnumMember */)) { + diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; + } + if (diagnosticMessage) { + var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; + var literal = (withMinus ? "-" : "") + "0o" + node.text; + return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); + } + } + } + function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); + return true; + } + } + function getAmbientModules() { + var result = []; + globals.forEach(function (global, sym) { + if (ambientModuleSymbolRegex.test(ts.unescapeLeadingUnderscores(sym))) { + result.push(global); + } + }); + return result; + } + function checkGrammarImportCallExpression(node) { + if (modulekind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + } + if (node.typeArguments) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); + } + var nodeArguments = node.arguments; + if (nodeArguments.length !== 1) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument); + } + // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import. + // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import. + if (ts.isSpreadElement(nodeArguments[0])) { + return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); + } + } + } + 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 */: + return true; + default: + return ts.isDeclarationName(name); + } + } + function isSomeImportDeclaration(decl) { + switch (decl.kind) { + case 239 /* ImportClause */: // For default import + case 237 /* ImportEqualsDeclaration */: + case 240 /* NamespaceImport */: + case 242 /* ImportSpecifier */:// For rename import `x as y` + return true; + case 71 /* Identifier */: + // For regular import, `decl` is an Identifier under the ImportSpecifier. + return decl.parent.kind === 242 /* ImportSpecifier */; + default: + return false; + } + } })(ts || (ts = {})); /// /// @@ -11159,13 +45412,13 @@ var ts; return node; } function createLiteralFromNode(sourceNode) { - var node = createStringLiteral(sourceNode.text); + var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; return node; } function createIdentifier(text, typeArguments) { var node = createSynthesizedNode(71 /* Identifier */); - node.text = ts.escapeIdentifier(text); + node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; node.autoGenerateKind = 0 /* None */; node.autoGenerateId = 0; @@ -11177,7 +45430,7 @@ var ts; ts.createIdentifier = createIdentifier; function updateIdentifier(node, typeArguments) { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(node.text, typeArguments), node) + ? updateNode(createIdentifier(ts.unescapeLeadingUnderscores(node.escapedText), typeArguments), node) : node; } ts.updateIdentifier = updateIdentifier; @@ -11360,13 +45613,14 @@ var ts; return node; } ts.createProperty = createProperty; - function updateProperty(node, decorators, modifiers, name, type, initializer) { + function updateProperty(node, decorators, modifiers, name, questionToken, type, initializer) { return node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name + || node.questionToken !== questionToken || node.type !== type || node.initializer !== initializer - ? updateNode(createProperty(decorators, modifiers, name, node.questionToken, type, initializer), node) + ? updateNode(createProperty(decorators, modifiers, name, questionToken, type, initializer), node) : node; } ts.updateProperty = updateProperty; @@ -11406,6 +45660,7 @@ var ts; || node.modifiers !== modifiers || node.asteriskToken !== asteriskToken || node.name !== name + || node.questionToken !== questionToken || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type @@ -11603,7 +45858,7 @@ var ts; ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { var node = createSynthesizedNode(164 /* ArrayType */); - node.elementType = ts.parenthesizeElementTypeMember(elementType); + node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } ts.createArrayTypeNode = createArrayTypeNode; @@ -11808,7 +46063,7 @@ var ts; // instead of using the default from createPropertyAccess return node.expression !== expression || node.name !== name - ? updateNode(setEmitFlags(createPropertyAccess(expression, name), getEmitFlags(node)), node) + ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) : node; } ts.updatePropertyAccess = updatePropertyAccess; @@ -13096,7 +47351,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(295 /* NotEmittedStatement */); + var node = createSynthesizedNode(287 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -13108,7 +47363,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(299 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(291 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -13120,7 +47375,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(290 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -13135,7 +47390,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(296 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(288 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -13151,7 +47406,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 297 /* CommaListExpression */) { + if (node.kind === 289 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -13161,7 +47416,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(297 /* CommaListExpression */); + var node = createSynthesizedNode(289 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -13185,7 +47440,18 @@ var ts; return node; } ts.updateBundle = updateBundle; - // Compound nodes + function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) { + return createCall(createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ param ? [param] : [], + /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), + /*typeArguments*/ undefined, + /*argumentsArray*/ paramValue ? [paramValue] : []); + } + ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression; function createComma(left, right) { return createBinary(left, 26 /* CommaToken */, right); } @@ -13306,14 +47572,6 @@ var ts; return range; } ts.setTextRange = setTextRange; - /** - * Gets flags that control emit behavior of a node. - */ - function getEmitFlags(node) { - var emitNode = node.emitNode; - return emitNode && emitNode.flags; - } - ts.getEmitFlags = getEmitFlags; /** * Sets flags that control emit behavior of a node. */ @@ -13338,6 +47596,14 @@ var ts; return node; } ts.setSourceMapRange = setSourceMapRange; + var SourceMapSource; + /** + * Create an external source map source file reference + */ + function createSourceMapSource(fileName, text, skipTrivia) { + return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); + } + ts.createSourceMapSource = createSourceMapSource; /** * Gets the TextRange to use for source maps for a token of a node. */ @@ -13519,6 +47785,7 @@ var ts; var flags = sourceEmitNode.flags, leadingComments = sourceEmitNode.leadingComments, trailingComments = sourceEmitNode.trailingComments, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges, constantValue = sourceEmitNode.constantValue, helpers = sourceEmitNode.helpers; if (!destEmitNode) destEmitNode = {}; + // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. if (leadingComments) destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments); if (trailingComments) @@ -13633,12 +47900,12 @@ var ts; function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) { if (ts.isQualifiedName(jsxFactory)) { var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - var right = ts.createIdentifier(jsxFactory.right.text); - right.text = jsxFactory.right.text; + var right = ts.createIdentifier(ts.unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + right.escapedText = jsxFactory.right.escapedText; return ts.createPropertyAccess(left, right); } else { - return createReactNamespace(jsxFactory.text, parent); + return createReactNamespace(ts.unescapeLeadingUnderscores(jsxFactory.escapedText), parent); } } function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) { @@ -13875,7 +48142,7 @@ var ts; function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) { var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; if (property === firstAccessor) { - var properties_1 = []; + var properties_8 = []; if (getAccessor) { var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, /*asteriskToken*/ undefined, @@ -13885,7 +48152,7 @@ var ts; ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); - properties_1.push(getter); + properties_8.push(getter); } if (setAccessor) { var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, @@ -13896,15 +48163,15 @@ var ts; ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); - properties_1.push(setter); + properties_8.push(setter); } - properties_1.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); - properties_1.push(ts.createPropertyAssignment("configurable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("enumerable", ts.createTrue())); + properties_8.push(ts.createPropertyAssignment("configurable", ts.createTrue())); var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ receiver, createExpressionForPropertyName(property.name), - ts.createObjectLiteral(properties_1, multiLine) + ts.createObjectLiteral(properties_8, multiLine) ]), /*location*/ firstAccessor); return ts.aggregateTransformFlags(expression); @@ -14063,8 +48330,20 @@ var ts; return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node); } ts.convertToFunctionBody = convertToFunctionBody; + function convertFunctionDeclarationToExpression(node) { + ts.Debug.assert(!!node.body); + var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); + ts.setOriginalNode(updated, node); + ts.setTextRange(updated, node); + if (node.startsOnNewLine) { + updated.startsOnNewLine = true; + } + ts.aggregateTransformFlags(updated); + return updated; + } + ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression; function isUseStrictPrologue(node) { - return node.expression.text === "use strict"; + return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; } /** * Add any necessary prologue-directives into target statement-array. @@ -14147,8 +48426,8 @@ var ts; */ function ensureUseStrict(statements) { var foundUseStrict = false; - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; + for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { + var statement = statements_3[_i]; if (ts.isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { foundUseStrict = true; @@ -14177,7 +48456,7 @@ var ts; * BinaryExpression. */ function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { - var skipped = skipPartiallyEmittedExpressions(operand); + var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. if (skipped.kind === 185 /* ParenthesizedExpression */) { return operand; @@ -14215,7 +48494,7 @@ var ts; // the intended order of operations: `(a ** b) ** c` var binaryOperatorPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, binaryOperator); var binaryOperatorAssociativity = ts.getOperatorAssociativity(194 /* BinaryExpression */, binaryOperator); - var emittedOperand = skipPartiallyEmittedExpressions(operand); + var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { case -1 /* LessThan */: @@ -14307,7 +48586,7 @@ var ts; * emitted without parentheses. */ function getLiteralKindOfBinaryPlusOperand(node) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); if (ts.isLiteralKind(node.kind)) { return node.kind; } @@ -14327,7 +48606,7 @@ var ts; } function parenthesizeForConditionalHead(condition) { var conditionalPrecedence = ts.getOperatorPrecedence(195 /* ConditionalExpression */, 55 /* QuestionToken */); - var emittedCondition = skipPartiallyEmittedExpressions(condition); + var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { return ts.createParen(condition); @@ -14351,7 +48630,7 @@ var ts; * @param expression The Expression node. */ function parenthesizeForNew(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); switch (emittedExpression.kind) { case 181 /* CallExpression */: return ts.createParen(expression); @@ -14376,7 +48655,7 @@ var ts; // NewExpression: // new C.x -> not the same as (new C).x // - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) && (emittedExpression.kind !== 182 /* NewExpression */ || emittedExpression.arguments)) { return expression; @@ -14414,7 +48693,7 @@ var ts; } ts.parenthesizeListElements = parenthesizeListElements; function parenthesizeExpressionForList(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); var commaPrecedence = ts.getOperatorPrecedence(194 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence @@ -14423,14 +48702,14 @@ var ts; } ts.parenthesizeExpressionForList = parenthesizeExpressionForList; function parenthesizeExpressionForExpressionStatement(expression) { - var emittedExpression = skipPartiallyEmittedExpressions(expression); + var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; - var kind = skipPartiallyEmittedExpressions(callee).kind; + var kind = ts.skipPartiallyEmittedExpressions(callee).kind; if (kind === 186 /* FunctionExpression */ || kind === 187 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); - return recreatePartiallyEmittedExpressions(expression, mutableCall); + return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } else { @@ -14453,37 +48732,32 @@ var ts; return member; } ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; + function parenthesizeArrayTypeMember(member) { + switch (member.kind) { + case 162 /* TypeQuery */: + case 170 /* TypeOperator */: + return ts.createParenthesizedType(member); + } + return parenthesizeElementTypeMember(member); + } + ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember; function parenthesizeElementTypeMembers(members) { return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember)); } ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers; function parenthesizeTypeParameters(typeParameters) { if (ts.some(typeParameters)) { - var nodeArray = ts.createNodeArray(); + var params = []; for (var i = 0; i < typeParameters.length; ++i) { var entry = typeParameters[i]; - nodeArray.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? + params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ? ts.createParenthesizedType(entry) : entry); } - return nodeArray; + return ts.createNodeArray(params); } } ts.parenthesizeTypeParameters = parenthesizeTypeParameters; - /** - * Clones a series of not-emitted expressions with a new inner expression. - * - * @param originalOuterExpression The original outer expression. - * @param newInnerExpression The new inner expression. - */ - function recreatePartiallyEmittedExpressions(originalOuterExpression, newInnerExpression) { - if (ts.isPartiallyEmittedExpression(originalOuterExpression)) { - var clone_1 = ts.getMutableClone(originalOuterExpression); - clone_1.expression = recreatePartiallyEmittedExpressions(clone_1.expression, newInnerExpression); - return clone_1; - } - return newInnerExpression; - } function getLeftmostExpression(node) { while (true) { switch (node.kind) { @@ -14501,7 +48775,7 @@ var ts; case 179 /* PropertyAccessExpression */: node = node.expression; continue; - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -14522,6 +48796,21 @@ var ts; OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 4] = "PartiallyEmittedExpressions"; OuterExpressionKinds[OuterExpressionKinds["All"] = 7] = "All"; })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {})); + function isOuterExpression(node, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + switch (node.kind) { + case 185 /* ParenthesizedExpression */: + return (kinds & 1 /* Parentheses */) !== 0; + case 184 /* TypeAssertionExpression */: + case 202 /* AsExpression */: + case 203 /* NonNullExpression */: + return (kinds & 2 /* Assertions */) !== 0; + case 288 /* PartiallyEmittedExpression */: + return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; + } + return false; + } + ts.isOuterExpression = isOuterExpression; function skipOuterExpressions(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } var previousNode; @@ -14534,7 +48823,7 @@ var ts; node = skipAssertions(node); } if (kinds & 4 /* PartiallyEmittedExpressions */) { - node = skipPartiallyEmittedExpressions(node); + node = ts.skipPartiallyEmittedExpressions(node); } } while (previousNode !== node); return node; @@ -14548,19 +48837,29 @@ var ts; } ts.skipParentheses = skipParentheses; function skipAssertions(node) { - while (ts.isAssertionExpression(node)) { + while (ts.isAssertionExpression(node) || node.kind === 203 /* NonNullExpression */) { node = node.expression; } return node; } ts.skipAssertions = skipAssertions; - function skipPartiallyEmittedExpressions(node) { - while (node.kind === 296 /* PartiallyEmittedExpression */) { - node = node.expression; + function updateOuterExpression(outerExpression, expression) { + switch (outerExpression.kind) { + case 185 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 184 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 202 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 203 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } - return node; } - ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function recreateOuterExpressions(outerExpression, innerExpression, kinds) { + if (kinds === void 0) { kinds = 7 /* All */; } + if (outerExpression && isOuterExpression(outerExpression, kinds)) { + return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression)); + } + return innerExpression; + } + ts.recreateOuterExpressions = recreateOuterExpressions; function startOnNewLine(node) { node.startsOnNewLine = true; return node; @@ -14572,23 +48871,33 @@ var ts; return emitNode && emitNode.externalHelpersModuleName; } ts.getExternalHelpersModuleName = getExternalHelpersModuleName; - function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions) { - if (compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues) { + if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { var externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } - var helpers = ts.getEmitHelpers(node); - if (helpers) { - for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { - var helper = helpers_2[_i]; - if (!helper.scoped) { - var parseNode = ts.getOriginalNode(node, ts.isSourceFile); - var emitNode = ts.getOrCreateEmitNode(parseNode); - return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var create = hasExportStarsToExportValues + && moduleKind !== ts.ModuleKind.System + && moduleKind !== ts.ModuleKind.ES2015; + if (!create) { + var helpers = ts.getEmitHelpers(node); + if (helpers) { + for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) { + var helper = helpers_2[_i]; + if (!helper.scoped) { + create = true; + break; + } } } } + if (create) { + var parseNode = ts.getOriginalNode(node, ts.isSourceFile); + var emitNode = ts.getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText)); + } } } ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded; @@ -14691,7 +49000,7 @@ var ts; // `1` in `[[a] = 1] = ...` return bindingElement.right; } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { // Recovery consistent with existing emit. return getInitializerOfBindingOrAssignmentElement(bindingElement.expression); } @@ -14753,7 +49062,7 @@ var ts; // `a[0]` in `[a[0] = 1] = ...` return getTargetOfBindingOrAssignmentElement(bindingElement.left); } - if (ts.isSpreadExpression(bindingElement)) { + if (ts.isSpreadElement(bindingElement)) { // `a` in `[...a] = ...` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -14908,33246 +49217,6 @@ var ts; return node; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; - function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { - var externalImports = []; - var exportSpecifiers = ts.createMultiMap(); - var exportedBindings = []; - var uniqueExports = ts.createMap(); - var exportedNames; - var hasExportDefault = false; - var exportEquals = undefined; - var hasExportStarsToExportValues = false; - var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions); - var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); - if (externalHelpersImportDeclaration) { - externalImports.push(externalHelpersImportDeclaration); - } - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 238 /* ImportDeclaration */: - // import "mod" - // import x from "mod" - // import * as x from "mod" - // import { x, y } from "mod" - externalImports.push(node); - break; - case 237 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { - // import x = require("mod") - externalImports.push(node); - } - break; - case 244 /* ExportDeclaration */: - if (node.moduleSpecifier) { - if (!node.exportClause) { - // export * from "mod" - externalImports.push(node); - hasExportStarsToExportValues = true; - } - else { - // export { x, y } from "mod" - externalImports.push(node); - } - } - else { - // export { x, y } - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - if (!uniqueExports.get(specifier.name.text)) { - var name = specifier.propertyName || specifier.name; - exportSpecifiers.add(name.text, specifier); - var decl = resolver.getReferencedImportDeclaration(name) - || resolver.getReferencedValueDeclaration(name); - if (decl) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(decl), specifier.name); - } - uniqueExports.set(specifier.name.text, true); - exportedNames = ts.append(exportedNames, specifier.name); - } - } - } - break; - case 243 /* ExportAssignment */: - if (node.isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; - case 208 /* VariableStatement */: - if (ts.hasModifier(node, 1 /* Export */)) { - for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { - var decl = _e[_d]; - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); - } - } - break; - case 228 /* FunctionDeclaration */: - if (ts.hasModifier(node, 1 /* Export */)) { - if (ts.hasModifier(node, 512 /* Default */)) { - // export default function() { } - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - // export function x() { } - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - case 229 /* ClassDeclaration */: - if (ts.hasModifier(node, 1 /* Export */)) { - if (ts.hasModifier(node, 512 /* Default */)) { - // export default class { } - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), getDeclarationName(node)); - hasExportDefault = true; - } - } - else { - // export class x { } - var name = node.name; - if (!uniqueExports.get(name.text)) { - multiMapSparseArrayAdd(exportedBindings, ts.getOriginalNodeId(node), name); - uniqueExports.set(name.text, true); - exportedNames = ts.append(exportedNames, name); - } - } - } - break; - } - } - return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; - } - ts.collectExternalModuleInfo = collectExternalModuleInfo; - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { - if (ts.isBindingPattern(decl.name)) { - for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); - } - } - } - else if (!ts.isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(decl.name.text)) { - uniqueExports.set(decl.name.text, true); - exportedNames = ts.append(exportedNames, decl.name); - } - } - return exportedNames; - } - /** Use a sparse array as a multi-map. */ - function multiMapSparseArrayAdd(map, key, value) { - var values = map[key]; - if (values) { - values.push(value); - } - else { - map[key] = values = [value]; - } - return values; - } -})(ts || (ts = {})); -/// -/// -/// -var ts; -(function (ts) { - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - function createNode(kind, pos, end) { - if (kind === 265 /* SourceFile */) { - return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); - } - else if (kind === 71 /* Identifier */) { - return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); - } - else if (kind < 143 /* FirstNode */) { - return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); - } - else { - return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); - } - } - ts.createNode = createNode; - function visitNode(cbNode, node) { - if (node) { - return cbNode(node); - } - } - function visitNodeArray(cbNodes, nodes) { - if (nodes) { - return cbNodes(nodes); - } - } - function visitEachNode(cbNode, nodes) { - if (nodes) { - for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { - var node = nodes_1[_i]; - var result = cbNode(node); - if (result) { - return result; - } - } - } - } - // Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes - // stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, - // embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns - // a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned. - function forEachChild(node, cbNode, cbNodeArray) { - 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. - var visitNodes = cbNodeArray ? visitNodeArray : visitEachNode; - var cbNodes = cbNodeArray || cbNode; - switch (node.kind) { - case 143 /* QualifiedName */: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); - case 145 /* TypeParameter */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.constraint) || - visitNode(cbNode, node.default) || - visitNode(cbNode, node.expression); - case 262 /* ShorthandPropertyAssignment */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.equalsToken) || - visitNode(cbNode, node.objectAssignmentInitializer); - case 263 /* SpreadAssignment */: - return visitNode(cbNode, node.expression); - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 261 /* PropertyAssignment */: - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.questionToken) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type) || - visitNode(cbNode, node.equalsGreaterThanToken) || - visitNode(cbNode, node.body); - case 159 /* TypeReference */: - return visitNode(cbNode, node.typeName) || - visitNodes(cbNodes, node.typeArguments); - case 158 /* TypePredicate */: - return visitNode(cbNode, node.parameterName) || - visitNode(cbNode, node.type); - case 162 /* TypeQuery */: - return visitNode(cbNode, node.exprName); - case 163 /* TypeLiteral */: - return visitNodes(cbNodes, node.members); - case 164 /* ArrayType */: - return visitNode(cbNode, node.elementType); - case 165 /* TupleType */: - return visitNodes(cbNodes, node.elementTypes); - case 166 /* UnionType */: - case 167 /* IntersectionType */: - return visitNodes(cbNodes, node.types); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: - return visitNode(cbNode, node.type); - case 171 /* IndexedAccessType */: - return visitNode(cbNode, node.objectType) || - visitNode(cbNode, node.indexType); - case 172 /* MappedType */: - return visitNode(cbNode, node.readonlyToken) || - visitNode(cbNode, node.typeParameter) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); - case 173 /* LiteralType */: - return visitNode(cbNode, node.literal); - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: - return visitNodes(cbNodes, node.elements); - case 177 /* ArrayLiteralExpression */: - return visitNodes(cbNodes, node.elements); - case 178 /* ObjectLiteralExpression */: - return visitNodes(cbNodes, node.properties); - case 179 /* PropertyAccessExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.name); - case 180 /* ElementAccessExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.argumentExpression); - case 181 /* CallExpression */: - case 182 /* NewExpression */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments) || - visitNodes(cbNodes, node.arguments); - case 183 /* TaggedTemplateExpression */: - return visitNode(cbNode, node.tag) || - visitNode(cbNode, node.template); - case 184 /* TypeAssertionExpression */: - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.expression); - case 185 /* ParenthesizedExpression */: - return visitNode(cbNode, node.expression); - case 188 /* DeleteExpression */: - return visitNode(cbNode, node.expression); - case 189 /* TypeOfExpression */: - return visitNode(cbNode, node.expression); - case 190 /* VoidExpression */: - return visitNode(cbNode, node.expression); - case 192 /* PrefixUnaryExpression */: - return visitNode(cbNode, node.operand); - case 197 /* YieldExpression */: - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); - case 191 /* AwaitExpression */: - return visitNode(cbNode, node.expression); - case 193 /* PostfixUnaryExpression */: - return visitNode(cbNode, node.operand); - case 194 /* BinaryExpression */: - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.operatorToken) || - visitNode(cbNode, node.right); - case 202 /* AsExpression */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.type); - case 203 /* NonNullExpression */: - return visitNode(cbNode, node.expression); - case 204 /* MetaProperty */: - return visitNode(cbNode, node.name); - case 195 /* ConditionalExpression */: - return visitNode(cbNode, node.condition) || - visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.whenTrue) || - visitNode(cbNode, node.colonToken) || - visitNode(cbNode, node.whenFalse); - case 198 /* SpreadElement */: - return visitNode(cbNode, node.expression); - case 207 /* Block */: - case 234 /* ModuleBlock */: - return visitNodes(cbNodes, node.statements); - case 265 /* SourceFile */: - return visitNodes(cbNodes, node.statements) || - visitNode(cbNode, node.endOfFileToken); - case 208 /* VariableStatement */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.declarationList); - case 227 /* VariableDeclarationList */: - return visitNodes(cbNodes, node.declarations); - case 210 /* ExpressionStatement */: - return visitNode(cbNode, node.expression); - case 211 /* IfStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.thenStatement) || - visitNode(cbNode, node.elseStatement); - case 212 /* DoStatement */: - return visitNode(cbNode, node.statement) || - visitNode(cbNode, node.expression); - case 213 /* WhileStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 214 /* ForStatement */: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.condition) || - visitNode(cbNode, node.incrementor) || - visitNode(cbNode, node.statement); - case 215 /* ForInStatement */: - return visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 216 /* ForOfStatement */: - return visitNode(cbNode, node.awaitModifier) || - visitNode(cbNode, node.initializer) || - visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: - return visitNode(cbNode, node.label); - case 219 /* ReturnStatement */: - return visitNode(cbNode, node.expression); - case 220 /* WithStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); - case 221 /* SwitchStatement */: - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); - case 235 /* CaseBlock */: - return visitNodes(cbNodes, node.clauses); - case 257 /* CaseClause */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.statements); - case 258 /* DefaultClause */: - return visitNodes(cbNodes, node.statements); - case 222 /* LabeledStatement */: - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); - case 223 /* ThrowStatement */: - return visitNode(cbNode, node.expression); - case 224 /* TryStatement */: - return visitNode(cbNode, node.tryBlock) || - visitNode(cbNode, node.catchClause) || - visitNode(cbNode, node.finallyBlock); - case 260 /* CatchClause */: - return visitNode(cbNode, node.variableDeclaration) || - visitNode(cbNode, node.block); - case 147 /* Decorator */: - return visitNode(cbNode, node.expression); - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 230 /* InterfaceDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNodes(cbNodes, node.heritageClauses) || - visitNodes(cbNodes, node.members); - case 231 /* TypeAliasDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); - case 232 /* EnumDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.members); - case 264 /* EnumMember */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 233 /* ModuleDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); - case 237 /* ImportEqualsDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); - case 238 /* ImportDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.importClause) || - visitNode(cbNode, node.moduleSpecifier); - case 239 /* ImportClause */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.namedBindings); - case 236 /* NamespaceExportDeclaration */: - return visitNode(cbNode, node.name); - case 240 /* NamespaceImport */: - return visitNode(cbNode, node.name); - case 241 /* NamedImports */: - case 245 /* NamedExports */: - return visitNodes(cbNodes, node.elements); - case 244 /* ExportDeclaration */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.exportClause) || - visitNode(cbNode, node.moduleSpecifier); - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: - return visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name); - case 243 /* ExportAssignment */: - return visitNodes(cbNodes, node.decorators) || - visitNodes(cbNodes, node.modifiers) || - visitNode(cbNode, node.expression); - case 196 /* TemplateExpression */: - return visitNode(cbNode, node.head) || visitNodes(cbNodes, node.templateSpans); - case 205 /* TemplateSpan */: - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 144 /* ComputedPropertyName */: - return visitNode(cbNode, node.expression); - case 259 /* HeritageClause */: - return visitNodes(cbNodes, node.types); - case 201 /* ExpressionWithTypeArguments */: - return visitNode(cbNode, node.expression) || - visitNodes(cbNodes, node.typeArguments); - case 248 /* ExternalModuleReference */: - 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) || - visitNode(cbNode, node.closingElement); - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: - return visitNode(cbNode, node.tagName) || - visitNode(cbNode, node.attributes); - case 254 /* JsxAttributes */: - return visitNodes(cbNodes, node.properties); - case 253 /* JsxAttribute */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); - case 255 /* JsxSpreadAttribute */: - return visitNode(cbNode, node.expression); - case 256 /* JsxExpression */: - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.expression); - case 252 /* JsxClosingElement */: - return visitNode(cbNode, node.tagName); - case 267 /* JSDocTypeExpression */: - return visitNode(cbNode, node.type); - case 271 /* JSDocUnionType */: - return visitNodes(cbNodes, node.types); - case 272 /* JSDocTupleType */: - return visitNodes(cbNodes, node.types); - case 270 /* JSDocArrayType */: - return visitNode(cbNode, node.elementType); - case 274 /* JSDocNonNullableType */: - return visitNode(cbNode, node.type); - case 273 /* JSDocNullableType */: - return visitNode(cbNode, node.type); - case 275 /* JSDocRecordType */: - return visitNode(cbNode, node.literal); - case 277 /* JSDocTypeReference */: - return visitNode(cbNode, node.name) || - visitNodes(cbNodes, node.typeArguments); - case 278 /* JSDocOptionalType */: - return visitNode(cbNode, node.type); - case 279 /* JSDocFunctionType */: - return visitNodes(cbNodes, node.parameters) || - visitNode(cbNode, node.type); - case 280 /* JSDocVariadicType */: - return visitNode(cbNode, node.type); - case 281 /* JSDocConstructorType */: - return visitNode(cbNode, node.type); - case 282 /* JSDocThisType */: - return visitNode(cbNode, node.type); - case 276 /* JSDocRecordMember */: - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.type); - case 283 /* JSDocComment */: - return visitNodes(cbNodes, node.tags); - case 286 /* JSDocParameterTag */: - return visitNode(cbNode, node.preParameterName) || - visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.postParameterName); - case 287 /* JSDocReturnTag */: - return visitNode(cbNode, node.typeExpression); - case 288 /* JSDocTypeTag */: - return visitNode(cbNode, node.typeExpression); - case 285 /* JSDocAugmentsTag */: - return visitNode(cbNode, node.typeExpression); - case 289 /* JSDocTemplateTag */: - return visitNodes(cbNodes, node.typeParameters); - case 290 /* JSDocTypedefTag */: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.fullName) || - visitNode(cbNode, node.name) || - visitNode(cbNode, node.jsDocTypeLiteral); - case 292 /* JSDocTypeLiteral */: - return visitNodes(cbNodes, node.jsDocPropertyTags); - case 291 /* JSDocPropertyTag */: - return visitNode(cbNode, node.typeExpression) || - visitNode(cbNode, node.name); - case 296 /* PartiallyEmittedExpression */: - return visitNode(cbNode, node.expression); - case 293 /* JSDocLiteralType */: - return visitNode(cbNode, node.literal); - } - } - ts.forEachChild = forEachChild; - function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { - if (setParentNodes === void 0) { setParentNodes = false; } - ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); - ts.performance.mark("afterParse"); - ts.performance.measure("Parse", "beforeParse", "afterParse"); - return result; - } - ts.createSourceFile = createSourceFile; - function parseIsolatedEntityName(text, languageVersion) { - return Parser.parseIsolatedEntityName(text, languageVersion); - } - ts.parseIsolatedEntityName = parseIsolatedEntityName; - // See also `isExternalOrCommonJsModule` in utilities.ts - function isExternalModule(file) { - return file.externalModuleIndicator !== undefined; - } - ts.isExternalModule = isExternalModule; - // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter - // indicates what changed between the 'text' that this SourceFile has and the 'newText'. - // The SourceFile will be created with the compiler attempting to reuse as many nodes from - // this file as possible. - // - // Note: this function mutates nodes from this SourceFile. That means any existing nodes - // from this SourceFile that are being held onto may change as a result (including - // becoming detached from any SourceFile). It is recommended that this SourceFile not - // be used once 'update' is called on it. - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - return IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); - } - ts.updateSourceFile = updateSourceFile; - /* @internal */ - function parseIsolatedJSDocComment(content, start, length) { - var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); - if (result && result.jsDoc) { - // because the jsDocComment was parsed out of the source file, it might - // not be covered by the fixupParentReferences. - Parser.fixupParentReferences(result.jsDoc); - } - return result; - } - ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - /* @internal */ - // Exposed only for testing. - function parseJSDocTypeExpressionForTests(content, start, length) { - return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); - } - ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; - // Implement the parser as a singleton module. We do this for perf reasons because creating - // parser instances can actually be expensive enough to impact us on projects with many source - // files. - var Parser; - (function (Parser) { - // Share a single scanner across all calls to parse a source file. This helps speed things - // up by avoiding the cost of creating/compiling scanners over and over again. - var scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); - var disallowInAndDecoratorContext = 2048 /* DisallowInContext */ | 8192 /* DecoratorContext */; - // capture constructors in 'initializeState' to avoid null checks - var NodeConstructor; - var TokenConstructor; - var IdentifierConstructor; - var SourceFileConstructor; - var sourceFile; - var parseDiagnostics; - var syntaxCursor; - var currentToken; - var sourceText; - var nodeCount; - var identifiers; - var identifierCount; - var parsingContext; - // Flags that dictate what parsing context we're in. For example: - // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is - // that some tokens that would be considered identifiers may be considered keywords. - // - // When adding more parser context flags, consider which is the more common case that the - // flag will be in. This should be the 'false' state for that flag. The reason for this is - // that we don't store data in our nodes unless the value is in the *non-default* state. So, - // for example, more often than code 'allows-in' (or doesn't 'disallow-in'). We opt for - // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost - // all nodes would need extra state on them to store this info. - // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 - // grammar specification. - // - // An important thing about these context concepts. By default they are effectively inherited - // while parsing through every grammar production. i.e. if you don't change them, then when - // you parse a sub-production, it will have the same context values as the parent production. - // This is great most of the time. After all, consider all the 'expression' grammar productions - // and how nearly all of them pass along the 'in' and 'yield' context values: - // - // EqualityExpression[In, Yield] : - // RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield] - // EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield] - // - // Where you have to be careful is then understanding what the points are in the grammar - // where the values are *not* passed along. For example: - // - // SingleNameBinding[Yield,GeneratorParameter] - // [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt - // [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt - // - // Here this is saying that if the GeneratorParameter context flag is set, that we should - // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier - // and we should explicitly unset the 'yield' context flag before calling into the Initializer. - // production. Conversely, if the GeneratorParameter context flag is not set, then we - // should leave the 'yield' context flag alone. - // - // Getting this all correct is tricky and requires careful reading of the grammar to - // understand when these values should be changed versus when they should be inherited. - // - // Note: it should not be necessary to save/restore these flags during speculative/lookahead - // parsing. These context flags are naturally stored and restored through normal recursive - // descent parsing and unwinding. - var contextFlags; - // Whether or not we've had a parse error since creating the last AST node. If we have - // encountered an error, it will be stored on the next AST node we create. Parse errors - // can be broken down into three categories: - // - // 1) An error that occurred during scanning. For example, an unterminated literal, or a - // character that was completely not understood. - // - // 2) A token was expected, but was not present. This type of error is commonly produced - // by the 'parseExpected' function. - // - // 3) A token was present that no parsing function was able to consume. This type of error - // only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser - // decides to skip the token. - // - // In all of these cases, we want to mark the next node as having had an error before it. - // With this mark, we can know in incremental settings if this node can be reused, or if - // we have to reparse it. If we don't keep this information around, we may just reuse the - // node. in that event we would then not produce the same errors as we did before, causing - // significant confusion problems. - // - // Note: it is necessary that this value be saved/restored during speculative/lookahead - // parsing. During lookahead parsing, we will often create a node. That node will have - // this value attached, and then this value will be set back to 'false'. If we decide to - // rewind, we must get back to the same value we had prior to the lookahead. - // - // Note: any errors at the end of the file that do not precede a regular node, should get - // attached to the EOF token. - var parseErrorBeforeNextFinishedNode = false; - function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { - scriptKind = ts.ensureScriptKind(fileName, scriptKind); - initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); - var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); - clearState(); - return result; - } - Parser.parseSourceFile = parseSourceFile; - function parseIsolatedEntityName(content, languageVersion) { - initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */); - // Prime the scanner. - nextToken(); - var entityName = parseEntityName(/*allowReservedWords*/ true); - var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length; - clearState(); - return isInvalid ? entityName : undefined; - } - Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function getLanguageVariant(scriptKind) { - // .tsx and .jsx files are treated as jsx language variant. - return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ ? 1 /* JSX */ : 0 /* Standard */; - } - function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { - NodeConstructor = ts.objectAllocator.getNodeConstructor(); - TokenConstructor = ts.objectAllocator.getTokenConstructor(); - IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); - SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); - sourceText = _sourceText; - syntaxCursor = _syntaxCursor; - parseDiagnostics = []; - parsingContext = 0; - identifiers = ts.createMap(); - identifierCount = 0; - nodeCount = 0; - contextFlags = scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */ ? 65536 /* JavaScriptFile */ : 0 /* None */; - parseErrorBeforeNextFinishedNode = false; - // Initialize and prime the scanner before parsing the source elements. - scanner.setText(sourceText); - scanner.setOnError(scanError); - scanner.setScriptTarget(languageVersion); - scanner.setLanguageVariant(getLanguageVariant(scriptKind)); - } - function clearState() { - // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily. - scanner.setText(""); - scanner.setOnError(undefined); - // Clear any data. We don't want to accidentally hold onto it for too long. - parseDiagnostics = undefined; - sourceFile = undefined; - identifiers = undefined; - syntaxCursor = undefined; - sourceText = undefined; - } - function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { - sourceFile = createSourceFile(fileName, languageVersion, scriptKind); - sourceFile.flags = contextFlags; - // Prime the scanner. - nextToken(); - processReferenceComments(sourceFile); - sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); - ts.Debug.assert(token() === 1 /* EndOfFileToken */); - sourceFile.endOfFileToken = parseTokenNode(); - setExternalModuleIndicator(sourceFile); - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.identifiers = identifiers; - sourceFile.parseDiagnostics = parseDiagnostics; - if (setParentNodes) { - fixupParentReferences(sourceFile); - } - return sourceFile; - } - function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); - if (!jsDoc) { - continue; - } - if (!node.jsDoc) { - node.jsDoc = []; - } - node.jsDoc.push(jsDoc); - } - } - return node; - } - function fixupParentReferences(rootNode) { - // normally parent references are set during binding. However, for clients that only need - // a syntax tree, and no semantic features, then the binding process is an unnecessary - // overhead. This functions allows us to set all the parents, without all the expense of - // binding. - var parent = rootNode; - forEachChild(rootNode, visitNode); - return; - function visitNode(n) { - // walk down setting parents that differ from the parent we think it should be. This - // allows us to quickly bail out of setting parents for subtrees during incremental - // parsing - if (n.parent !== parent) { - n.parent = parent; - var saveParent = parent; - parent = n; - forEachChild(n, visitNode); - if (n.jsDoc) { - for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - jsDoc.parent = n; - parent = jsDoc; - forEachChild(jsDoc, visitNode); - } - } - parent = saveParent; - } - } - } - Parser.fixupParentReferences = fixupParentReferences; - function createSourceFile(fileName, languageVersion, scriptKind) { - // code from createNode is inlined here so createNode won't have to deal with special case of creating source files - // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(265 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); - nodeCount++; - sourceFile.text = sourceText; - sourceFile.bindDiagnostics = []; - sourceFile.languageVersion = languageVersion; - sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.languageVariant = getLanguageVariant(scriptKind); - sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); - sourceFile.scriptKind = scriptKind; - return sourceFile; - } - function setContextFlag(val, flag) { - if (val) { - contextFlags |= flag; - } - else { - contextFlags &= ~flag; - } - } - function setDisallowInContext(val) { - setContextFlag(val, 2048 /* DisallowInContext */); - } - function setYieldContext(val) { - setContextFlag(val, 4096 /* YieldContext */); - } - function setDecoratorContext(val) { - setContextFlag(val, 8192 /* DecoratorContext */); - } - function setAwaitContext(val) { - setContextFlag(val, 16384 /* AwaitContext */); - } - function doOutsideOfContext(context, func) { - // contextFlagsToClear will contain only the context flags that are - // currently set that we need to temporarily clear - // We don't just blindly reset to the previous flags to ensure - // that we do not mutate cached flags for the incremental - // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and - // HasAggregatedChildData). - var contextFlagsToClear = context & contextFlags; - if (contextFlagsToClear) { - // clear the requested context flags - setContextFlag(/*val*/ false, contextFlagsToClear); - var result = func(); - // restore the context flags we just cleared - setContextFlag(/*val*/ true, contextFlagsToClear); - return result; - } - // no need to do anything special as we are not in any of the requested contexts - return func(); - } - function doInsideOfContext(context, func) { - // contextFlagsToSet will contain only the context flags that - // are not currently set that we need to temporarily enable. - // We don't just blindly reset to the previous flags to ensure - // that we do not mutate cached flags for the incremental - // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and - // HasAggregatedChildData). - var contextFlagsToSet = context & ~contextFlags; - if (contextFlagsToSet) { - // set the requested context flags - setContextFlag(/*val*/ true, contextFlagsToSet); - var result = func(); - // reset the context flags we just set - setContextFlag(/*val*/ false, contextFlagsToSet); - return result; - } - // no need to do anything special as we are already in all of the requested contexts - return func(); - } - function allowInAnd(func) { - return doOutsideOfContext(2048 /* DisallowInContext */, func); - } - function disallowInAnd(func) { - return doInsideOfContext(2048 /* DisallowInContext */, func); - } - function doInYieldContext(func) { - return doInsideOfContext(4096 /* YieldContext */, func); - } - function doInDecoratorContext(func) { - return doInsideOfContext(8192 /* DecoratorContext */, func); - } - function doInAwaitContext(func) { - return doInsideOfContext(16384 /* AwaitContext */, func); - } - function doOutsideOfAwaitContext(func) { - return doOutsideOfContext(16384 /* AwaitContext */, func); - } - function doInYieldAndAwaitContext(func) { - return doInsideOfContext(4096 /* YieldContext */ | 16384 /* AwaitContext */, func); - } - function inContext(flags) { - return (contextFlags & flags) !== 0; - } - function inYieldContext() { - return inContext(4096 /* YieldContext */); - } - function inDisallowInContext() { - return inContext(2048 /* DisallowInContext */); - } - function inDecoratorContext() { - return inContext(8192 /* DecoratorContext */); - } - function inAwaitContext() { - return inContext(16384 /* AwaitContext */); - } - function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); - } - function parseErrorAtPosition(start, length, message, arg0) { - // Don't report another error if it would just be at the same position as the last error. - var lastError = ts.lastOrUndefined(parseDiagnostics); - if (!lastError || start !== lastError.start) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); - } - // Mark that we've encountered an error. We'll set an appropriate bit on the next - // node we finish so that it can't be reused incrementally. - parseErrorBeforeNextFinishedNode = true; - } - function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); - } - function getNodePos() { - return scanner.getStartPos(); - } - function getNodeEnd() { - return scanner.getStartPos(); - } - // Use this function to access the current token instead of reading the currentToken - // variable. Since function results aren't narrowed in control flow analysis, this ensures - // that the type checker doesn't make wrong assumptions about the type of the current - // token (e.g. a call to nextToken() changes the current token but the checker doesn't - // reason about this side effect). Mainstream VMs inline simple functions like this, so - // there is no performance penalty. - function token() { - return currentToken; - } - function nextToken() { - return currentToken = scanner.scan(); - } - function reScanGreaterToken() { - return currentToken = scanner.reScanGreaterToken(); - } - function reScanSlashToken() { - return currentToken = scanner.reScanSlashToken(); - } - function reScanTemplateToken() { - return currentToken = scanner.reScanTemplateToken(); - } - function scanJsxIdentifier() { - return currentToken = scanner.scanJsxIdentifier(); - } - function scanJsxText() { - return currentToken = scanner.scanJsxToken(); - } - function scanJsxAttributeValue() { - return currentToken = scanner.scanJsxAttributeValue(); - } - function speculationHelper(callback, isLookAhead) { - // Keep track of the state we'll need to rollback to if lookahead fails (or if the - // caller asked us to always reset our state). - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - // Note: it is not actually necessary to save/restore the context flags here. That's - // because the saving/restoring of these flags happens naturally through the recursive - // descent nature of our parser. However, we still store this here just so we can - // assert that invariant holds. - var saveContextFlags = contextFlags; - // If we're only looking ahead, then tell the scanner to only lookahead as well. - // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the - // same. - var result = isLookAhead - ? scanner.lookAhead(callback) - : scanner.tryScan(callback); - ts.Debug.assert(saveContextFlags === contextFlags); - // If our callback returned something 'falsy' or we're just looking ahead, - // then unconditionally restore us to where we were. - if (!result || isLookAhead) { - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - } - return result; - } - /** Invokes the provided callback then unconditionally restores the parser to the state it - * was in immediately prior to invoking the callback. The result of invoking the callback - * is returned from this function. - */ - function lookAhead(callback) { - return speculationHelper(callback, /*isLookAhead*/ true); - } - /** Invokes the provided callback. If the callback returns something falsy, then it restores - * the parser to the state it was in immediately prior to invoking the callback. If the - * callback returns something truthy, then the parser state is not rolled back. The result - * of invoking the callback is returned from this function. - */ - function tryParse(callback) { - return speculationHelper(callback, /*isLookAhead*/ false); - } - // Ignore strict mode flag because we will report an error in type checker instead. - function isIdentifier() { - if (token() === 71 /* Identifier */) { - return true; - } - // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is - // considered a keyword and is not an identifier. - if (token() === 116 /* YieldKeyword */ && inYieldContext()) { - return false; - } - // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is - // considered a keyword and is not an identifier. - if (token() === 121 /* AwaitKeyword */ && inAwaitContext()) { - return false; - } - return token() > 107 /* LastReservedWord */; - } - function parseExpected(kind, diagnosticMessage, shouldAdvance) { - if (shouldAdvance === void 0) { shouldAdvance = true; } - if (token() === kind) { - if (shouldAdvance) { - nextToken(); - } - return true; - } - // Report specific message if provided with one. Otherwise, report generic fallback message. - if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage); - } - else { - parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); - } - return false; - } - function parseOptional(t) { - if (token() === t) { - nextToken(); - return true; - } - return false; - } - function parseOptionalToken(t) { - if (token() === t) { - return parseTokenNode(); - } - return undefined; - } - function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { - return parseOptionalToken(t) || - createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); - } - function parseTokenNode() { - var node = createNode(token()); - nextToken(); - return finishNode(node); - } - function canParseSemicolon() { - // If there's a real semicolon, then we can always parse it out. - if (token() === 25 /* SemicolonToken */) { - return true; - } - // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === 18 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); - } - function parseSemicolon() { - if (canParseSemicolon()) { - if (token() === 25 /* SemicolonToken */) { - // consume the semicolon if it was explicitly provided. - nextToken(); - } - return true; - } - else { - return parseExpected(25 /* SemicolonToken */); - } - } - // note: this function creates only node - function createNode(kind, pos) { - nodeCount++; - if (!(pos >= 0)) { - pos = scanner.getStartPos(); - } - return kind >= 143 /* FirstNode */ ? new NodeConstructor(kind, pos, pos) : - kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, pos, pos) : - new TokenConstructor(kind, pos, pos); - } - function createNodeArray(elements, pos) { - var array = (elements || []); - if (!(pos >= 0)) { - pos = getNodePos(); - } - array.pos = pos; - array.end = pos; - return array; - } - function finishNode(node, end) { - node.end = end === undefined ? scanner.getStartPos() : end; - if (contextFlags) { - node.flags |= contextFlags; - } - // Keep track on the node if we encountered an error while parsing it. If we did, then - // we cannot reuse the node incrementally. Once we've marked this node, clear out the - // flag so that we don't mark any subsequent nodes. - if (parseErrorBeforeNextFinishedNode) { - parseErrorBeforeNextFinishedNode = false; - node.flags |= 32768 /* ThisNodeHasError */; - } - return node; - } - function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { - if (reportAtCurrentPosition) { - parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); - } - else { - parseErrorAtCurrentToken(diagnosticMessage, arg0); - } - var result = createNode(kind, scanner.getStartPos()); - result.text = ""; - return finishNode(result); - } - function internIdentifier(text) { - text = ts.escapeIdentifier(text); - var identifier = identifiers.get(text); - if (identifier === undefined) { - identifiers.set(text, identifier = text); - } - return identifier; - } - // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues - // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for - // each identifier in order to reduce memory consumption. - function createIdentifier(isIdentifier, diagnosticMessage) { - identifierCount++; - if (isIdentifier) { - var node = createNode(71 /* Identifier */); - // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker - if (token() !== 71 /* Identifier */) { - node.originalKeywordKind = token(); - } - node.text = internIdentifier(scanner.getTokenValue()); - nextToken(); - return finishNode(node); - } - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics.Identifier_expected); - } - function parseIdentifier(diagnosticMessage) { - return createIdentifier(isIdentifier(), diagnosticMessage); - } - function parseIdentifierName() { - return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function isLiteralPropertyName() { - return ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */; - } - function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */) { - return parseLiteralNode(/*internName*/ true); - } - if (allowComputedPropertyNames && token() === 21 /* OpenBracketToken */) { - return parseComputedPropertyName(); - } - return parseIdentifierName(); - } - function parsePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true); - } - function parseSimplePropertyName() { - return parsePropertyNameWorker(/*allowComputedPropertyNames*/ false); - } - function isSimplePropertyName() { - return token() === 9 /* StringLiteral */ || token() === 8 /* NumericLiteral */ || ts.tokenIsIdentifierOrKeyword(token()); - } - function parseComputedPropertyName() { - // PropertyName [Yield]: - // LiteralPropertyName - // ComputedPropertyName[?Yield] - var node = createNode(144 /* ComputedPropertyName */); - parseExpected(21 /* OpenBracketToken */); - // We parse any expression (including a comma expression). But the grammar - // says that only an assignment expression is allowed, so the grammar checker - // will error if it sees a comma expression. - node.expression = allowInAnd(parseExpression); - parseExpected(22 /* CloseBracketToken */); - return finishNode(node); - } - function parseContextualModifier(t) { - return token() === t && tryParse(nextTokenCanFollowModifier); - } - function nextTokenIsOnSameLineAndCanFollowModifier() { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return false; - } - return canFollowModifier(); - } - function nextTokenCanFollowModifier() { - if (token() === 76 /* ConstKeyword */) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; - } - if (token() === 84 /* ExportKeyword */) { - nextToken(); - if (token() === 79 /* DefaultKeyword */) { - return lookAhead(nextTokenIsClassOrFunctionOrAsync); - } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - } - if (token() === 79 /* DefaultKeyword */) { - return nextTokenIsClassOrFunctionOrAsync(); - } - if (token() === 115 /* StaticKeyword */) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); - } - function parseAnyContextualModifier() { - return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); - } - function canFollowModifier() { - return token() === 21 /* OpenBracketToken */ - || token() === 17 /* OpenBraceToken */ - || token() === 39 /* AsteriskToken */ - || token() === 24 /* DotDotDotToken */ - || isLiteralPropertyName(); - } - function nextTokenIsClassOrFunctionOrAsync() { - nextToken(); - return token() === 75 /* ClassKeyword */ || token() === 89 /* FunctionKeyword */ || - (token() === 117 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) || - (token() === 120 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); - } - // True if positioned at the start of a list element - function isListElement(parsingContext, inErrorRecovery) { - var node = currentNode(parsingContext); - if (node) { - return true; - } - switch (parsingContext) { - case 0 /* SourceElements */: - case 1 /* BlockStatements */: - case 3 /* SwitchClauseStatements */: - // If we're in error recovery, then we don't want to treat ';' as an empty statement. - // The problem is that ';' can show up in far too many contexts, and if we see one - // and assume it's a statement, then we may bail out inappropriately from whatever - // we're parsing. For example, if we have a semicolon in the middle of a class, then - // we really don't want to assume the class is over and we're on a statement in the - // outer module. We just want to consume and move on. - return !(token() === 25 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement(); - case 2 /* SwitchClauses */: - return token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; - case 4 /* TypeMembers */: - return lookAhead(isTypeMemberStart); - case 5 /* ClassMembers */: - // We allow semicolons as class elements (as specified by ES6) as long as we're - // not in error recovery. If we're in error recovery, we don't want an errant - // semicolon to be treated as a class member (since they're almost always used - // for statements. - return lookAhead(isClassMemberStart) || (token() === 25 /* SemicolonToken */ && !inErrorRecovery); - case 6 /* EnumMembers */: - // Include open bracket computed properties. This technically also lets in indexers, - // which would be a candidate for improved error reporting. - return token() === 21 /* OpenBracketToken */ || isLiteralPropertyName(); - case 12 /* ObjectLiteralMembers */: - return token() === 21 /* OpenBracketToken */ || token() === 39 /* AsteriskToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 17 /* RestProperties */: - return isLiteralPropertyName(); - case 9 /* ObjectBindingElements */: - return token() === 21 /* OpenBracketToken */ || token() === 24 /* DotDotDotToken */ || isLiteralPropertyName(); - case 7 /* HeritageClauseElement */: - // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{` - // That way we won't consume the body of a class in its heritage clause. - if (token() === 17 /* OpenBraceToken */) { - return lookAhead(isValidHeritageClauseObjectLiteral); - } - if (!inErrorRecovery) { - return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - else { - // If we're in error recovery we tighten up what we're willing to match. - // That way we don't treat something like "this" as a valid heritage clause - // element during recovery. - return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); - } - case 8 /* VariableDeclarations */: - return isIdentifierOrPattern(); - case 10 /* ArrayBindingElements */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); - case 18 /* TypeParameters */: - return isIdentifier(); - case 11 /* ArgumentExpressions */: - case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); - case 16 /* Parameters */: - return isStartOfParameter(); - case 19 /* TypeArguments */: - case 20 /* TupleElementTypes */: - return token() === 26 /* CommaToken */ || isStartOfType(); - case 21 /* HeritageClauses */: - return isHeritageClause(); - case 22 /* ImportOrExportSpecifiers */: - return ts.tokenIsIdentifierOrKeyword(token()); - case 13 /* JsxAttributes */: - return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17 /* OpenBraceToken */; - case 14 /* JsxChildren */: - return true; - case 23 /* JSDocFunctionParameters */: - case 24 /* JSDocTypeArguments */: - case 26 /* JSDocTupleTypes */: - return JSDocParser.isJSDocType(); - case 25 /* JSDocRecordMembers */: - return isSimplePropertyName(); - } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); - } - function isValidHeritageClauseObjectLiteral() { - ts.Debug.assert(token() === 17 /* OpenBraceToken */); - if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not - // the class body) if we have: - // - // extends {} { - // extends {}, - // extends {} extends - // extends {} implements - var next = nextToken(); - return next === 26 /* CommaToken */ || next === 17 /* OpenBraceToken */ || next === 85 /* ExtendsKeyword */ || next === 108 /* ImplementsKeyword */; - } - return true; - } - function nextTokenIsIdentifier() { - nextToken(); - return isIdentifier(); - } - function nextTokenIsIdentifierOrKeyword() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()); - } - function isHeritageClauseExtendsOrImplementsKeyword() { - if (token() === 108 /* ImplementsKeyword */ || - token() === 85 /* ExtendsKeyword */) { - return lookAhead(nextTokenIsStartOfExpression); - } - return false; - } - function nextTokenIsStartOfExpression() { - nextToken(); - return isStartOfExpression(); - } - // True if positioned at a list terminator - function isListTerminator(kind) { - if (token() === 1 /* EndOfFileToken */) { - // Being at the end of the file ends all lists. - return true; - } - switch (kind) { - case 1 /* BlockStatements */: - case 2 /* SwitchClauses */: - case 4 /* TypeMembers */: - case 5 /* ClassMembers */: - case 6 /* EnumMembers */: - case 12 /* ObjectLiteralMembers */: - case 9 /* ObjectBindingElements */: - case 22 /* ImportOrExportSpecifiers */: - return token() === 18 /* CloseBraceToken */; - case 3 /* SwitchClauseStatements */: - return token() === 18 /* CloseBraceToken */ || token() === 73 /* CaseKeyword */ || token() === 79 /* DefaultKeyword */; - case 7 /* HeritageClauseElement */: - return token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; - case 8 /* VariableDeclarations */: - return isVariableDeclaratorListTerminator(); - case 18 /* TypeParameters */: - // Tokens other than '>' are here for better error recovery - return token() === 29 /* GreaterThanToken */ || token() === 19 /* OpenParenToken */ || token() === 17 /* OpenBraceToken */ || token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; - case 11 /* ArgumentExpressions */: - // Tokens other than ')' are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 25 /* SemicolonToken */; - case 15 /* ArrayLiteralMembers */: - case 20 /* TupleElementTypes */: - case 10 /* ArrayBindingElements */: - return token() === 22 /* CloseBracketToken */; - case 16 /* Parameters */: - case 17 /* RestProperties */: - // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === 20 /* CloseParenToken */ || token() === 22 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; - case 19 /* TypeArguments */: - // All other tokens should cause the type-argument to terminate except comma token - return token() !== 26 /* CommaToken */; - case 21 /* HeritageClauses */: - return token() === 17 /* OpenBraceToken */ || token() === 18 /* CloseBraceToken */; - case 13 /* JsxAttributes */: - return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; - case 14 /* JsxChildren */: - return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); - case 23 /* JSDocFunctionParameters */: - return token() === 20 /* CloseParenToken */ || token() === 56 /* ColonToken */ || token() === 18 /* CloseBraceToken */; - case 24 /* JSDocTypeArguments */: - return token() === 29 /* GreaterThanToken */ || token() === 18 /* CloseBraceToken */; - case 26 /* JSDocTupleTypes */: - return token() === 22 /* CloseBracketToken */ || token() === 18 /* CloseBraceToken */; - case 25 /* JSDocRecordMembers */: - return token() === 18 /* CloseBraceToken */; - } - } - function isVariableDeclaratorListTerminator() { - // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. - if (canParseSemicolon()) { - return true; - } - // in the case where we're parsing the variable declarator of a 'for-in' statement, we - // are done if we see an 'in' keyword in front of us. Same with for-of - if (isInOrOfKeyword(token())) { - return true; - } - // ERROR RECOVERY TWEAK: - // For better error recovery, if we see an '=>' then we just stop immediately. We've got an - // arrow function here and it's going to be very unlikely that we'll resynchronize and get - // another variable declaration. - if (token() === 36 /* EqualsGreaterThanToken */) { - return true; - } - // Keep trying to parse out variable declarators. - return false; - } - // True if positioned at element or terminator of the current list or any enclosing list - function isInSomeParsingContext() { - for (var kind = 0; kind < 27 /* Count */; kind++) { - if (parsingContext & (1 << kind)) { - if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { - return true; - } - } - } - return false; - } - // Parses a list of elements - function parseList(kind, parseElement) { - var saveParsingContext = parsingContext; - parsingContext |= 1 << kind; - var result = createNodeArray(); - while (!isListTerminator(kind)) { - if (isListElement(kind, /*inErrorRecovery*/ false)) { - var element = parseListElement(kind, parseElement); - result.push(element); - continue; - } - if (abortParsingListOrMoveToNextToken(kind)) { - break; - } - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function parseListElement(parsingContext, parseElement) { - var node = currentNode(parsingContext); - if (node) { - return consumeNode(node); - } - return parseElement(); - } - function currentNode(parsingContext) { - // If there is an outstanding parse error that we've encountered, but not attached to - // some node, then we cannot get a node from the old source tree. This is because we - // want to mark the next node we encounter as being unusable. - // - // Note: This may be too conservative. Perhaps we could reuse the node and set the bit - // on it (or its leftmost child) as having the error. For now though, being conservative - // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. - return undefined; - } - var node = syntaxCursor.currentNode(scanner.getStartPos()); - // Can't reuse a missing node. - if (ts.nodeIsMissing(node)) { - return undefined; - } - // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } - // Can't reuse a node that contains a parse error. This is necessary so that we - // produce the same set of errors again. - if (ts.containsParseError(node)) { - return undefined; - } - // We can only reuse a node if it was parsed under the same strict mode that we're - // currently in. i.e. if we originally parsed a node in non-strict mode, but then - // the user added 'using strict' at the top of the file, then we can't use that node - // again as the presence of strict mode may cause us to parse the tokens in the file - // differently. - // - // Note: we *can* reuse tokens when the strict mode changes. That's because tokens - // are unaffected by strict mode. It's just the parser will decide what to do with it - // differently depending on what mode it is in. - // - // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 96256 /* ContextFlags */; - if (nodeContextFlags !== contextFlags) { - return undefined; - } - // Ok, we have a node that looks like it could be reused. Now verify that it is valid - // in the current list parsing context that we're currently at. - if (!canReuseNode(node, parsingContext)) { - return undefined; - } - return node; - } - function consumeNode(node) { - // Move the scanner so it is after the node we just consumed. - scanner.setTextPos(node.end); - nextToken(); - return node; - } - function canReuseNode(node, parsingContext) { - switch (parsingContext) { - case 5 /* ClassMembers */: - return isReusableClassMember(node); - case 2 /* SwitchClauses */: - return isReusableSwitchClause(node); - case 0 /* SourceElements */: - case 1 /* BlockStatements */: - case 3 /* SwitchClauseStatements */: - return isReusableStatement(node); - case 6 /* EnumMembers */: - return isReusableEnumMember(node); - case 4 /* TypeMembers */: - return isReusableTypeMember(node); - case 8 /* VariableDeclarations */: - return isReusableVariableDeclaration(node); - case 16 /* Parameters */: - return isReusableParameter(node); - case 17 /* RestProperties */: - return false; - // Any other lists we do not care about reusing nodes in. But feel free to add if - // you can do so safely. Danger areas involve nodes that may involve speculative - // parsing. If speculative parsing is involved with the node, then the range the - // parser reached while looking ahead might be in the edited range (see the example - // in canReuseVariableDeclaratorNode for a good case of this). - case 21 /* HeritageClauses */: - // This would probably be safe to reuse. There is no speculative parsing with - // heritage clauses. - case 18 /* TypeParameters */: - // This would probably be safe to reuse. There is no speculative parsing with - // type parameters. Note that that's because type *parameters* only occur in - // unambiguous *type* contexts. While type *arguments* occur in very ambiguous - // *expression* contexts. - case 20 /* TupleElementTypes */: - // This would probably be safe to reuse. There is no speculative parsing with - // tuple types. - // Technically, type argument list types are probably safe to reuse. While - // speculative parsing is involved with them (since type argument lists are only - // produced from speculative parsing a < as a type argument list), we only have - // the types because speculative parsing succeeded. Thus, the lookahead never - // went past the end of the list and rewound. - case 19 /* TypeArguments */: - // Note: these are almost certainly not safe to ever reuse. Expressions commonly - // need a large amount of lookahead, and we should not reuse them as they may - // have actually intersected the edit. - case 11 /* ArgumentExpressions */: - // This is not safe to reuse for the same reason as the 'AssignmentExpression' - // cases. i.e. a property assignment may end with an expression, and thus might - // have lookahead far beyond it's old node. - case 12 /* ObjectLiteralMembers */: - // This is probably not safe to reuse. There can be speculative parsing with - // type names in a heritage clause. There can be generic names in the type - // name list, and there can be left hand side expressions (which can have type - // arguments.) - case 7 /* HeritageClauseElement */: - // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes - // on any given element. Same for children. - case 13 /* JsxAttributes */: - case 14 /* JsxChildren */: - } - return false; - } - function isReusableClassMember(node) { - if (node) { - switch (node.kind) { - case 152 /* Constructor */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 149 /* PropertyDeclaration */: - case 206 /* SemicolonClassElement */: - return true; - case 151 /* MethodDeclaration */: - // Method declarations are not necessarily reusable. An object-literal - // may have a method calls "constructor(...)" and we must reparse that - // into an actual .ConstructorDeclaration. - var methodDeclaration = node; - var nameIsConstructor = methodDeclaration.name.kind === 71 /* Identifier */ && - methodDeclaration.name.originalKeywordKind === 123 /* ConstructorKeyword */; - return !nameIsConstructor; - } - } - return false; - } - function isReusableSwitchClause(node) { - if (node) { - switch (node.kind) { - case 257 /* CaseClause */: - case 258 /* DefaultClause */: - return true; - } - } - return false; - } - function isReusableStatement(node) { - if (node) { - switch (node.kind) { - case 228 /* FunctionDeclaration */: - case 208 /* VariableStatement */: - case 207 /* Block */: - case 211 /* IfStatement */: - case 210 /* ExpressionStatement */: - case 223 /* ThrowStatement */: - case 219 /* ReturnStatement */: - case 221 /* SwitchStatement */: - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 214 /* ForStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 209 /* EmptyStatement */: - case 224 /* TryStatement */: - case 222 /* LabeledStatement */: - case 212 /* DoStatement */: - case 225 /* DebuggerStatement */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - case 231 /* TypeAliasDeclaration */: - return true; - } - } - return false; - } - function isReusableEnumMember(node) { - return node.kind === 264 /* EnumMember */; - } - function isReusableTypeMember(node) { - if (node) { - switch (node.kind) { - case 156 /* ConstructSignature */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 148 /* PropertySignature */: - case 155 /* CallSignature */: - return true; - } - } - return false; - } - function isReusableVariableDeclaration(node) { - if (node.kind !== 226 /* VariableDeclaration */) { - return false; - } - // Very subtle incremental parsing bug. Consider the following code: - // - // let v = new List < A, B - // - // This is actually legal code. It's a list of variable declarators "v = new List() - // - // then we have a problem. "v = new List= 0) { - // Always preserve a trailing comma by marking it on the NodeArray - result.hasTrailingComma = true; - } - result.end = getNodeEnd(); - parsingContext = saveParsingContext; - return result; - } - function createMissingList() { - return createNodeArray(); - } - function parseBracketedList(kind, parseElement, open, close) { - if (parseExpected(open)) { - var result = parseDelimitedList(kind, parseElement); - parseExpected(close); - return result; - } - return createMissingList(); - } - // The allowReservedWords parameter controls whether reserved words are permitted after the first dot - function parseEntityName(allowReservedWords, diagnosticMessage) { - var entity = parseIdentifier(diagnosticMessage); - while (parseOptional(23 /* DotToken */)) { - var node = createNode(143 /* QualifiedName */, entity.pos); // !!! - node.left = entity; - node.right = parseRightSideOfDot(allowReservedWords); - entity = finishNode(node); - } - return entity; - } - function parseRightSideOfDot(allowIdentifierNames) { - // Technically a keyword is valid here as all identifiers and keywords are identifier names. - // However, often we'll encounter this in error situations when the identifier or keyword - // is actually starting another valid construct. - // - // So, we check for the following specific case: - // - // name. - // identifierOrKeyword identifierNameOrKeyword - // - // Note: the newlines are important here. For example, if that above code - // were rewritten into: - // - // name.identifierOrKeyword - // identifierNameOrKeyword - // - // Then we would consider it valid. That's because ASI would take effect and - // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". - // In the first case though, ASI will not take effect because there is not a - // line terminator after the identifier or keyword. - if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { - var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - if (matchesPattern) { - // Report that we need an identifier. However, report it right after the dot, - // and not on the next token. This is because the next token might actually - // be an identifier and the error would be quite confusing. - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); - } - } - return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); - } - function parseTemplateExpression() { - var template = createNode(196 /* TemplateExpression */); - template.head = parseTemplateHead(); - ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); - var templateSpans = createNodeArray(); - do { - templateSpans.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(templateSpans).literal.kind === 15 /* TemplateMiddle */); - templateSpans.end = getNodeEnd(); - template.templateSpans = templateSpans; - return finishNode(template); - } - function parseTemplateSpan() { - var span = createNode(205 /* TemplateSpan */); - span.expression = allowInAnd(parseExpression); - var literal; - if (token() === 18 /* CloseBraceToken */) { - reScanTemplateToken(); - literal = parseTemplateMiddleOrTemplateTail(); - } - else { - literal = parseExpectedToken(16 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(18 /* CloseBraceToken */)); - } - span.literal = literal; - return finishNode(span); - } - function parseLiteralNode(internName) { - return parseLiteralLikeNode(token(), internName); - } - function parseTemplateHead() { - var fragment = parseLiteralLikeNode(token(), /*internName*/ false); - ts.Debug.assert(fragment.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); - return fragment; - } - function parseTemplateMiddleOrTemplateTail() { - var fragment = parseLiteralLikeNode(token(), /*internName*/ false); - ts.Debug.assert(fragment.kind === 15 /* TemplateMiddle */ || fragment.kind === 16 /* TemplateTail */, "Template fragment has wrong token kind"); - return fragment; - } - function parseLiteralLikeNode(kind, internName) { - var node = createNode(kind); - var text = scanner.getTokenValue(); - node.text = internName ? internIdentifier(text) : text; - if (scanner.hasExtendedUnicodeEscape()) { - node.hasExtendedUnicodeEscape = true; - } - if (scanner.isUnterminated()) { - node.isUnterminated = true; - } - // Octal literals are not allowed in strict mode or ES5 - // Note that theoretically the following condition would hold true literals like 009, - // which is not octal.But because of how the scanner separates the tokens, we would - // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. - // We also do not need to check for negatives because any prefix operator would be part of a - // parent unary expression. - if (node.kind === 8 /* NumericLiteral */) { - node.numericLiteralFlags = scanner.getNumericLiteralFlags(); - } - nextToken(); - finishNode(node); - return node; - } - // TYPES - function parseTypeReference() { - var node = createNode(159 /* TypeReference */); - node.typeName = parseEntityName(/*allowReservedWords*/ false, ts.Diagnostics.Type_expected); - if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } - return finishNode(node); - } - function parseThisTypePredicate(lhs) { - nextToken(); - var node = createNode(158 /* TypePredicate */, lhs.pos); - node.parameterName = lhs; - node.type = parseType(); - return finishNode(node); - } - function parseThisTypeNode() { - var node = createNode(169 /* ThisType */); - nextToken(); - return finishNode(node); - } - function parseTypeQuery() { - var node = createNode(162 /* TypeQuery */); - parseExpected(103 /* TypeOfKeyword */); - node.exprName = parseEntityName(/*allowReservedWords*/ true); - return finishNode(node); - } - function parseTypeParameter() { - var node = createNode(145 /* TypeParameter */); - node.name = parseIdentifier(); - if (parseOptional(85 /* ExtendsKeyword */)) { - // It's not uncommon for people to write improper constraints to a generic. If the - // user writes a constraint that is an expression and not an actual type, then parse - // it out as an expression (so we can recover well), but report that a type is needed - // instead. - if (isStartOfType() || !isStartOfExpression()) { - node.constraint = parseType(); - } - else { - // It was not a type, and it looked like an expression. Parse out an expression - // here so we recover well. Note: it is important that we call parseUnaryExpression - // and not parseExpression here. If the user has: - // - // - // - // We do *not* want to consume the > as we're consuming the expression for "". - node.expression = parseUnaryExpressionOrHigher(); - } - } - if (parseOptional(58 /* EqualsToken */)) { - node.default = parseType(); - } - return finishNode(node); - } - function parseTypeParameters() { - if (token() === 27 /* LessThanToken */) { - return parseBracketedList(18 /* TypeParameters */, parseTypeParameter, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } - } - function parseParameterType() { - if (parseOptional(56 /* ColonToken */)) { - return parseType(); - } - return undefined; - } - function isStartOfParameter() { - return token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern() || ts.isModifierKind(token()) || token() === 57 /* AtToken */ || token() === 99 /* ThisKeyword */; - } - function parseParameter() { - var node = createNode(146 /* Parameter */); - if (token() === 99 /* ThisKeyword */) { - node.name = createIdentifier(/*isIdentifier*/ true); - node.type = parseParameterType(); - return finishNode(node); - } - node.decorators = parseDecorators(); - node.modifiers = parseModifiers(); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - node.name = parseIdentifierOrPattern(); - if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { - // in cases like - // 'use strict' - // function foo(static) - // isParameter('static') === true, because of isModifier('static') - // however 'static' is not a legal identifier in a strict mode. - // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined) - // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM) - // to avoid this we'll advance cursor to the next token. - nextToken(); - } - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - node.type = parseParameterType(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ true); - // Do not check for initializers in an ambient context for parameters. This is not - // a grammar error because the grammar allows arbitrary call signatures in - // an ambient context. - // It is actually not necessary for this to be an error at all. The reason is that - // function/constructor implementations are syntactically disallowed in ambient - // contexts. In addition, parameter initializers are semantically disallowed in - // overload signatures. So parameter initializers are transitively disallowed in - // ambient contexts. - return addJSDocComment(finishNode(node)); - } - function parseBindingElementInitializer(inParameter) { - return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); - } - function parseParameterInitializer() { - return parseInitializer(/*inParameter*/ true); - } - function fillSignature(returnToken, yieldContext, awaitContext, requireCompleteParameterList, signature) { - var returnTokenRequired = returnToken === 36 /* EqualsGreaterThanToken */; - signature.typeParameters = parseTypeParameters(); - signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); - if (returnTokenRequired) { - parseExpected(returnToken); - signature.type = parseTypeOrTypePredicate(); - } - else if (parseOptional(returnToken)) { - signature.type = parseTypeOrTypePredicate(); - } - } - function parseParameterList(yieldContext, awaitContext, requireCompleteParameterList) { - // FormalParameters [Yield,Await]: (modified) - // [empty] - // FormalParameterList[?Yield,Await] - // - // FormalParameter[Yield,Await]: (modified) - // BindingElement[?Yield,Await] - // - // BindingElement [Yield,Await]: (modified) - // SingleNameBinding[?Yield,?Await] - // BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - // - // SingleNameBinding [Yield,Await]: - // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(19 /* OpenParenToken */)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(yieldContext); - setAwaitContext(awaitContext); - var result = parseDelimitedList(16 /* Parameters */, parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20 /* CloseParenToken */) && requireCompleteParameterList) { - // Caller insisted that we had to end with a ) We didn't. So just return - // undefined here. - return undefined; - } - return result; - } - // We didn't even have an open paren. If the caller requires a complete parameter list, - // we definitely can't provide that. However, if they're ok with an incomplete one, - // then just return an empty set of parameters. - return requireCompleteParameterList ? undefined : createMissingList(); - } - function parseTypeMemberSemicolon() { - // We allow type members to be separated by commas or (possibly ASI) semicolons. - // First check if it was a comma. If so, we're done with the member. - if (parseOptional(26 /* CommaToken */)) { - return; - } - // Didn't have a comma. We must have a (possible ASI) semicolon. - parseSemicolon(); - } - function parseSignatureMember(kind) { - var node = createNode(kind); - if (kind === 156 /* ConstructSignature */) { - parseExpected(94 /* NewKeyword */); - } - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(node)); - } - function isIndexSignature() { - if (token() !== 21 /* OpenBracketToken */) { - return false; - } - return lookAhead(isUnambiguouslyIndexSignature); - } - function isUnambiguouslyIndexSignature() { - // The only allowed sequence is: - // - // [id: - // - // However, for error recovery, we also check the following cases: - // - // [... - // [id, - // [id?, - // [id?: - // [id?] - // [public id - // [private id - // [protected id - // [] - // - nextToken(); - if (token() === 24 /* DotDotDotToken */ || token() === 22 /* CloseBracketToken */) { - return true; - } - if (ts.isModifierKind(token())) { - nextToken(); - if (isIdentifier()) { - return true; - } - } - else if (!isIdentifier()) { - return false; - } - else { - // Skip the identifier - nextToken(); - } - // A colon signifies a well formed indexer - // A comma should be a badly formed indexer because comma expressions are not allowed - // in computed properties. - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */) { - return true; - } - // Question mark could be an indexer with an optional property, - // or it could be a conditional expression in a computed property. - if (token() !== 55 /* QuestionToken */) { - return false; - } - // If any of the following tokens are after the question mark, it cannot - // be a conditional expression, so treat it as an indexer. - nextToken(); - return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; - } - function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { - var node = createNode(157 /* IndexSignature */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); - node.type = parseTypeAnnotation(); - parseTypeMemberSemicolon(); - return finishNode(node); - } - function parsePropertyOrMethodSignature(fullStart, modifiers) { - var name = parsePropertyName(); - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - var method = createNode(150 /* MethodSignature */, fullStart); - method.modifiers = modifiers; - method.name = name; - method.questionToken = questionToken; - // Method signatures don't exist in expression contexts. So they have neither - // [Yield] nor [Await] - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, method); - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(method)); - } - else { - var property = createNode(148 /* PropertySignature */, fullStart); - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - if (token() === 58 /* EqualsToken */) { - // Although type literal properties cannot not have initializers, we attempt - // to parse an initializer so we can report in the checker that an interface - // property or type literal property cannot have an initializer. - property.initializer = parseNonParameterInitializer(); - } - parseTypeMemberSemicolon(); - return addJSDocComment(finishNode(property)); - } - } - function isTypeMemberStart() { - // Return true if we have the start of a signature member - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return true; - } - var idToken; - // Eat up all modifiers, but hold on to the last one in case it is actually an identifier - while (ts.isModifierKind(token())) { - idToken = true; - nextToken(); - } - // Index signatures and computed property names are type members - if (token() === 21 /* OpenBracketToken */) { - return true; - } - // Try to get the first property-like token following all modifiers - if (isLiteralPropertyName()) { - idToken = true; - nextToken(); - } - // If we were able to get any potential identifier, check that it is - // the start of a member declaration - if (idToken) { - return token() === 19 /* OpenParenToken */ || - token() === 27 /* LessThanToken */ || - token() === 55 /* QuestionToken */ || - token() === 56 /* ColonToken */ || - token() === 26 /* CommaToken */ || - canParseSemicolon(); - } - return false; - } - function parseTypeMember() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(155 /* CallSignature */); - } - if (token() === 94 /* NewKeyword */ && lookAhead(isStartOfConstructSignature)) { - return parseSignatureMember(156 /* ConstructSignature */); - } - var fullStart = getNodePos(); - var modifiers = parseModifiers(); - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, /*decorators*/ undefined, modifiers); - } - return parsePropertyOrMethodSignature(fullStart, modifiers); - } - function isStartOfConstructSignature() { - nextToken(); - return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; - } - function parseTypeLiteral() { - var node = createNode(163 /* TypeLiteral */); - node.members = parseObjectTypeMembers(); - return finishNode(node); - } - function parseObjectTypeMembers() { - var members; - if (parseExpected(17 /* OpenBraceToken */)) { - members = parseList(4 /* TypeMembers */, parseTypeMember); - parseExpected(18 /* CloseBraceToken */); - } - else { - members = createMissingList(); - } - return members; - } - function isStartOfMappedType() { - nextToken(); - if (token() === 131 /* ReadonlyKeyword */) { - nextToken(); - } - return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; - } - function parseMappedTypeParameter() { - var node = createNode(145 /* TypeParameter */); - node.name = parseIdentifier(); - parseExpected(92 /* InKeyword */); - node.constraint = parseType(); - return finishNode(node); - } - function parseMappedType() { - var node = createNode(172 /* MappedType */); - parseExpected(17 /* OpenBraceToken */); - node.readonlyToken = parseOptionalToken(131 /* ReadonlyKeyword */); - parseExpected(21 /* OpenBracketToken */); - node.typeParameter = parseMappedTypeParameter(); - parseExpected(22 /* CloseBracketToken */); - node.questionToken = parseOptionalToken(55 /* QuestionToken */); - node.type = parseTypeAnnotation(); - parseSemicolon(); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseTupleType() { - var node = createNode(165 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); - return finishNode(node); - } - function parseParenthesizedType() { - var node = createNode(168 /* ParenthesizedType */); - parseExpected(19 /* OpenParenToken */); - node.type = parseType(); - parseExpected(20 /* CloseParenToken */); - return finishNode(node); - } - function parseFunctionOrConstructorType(kind) { - var node = createNode(kind); - if (kind === 161 /* ConstructorType */) { - parseExpected(94 /* NewKeyword */); - } - fillSignature(36 /* EqualsGreaterThanToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - return finishNode(node); - } - function parseKeywordAndNoDot() { - var node = parseTokenNode(); - return token() === 23 /* DotToken */ ? undefined : node; - } - function parseLiteralTypeNode() { - var node = createNode(173 /* LiteralType */); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; - } - function nextTokenIsNumericLiteral() { - return nextToken() === 8 /* NumericLiteral */; - } - function parseNonArrayType() { - switch (token()) { - case 119 /* AnyKeyword */: - case 136 /* StringKeyword */: - case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 139 /* UndefinedKeyword */: - case 130 /* NeverKeyword */: - case 134 /* ObjectKeyword */: - // If these are followed by a dot, then parse these out as a dotted type reference instead. - var node = tryParse(parseKeywordAndNoDot); - return node || parseTypeReference(); - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - return parseLiteralTypeNode(); - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); - case 105 /* VoidKeyword */: - case 95 /* NullKeyword */: - return parseTokenNode(); - case 99 /* ThisKeyword */: { - var thisKeyword = parseThisTypeNode(); - if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - return parseThisTypePredicate(thisKeyword); - } - else { - return thisKeyword; - } - } - case 103 /* TypeOfKeyword */: - return parseTypeQuery(); - case 17 /* OpenBraceToken */: - return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); - case 21 /* OpenBracketToken */: - return parseTupleType(); - case 19 /* OpenParenToken */: - return parseParenthesizedType(); - default: - return parseTypeReference(); - } - } - function isStartOfType() { - switch (token()) { - case 119 /* AnyKeyword */: - case 136 /* StringKeyword */: - case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 139 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 99 /* ThisKeyword */: - case 103 /* TypeOfKeyword */: - case 130 /* NeverKeyword */: - case 17 /* OpenBraceToken */: - case 21 /* OpenBracketToken */: - case 27 /* LessThanToken */: - case 49 /* BarToken */: - case 48 /* AmpersandToken */: - case 94 /* NewKeyword */: - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 134 /* ObjectKeyword */: - return true; - case 38 /* MinusToken */: - return lookAhead(nextTokenIsNumericLiteral); - case 19 /* OpenParenToken */: - // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, - // or something that starts a type. We don't want to consider things like '(1)' a type. - return lookAhead(isStartOfParenthesizedOrFunctionType); - default: - return isIdentifier(); - } - } - function isStartOfParenthesizedOrFunctionType() { - nextToken(); - return token() === 20 /* CloseParenToken */ || isStartOfParameter() || isStartOfType(); - } - function parseArrayTypeOrHigher() { - var type = parseNonArrayType(); - while (!scanner.hasPrecedingLineBreak() && parseOptional(21 /* OpenBracketToken */)) { - if (isStartOfType()) { - var node = createNode(171 /* IndexedAccessType */, type.pos); - node.objectType = type; - node.indexType = parseType(); - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); - } - else { - var node = createNode(164 /* ArrayType */, type.pos); - node.elementType = type; - parseExpected(22 /* CloseBracketToken */); - type = finishNode(node); - } - } - return type; - } - function parseTypeOperator(operator) { - var node = createNode(170 /* TypeOperator */); - parseExpected(operator); - node.operator = operator; - node.type = parseTypeOperatorOrHigher(); - return finishNode(node); - } - function parseTypeOperatorOrHigher() { - switch (token()) { - case 127 /* KeyOfKeyword */: - return parseTypeOperator(127 /* KeyOfKeyword */); - } - return parseArrayTypeOrHigher(); - } - function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { - parseOptional(operator); - var type = parseConstituentType(); - if (token() === operator) { - var types = createNodeArray([type], type.pos); - while (parseOptional(operator)) { - types.push(parseConstituentType()); - } - types.end = getNodeEnd(); - var node = createNode(kind, type.pos); - node.types = types; - type = finishNode(node); - } - return type; - } - function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(167 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); - } - function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(166 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); - } - function isStartOfFunctionType() { - if (token() === 27 /* LessThanToken */) { - return true; - } - return token() === 19 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType); - } - function skipParameterStart() { - if (ts.isModifierKind(token())) { - // Skip modifiers - parseModifiers(); - } - if (isIdentifier() || token() === 99 /* ThisKeyword */) { - nextToken(); - return true; - } - if (token() === 21 /* OpenBracketToken */ || token() === 17 /* OpenBraceToken */) { - // Return true if we can parse an array or object binding pattern with no errors - var previousErrorCount = parseDiagnostics.length; - parseIdentifierOrPattern(); - return previousErrorCount === parseDiagnostics.length; - } - return false; - } - function isUnambiguouslyStartOfFunctionType() { - nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { - // ( ) - // ( ... - return true; - } - if (skipParameterStart()) { - // We successfully skipped modifiers (if any) and an identifier or binding pattern, - // now see if we have something that indicates a parameter declaration - if (token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || - token() === 55 /* QuestionToken */ || token() === 58 /* EqualsToken */) { - // ( xxx : - // ( xxx , - // ( xxx ? - // ( xxx = - return true; - } - if (token() === 20 /* CloseParenToken */) { - nextToken(); - if (token() === 36 /* EqualsGreaterThanToken */) { - // ( xxx ) => - return true; - } - } - } - return false; - } - function parseTypeOrTypePredicate() { - var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); - var type = parseType(); - if (typePredicateVariable) { - var node = createNode(158 /* TypePredicate */, typePredicateVariable.pos); - node.parameterName = typePredicateVariable; - node.type = type; - return finishNode(node); - } - else { - return type; - } - } - function parseTypePredicatePrefix() { - var id = parseIdentifier(); - if (token() === 126 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - return id; - } - } - function parseType() { - // The rules about 'yield' only apply to actual code/expression contexts. They don't - // apply to 'type' contexts. So we disable these parameters here before moving on. - return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); - } - function parseTypeWorker() { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(160 /* FunctionType */); - } - if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(161 /* ConstructorType */); - } - return parseUnionTypeOrHigher(); - } - function parseTypeAnnotation() { - return parseOptional(56 /* ColonToken */) ? parseType() : undefined; - } - // EXPRESSIONS - function isStartOfLeftHandSideExpression() { - switch (token()) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 19 /* OpenParenToken */: - case 21 /* OpenBracketToken */: - case 17 /* OpenBraceToken */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 94 /* NewKeyword */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 71 /* Identifier */: - return true; - default: - return isIdentifier(); - } - } - function isStartOfExpression() { - if (isStartOfLeftHandSideExpression()) { - return true; - } - switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - case 27 /* LessThanToken */: - case 121 /* AwaitKeyword */: - case 116 /* YieldKeyword */: - // Yield/await always starts an expression. Either it is an identifier (in which case - // it is definitely an expression). Or it's a keyword (either because we're in - // a generator or async function, or in strict mode (or both)) and it started a yield or await expression. - return true; - default: - // Error tolerance. If we see the start of some binary operator, we consider - // that the start of an expression. That way we'll parse out a missing identifier, - // give a good message about an identifier being missing, and then consume the - // rest of the binary expression. - if (isBinaryOperator()) { - return true; - } - return isIdentifier(); - } - } - function isStartOfExpressionStatement() { - // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== 17 /* OpenBraceToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - token() !== 57 /* AtToken */ && - isStartOfExpression(); - } - function parseExpression() { - // Expression[in]: - // AssignmentExpression[in] - // Expression[in] , AssignmentExpression[in] - // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ false); - } - var expr = parseAssignmentExpressionOrHigher(); - var operatorToken; - while ((operatorToken = parseOptionalToken(26 /* CommaToken */))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); - } - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ true); - } - return expr; - } - function parseInitializer(inParameter) { - if (token() !== 58 /* EqualsToken */) { - // It's not uncommon during typing for the user to miss writing the '=' token. Check if - // there is no newline after the last token and if we're on an expression. If so, parse - // this as an equals-value clause with a missing equals. - // NOTE: There are two places where we allow equals-value clauses. The first is in a - // variable declarator. The second is with a parameter. For variable declarators - // it's more likely that a { would be a allowed (as an object literal). While this - // is also allowed for parameters, the risk is that we consume the { as an object - // literal when it really will be for the block following the parameter. - if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17 /* OpenBraceToken */) || !isStartOfExpression()) { - // preceding line break, open brace in a parameter (likely a function body) or current token is not an expression - - // do not try to parse initializer - return undefined; - } - } - // Initializer[In, Yield] : - // = AssignmentExpression[?In, ?Yield] - parseExpected(58 /* EqualsToken */); - return parseAssignmentExpressionOrHigher(); - } - function parseAssignmentExpressionOrHigher() { - // AssignmentExpression[in,yield]: - // 1) ConditionalExpression[?in,?yield] - // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] - // 3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield] - // 4) ArrowFunctionExpression[?in,?yield] - // 5) AsyncArrowFunctionExpression[in,yield,await] - // 6) [+Yield] YieldExpression[?In] - // - // Note: for ease of implementation we treat productions '2' and '3' as the same thing. - // (i.e. they're both BinaryExpressions with an assignment operator in it). - // First, do the simple check if we have a YieldExpression (production '6'). - if (isYieldExpression()) { - return parseYieldExpression(); - } - // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized - // parameter list or is an async arrow function. - // AsyncArrowFunctionExpression: - // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] - // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression". - // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". - // - // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done - // with AssignmentExpression if we see one. - var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); - if (arrowExpression) { - return arrowExpression; - } - // Now try to see if we're in production '1', '2' or '3'. A conditional expression can - // start with a LogicalOrExpression, while the assignment productions can only start with - // LeftHandSideExpressions. - // - // So, first, we try to just parse out a BinaryExpression. If we get something that is a - // LeftHandSide or higher, then we can try to parse out the assignment expression part. - // Otherwise, we try to parse out the conditional expression bit. We want to allow any - // binary expression here, so we pass in the 'lowest' precedence here so that it matches - // and consumes anything. - var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized - // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single - // identifier and the current token is an arrow. - if (expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { - return parseSimpleArrowFunctionExpression(expr); - } - // Now see if we might be in cases '2' or '3'. - // If the expression was a LHS expression, and we have an assignment operator, then - // we're in '2' or '3'. Consume the assignment and return. - // - // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= - if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); - } - // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr); - } - function isYieldExpression() { - if (token() === 116 /* YieldKeyword */) { - // If we have a 'yield' keyword, and this is a context where yield expressions are - // allowed, then definitely parse out a yield expression. - if (inYieldContext()) { - return true; - } - // We're in a context where 'yield expr' is not allowed. However, if we can - // definitely tell that the user was trying to parse a 'yield expr' and not - // just a normal expr that start with a 'yield' identifier, then parse out - // a 'yield expr'. We can then report an error later that they are only - // allowed in generator expressions. - // - // for example, if we see 'yield(foo)', then we'll have to treat that as an - // invocation expression of something called 'yield'. However, if we have - // 'yield foo' then that is not legal as a normal expression, so we can - // definitely recognize this as a yield expression. - // - // for now we just check if the next token is an identifier. More heuristics - // can be added here later as necessary. We just need to make sure that we - // don't accidentally consume something legal. - return lookAhead(nextTokenIsIdentifierOrKeywordOrNumberOnSameLine); - } - return false; - } - function nextTokenIsIdentifierOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && isIdentifier(); - } - function parseYieldExpression() { - var node = createNode(197 /* YieldExpression */); - // YieldExpression[In] : - // yield - // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] - // yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] - nextToken(); - if (!scanner.hasPrecedingLineBreak() && - (token() === 39 /* AsteriskToken */ || isStartOfExpression())) { - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - else { - // if the next token is not on the same line as yield. or we don't have an '*' or - // the start of an expression, then this is just a simple "yield" expression. - return finishNode(node); - } - } - function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { - ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - var node; - if (asyncModifier) { - node = createNode(187 /* ArrowFunction */, asyncModifier.pos); - node.modifiers = asyncModifier; - } - else { - node = createNode(187 /* ArrowFunction */, identifier.pos); - } - var parameter = createNode(146 /* Parameter */, identifier.pos); - parameter.name = identifier; - finishNode(parameter); - node.parameters = createNodeArray([parameter], parameter.pos); - node.parameters.end = parameter.end; - node.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); - node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier); - return addJSDocComment(finishNode(node)); - } - function tryParseParenthesizedArrowFunctionExpression() { - var triState = isParenthesizedArrowFunctionExpression(); - if (triState === 0 /* False */) { - // It's definitely not a parenthesized arrow function expression. - return undefined; - } - // If we definitely have an arrow function, then we can just parse one, not requiring a - // following => or { token. Otherwise, we *might* have an arrow function. Try to parse - // it out, but don't allow any ambiguity, and return 'undefined' if this could be an - // expression instead. - var arrowFunction = triState === 1 /* True */ - ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) - : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); - if (!arrowFunction) { - // Didn't appear to actually be a parenthesized arrow function. Just bail out. - return undefined; - } - var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256 /* Async */); - // If we have an arrow, then try to parse the body. Even if not, try to parse if we - // have an opening brace, just in case we're in an error state. - var lastToken = token(); - arrowFunction.equalsGreaterThanToken = parseExpectedToken(36 /* EqualsGreaterThanToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, "=>"); - arrowFunction.body = (lastToken === 36 /* EqualsGreaterThanToken */ || lastToken === 17 /* OpenBraceToken */) - ? parseArrowFunctionExpressionBody(isAsync) - : parseIdentifier(); - return addJSDocComment(finishNode(arrowFunction)); - } - // True -> We definitely expect a parenthesized arrow function here. - // False -> There *cannot* be a parenthesized arrow function here. - // Unknown -> There *might* be a parenthesized arrow function here. - // Speculatively look ahead to be sure, and rollback if not. - function isParenthesizedArrowFunctionExpression() { - if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */ || token() === 120 /* AsyncKeyword */) { - return lookAhead(isParenthesizedArrowFunctionExpressionWorker); - } - if (token() === 36 /* EqualsGreaterThanToken */) { - // ERROR RECOVERY TWEAK: - // If we see a standalone => try to parse it as an arrow function expression as that's - // likely what the user intended to write. - return 1 /* True */; - } - // Definitely not a parenthesized arrow function. - return 0 /* False */; - } - function isParenthesizedArrowFunctionExpressionWorker() { - if (token() === 120 /* AsyncKeyword */) { - nextToken(); - if (scanner.hasPrecedingLineBreak()) { - return 0 /* False */; - } - if (token() !== 19 /* OpenParenToken */ && token() !== 27 /* LessThanToken */) { - return 0 /* False */; - } - } - var first = token(); - var second = nextToken(); - if (first === 19 /* OpenParenToken */) { - if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". - // This is an arrow function with no parameters. - // The last one is not actually an arrow function, - // but this is probably what the user intended. - var third = nextToken(); - switch (third) { - case 36 /* EqualsGreaterThanToken */: - case 56 /* ColonToken */: - case 17 /* OpenBraceToken */: - return 1 /* True */; - default: - return 0 /* False */; - } - } - // If encounter "([" or "({", this could be the start of a binding pattern. - // Examples: - // ([ x ]) => { } - // ({ x }) => { } - // ([ x ]) - // ({ x }) - if (second === 21 /* OpenBracketToken */ || second === 17 /* OpenBraceToken */) { - return 2 /* Unknown */; - } - // Simple case: "(..." - // This is an arrow function with a rest parameter. - if (second === 24 /* DotDotDotToken */) { - return 1 /* True */; - } - // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. - // Note: we could be a little more lenient and allow - // "(public" or "(private". These would not ever actually be allowed, - // but we could provide a good error message instead of bailing out. - if (!isIdentifier()) { - return 0 /* False */; - } - // If we have something like "(a:", then we must have a - // type-annotated parameter in an arrow function expression. - if (nextToken() === 56 /* ColonToken */) { - return 1 /* True */; - } - // This *could* be a parenthesized arrow function. - // Return Unknown to let the caller know. - return 2 /* Unknown */; - } - else { - ts.Debug.assert(first === 27 /* LessThanToken */); - // If we have "<" not followed by an identifier, - // then this definitely is not an arrow function. - if (!isIdentifier()) { - return 0 /* False */; - } - // JSX overrides - if (sourceFile.languageVariant === 1 /* JSX */) { - var isArrowFunctionInJsx = lookAhead(function () { - var third = nextToken(); - if (third === 85 /* ExtendsKeyword */) { - var fourth = nextToken(); - switch (fourth) { - case 58 /* EqualsToken */: - case 29 /* GreaterThanToken */: - return false; - default: - return true; - } - } - else if (third === 26 /* CommaToken */) { - return true; - } - return false; - }); - if (isArrowFunctionInJsx) { - return 1 /* True */; - } - return 0 /* False */; - } - // This *could* be a parenthesized arrow function. - return 2 /* Unknown */; - } - } - function parsePossibleParenthesizedArrowFunctionExpressionHead() { - return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); - } - function tryParseAsyncSimpleArrowFunctionExpression() { - // We do a check here so that we won't be doing unnecessarily call to "lookAhead" - if (token() === 120 /* AsyncKeyword */) { - var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); - if (isUnParenthesizedAsyncArrowFunction === 1 /* True */) { - var asyncModifier = parseModifiersForArrowFunction(); - var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - return parseSimpleArrowFunctionExpression(expr, asyncModifier); - } - } - return undefined; - } - function isUnParenthesizedAsyncArrowFunctionWorker() { - // AsyncArrowFunctionExpression: - // 1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In] - // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] - if (token() === 120 /* AsyncKeyword */) { - nextToken(); - // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function - // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { - return 0 /* False */; - } - // Check for un-parenthesized AsyncArrowFunction - var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); - if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 /* Identifier */ && token() === 36 /* EqualsGreaterThanToken */) { - return 1 /* True */; - } - } - return 0 /* False */; - } - function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNode(187 /* ArrowFunction */); - node.modifiers = parseModifiersForArrowFunction(); - var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); - // Arrow functions are never generators. - // - // If we're speculatively parsing a signature for a parenthesized arrow function, then - // we have to have a complete parameter list. Otherwise we might see something like - // a => (b => c) - // And think that "(b =>" was actually a parenthesized arrow function with a missing - // close paren. - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ !allowAmbiguity, node); - // If we couldn't get parameters, we definitely could not parse out an arrow function. - if (!node.parameters) { - return undefined; - } - // Parsing a signature isn't enough. - // Parenthesized arrow signatures often look like other valid expressions. - // For instance: - // - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value. - // - "(x,y)" is a comma expression parsed as a signature with two parameters. - // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. - // - // So we need just a bit of lookahead to ensure that it can only be a signature. - if (!allowAmbiguity && token() !== 36 /* EqualsGreaterThanToken */ && token() !== 17 /* OpenBraceToken */) { - // Returning undefined here will cause our caller to rewind to where we started from. - return undefined; - } - return node; - } - function parseArrowFunctionExpressionBody(isAsync) { - if (token() === 17 /* OpenBraceToken */) { - return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); - } - if (token() !== 25 /* SemicolonToken */ && - token() !== 89 /* FunctionKeyword */ && - token() !== 75 /* ClassKeyword */ && - isStartOfStatement() && - !isStartOfExpressionStatement()) { - // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations) - // - // Here we try to recover from a potential error situation in the case where the - // user meant to supply a block. For example, if the user wrote: - // - // a => - // let v = 0; - // } - // - // they may be missing an open brace. Check to see if that's the case so we can - // try to recover better. If we don't do this, then the next close curly we see may end - // up preemptively closing the containing construct. - // - // Note: even when 'ignoreMissingOpenBrace' is passed as true, parseBody will still error. - return parseFunctionBlock(/*allowYield*/ false, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ true); - } - return isAsync - ? doInAwaitContext(parseAssignmentExpressionOrHigher) - : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); - } - function parseConditionalExpressionRest(leftOperand) { - // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (!questionToken) { - return leftOperand; - } - // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and - // we do not that for the 'whenFalse' part. - var node = createNode(195 /* ConditionalExpression */, leftOperand.pos); - node.condition = leftOperand; - node.questionToken = questionToken; - node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); - node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseBinaryExpressionOrHigher(precedence) { - var leftOperand = parseUnaryExpressionOrHigher(); - return parseBinaryExpressionRest(precedence, leftOperand); - } - function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 142 /* OfKeyword */; - } - function parseBinaryExpressionRest(precedence, leftOperand) { - while (true) { - // We either have a binary operator here, or we're finished. We call - // reScanGreaterToken so that we merge token sequences like > and = into >= - reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); - // Check the precedence to see if we should "take" this operator - // - For left associative operator (all operator but **), consume the operator, - // recursively call the function below, and parse binaryExpression as a rightOperand - // of the caller if the new precedence of the operator is greater then or equal to the current precedence. - // For example: - // a - b - c; - // ^token; leftOperand = b. Return b to the caller as a rightOperand - // a * b - c - // ^token; leftOperand = b. Return b to the caller as a rightOperand - // a - b * c; - // ^token; leftOperand = b. Return b * c to the caller as a rightOperand - // - For right associative operator (**), consume the operator, recursively call the function - // and parse binaryExpression as a rightOperand of the caller if the new precedence of - // the operator is strictly grater than the current precedence - // For example: - // a ** b ** c; - // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand - // a - b ** c; - // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand - // a ** b - c - // ^token; leftOperand = b. Return b to the caller as a rightOperand - var consumeCurrentOperator = token() === 40 /* AsteriskAsteriskToken */ ? - newPrecedence >= precedence : - newPrecedence > precedence; - if (!consumeCurrentOperator) { - break; - } - if (token() === 92 /* InKeyword */ && inDisallowInContext()) { - break; - } - if (token() === 118 /* AsKeyword */) { - // Make sure we *do* perform ASI for constructs like this: - // var x = foo - // as (Bar) - // This should be parsed as an initialized variable, followed - // by a function call to 'as' with the argument 'Bar' - if (scanner.hasPrecedingLineBreak()) { - break; - } - else { - nextToken(); - leftOperand = makeAsExpression(leftOperand, parseType()); - } - } - else { - leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); - } - } - return leftOperand; - } - function isBinaryOperator() { - if (inDisallowInContext() && token() === 92 /* InKeyword */) { - return false; - } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54 /* BarBarToken */: - return 1; - case 53 /* AmpersandAmpersandToken */: - return 2; - case 49 /* BarToken */: - return 3; - case 50 /* CaretToken */: - return 4; - case 48 /* AmpersandToken */: - return 5; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 6; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - return 7; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 8; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 9; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 10; - case 40 /* AsteriskAsteriskToken */: - return 11; - } - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; - } - function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(194 /* BinaryExpression */, left.pos); - node.left = left; - node.operatorToken = operatorToken; - node.right = right; - return finishNode(node); - } - function makeAsExpression(left, right) { - var node = createNode(202 /* AsExpression */, left.pos); - node.expression = left; - node.type = right; - return finishNode(node); - } - function parsePrefixUnaryExpression() { - var node = createNode(192 /* PrefixUnaryExpression */); - node.operator = token(); - nextToken(); - node.operand = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseDeleteExpression() { - var node = createNode(188 /* DeleteExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseTypeOfExpression() { - var node = createNode(189 /* TypeOfExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseVoidExpression() { - var node = createNode(190 /* VoidExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function isAwaitExpression() { - if (token() === 121 /* AwaitKeyword */) { - if (inAwaitContext()) { - return true; - } - // here we are using similar heuristics as 'isYieldExpression' - return lookAhead(nextTokenIsIdentifierOnSameLine); - } - return false; - } - function parseAwaitExpression() { - var node = createNode(191 /* AwaitExpression */); - nextToken(); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - /** - * Parse ES7 exponential expression and await expression - * - * ES7 ExponentiationExpression: - * 1) UnaryExpression[?Yield] - * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] - * - */ - function parseUnaryExpressionOrHigher() { - /** - * ES7 UpdateExpression: - * 1) LeftHandSideExpression[?Yield] - * 2) LeftHandSideExpression[?Yield][no LineTerminator here]++ - * 3) LeftHandSideExpression[?Yield][no LineTerminator here]-- - * 4) ++UnaryExpression[?Yield] - * 5) --UnaryExpression[?Yield] - */ - if (isUpdateExpression()) { - var incrementExpression = parseIncrementExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : - incrementExpression; - } - /** - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] - * 2) delete UpdateExpression[?yield] - * 3) void UpdateExpression[?yield] - * 4) typeof UpdateExpression[?yield] - * 5) + UpdateExpression[?yield] - * 6) - UpdateExpression[?yield] - * 7) ~ UpdateExpression[?yield] - * 8) ! UpdateExpression[?yield] - */ - var unaryOperator = token(); - var simpleUnaryExpression = parseSimpleUnaryExpression(); - if (token() === 40 /* AsteriskAsteriskToken */) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 184 /* TypeAssertionExpression */) { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); - } - else { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); - } - } - return simpleUnaryExpression; - } - /** - * Parse ES7 simple-unary expression or higher: - * - * ES7 UnaryExpression: - * 1) UpdateExpression[?yield] - * 2) delete UnaryExpression[?yield] - * 3) void UnaryExpression[?yield] - * 4) typeof UnaryExpression[?yield] - * 5) + UnaryExpression[?yield] - * 6) - UnaryExpression[?yield] - * 7) ~ UnaryExpression[?yield] - * 8) ! UnaryExpression[?yield] - * 9) [+Await] await UnaryExpression[?yield] - */ - function parseSimpleUnaryExpression() { - switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - return parsePrefixUnaryExpression(); - case 80 /* DeleteKeyword */: - return parseDeleteExpression(); - case 103 /* TypeOfKeyword */: - return parseTypeOfExpression(); - case 105 /* VoidKeyword */: - return parseVoidExpression(); - case 27 /* LessThanToken */: - // This is modified UnaryExpression grammar in TypeScript - // UnaryExpression (modified): - // < type > UnaryExpression - return parseTypeAssertion(); - case 121 /* AwaitKeyword */: - if (isAwaitExpression()) { - return parseAwaitExpression(); - } - // falls through - default: - return parseIncrementExpression(); - } - } - /** - * Check if the current token can possibly be an ES7 increment expression. - * - * ES7 UpdateExpression: - * LeftHandSideExpression[?Yield] - * LeftHandSideExpression[?Yield][no LineTerminator here]++ - * LeftHandSideExpression[?Yield][no LineTerminator here]-- - * ++LeftHandSideExpression[?Yield] - * --LeftHandSideExpression[?Yield] - */ - function isUpdateExpression() { - // This function is called inside parseUnaryExpression to decide - // whether to call parseSimpleUnaryExpression or call parseIncrementExpression directly - switch (token()) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - case 51 /* ExclamationToken */: - case 80 /* DeleteKeyword */: - case 103 /* TypeOfKeyword */: - case 105 /* VoidKeyword */: - case 121 /* AwaitKeyword */: - return false; - case 27 /* LessThanToken */: - // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression - if (sourceFile.languageVariant !== 1 /* JSX */) { - return false; - } - // We are in JSX context and the token is part of JSXElement. - // falls through - default: - return true; - } - } - /** - * Parse ES7 IncrementExpression. IncrementExpression is used instead of ES6's PostFixExpression. - * - * ES7 IncrementExpression[yield]: - * 1) LeftHandSideExpression[?yield] - * 2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++ - * 3) LeftHandSideExpression[?yield] [[no LineTerminator here]]-- - * 4) ++LeftHandSideExpression[?yield] - * 5) --LeftHandSideExpression[?yield] - * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression - */ - function parseIncrementExpression() { - if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(192 /* PrefixUnaryExpression */); - node.operator = token(); - nextToken(); - node.operand = parseLeftHandSideExpressionOrHigher(); - return finishNode(node); - } - else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeyword)) { - // JSXElement is part of primaryExpression - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); - } - var expression = parseLeftHandSideExpressionOrHigher(); - ts.Debug.assert(ts.isLeftHandSideExpression(expression)); - if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(193 /* PostfixUnaryExpression */, expression.pos); - node.operand = expression; - node.operator = token(); - nextToken(); - return finishNode(node); - } - return expression; - } - function parseLeftHandSideExpressionOrHigher() { - // Original Ecma: - // LeftHandSideExpression: See 11.2 - // NewExpression - // CallExpression - // - // Our simplification: - // - // LeftHandSideExpression: See 11.2 - // MemberExpression - // CallExpression - // - // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with - // MemberExpression to make our lives easier. - // - // to best understand the below code, it's important to see how CallExpression expands - // out into its own productions: - // - // CallExpression: - // MemberExpression Arguments - // CallExpression Arguments - // CallExpression[Expression] - // CallExpression.IdentifierName - // super ( ArgumentListopt ) - // super.IdentifierName - // - // Because of the recursion in these calls, we need to bottom out first. There are two - // bottom out states we can run into. Either we see 'super' which must start either of - // the last two CallExpression productions. Or we have a MemberExpression which either - // completes the LeftHandSideExpression, or starts the beginning of the first four - // CallExpression productions. - var expression = token() === 97 /* SuperKeyword */ - ? parseSuperExpression() - : parseMemberExpressionOrHigher(); - // Now, we *may* be complete. However, we might have consumed the start of a - // CallExpression. As such, we need to consume the rest of it here to be complete. - return parseCallExpressionRest(expression); - } - function parseMemberExpressionOrHigher() { - // Note: to make our lives simpler, we decompose the the NewExpression productions and - // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. - // like so: - // - // PrimaryExpression : See 11.1 - // this - // Identifier - // Literal - // ArrayLiteral - // ObjectLiteral - // (Expression) - // FunctionExpression - // new MemberExpression Arguments? - // - // MemberExpression : See 11.2 - // PrimaryExpression - // MemberExpression[Expression] - // MemberExpression.IdentifierName - // - // CallExpression : See 11.2 - // MemberExpression - // CallExpression Arguments - // CallExpression[Expression] - // CallExpression.IdentifierName - // - // Technically this is ambiguous. i.e. CallExpression defines: - // - // CallExpression: - // CallExpression Arguments - // - // If you see: "new Foo()" - // - // Then that could be treated as a single ObjectCreationExpression, or it could be - // treated as the invocation of "new Foo". We disambiguate that in code (to match - // the original grammar) by making sure that if we see an ObjectCreationExpression - // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think - // about this is that for every "new" that we see, we will consume an argument list if - // it is there as part of the *associated* object creation node. Any additional - // argument lists we see, will become invocation expressions. - // - // Because there are no other places in the grammar now that refer to FunctionExpression - // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression - // production. - // - // Because CallExpression and MemberExpression are left recursive, we need to bottom out - // of the recursion immediately. So we parse out a primary expression to start with. - var expression = parsePrimaryExpression(); - return parseMemberExpressionRest(expression); - } - function parseSuperExpression() { - var expression = parseTokenNode(); - if (token() === 19 /* OpenParenToken */ || token() === 23 /* DotToken */ || token() === 21 /* OpenBracketToken */) { - return expression; - } - // If we have seen "super" it must be followed by '(' or '.'. - // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(179 /* PropertyAccessExpression */, expression.pos); - node.expression = expression; - parseExpectedToken(23 /* DotToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); - node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); - return finishNode(node); - } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 71 /* Identifier */) { - return lhs.text === rhs.text; - } - if (lhs.kind === 99 /* ThisKeyword */) { - return true; - } - // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only - // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression - // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element - return lhs.name.text === rhs.name.text && - tagNamesAreEquivalent(lhs.expression, rhs.expression); - } - function parseJsxElementOrSelfClosingElement(inExpressionContext) { - var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); - var result; - if (opening.kind === 251 /* JsxOpeningElement */) { - var node = createNode(249 /* JsxElement */, opening.pos); - node.openingElement = opening; - node.children = parseJsxChildren(node.openingElement.tagName); - node.closingElement = parseJsxClosingElement(inExpressionContext); - if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); - } - result = finishNode(node); - } - else { - ts.Debug.assert(opening.kind === 250 /* JsxSelfClosingElement */); - // Nothing else to do for self-closing elements - result = opening; - } - // If the user writes the invalid code '
' in an expression context (i.e. not wrapped in - // an enclosing tag), we'll naively try to parse ^ this as a 'less than' operator and the remainder of the tag - // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX - // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter - // does less damage and we can report a better error. - // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios - // of one sort or another. - if (inExpressionContext && token() === 27 /* LessThanToken */) { - var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); }); - if (invalidElement) { - parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(194 /* BinaryExpression */, result.pos); - badNode.end = invalidElement.end; - badNode.left = result; - badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); - badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; - return badNode; - } - } - return result; - } - function parseJsxText() { - var node = createNode(10 /* JsxText */, scanner.getStartPos()); - node.containsOnlyWhiteSpaces = currentToken === 11 /* JsxTextAllWhiteSpaces */; - currentToken = scanner.scanJsxToken(); - return finishNode(node); - } - function parseJsxChild() { - switch (token()) { - case 10 /* JsxText */: - case 11 /* JsxTextAllWhiteSpaces */: - return parseJsxText(); - case 17 /* OpenBraceToken */: - return parseJsxExpression(/*inExpressionContext*/ false); - case 27 /* LessThanToken */: - return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ false); - } - ts.Debug.fail("Unknown JSX child kind " + token()); - } - function parseJsxChildren(openingTagName) { - var result = createNodeArray(); - var saveParsingContext = parsingContext; - parsingContext |= 1 << 14 /* JsxChildren */; - while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28 /* LessThanSlashToken */) { - // Closing tag - break; - } - else if (token() === 1 /* EndOfFileToken */) { - // If we hit EOF, issue the error at the tag that lacks the closing element - // rather than at the end of the file (which is useless) - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); - break; - } - else if (token() === 7 /* ConflictMarkerTrivia */) { - break; - } - var child = parseJsxChild(); - if (child) { - result.push(child); - } - } - result.end = scanner.getTokenPos(); - parsingContext = saveParsingContext; - return result; - } - function parseJsxAttributes() { - var jsxAttributes = createNode(254 /* JsxAttributes */); - jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); - return finishNode(jsxAttributes); - } - function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { - var fullStart = scanner.getStartPos(); - parseExpected(27 /* LessThanToken */); - var tagName = parseJsxElementName(); - var attributes = parseJsxAttributes(); - var node; - if (token() === 29 /* GreaterThanToken */) { - // Closing tag, so scan the immediately-following text with the JSX scanning instead - // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate - // scanning errors - node = createNode(251 /* JsxOpeningElement */, fullStart); - scanJsxText(); - } - else { - parseExpected(41 /* SlashToken */); - if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); - } - else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); - } - node = createNode(250 /* JsxSelfClosingElement */, fullStart); - } - node.tagName = tagName; - node.attributes = attributes; - return finishNode(node); - } - function parseJsxElementName() { - scanJsxIdentifier(); - // JsxElement can have name in the form of - // propertyAccessExpression - // primaryExpression in the form of an identifier and "this" keyword - // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword - // We only want to consider "this" as a primaryExpression - var expression = token() === 99 /* ThisKeyword */ ? - parseTokenNode() : parseIdentifierName(); - while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); - expression = finishNode(propertyAccess); - } - return expression; - } - function parseJsxExpression(inExpressionContext) { - var node = createNode(256 /* JsxExpression */); - parseExpected(17 /* OpenBraceToken */); - if (token() !== 18 /* CloseBraceToken */) { - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - node.expression = parseAssignmentExpressionOrHigher(); - } - if (inExpressionContext) { - parseExpected(18 /* CloseBraceToken */); - } - else { - parseExpected(18 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); - } - return finishNode(node); - } - function parseJsxAttribute() { - if (token() === 17 /* OpenBraceToken */) { - return parseJsxSpreadAttribute(); - } - scanJsxIdentifier(); - var node = createNode(253 /* JsxAttribute */); - node.name = parseIdentifierName(); - if (token() === 58 /* EqualsToken */) { - switch (scanJsxAttributeValue()) { - case 9 /* StringLiteral */: - node.initializer = parseLiteralNode(); - break; - default: - node.initializer = parseJsxExpression(/*inExpressionContext*/ true); - break; - } - } - return finishNode(node); - } - function parseJsxSpreadAttribute() { - var node = createNode(255 /* JsxSpreadAttribute */); - parseExpected(17 /* OpenBraceToken */); - parseExpected(24 /* DotDotDotToken */); - node.expression = parseExpression(); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseJsxClosingElement(inExpressionContext) { - var node = createNode(252 /* JsxClosingElement */); - parseExpected(28 /* LessThanSlashToken */); - node.tagName = parseJsxElementName(); - if (inExpressionContext) { - parseExpected(29 /* GreaterThanToken */); - } - else { - parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); - scanJsxText(); - } - return finishNode(node); - } - function parseTypeAssertion() { - var node = createNode(184 /* TypeAssertionExpression */); - parseExpected(27 /* LessThanToken */); - node.type = parseType(); - parseExpected(29 /* GreaterThanToken */); - node.expression = parseSimpleUnaryExpression(); - return finishNode(node); - } - function parseMemberExpressionRest(expression) { - while (true) { - var dotToken = parseOptionalToken(23 /* DotToken */); - if (dotToken) { - var propertyAccess = createNode(179 /* PropertyAccessExpression */, expression.pos); - propertyAccess.expression = expression; - propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); - expression = finishNode(propertyAccess); - continue; - } - if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { - nextToken(); - var nonNullExpression = createNode(203 /* NonNullExpression */, expression.pos); - nonNullExpression.expression = expression; - expression = finishNode(nonNullExpression); - continue; - } - // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(180 /* ElementAccessExpression */, expression.pos); - indexedAccess.expression = expression; - // It's not uncommon for a user to write: "new Type[]". - // Check for that common pattern and report a better error message. - if (token() !== 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { - var literal = indexedAccess.argumentExpression; - literal.text = internIdentifier(literal.text); - } - } - parseExpected(22 /* CloseBracketToken */); - expression = finishNode(indexedAccess); - continue; - } - if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { - var tagExpression = createNode(183 /* TaggedTemplateExpression */, expression.pos); - tagExpression.tag = expression; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ - ? parseLiteralNode() - : parseTemplateExpression(); - expression = finishNode(tagExpression); - continue; - } - return expression; - } - } - function parseCallExpressionRest(expression) { - while (true) { - expression = parseMemberExpressionRest(expression); - if (token() === 27 /* LessThanToken */) { - // See if this is the start of a generic invocation. If so, consume it and - // keep checking for postfix expressions. Otherwise, it's just a '<' that's - // part of an arithmetic expression. Break out so we consume it higher in the - // stack. - var typeArguments = tryParse(parseTypeArgumentsInExpression); - if (!typeArguments) { - return expression; - } - var callExpr = createNode(181 /* CallExpression */, expression.pos); - callExpr.expression = expression; - callExpr.typeArguments = typeArguments; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(181 /* CallExpression */, expression.pos); - callExpr.expression = expression; - callExpr.arguments = parseArgumentList(); - expression = finishNode(callExpr); - continue; - } - return expression; - } - } - function parseArgumentList() { - parseExpected(19 /* OpenParenToken */); - var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression); - parseExpected(20 /* CloseParenToken */); - return result; - } - function parseTypeArgumentsInExpression() { - if (!parseOptional(27 /* LessThanToken */)) { - return undefined; - } - var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); - if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. - return undefined; - } - // If we have a '<', then only parse this as a argument list if the type arguments - // are complete and we have an open paren. if we don't, rewind and return nothing. - return typeArguments && canFollowTypeArgumentsInExpression() - ? typeArguments - : undefined; - } - function canFollowTypeArgumentsInExpression() { - switch (token()) { - case 19 /* OpenParenToken */: // foo( - // this case are the only case where this token can legally follow a type argument - // list. So we definitely want to treat this as a type arg list. - case 23 /* DotToken */: // foo. - case 20 /* CloseParenToken */: // foo) - case 22 /* CloseBracketToken */: // foo] - case 56 /* ColonToken */: // foo: - case 25 /* SemicolonToken */: // foo; - case 55 /* QuestionToken */: // foo? - case 32 /* EqualsEqualsToken */: // foo == - case 34 /* EqualsEqualsEqualsToken */: // foo === - case 33 /* ExclamationEqualsToken */: // foo != - case 35 /* ExclamationEqualsEqualsToken */: // foo !== - case 53 /* AmpersandAmpersandToken */: // foo && - case 54 /* BarBarToken */: // foo || - case 50 /* CaretToken */: // foo ^ - case 48 /* AmpersandToken */: // foo & - case 49 /* BarToken */: // foo | - case 18 /* CloseBraceToken */: // foo } - case 1 /* EndOfFileToken */: - // these cases can't legally follow a type arg list. However, they're not legal - // expressions either. The user is probably in the middle of a generic type. So - // treat it as such. - return true; - case 26 /* CommaToken */: // foo, - case 17 /* OpenBraceToken */: // foo { - // We don't want to treat these as type arguments. Otherwise we'll parse this - // as an invocation expression. Instead, we want to parse out the expression - // in isolation from the type arguments. - default: - // Anything else treat as an expression. - return false; - } - } - function parsePrimaryExpression() { - switch (token()) { - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - return parseLiteralNode(); - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - return parseTokenNode(); - case 19 /* OpenParenToken */: - return parseParenthesizedExpression(); - case 21 /* OpenBracketToken */: - return parseArrayLiteralExpression(); - case 17 /* OpenBraceToken */: - return parseObjectLiteralExpression(); - case 120 /* AsyncKeyword */: - // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher. - // If we encounter `async [no LineTerminator here] function` then this is an async - // function; otherwise, its an identifier. - if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { - break; - } - return parseFunctionExpression(); - case 75 /* ClassKeyword */: - return parseClassExpression(); - case 89 /* FunctionKeyword */: - return parseFunctionExpression(); - case 94 /* NewKeyword */: - return parseNewExpression(); - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { - return parseLiteralNode(); - } - break; - case 14 /* TemplateHead */: - return parseTemplateExpression(); - } - return parseIdentifier(ts.Diagnostics.Expression_expected); - } - function parseParenthesizedExpression() { - var node = createNode(185 /* ParenthesizedExpression */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - return finishNode(node); - } - function parseSpreadElement() { - var node = createNode(198 /* SpreadElement */); - parseExpected(24 /* DotDotDotToken */); - node.expression = parseAssignmentExpressionOrHigher(); - return finishNode(node); - } - function parseArgumentOrArrayLiteralElement() { - return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(200 /* OmittedExpression */) : - parseAssignmentExpressionOrHigher(); - } - function parseArgumentExpression() { - return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); - } - function parseArrayLiteralExpression() { - var node = createNode(177 /* ArrayLiteralExpression */); - parseExpected(21 /* OpenBracketToken */); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); - parseExpected(22 /* CloseBracketToken */); - return finishNode(node); - } - function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { - if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(153 /* GetAccessor */, fullStart, decorators, modifiers); - } - else if (parseContextualModifier(135 /* SetKeyword */)) { - return parseAccessorDeclaration(154 /* SetAccessor */, fullStart, decorators, modifiers); - } - return undefined; - } - function parseObjectLiteralElement() { - var fullStart = scanner.getStartPos(); - var dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - if (dotDotDotToken) { - var spreadElement = createNode(263 /* SpreadAssignment */, fullStart); - spreadElement.expression = parseAssignmentExpressionOrHigher(); - return addJSDocComment(finishNode(spreadElement)); - } - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); - } - // check if it is short-hand property assignment or normal property assignment - // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production - // CoverInitializedName[Yield] : - // IdentifierReference[?Yield] Initializer[In, ?Yield] - // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern - var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); - if (isShorthandPropertyAssignment) { - var shorthandDeclaration = createNode(262 /* ShorthandPropertyAssignment */, fullStart); - shorthandDeclaration.name = propertyName; - shorthandDeclaration.questionToken = questionToken; - var equalsToken = parseOptionalToken(58 /* EqualsToken */); - if (equalsToken) { - shorthandDeclaration.equalsToken = equalsToken; - shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); - } - return addJSDocComment(finishNode(shorthandDeclaration)); - } - else { - var propertyAssignment = createNode(261 /* PropertyAssignment */, fullStart); - propertyAssignment.modifiers = modifiers; - propertyAssignment.name = propertyName; - propertyAssignment.questionToken = questionToken; - parseExpected(56 /* ColonToken */); - propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); - return addJSDocComment(finishNode(propertyAssignment)); - } - } - function parseObjectLiteralExpression() { - var node = createNode(178 /* ObjectLiteralExpression */); - parseExpected(17 /* OpenBraceToken */); - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseFunctionExpression() { - // GeneratorExpression: - // function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody } - // - // FunctionExpression: - // function BindingIdentifier[opt](FormalParameters){ FunctionBody } - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ false); - } - var node = createNode(186 /* FunctionExpression */); - node.modifiers = parseModifiers(); - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var isGenerator = !!node.asteriskToken; - var isAsync = !!(ts.getModifierFlags(node) & 256 /* Async */); - node.name = - isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : - isGenerator ? doInYieldContext(parseOptionalIdentifier) : - isAsync ? doInAwaitContext(parseOptionalIdentifier) : - parseOptionalIdentifier(); - fillSignature(56 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlock(/*allowYield*/ isGenerator, /*allowAwait*/ isAsync, /*ignoreMissingOpenBrace*/ false); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ true); - } - return addJSDocComment(finishNode(node)); - } - function parseOptionalIdentifier() { - return isIdentifier() ? parseIdentifier() : undefined; - } - function parseNewExpression() { - var fullStart = scanner.getStartPos(); - parseExpected(94 /* NewKeyword */); - if (parseOptional(23 /* DotToken */)) { - var node_1 = createNode(204 /* MetaProperty */, fullStart); - node_1.keywordToken = 94 /* NewKeyword */; - node_1.name = parseIdentifierName(); - return finishNode(node_1); - } - var node = createNode(182 /* NewExpression */, fullStart); - node.expression = parseMemberExpressionOrHigher(); - node.typeArguments = tryParse(parseTypeArgumentsInExpression); - if (node.typeArguments || token() === 19 /* OpenParenToken */) { - node.arguments = parseArgumentList(); - } - return finishNode(node); - } - // STATEMENTS - function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(207 /* Block */); - if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { - if (scanner.hasPrecedingLineBreak()) { - node.multiLine = true; - } - node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseFunctionBlock(allowYield, allowAwait, ignoreMissingOpenBrace, diagnosticMessage) { - var savedYieldContext = inYieldContext(); - setYieldContext(allowYield); - var savedAwaitContext = inAwaitContext(); - setAwaitContext(allowAwait); - // We may be in a [Decorator] context when parsing a function expression or - // arrow function. The body of the function is not in [Decorator] context. - var saveDecoratorContext = inDecoratorContext(); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ false); - } - var block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); - if (saveDecoratorContext) { - setDecoratorContext(/*val*/ true); - } - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - return block; - } - function parseEmptyStatement() { - var node = createNode(209 /* EmptyStatement */); - parseExpected(25 /* SemicolonToken */); - return finishNode(node); - } - function parseIfStatement() { - var node = createNode(211 /* IfStatement */); - parseExpected(90 /* IfKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - node.thenStatement = parseStatement(); - node.elseStatement = parseOptional(82 /* ElseKeyword */) ? parseStatement() : undefined; - return finishNode(node); - } - function parseDoStatement() { - var node = createNode(212 /* DoStatement */); - parseExpected(81 /* DoKeyword */); - node.statement = parseStatement(); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html - // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in - // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby - // do;while(0)x will have a semicolon inserted before x. - parseOptional(25 /* SemicolonToken */); - return finishNode(node); - } - function parseWhileStatement() { - var node = createNode(213 /* WhileStatement */); - parseExpected(106 /* WhileKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - node.statement = parseStatement(); - return finishNode(node); - } - function parseForOrForInOrForOfStatement() { - var pos = getNodePos(); - parseExpected(88 /* ForKeyword */); - var awaitToken = parseOptionalToken(121 /* AwaitKeyword */); - parseExpected(19 /* OpenParenToken */); - var initializer = undefined; - if (token() !== 25 /* SemicolonToken */) { - if (token() === 104 /* VarKeyword */ || token() === 110 /* LetKeyword */ || token() === 76 /* ConstKeyword */) { - initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); - } - else { - initializer = disallowInAnd(parseExpression); - } - } - var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(142 /* OfKeyword */) : parseOptional(142 /* OfKeyword */)) { - var forOfStatement = createNode(216 /* ForOfStatement */, pos); - forOfStatement.awaitModifier = awaitToken; - forOfStatement.initializer = initializer; - forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); - parseExpected(20 /* CloseParenToken */); - forOrForInOrForOfStatement = forOfStatement; - } - else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(215 /* ForInStatement */, pos); - forInStatement.initializer = initializer; - forInStatement.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - forOrForInOrForOfStatement = forInStatement; - } - else { - var forStatement = createNode(214 /* ForStatement */, pos); - forStatement.initializer = initializer; - parseExpected(25 /* SemicolonToken */); - if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { - forStatement.condition = allowInAnd(parseExpression); - } - parseExpected(25 /* SemicolonToken */); - if (token() !== 20 /* CloseParenToken */) { - forStatement.incrementor = allowInAnd(parseExpression); - } - parseExpected(20 /* CloseParenToken */); - forOrForInOrForOfStatement = forStatement; - } - forOrForInOrForOfStatement.statement = parseStatement(); - return finishNode(forOrForInOrForOfStatement); - } - function parseBreakOrContinueStatement(kind) { - var node = createNode(kind); - parseExpected(kind === 218 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); - if (!canParseSemicolon()) { - node.label = parseIdentifier(); - } - parseSemicolon(); - return finishNode(node); - } - function parseReturnStatement() { - var node = createNode(219 /* ReturnStatement */); - parseExpected(96 /* ReturnKeyword */); - if (!canParseSemicolon()) { - node.expression = allowInAnd(parseExpression); - } - parseSemicolon(); - return finishNode(node); - } - function parseWithStatement() { - var node = createNode(220 /* WithStatement */); - parseExpected(107 /* WithKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - node.statement = parseStatement(); - return finishNode(node); - } - function parseCaseClause() { - var node = createNode(257 /* CaseClause */); - parseExpected(73 /* CaseKeyword */); - node.expression = allowInAnd(parseExpression); - parseExpected(56 /* ColonToken */); - node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); - return finishNode(node); - } - function parseDefaultClause() { - var node = createNode(258 /* DefaultClause */); - parseExpected(79 /* DefaultKeyword */); - parseExpected(56 /* ColonToken */); - node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); - return finishNode(node); - } - function parseCaseOrDefaultClause() { - return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); - } - function parseSwitchStatement() { - var node = createNode(221 /* SwitchStatement */); - parseExpected(98 /* SwitchKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = allowInAnd(parseExpression); - parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(235 /* CaseBlock */, scanner.getStartPos()); - parseExpected(17 /* OpenBraceToken */); - caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); - parseExpected(18 /* CloseBraceToken */); - node.caseBlock = finishNode(caseBlock); - return finishNode(node); - } - function parseThrowStatement() { - // ThrowStatement[Yield] : - // throw [no LineTerminator here]Expression[In, ?Yield]; - // Because of automatic semicolon insertion, we need to report error if this - // throw could be terminated with a semicolon. Note: we can't call 'parseExpression' - // directly as that might consume an expression on the following line. - // We just return 'undefined' in that case. The actual error will be reported in the - // grammar walker. - var node = createNode(223 /* ThrowStatement */); - parseExpected(100 /* ThrowKeyword */); - node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); - parseSemicolon(); - return finishNode(node); - } - // TODO: Review for error recovery - function parseTryStatement() { - var node = createNode(224 /* TryStatement */); - parseExpected(102 /* TryKeyword */); - node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; - // If we don't have a catch clause, then we must have a finally clause. Try to parse - // one out no matter what. - if (!node.catchClause || token() === 87 /* FinallyKeyword */) { - parseExpected(87 /* FinallyKeyword */); - node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - } - return finishNode(node); - } - function parseCatchClause() { - var result = createNode(260 /* CatchClause */); - parseExpected(74 /* CatchKeyword */); - if (parseExpected(19 /* OpenParenToken */)) { - result.variableDeclaration = parseVariableDeclaration(); - } - parseExpected(20 /* CloseParenToken */); - result.block = parseBlock(/*ignoreMissingOpenBrace*/ false); - return finishNode(result); - } - function parseDebuggerStatement() { - var node = createNode(225 /* DebuggerStatement */); - parseExpected(78 /* DebuggerKeyword */); - parseSemicolon(); - return finishNode(node); - } - function parseExpressionOrLabeledStatement() { - // Avoiding having to do the lookahead for a labeled statement by just trying to parse - // out an expression, seeing if it is identifier and then seeing if it is followed by - // a colon. - var fullStart = scanner.getStartPos(); - var expression = allowInAnd(parseExpression); - if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - var labeledStatement = createNode(222 /* LabeledStatement */, fullStart); - labeledStatement.label = expression; - labeledStatement.statement = parseStatement(); - return addJSDocComment(finishNode(labeledStatement)); - } - else { - var expressionStatement = createNode(210 /* ExpressionStatement */, fullStart); - expressionStatement.expression = expression; - parseSemicolon(); - return addJSDocComment(finishNode(expressionStatement)); - } - } - function nextTokenIsIdentifierOrKeywordOnSameLine() { - nextToken(); - return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsClassKeywordOnSameLine() { - nextToken(); - return token() === 75 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsFunctionKeywordOnSameLine() { - nextToken(); - return token() === 89 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak(); - } - function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() { - nextToken(); - return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */) && !scanner.hasPrecedingLineBreak(); - } - function isDeclaration() { - while (true) { - switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - return true; - // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; - // however, an identifier cannot be followed by another identifier on the same line. This is what we - // count on to parse out the respective declarations. For instance, we exploit this to say that - // - // namespace n - // - // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees - // - // namespace - // n - // - // as the identifier 'namespace' on one line followed by the identifier 'n' on another. - // We need to look one token ahead to see if it permissible to try parsing a declaration. - // - // *Note*: 'interface' is actually a strict mode reserved word. So while - // - // "use strict" - // interface - // I {} - // - // could be legal, it would add complexity for very little gain. - case 109 /* InterfaceKeyword */: - case 138 /* TypeKeyword */: - return nextTokenIsIdentifierOnSameLine(); - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - return nextTokenIsIdentifierOrStringLiteralOnSameLine(); - case 117 /* AbstractKeyword */: - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 131 /* ReadonlyKeyword */: - nextToken(); - // ASI takes effect for this modifier. - if (scanner.hasPrecedingLineBreak()) { - return false; - } - continue; - case 141 /* GlobalKeyword */: - nextToken(); - return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; - case 91 /* ImportKeyword */: - nextToken(); - return token() === 9 /* StringLiteral */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token()); - case 84 /* ExportKeyword */: - nextToken(); - if (token() === 58 /* EqualsToken */ || token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */ || token() === 79 /* DefaultKeyword */ || - token() === 118 /* AsKeyword */) { - return true; - } - continue; - case 115 /* StaticKeyword */: - nextToken(); - continue; - default: - return false; - } - } - } - function isStartOfDeclaration() { - return lookAhead(isDeclaration); - } - function isStartOfStatement() { - switch (token()) { - case 57 /* AtToken */: - case 25 /* SemicolonToken */: - case 17 /* OpenBraceToken */: - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 89 /* FunctionKeyword */: - case 75 /* ClassKeyword */: - case 83 /* EnumKeyword */: - case 90 /* IfKeyword */: - case 81 /* DoKeyword */: - case 106 /* WhileKeyword */: - case 88 /* ForKeyword */: - case 77 /* ContinueKeyword */: - case 72 /* BreakKeyword */: - case 96 /* ReturnKeyword */: - case 107 /* WithKeyword */: - case 98 /* SwitchKeyword */: - case 100 /* ThrowKeyword */: - case 102 /* TryKeyword */: - case 78 /* DebuggerKeyword */: - // 'catch' and 'finally' do not actually indicate that the code is part of a statement, - // however, we say they are here so that we may gracefully parse them and error later. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - return true; - case 76 /* ConstKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - return isStartOfDeclaration(); - case 120 /* AsyncKeyword */: - case 124 /* DeclareKeyword */: - case 109 /* InterfaceKeyword */: - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - case 138 /* TypeKeyword */: - case 141 /* GlobalKeyword */: - // When these don't start a declaration, they're an identifier in an expression statement - return true; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 131 /* ReadonlyKeyword */: - // When these don't start a declaration, they may be the start of a class member if an identifier - // immediately follows. Otherwise they're an identifier in an expression statement. - return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); - default: - return isStartOfExpression(); - } - } - function nextTokenIsIdentifierOrStartOfDestructuring() { - nextToken(); - return isIdentifier() || token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */; - } - function isLetDeclaration() { - // In ES6 'let' always starts a lexical declaration if followed by an identifier or { - // or [. - return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); - } - function parseStatement() { - switch (token()) { - case 25 /* SemicolonToken */: - return parseEmptyStatement(); - case 17 /* OpenBraceToken */: - return parseBlock(/*ignoreMissingOpenBrace*/ false); - case 104 /* VarKeyword */: - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 110 /* LetKeyword */: - if (isLetDeclaration()) { - return parseVariableStatement(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - } - break; - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 75 /* ClassKeyword */: - return parseClassDeclaration(scanner.getStartPos(), /*decorators*/ undefined, /*modifiers*/ undefined); - case 90 /* IfKeyword */: - return parseIfStatement(); - case 81 /* DoKeyword */: - return parseDoStatement(); - case 106 /* WhileKeyword */: - return parseWhileStatement(); - case 88 /* ForKeyword */: - return parseForOrForInOrForOfStatement(); - case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(217 /* ContinueStatement */); - case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(218 /* BreakStatement */); - case 96 /* ReturnKeyword */: - return parseReturnStatement(); - case 107 /* WithKeyword */: - return parseWithStatement(); - case 98 /* SwitchKeyword */: - return parseSwitchStatement(); - case 100 /* ThrowKeyword */: - return parseThrowStatement(); - case 102 /* TryKeyword */: - // Include 'catch' and 'finally' for error recovery. - case 74 /* CatchKeyword */: - case 87 /* FinallyKeyword */: - return parseTryStatement(); - case 78 /* DebuggerKeyword */: - return parseDebuggerStatement(); - case 57 /* AtToken */: - return parseDeclaration(); - case 120 /* AsyncKeyword */: - case 109 /* InterfaceKeyword */: - case 138 /* TypeKeyword */: - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 83 /* EnumKeyword */: - case 84 /* ExportKeyword */: - case 91 /* ImportKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 114 /* PublicKeyword */: - case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: - case 131 /* ReadonlyKeyword */: - case 141 /* GlobalKeyword */: - if (isStartOfDeclaration()) { - return parseDeclaration(); - } - break; - } - return parseExpressionOrLabeledStatement(); - } - function parseDeclaration() { - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(); - switch (token()) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - return parseVariableStatement(fullStart, decorators, modifiers); - case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(fullStart, decorators, modifiers); - case 75 /* ClassKeyword */: - return parseClassDeclaration(fullStart, decorators, modifiers); - case 109 /* InterfaceKeyword */: - return parseInterfaceDeclaration(fullStart, decorators, modifiers); - case 138 /* TypeKeyword */: - return parseTypeAliasDeclaration(fullStart, decorators, modifiers); - case 83 /* EnumKeyword */: - return parseEnumDeclaration(fullStart, decorators, modifiers); - case 141 /* GlobalKeyword */: - case 128 /* ModuleKeyword */: - case 129 /* NamespaceKeyword */: - return parseModuleDeclaration(fullStart, decorators, modifiers); - case 91 /* ImportKeyword */: - return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); - case 84 /* ExportKeyword */: - nextToken(); - switch (token()) { - case 79 /* DefaultKeyword */: - case 58 /* EqualsToken */: - return parseExportAssignment(fullStart, decorators, modifiers); - case 118 /* AsKeyword */: - return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); - default: - return parseExportDeclaration(fullStart, decorators, modifiers); - } - default: - if (decorators || modifiers) { - // We reached this point because we encountered decorators and/or modifiers and assumed a declaration - // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var node = createMissingNode(247 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - node.pos = fullStart; - node.decorators = decorators; - node.modifiers = modifiers; - return finishNode(node); - } - } - } - function nextTokenIsIdentifierOrStringLiteralOnSameLine() { - nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9 /* StringLiteral */); - } - function parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage) { - if (token() !== 17 /* OpenBraceToken */ && canParseSemicolon()) { - parseSemicolon(); - return; - } - return parseFunctionBlock(isGenerator, isAsync, /*ignoreMissingOpenBrace*/ false, diagnosticMessage); - } - // DECLARATIONS - function parseArrayBindingElement() { - if (token() === 26 /* CommaToken */) { - return createNode(200 /* OmittedExpression */); - } - var node = createNode(176 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - node.name = parseIdentifierOrPattern(); - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); - return finishNode(node); - } - function parseObjectBindingElement() { - var node = createNode(176 /* BindingElement */); - node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); - var tokenIsIdentifier = isIdentifier(); - var propertyName = parsePropertyName(); - if (tokenIsIdentifier && token() !== 56 /* ColonToken */) { - node.name = propertyName; - } - else { - parseExpected(56 /* ColonToken */); - node.propertyName = propertyName; - node.name = parseIdentifierOrPattern(); - } - node.initializer = parseBindingElementInitializer(/*inParameter*/ false); - return finishNode(node); - } - function parseObjectBindingPattern() { - var node = createNode(174 /* ObjectBindingPattern */); - parseExpected(17 /* OpenBraceToken */); - node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); - parseExpected(18 /* CloseBraceToken */); - return finishNode(node); - } - function parseArrayBindingPattern() { - var node = createNode(175 /* ArrayBindingPattern */); - parseExpected(21 /* OpenBracketToken */); - node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); - parseExpected(22 /* CloseBracketToken */); - return finishNode(node); - } - function isIdentifierOrPattern() { - return token() === 17 /* OpenBraceToken */ || token() === 21 /* OpenBracketToken */ || isIdentifier(); - } - function parseIdentifierOrPattern() { - if (token() === 21 /* OpenBracketToken */) { - return parseArrayBindingPattern(); - } - if (token() === 17 /* OpenBraceToken */) { - return parseObjectBindingPattern(); - } - return parseIdentifier(); - } - function parseVariableDeclaration() { - var node = createNode(226 /* VariableDeclaration */); - node.name = parseIdentifierOrPattern(); - node.type = parseTypeAnnotation(); - if (!isInOrOfKeyword(token())) { - node.initializer = parseInitializer(/*inParameter*/ false); - } - return finishNode(node); - } - function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(227 /* VariableDeclarationList */); - switch (token()) { - case 104 /* VarKeyword */: - break; - case 110 /* LetKeyword */: - node.flags |= 1 /* Let */; - break; - case 76 /* ConstKeyword */: - node.flags |= 2 /* Const */; - break; - default: - ts.Debug.fail(); - } - nextToken(); - // The user may have written the following: - // - // for (let of X) { } - // - // In this case, we want to parse an empty declaration list, and then parse 'of' - // as a keyword. The reason this is not automatic is that 'of' is a valid identifier. - // So we need to look ahead to determine if 'of' should be treated as a keyword in - // this context. - // The checker will then give an error that there is an empty declaration list. - if (token() === 142 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { - node.declarations = createMissingList(); - } - else { - var savedDisallowIn = inDisallowInContext(); - setDisallowInContext(inForStatementInitializer); - node.declarations = parseDelimitedList(8 /* VariableDeclarations */, parseVariableDeclaration); - setDisallowInContext(savedDisallowIn); - } - return finishNode(node); - } - function canFollowContextualOfKeyword() { - return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; - } - function parseVariableStatement(fullStart, decorators, modifiers) { - var node = createNode(208 /* VariableStatement */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - function parseFunctionDeclaration(fullStart, decorators, modifiers) { - var node = createNode(228 /* FunctionDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(89 /* FunctionKeyword */); - node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); - var isGenerator = !!node.asteriskToken; - var isAsync = ts.hasModifier(node, 256 /* Async */); - fillSignature(56 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseConstructorDeclaration(pos, decorators, modifiers) { - var node = createNode(152 /* Constructor */, pos); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(123 /* ConstructorKeyword */); - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false, ts.Diagnostics.or_expected); - return addJSDocComment(finishNode(node)); - } - function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { - var method = createNode(151 /* MethodDeclaration */, fullStart); - method.decorators = decorators; - method.modifiers = modifiers; - method.asteriskToken = asteriskToken; - method.name = name; - method.questionToken = questionToken; - var isGenerator = !!asteriskToken; - var isAsync = ts.hasModifier(method, 256 /* Async */); - fillSignature(56 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); - method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); - return addJSDocComment(finishNode(method)); - } - function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { - var property = createNode(149 /* PropertyDeclaration */, fullStart); - property.decorators = decorators; - property.modifiers = modifiers; - property.name = name; - property.questionToken = questionToken; - property.type = parseTypeAnnotation(); - // For instance properties specifically, since they are evaluated inside the constructor, - // we do *not * want to parse yield expressions, so we specifically turn the yield context - // off. The grammar would look something like this: - // - // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; - // - // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = ts.hasModifier(property, 32 /* Static */) - ? allowInAnd(parseNonParameterInitializer) - : doOutsideOfContext(4096 /* YieldContext */ | 2048 /* DisallowInContext */, parseNonParameterInitializer); - parseSemicolon(); - return addJSDocComment(finishNode(property)); - } - function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { - var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); - var name = parsePropertyName(); - // Note: this is not legal as per the grammar. But we allow it in the parser and - // report an error in the grammar checker. - var questionToken = parseOptionalToken(55 /* QuestionToken */); - if (asteriskToken || token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); - } - else { - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); - } - } - function parseNonParameterInitializer() { - return parseInitializer(/*inParameter*/ false); - } - function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - node.name = parsePropertyName(); - fillSignature(56 /* ColonToken */, /*yieldContext*/ false, /*awaitContext*/ false, /*requireCompleteParameterList*/ false, node); - node.body = parseFunctionBlockOrSemicolon(/*isGenerator*/ false, /*isAsync*/ false); - return addJSDocComment(finishNode(node)); - } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 131 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } - function isClassMemberStart() { - var idToken; - if (token() === 57 /* AtToken */) { - return true; - } - // Eat up all modifiers, but hold on to the last one in case it is actually an identifier. - while (ts.isModifierKind(token())) { - idToken = token(); - // If the idToken is a class modifier (protected, private, public, and static), it is - // certain that we are starting to parse class member. This allows better error recovery - // Example: - // public foo() ... // true - // public @dec blah ... // true; we will then report an error later - // export public ... // true; we will then report an error later - if (isClassMemberModifier(idToken)) { - return true; - } - nextToken(); - } - if (token() === 39 /* AsteriskToken */) { - return true; - } - // Try to get the first property-like token following all modifiers. - // This can either be an identifier or the 'get' or 'set' keywords. - if (isLiteralPropertyName()) { - idToken = token(); - nextToken(); - } - // Index signatures and computed properties are class members; we can parse. - if (token() === 21 /* OpenBracketToken */) { - return true; - } - // If we were able to get any potential identifier... - if (idToken !== undefined) { - // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!ts.isKeyword(idToken) || idToken === 135 /* SetKeyword */ || idToken === 125 /* GetKeyword */) { - return true; - } - // If it *is* a keyword, but not an accessor, check a little farther along - // to see if it should actually be parsed as a class member. - switch (token()) { - case 19 /* OpenParenToken */: // Method declaration - case 27 /* LessThanToken */: // Generic Method declaration - case 56 /* ColonToken */: // Type Annotation for declaration - case 58 /* EqualsToken */: // Initializer for declaration - case 55 /* QuestionToken */: - return true; - default: - // Covers - // - Semicolons (declaration termination) - // - Closing braces (end-of-class, must be declaration) - // - End-of-files (not valid, but permitted so that it gets caught later on) - // - Line-breaks (enabling *automatic semicolon insertion*) - return canParseSemicolon(); - } - } - return false; - } - function parseDecorators() { - var decorators; - while (true) { - var decoratorStart = getNodePos(); - if (!parseOptional(57 /* AtToken */)) { - break; - } - var decorator = createNode(147 /* Decorator */, decoratorStart); - decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); - finishNode(decorator); - if (!decorators) { - decorators = createNodeArray([decorator], decoratorStart); - } - else { - decorators.push(decorator); - } - } - if (decorators) { - decorators.end = getNodeEnd(); - } - return decorators; - } - /* - * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member. - * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect - * and turns it into a standalone declaration), then it is better to parse it and report an error later. - * - * In such situations, 'permitInvalidConstAsModifier' should be set to true. - */ - function parseModifiers(permitInvalidConstAsModifier) { - var modifiers; - while (true) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - if (token() === 76 /* ConstKeyword */ && permitInvalidConstAsModifier) { - // We need to ensure that any subsequent modifiers appear on the same line - // so that when 'const' is a standalone declaration, we don't issue an error. - if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { - break; - } - } - else { - if (!parseAnyContextualModifier()) { - break; - } - } - var modifier = finishNode(createNode(modifierKind, modifierStart)); - if (!modifiers) { - modifiers = createNodeArray([modifier], modifierStart); - } - else { - modifiers.push(modifier); - } - } - if (modifiers) { - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseModifiersForArrowFunction() { - var modifiers; - if (token() === 120 /* AsyncKeyword */) { - var modifierStart = scanner.getStartPos(); - var modifierKind = token(); - nextToken(); - var modifier = finishNode(createNode(modifierKind, modifierStart)); - modifiers = createNodeArray([modifier], modifierStart); - modifiers.end = scanner.getStartPos(); - } - return modifiers; - } - function parseClassElement() { - if (token() === 25 /* SemicolonToken */) { - var result = createNode(206 /* SemicolonClassElement */); - nextToken(); - return finishNode(result); - } - var fullStart = getNodePos(); - var decorators = parseDecorators(); - var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); - var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); - if (accessor) { - return accessor; - } - if (token() === 123 /* ConstructorKeyword */) { - return parseConstructorDeclaration(fullStart, decorators, modifiers); - } - if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); - } - // It is very important that we check this *after* checking indexers because - // the [ token can start an index signature or a computed property name - if (ts.tokenIsIdentifierOrKeyword(token()) || - token() === 9 /* StringLiteral */ || - token() === 8 /* NumericLiteral */ || - token() === 39 /* AsteriskToken */ || - token() === 21 /* OpenBracketToken */) { - return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); - } - if (decorators || modifiers) { - // treat this as a property declaration with a missing name. - var name = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); - } - // 'isClassMemberStart' should have hinted not to attempt parsing. - ts.Debug.fail("Should not have attempted to parse class member declaration."); - } - function parseClassExpression() { - return parseClassDeclarationOrExpression( - /*fullStart*/ scanner.getStartPos(), - /*decorators*/ undefined, - /*modifiers*/ undefined, 199 /* ClassExpression */); - } - function parseClassDeclaration(fullStart, decorators, modifiers) { - return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229 /* ClassDeclaration */); - } - function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { - var node = createNode(kind, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(75 /* ClassKeyword */); - node.name = parseNameOfClassDeclarationOrExpression(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - if (parseExpected(17 /* OpenBraceToken */)) { - // ClassTail[Yield,Await] : (Modified) See 14.5 - // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } - node.members = parseClassMembers(); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseNameOfClassDeclarationOrExpression() { - // implements is a future reserved word so - // 'class implements' might mean either - // - class expression with omitted name, 'implements' starts heritage clause - // - class with name 'implements' - // 'isImplementsClause' helps to disambiguate between these two cases - return isIdentifier() && !isImplementsClause() - ? parseIdentifier() - : undefined; - } - function isImplementsClause() { - return token() === 108 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword); - } - function parseHeritageClauses() { - // ClassTail[Yield,Await] : (Modified) See 14.5 - // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } - if (isHeritageClause()) { - return parseList(21 /* HeritageClauses */, parseHeritageClause); - } - return undefined; - } - function parseHeritageClause() { - var tok = token(); - if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(259 /* HeritageClause */); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; - } - function parseExpressionWithTypeArguments() { - var node = createNode(201 /* ExpressionWithTypeArguments */); - node.expression = parseLeftHandSideExpressionOrHigher(); - if (token() === 27 /* LessThanToken */) { - node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); - } - return finishNode(node); - } - function isHeritageClause() { - return token() === 85 /* ExtendsKeyword */ || token() === 108 /* ImplementsKeyword */; - } - function parseClassMembers() { - return parseList(5 /* ClassMembers */, parseClassElement); - } - function parseInterfaceDeclaration(fullStart, decorators, modifiers) { - var node = createNode(230 /* InterfaceDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(109 /* InterfaceKeyword */); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - node.heritageClauses = parseHeritageClauses(); - node.members = parseObjectTypeMembers(); - return addJSDocComment(finishNode(node)); - } - function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { - var node = createNode(231 /* TypeAliasDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(138 /* TypeKeyword */); - node.name = parseIdentifier(); - node.typeParameters = parseTypeParameters(); - parseExpected(58 /* EqualsToken */); - node.type = parseType(); - parseSemicolon(); - return addJSDocComment(finishNode(node)); - } - // In an ambient declaration, the grammar only allows integer literals as initializers. - // In a non-ambient declaration, the grammar allows uninitialized members only in a - // ConstantEnumMemberSection, which starts at the beginning of an enum declaration - // or any time an integer literal initializer is encountered. - function parseEnumMember() { - var node = createNode(264 /* EnumMember */, scanner.getStartPos()); - node.name = parsePropertyName(); - node.initializer = allowInAnd(parseNonParameterInitializer); - return addJSDocComment(finishNode(node)); - } - function parseEnumDeclaration(fullStart, decorators, modifiers) { - var node = createNode(232 /* EnumDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - parseExpected(83 /* EnumKeyword */); - node.name = parseIdentifier(); - if (parseExpected(17 /* OpenBraceToken */)) { - node.members = parseDelimitedList(6 /* EnumMembers */, parseEnumMember); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.members = createMissingList(); - } - return addJSDocComment(finishNode(node)); - } - function parseModuleBlock() { - var node = createNode(234 /* ModuleBlock */, scanner.getStartPos()); - if (parseExpected(17 /* OpenBraceToken */)) { - node.statements = parseList(1 /* BlockStatements */, parseStatement); - parseExpected(18 /* CloseBraceToken */); - } - else { - node.statements = createMissingList(); - } - return finishNode(node); - } - function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); - // If we are parsing a dotted namespace name, we want to - // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 16 /* Namespace */; - node.decorators = decorators; - node.modifiers = modifiers; - node.flags |= flags; - node.name = parseIdentifier(); - node.body = parseOptional(23 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag) - : parseModuleBlock(); - return addJSDocComment(finishNode(node)); - } - function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { - var node = createNode(233 /* ModuleDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (token() === 141 /* GlobalKeyword */) { - // parse 'global' as name of global scope augmentation - node.name = parseIdentifier(); - node.flags |= 512 /* GlobalAugmentation */; - } - else { - node.name = parseLiteralNode(/*internName*/ true); - } - if (token() === 17 /* OpenBraceToken */) { - node.body = parseModuleBlock(); - } - else { - parseSemicolon(); - } - return finishNode(node); - } - function parseModuleDeclaration(fullStart, decorators, modifiers) { - var flags = 0; - if (token() === 141 /* GlobalKeyword */) { - // global augmentation - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - else if (parseOptional(129 /* NamespaceKeyword */)) { - flags |= 16 /* Namespace */; - } - else { - parseExpected(128 /* ModuleKeyword */); - if (token() === 9 /* StringLiteral */) { - return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); - } - } - return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); - } - function isExternalModuleReference() { - return token() === 132 /* RequireKeyword */ && - lookAhead(nextTokenIsOpenParen); - } - function nextTokenIsOpenParen() { - return nextToken() === 19 /* OpenParenToken */; - } - function nextTokenIsSlash() { - return nextToken() === 41 /* SlashToken */; - } - function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { - var exportDeclaration = createNode(236 /* NamespaceExportDeclaration */, fullStart); - exportDeclaration.decorators = decorators; - exportDeclaration.modifiers = modifiers; - parseExpected(118 /* AsKeyword */); - parseExpected(129 /* NamespaceKeyword */); - exportDeclaration.name = parseIdentifier(); - parseSemicolon(); - return finishNode(exportDeclaration); - } - function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { - parseExpected(91 /* ImportKeyword */); - var afterImportPos = scanner.getStartPos(); - var identifier; - if (isIdentifier()) { - identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 140 /* FromKeyword */) { - return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); - } - } - // Import statement - var importDeclaration = createNode(238 /* ImportDeclaration */, fullStart); - importDeclaration.decorators = decorators; - importDeclaration.modifiers = modifiers; - // ImportDeclaration: - // import ImportClause from ModuleSpecifier ; - // import ModuleSpecifier; - if (identifier || - token() === 39 /* AsteriskToken */ || - token() === 17 /* OpenBraceToken */) { - importDeclaration.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(140 /* FromKeyword */); - } - importDeclaration.moduleSpecifier = parseModuleSpecifier(); - parseSemicolon(); - return finishNode(importDeclaration); - } - function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { - var importEqualsDeclaration = createNode(237 /* ImportEqualsDeclaration */, fullStart); - importEqualsDeclaration.decorators = decorators; - importEqualsDeclaration.modifiers = modifiers; - importEqualsDeclaration.name = identifier; - parseExpected(58 /* EqualsToken */); - importEqualsDeclaration.moduleReference = parseModuleReference(); - parseSemicolon(); - return addJSDocComment(finishNode(importEqualsDeclaration)); - } - function parseImportClause(identifier, fullStart) { - // ImportClause: - // ImportedDefaultBinding - // NameSpaceImport - // NamedImports - // ImportedDefaultBinding, NameSpaceImport - // ImportedDefaultBinding, NamedImports - var importClause = createNode(239 /* ImportClause */, fullStart); - if (identifier) { - // ImportedDefaultBinding: - // ImportedBinding - importClause.name = identifier; - } - // If there was no default import or if there is comma token after default import - // parse namespace or named imports - if (!importClause.name || - parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(241 /* NamedImports */); - } - return finishNode(importClause); - } - function parseModuleReference() { - return isExternalModuleReference() - ? parseExternalModuleReference() - : parseEntityName(/*allowReservedWords*/ false); - } - function parseExternalModuleReference() { - var node = createNode(248 /* ExternalModuleReference */); - parseExpected(132 /* RequireKeyword */); - parseExpected(19 /* OpenParenToken */); - node.expression = parseModuleSpecifier(); - parseExpected(20 /* CloseParenToken */); - return finishNode(node); - } - function parseModuleSpecifier() { - if (token() === 9 /* StringLiteral */) { - var result = parseLiteralNode(); - internIdentifier(result.text); - return result; - } - else { - // We allow arbitrary expressions here, even though the grammar only allows string - // literals. We check to ensure that it is only a string literal later in the grammar - // check pass. - return parseExpression(); - } - } - function parseNamespaceImport() { - // NameSpaceImport: - // * as ImportedBinding - var namespaceImport = createNode(240 /* NamespaceImport */); - parseExpected(39 /* AsteriskToken */); - parseExpected(118 /* AsKeyword */); - namespaceImport.name = parseIdentifier(); - return finishNode(namespaceImport); - } - function parseNamedImportsOrExports(kind) { - var node = createNode(kind); - // NamedImports: - // { } - // { ImportsList } - // { ImportsList, } - // ImportsList: - // ImportSpecifier - // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 241 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); - return finishNode(node); - } - function parseExportSpecifier() { - return parseImportOrExportSpecifier(246 /* ExportSpecifier */); - } - function parseImportSpecifier() { - return parseImportOrExportSpecifier(242 /* ImportSpecifier */); - } - function parseImportOrExportSpecifier(kind) { - var node = createNode(kind); - // ImportSpecifier: - // BindingIdentifier - // IdentifierName as BindingIdentifier - // ExportSpecifier: - // IdentifierName - // IdentifierName as IdentifierName - var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - var checkIdentifierStart = scanner.getTokenPos(); - var checkIdentifierEnd = scanner.getTextPos(); - var identifierName = parseIdentifierName(); - if (token() === 118 /* AsKeyword */) { - node.propertyName = identifierName; - parseExpected(118 /* AsKeyword */); - checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); - checkIdentifierStart = scanner.getTokenPos(); - checkIdentifierEnd = scanner.getTextPos(); - node.name = parseIdentifierName(); - } - else { - node.name = identifierName; - } - if (kind === 242 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); - } - return finishNode(node); - } - function parseExportDeclaration(fullStart, decorators, modifiers) { - var node = createNode(244 /* ExportDeclaration */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(140 /* FromKeyword */); - node.moduleSpecifier = parseModuleSpecifier(); - } - else { - node.exportClause = parseNamedImportsOrExports(245 /* NamedExports */); - // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, - // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) - // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 140 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(140 /* FromKeyword */); - node.moduleSpecifier = parseModuleSpecifier(); - } - } - parseSemicolon(); - return finishNode(node); - } - function parseExportAssignment(fullStart, decorators, modifiers) { - var node = createNode(243 /* ExportAssignment */, fullStart); - node.decorators = decorators; - node.modifiers = modifiers; - if (parseOptional(58 /* EqualsToken */)) { - node.isExportEquals = true; - } - else { - parseExpected(79 /* DefaultKeyword */); - } - node.expression = parseAssignmentExpressionOrHigher(); - parseSemicolon(); - return finishNode(node); - } - function processReferenceComments(sourceFile) { - var triviaScanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); - var referencedFiles = []; - var typeReferenceDirectives = []; - var amdDependencies = []; - var amdModuleName; - var checkJsDirective = undefined; - // Keep scanning all the leading trivia in the file until we get to something that - // isn't trivia. Any single line comment will be analyzed to see if it is a - // reference comment. - while (true) { - var kind = triviaScanner.scan(); - if (kind !== 2 /* SingleLineCommentTrivia */) { - if (ts.isTrivia(kind)) { - continue; - } - else { - break; - } - } - var range = { - kind: triviaScanner.getToken(), - pos: triviaScanner.getTokenPos(), - end: triviaScanner.getTextPos(), - }; - var comment = sourceText.substring(range.pos, range.end); - var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); - if (referencePathMatchResult) { - var fileReference = referencePathMatchResult.fileReference; - sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - var diagnosticMessage = referencePathMatchResult.diagnosticMessage; - if (fileReference) { - if (referencePathMatchResult.isTypeReferenceDirective) { - typeReferenceDirectives.push(fileReference); - } - else { - referencedFiles.push(fileReference); - } - } - if (diagnosticMessage) { - parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); - } - } - else { - var amdModuleNameRegEx = /^\/\/\/\s*".length; - return parseErrorAtPosition(start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function parseQualifiedName(left) { - var result = createNode(143 /* QualifiedName */, left.pos); - result.left = left; - result.right = parseIdentifierName(); - return finishNode(result); - } - function parseJSDocRecordType() { - var result = createNode(275 /* JSDocRecordType */); - result.literal = parseTypeLiteral(); - return finishNode(result); - } - function parseJSDocNonNullableType() { - var result = createNode(274 /* JSDocNonNullableType */); - nextToken(); - result.type = parseJSDocType(); - return finishNode(result); - } - function parseJSDocTupleType() { - var result = createNode(272 /* JSDocTupleType */); - nextToken(); - result.types = parseDelimitedList(26 /* JSDocTupleTypes */, parseJSDocType); - checkForTrailingComma(result.types); - parseExpected(22 /* CloseBracketToken */); - return finishNode(result); - } - function checkForTrailingComma(list) { - if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - var start = list.end - ",".length; - parseErrorAtPosition(start, ",".length, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function parseJSDocUnionType() { - var result = createNode(271 /* JSDocUnionType */); - nextToken(); - result.types = parseJSDocTypeList(parseJSDocType()); - parseExpected(20 /* CloseParenToken */); - return finishNode(result); - } - function parseJSDocTypeList(firstType) { - ts.Debug.assert(!!firstType); - var types = createNodeArray([firstType], firstType.pos); - while (parseOptional(49 /* BarToken */)) { - types.push(parseJSDocType()); - } - types.end = scanner.getStartPos(); - return types; - } - function parseJSDocAllType() { - var result = createNode(268 /* JSDocAllType */); - nextToken(); - return finishNode(result); - } - function parseJSDocLiteralType() { - var result = createNode(293 /* JSDocLiteralType */); - result.literal = parseLiteralTypeNode(); - return finishNode(result); - } - function parseJSDocUnknownOrNullableType() { - var pos = scanner.getStartPos(); - // skip the ? - nextToken(); - // Need to lookahead to decide if this is a nullable or unknown type. - // Here are cases where we'll pick the unknown type: - // - // Foo(?, - // { a: ? } - // Foo(?) - // Foo - // Foo(?= - // (?| - if (token() === 26 /* CommaToken */ || - token() === 18 /* CloseBraceToken */ || - token() === 20 /* CloseParenToken */ || - token() === 29 /* GreaterThanToken */ || - token() === 58 /* EqualsToken */ || - token() === 49 /* BarToken */) { - var result = createNode(269 /* JSDocUnknownType */, pos); - return finishNode(result); - } - else { - var result = createNode(273 /* JSDocNullableType */, pos); - result.type = parseJSDocType(); - return finishNode(result); - } - } - function parseIsolatedJSDocComment(content, start, length) { - initializeState(content, 5 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */); - sourceFile = { languageVariant: 0 /* Standard */, text: content }; - var jsDoc = parseJSDocCommentWorker(start, length); - var diagnostics = parseDiagnostics; - clearState(); - return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined; - } - JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; - function parseJSDocComment(parent, start, length) { - var saveToken = currentToken; - var saveParseDiagnosticsLength = parseDiagnostics.length; - var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; - var comment = parseJSDocCommentWorker(start, length); - if (comment) { - comment.parent = parent; - } - currentToken = saveToken; - parseDiagnostics.length = saveParseDiagnosticsLength; - parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; - 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; - var end = length === undefined ? content.length : start + length; - length = end - start; - ts.Debug.assert(start >= 0); - ts.Debug.assert(start <= end); - ts.Debug.assert(end <= content.length); - var tags; - var comments = []; - var result; - // Check for /** (JSDoc opening part) - if (!isJsDocStart(content, start)) { - return result; - } - // + 3 for leading /**, - 5 in total for /** */ - scanner.scanRange(start + 3, length - 5, function () { - // Initially we can parse out a tag. We also have seen a starting asterisk. - // This is so that /** * @type */ doesn't parse. - var advanceToken = true; - var state = 1 /* SawAsterisk */; - var margin = undefined; - // + 4 for leading '/** ' - var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); - } - if (token() === 4 /* NewLineTrivia */) { - state = 0 /* BeginningOfLine */; - indent = 0; - nextJSDocToken(); - } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { - case 57 /* AtToken */: - if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { - removeTrailingNewlines(comments); - parseTag(indent); - // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. - // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning - // for malformed examples like `/** @param {string} x @returns {number} the length */` - state = 0 /* BeginningOfLine */; - advanceToken = false; - margin = undefined; - indent++; - } - else { - pushComment(scanner.getTokenText()); - } - break; - case 4 /* NewLineTrivia */: - comments.push(scanner.getTokenText()); - state = 0 /* BeginningOfLine */; - indent = 0; - break; - case 39 /* AsteriskToken */: - var asterisk = scanner.getTokenText(); - if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) { - // If we've already seen an asterisk, then we can no longer parse a tag on this line - state = 2 /* SavingComments */; - pushComment(asterisk); - } - else { - // Ignore the first asterisk on a line - state = 1 /* SawAsterisk */; - indent += asterisk.length; - } - break; - case 71 /* Identifier */: - // Anything else is doc comment text. We just save it. Because it - // wasn't a tag, we can no longer parse a tag on this line until we hit the next - // line break. - pushComment(scanner.getTokenText()); - state = 2 /* SavingComments */; - break; - case 5 /* WhitespaceTrivia */: - // only collect whitespace if we're already saving comments or have just crossed the comment indent margin - var whitespace = scanner.getTokenText(); - if (state === 2 /* SavingComments */) { - comments.push(whitespace); - } - else if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - break; - case 1 /* EndOfFileToken */: - break; - default: - // anything other than whitespace or asterisk at the beginning of the line starts the comment text - state = 2 /* SavingComments */; - pushComment(scanner.getTokenText()); - break; - } - if (advanceToken) { - nextJSDocToken(); - } - else { - advanceToken = true; - } - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - result = createJSDocComment(); - }); - return result; - function removeLeadingNewlines(comments) { - while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { - comments.shift(); - } - } - function removeTrailingNewlines(comments) { - while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { - comments.pop(); - } - } - function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 /* slash */ && - content.charCodeAt(start + 1) === 42 /* asterisk */ && - content.charCodeAt(start + 2) === 42 /* asterisk */ && - content.charCodeAt(start + 3) !== 42 /* asterisk */; - } - function createJSDocComment() { - var result = createNode(283 /* JSDocComment */, start); - result.tags = tags; - result.comment = comments.length ? comments.join("") : undefined; - return finishNode(result, end); - } - function skipWhitespace() { - while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { - nextJSDocToken(); - } - } - function parseTag(indent) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getTokenPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return; - } - var tag; - if (tagName) { - switch (tagName.text) { - case "augments": - tag = parseAugmentsTag(atToken, tagName); - break; - case "arg": - case "argument": - case "param": - tag = parseParamTag(atToken, tagName); - break; - case "return": - case "returns": - tag = parseReturnTag(atToken, tagName); - break; - case "template": - tag = parseTemplateTag(atToken, tagName); - break; - case "type": - tag = parseTypeTag(atToken, tagName); - break; - case "typedef": - tag = parseTypedefTag(atToken, tagName); - break; - default: - tag = parseUnknownTag(atToken, tagName); - break; - } - } - else { - tag = parseUnknownTag(atToken, tagName); - } - if (!tag) { - // a badly malformed tag should not be added to the list of tags - return; - } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); - } - function parseTagComments(indent) { - var comments = []; - var state = 0 /* BeginningOfLine */; - var margin; - function pushComment(text) { - if (!margin) { - margin = indent; - } - comments.push(text); - indent += text.length; - } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { - case 4 /* NewLineTrivia */: - if (state >= 1 /* SawAsterisk */) { - state = 0 /* BeginningOfLine */; - comments.push(scanner.getTokenText()); - } - indent = 0; - break; - case 57 /* AtToken */: - // Done - break; - case 5 /* WhitespaceTrivia */: - if (state === 2 /* SavingComments */) { - pushComment(scanner.getTokenText()); - } - else { - var whitespace = scanner.getTokenText(); - // if the whitespace crosses the margin, take only the whitespace that passes the margin - if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent - 1)); - } - indent += whitespace.length; - } - break; - case 39 /* AsteriskToken */: - if (state === 0 /* BeginningOfLine */) { - // leading asterisks start recording on the *next* (non-whitespace) token - state = 1 /* SawAsterisk */; - indent += scanner.getTokenText().length; - break; - } - // record the * as a comment - // falls through - default: - state = 2 /* SavingComments */; // leading identifiers start recording as well - pushComment(scanner.getTokenText()); - break; - } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); - } - removeLeadingNewlines(comments); - removeTrailingNewlines(comments); - return comments; - } - function parseUnknownTag(atToken, tagName) { - var result = createNode(284 /* JSDocTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - return finishNode(result); - } - function addTag(tag, comments) { - tag.comment = comments.join(""); - if (!tags) { - tags = createNodeArray([tag], tag.pos); - } - else { - tags.push(tag); - } - tags.end = tag.end; - } - function tryParseTypeExpression() { - return tryParse(function () { - skipWhitespace(); - if (token() !== 17 /* OpenBraceToken */) { - return undefined; - } - return parseJSDocTypeExpression(); - }); - } - function parseParamTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name; - var isBracketed; - // Looking for something like '[foo]' or 'foo' - if (parseOptionalToken(21 /* OpenBracketToken */)) { - name = parseJSDocIdentifierName(); - skipWhitespace(); - isBracketed = true; - // May have an optional default, e.g. '[foo = 42]' - if (parseOptionalToken(58 /* EqualsToken */)) { - parseExpression(); - } - parseExpected(22 /* CloseBracketToken */); - } - else if (ts.tokenIsIdentifierOrKeyword(token())) { - name = parseJSDocIdentifierName(); - } - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var preName, postName; - if (typeExpression) { - postName = name; - } - else { - preName = name; - } - if (!typeExpression) { - typeExpression = tryParseTypeExpression(); - } - var result = createNode(286 /* JSDocParameterTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.preParameterName = preName; - result.typeExpression = typeExpression; - result.postParameterName = postName; - result.parameterName = postName || preName; - result.isBracketed = isBracketed; - return finishNode(result); - } - function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocReturnTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(287 /* JSDocReturnTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 288 /* JSDocTypeTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - var result = createNode(288 /* JSDocTypeTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = tryParseTypeExpression(); - return finishNode(result); - } - function parsePropertyTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), /*length*/ 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var result = createNode(291 /* JSDocPropertyTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.name = name; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseAugmentsTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - var result = createNode(285 /* JSDocAugmentsTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeExpression = typeExpression; - return finishNode(result); - } - function parseTypedefTag(atToken, tagName) { - var typeExpression = tryParseTypeExpression(); - skipWhitespace(); - var typedefTag = createNode(290 /* JSDocTypedefTag */, atToken.pos); - typedefTag.atToken = atToken; - typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { - // if node is identifier - use it as name - // otherwise use name of the rightmost part that we were able to parse - typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } - typedefTag.typeExpression = typeExpression; - skipWhitespace(); - if (typeExpression) { - if (typeExpression.type.kind === 277 /* JSDocTypeReference */) { - var jsDocTypeReference = typeExpression.type; - if (jsDocTypeReference.name.kind === 71 /* Identifier */) { - var name = jsDocTypeReference.name; - if (name.text === "Object") { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - } - } - if (!typedefTag.jsDocTypeLiteral) { - typedefTag.jsDocTypeLiteral = typeExpression.type; - } - } - else { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } - return finishNode(typedefTag); - function scanChildTags() { - var jsDocTypeLiteral = createNode(292 /* JSDocTypeLiteral */, scanner.getStartPos()); - var resumePos = scanner.getStartPos(); - var canParseTag = true; - var seenAsterisk = false; - var parentTagTerminated = false; - while (token() !== 1 /* EndOfFileToken */ && !parentTagTerminated) { - nextJSDocToken(); - switch (token()) { - case 57 /* AtToken */: - if (canParseTag) { - parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } - } - seenAsterisk = false; - break; - case 4 /* NewLineTrivia */: - resumePos = scanner.getStartPos() - 1; - canParseTag = true; - seenAsterisk = false; - break; - case 39 /* AsteriskToken */: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case 71 /* Identifier */: - canParseTag = false; - break; - case 1 /* EndOfFileToken */: - break; - } - } - scanner.setTextPos(resumePos); - return finishNode(jsDocTypeLiteral); - } - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(233 /* ModuleDeclaration */, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); - return jsDocNamespaceNode; - } - if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { - typeNameOrNamespaceName.isInJSDocNamespace = true; - } - return typeNameOrNamespaceName; - } - } - function tryParseChildTag(parentTag) { - ts.Debug.assert(token() === 57 /* AtToken */); - var atToken = createNode(57 /* AtToken */, scanner.getStartPos()); - atToken.end = scanner.getTextPos(); - nextJSDocToken(); - var tagName = parseJSDocIdentifierName(); - skipWhitespace(); - if (!tagName) { - return false; - } - switch (tagName.text) { - case "type": - if (parentTag.jsDocTypeTag) { - // already has a @type tag, terminate the parent tag now. - return false; - } - parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); - return true; - case "prop": - case "property": - var propertyTag = parsePropertyTag(atToken, tagName); - if (propertyTag) { - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = []; - } - parentTag.jsDocPropertyTags.push(propertyTag); - return true; - } - // Error parsing property tag - return false; - } - return false; - } - function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocTemplateTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.text); - } - // Type parameter list looks like '@template T,U,V' - var typeParameters = createNodeArray(); - while (true) { - var name = parseJSDocIdentifierName(); - skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - var typeParameter = createNode(145 /* TypeParameter */, name.pos); - typeParameter.name = name; - finishNode(typeParameter); - typeParameters.push(typeParameter); - if (token() === 26 /* CommaToken */) { - nextJSDocToken(); - skipWhitespace(); - } - else { - break; - } - } - var result = createNode(289 /* JSDocTemplateTag */, atToken.pos); - result.atToken = atToken; - result.tagName = tagName; - result.typeParameters = typeParameters; - finishNode(result); - typeParameters.end = result.end; - return result; - } - function nextJSDocToken() { - return currentToken = scanner.scanJSDocToken(); - } - function parseJSDocIdentifierName() { - return createJSDocIdentifier(ts.tokenIsIdentifierOrKeyword(token())); - } - function createJSDocIdentifier(isIdentifier) { - if (!isIdentifier) { - parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - return undefined; - } - var pos = scanner.getTokenPos(); - var end = scanner.getTextPos(); - var result = createNode(71 /* Identifier */, pos); - result.text = content.substring(pos, end); - finishNode(result, end); - nextJSDocToken(); - return result; - } - } - JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; - })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); - })(Parser || (Parser = {})); - var IncrementalParser; - (function (IncrementalParser) { - function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { - aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */); - checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); - if (ts.textChangeRangeIsUnchanged(textChangeRange)) { - // if the text didn't change, then we can just return our current source file as-is. - return sourceFile; - } - if (sourceFile.statements.length === 0) { - // If we don't have any statements in the current source file, then there's no real - // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind); - } - // Make sure we're not trying to incrementally update a source file more than once. Once - // we do an update the original source file is considered unusable from that point onwards. - // - // This is because we do incremental parsing in-place. i.e. we take nodes from the old - // tree and give them new positions and parents. From that point on, trusting the old - // tree at all is not possible as far too much of it may violate invariants. - var incrementalSourceFile = sourceFile; - ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); - incrementalSourceFile.hasBeenIncrementallyParsed = true; - var oldText = sourceFile.text; - var syntaxCursor = createSyntaxCursor(sourceFile); - // Make the actual change larger so that we know to reparse anything whose lookahead - // might have intersected the change. - var changeRange = extendToAffectedRange(sourceFile, textChangeRange); - checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); - // Ensure that extending the affected range only moved the start of the change range - // earlier in the file. - ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); - ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); - ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); - // The is the amount the nodes after the edit range need to be adjusted. It can be - // positive (if the edit added characters), negative (if the edit deleted characters) - // or zero (if this was a pure overwrite with nothing added/removed). - var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; - // If we added or removed characters during the edit, then we need to go and adjust all - // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they - // may move backward (if we deleted chars). - // - // Doing this helps us out in two ways. First, it means that any nodes/tokens we want - // to reuse are already at the appropriate position in the new text. That way when we - // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes - // it very easy to determine if we can reuse a node. If the node's position is at where - // we are in the text, then we can reuse it. Otherwise we can't. If the node's position - // is ahead of us, then we'll need to rescan tokens. If the node's position is behind - // us, then we'll need to skip it or crumble it as appropriate - // - // We will also adjust the positions of nodes that intersect the change range as well. - // By doing this, we ensure that all the positions in the old tree are consistent, not - // just the positions of nodes entirely before/after the change range. By being - // consistent, we can then easily map from positions to nodes in the old tree easily. - // - // Also, mark any syntax elements that intersect the changed span. We know, up front, - // that we cannot reuse these elements. - updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); - // Now that we've set up our internal incremental state just proceed and parse the - // source file in the normal fashion. When possible the parser will retrieve and - // reuse nodes from the old tree. - // - // Note: passing in 'true' for setNodeParents is very important. When incrementally - // parsing, we will be reusing nodes from the old tree, and placing it into new - // parents. If we don't set the parents now, we'll end up with an observably - // inconsistent tree. Setting the parents on the new tree should be very fast. We - // will immediately bail out of walking any subtrees when we can see that their parents - // are already correct. - var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind); - return result; - } - IncrementalParser.updateSourceFile = updateSourceFile; - function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { - if (isArray) { - visitArray(element); - } - else { - visitNode(element); - } - return; - function visitNode(node) { - var text = ""; - if (aggressiveChecks && shouldCheckNode(node)) { - text = oldText.substring(node.pos, node.end); - } - // Ditch any existing LS children we may have created. This way we can avoid - // moving them forward. - if (node._children) { - node._children = undefined; - } - node.pos += delta; - node.end += delta; - if (aggressiveChecks && shouldCheckNode(node)) { - ts.Debug.assert(text === newText.substring(node.pos, node.end)); - } - forEachChild(node, visitNode, visitArray); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - forEachChild(jsDocComment, visitNode, visitArray); - } - } - checkNodePositions(node, aggressiveChecks); - } - function visitArray(array) { - array._children = undefined; - array.pos += delta; - array.end += delta; - for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { - var node = array_9[_i]; - visitNode(node); - } - } - } - function shouldCheckNode(node) { - switch (node.kind) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 71 /* Identifier */: - return true; - } - return false; - } - function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { - ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); - ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); - ts.Debug.assert(element.pos <= element.end); - // We have an element that intersects the change range in some way. It may have its - // start, or its end (or both) in the changed range. We want to adjust any part - // that intersects such that the final tree is in a consistent state. i.e. all - // children have spans within the span of their parent, and all siblings are ordered - // properly. - // We may need to update both the 'pos' and the 'end' of the element. - // If the 'pos' is before the start of the change, then we don't need to touch it. - // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have - // something like: - // - // -------------------AAA----------------- - // -------------------BBBCCCCCCC----------------- - // - // In this case, we consider any node that started in the change range to still be - // starting at the same position. - // - // however, if the delta is negative, then we instead have something like this: - // - // -------------------XXXYYYYYYY----------------- - // -------------------ZZZ----------------- - // - // In this case, any element that started in the 'X' range will keep its position. - // However any element that started after that will have their pos adjusted to be - // at the end of the new range. i.e. any node that started in the 'Y' range will - // be adjusted to have their start at the end of the 'Z' range. - // - // The element will keep its position if possible. Or Move backward to the new-end - // if it's in the 'Y' range. - element.pos = Math.min(element.pos, changeRangeNewEnd); - // If the 'end' is after the change range, then we always adjust it by the delta - // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we - // have something like: - // - // -------------------AAA----------------- - // -------------------BBBCCCCCCC----------------- - // - // In this case, we consider any node that ended inside the change range to keep its - // end position. - // - // however, if the delta is negative, then we instead have something like this: - // - // -------------------XXXYYYYYYY----------------- - // -------------------ZZZ----------------- - // - // In this case, any element that ended in the 'X' range will keep its position. - // However any element that ended after that will have their pos adjusted to be - // at the end of the new range. i.e. any node that ended in the 'Y' range will - // be adjusted to have their end at the end of the 'Z' range. - if (element.end >= changeRangeOldEnd) { - // Element ends after the change range. Always adjust the end pos. - element.end += delta; - } - else { - // Element ends in the change range. The element will keep its position if - // possible. Or Move backward to the new-end if it's in the 'Y' range. - element.end = Math.min(element.end, changeRangeNewEnd); - } - ts.Debug.assert(element.pos <= element.end); - if (element.parent) { - ts.Debug.assert(element.pos >= element.parent.pos); - ts.Debug.assert(element.end <= element.parent.end); - } - } - function checkNodePositions(node, aggressiveChecks) { - if (aggressiveChecks) { - var pos_2 = node.pos; - forEachChild(node, function (child) { - ts.Debug.assert(child.pos >= pos_2); - pos_2 = child.end; - }); - ts.Debug.assert(pos_2 <= node.end); - } - } - function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { - visitNode(sourceFile); - return; - function visitNode(child) { - ts.Debug.assert(child.pos <= child.end); - if (child.pos > changeRangeOldEnd) { - // Node is entirely past the change range. We need to move both its pos and - // end, forward or backward appropriately. - moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); - return; - } - // Check if the element intersects the change range. If it does, then it is not - // reusable. Also, we'll need to recurse to see what constituent portions we may - // be able to use. - var fullEnd = child.end; - if (fullEnd >= changeStart) { - child.intersectsChange = true; - child._children = undefined; - // Adjust the pos or end (or both) of the intersecting element accordingly. - adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - forEachChild(child, visitNode, visitArray); - checkNodePositions(child, aggressiveChecks); - return; - } - // Otherwise, the node is entirely before the change range. No need to do anything with it. - ts.Debug.assert(fullEnd < changeStart); - } - function visitArray(array) { - ts.Debug.assert(array.pos <= array.end); - if (array.pos > changeRangeOldEnd) { - // Array is entirely after the change range. We need to move it, and move any of - // its children. - moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); - return; - } - // Check if the element intersects the change range. If it does, then it is not - // reusable. Also, we'll need to recurse to see what constituent portions we may - // be able to use. - var fullEnd = array.end; - if (fullEnd >= changeStart) { - array.intersectsChange = true; - array._children = undefined; - // Adjust the pos or end (or both) of the intersecting array accordingly. - adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { - var node = array_10[_i]; - visitNode(node); - } - return; - } - // Otherwise, the array is entirely before the change range. No need to do anything with it. - ts.Debug.assert(fullEnd < changeStart); - } - } - function extendToAffectedRange(sourceFile, changeRange) { - // Consider the following code: - // void foo() { /; } - // - // If the text changes with an insertion of / just before the semicolon then we end up with: - // void foo() { //; } - // - // If we were to just use the changeRange a is, then we would not rescan the { token - // (as it does not intersect the actual original change range). Because an edit may - // change the token touching it, we actually need to look back *at least* one token so - // that the prior token sees that change. - var maxLookahead = 1; - var start = changeRange.span.start; - // the first iteration aligns us with the change start. subsequent iteration move us to - // the left by maxLookahead tokens. We only need to do this as long as we're not at the - // start of the tree. - for (var i = 0; start > 0 && i <= maxLookahead; i++) { - var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); - ts.Debug.assert(nearestNode.pos <= start); - var position = nearestNode.pos; - start = Math.max(0, position - 1); - } - var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); - var finalLength = changeRange.newLength + (changeRange.span.start - start); - return ts.createTextChangeRange(finalSpan, finalLength); - } - function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { - var bestResult = sourceFile; - var lastNodeEntirelyBeforePosition; - forEachChild(sourceFile, visit); - if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); - if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { - bestResult = lastChildOfLastEntireNodeBeforePosition; - } - } - return bestResult; - function getLastChild(node) { - while (true) { - var lastChild = getLastChildWorker(node); - if (lastChild) { - node = lastChild; - } - else { - return node; - } - } - } - function getLastChildWorker(node) { - var last = undefined; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } - function visit(child) { - if (ts.nodeIsMissing(child)) { - // Missing nodes are effectively invisible to us. We never even consider them - // When trying to find the nearest node before us. - return; - } - // If the child intersects this position, then this node is currently the nearest - // node that starts before the position. - if (child.pos <= position) { - if (child.pos >= bestResult.pos) { - // This node starts before the position, and is closer to the position than - // the previous best node we found. It is now the new best node. - bestResult = child; - } - // Now, the node may overlap the position, or it may end entirely before the - // position. If it overlaps with the position, then either it, or one of its - // children must be the nearest node before the position. So we can just - // recurse into this child to see if we can find something better. - if (position < child.end) { - // The nearest node is either this child, or one of the children inside - // of it. We've already marked this child as the best so far. Recurse - // in case one of the children is better. - forEachChild(child, visit); - // Once we look at the children of this node, then there's no need to - // continue any further. - return true; - } - else { - ts.Debug.assert(child.end <= position); - // The child ends entirely before this position. Say you have the following - // (where $ is the position) - // - // ? $ : <...> <...> - // - // We would want to find the nearest preceding node in "complex expr 2". - // To support that, we keep track of this node, and once we're done searching - // for a best node, we recurse down this node to see if we can find a good - // result in it. - // - // This approach allows us to quickly skip over nodes that are entirely - // before the position, while still allowing us to find any nodes in the - // last one that might be what we want. - lastNodeEntirelyBeforePosition = child; - } - } - else { - ts.Debug.assert(child.pos > position); - // We're now at a node that is entirely past the position we're searching for. - // This node (and all following nodes) could never contribute to the result, - // so just skip them by returning 'true' here. - return true; - } - } - } - function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { - var oldText = sourceFile.text; - if (textChangeRange) { - ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); - if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) { - var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - var newTextPrefix = newText.substr(0, textChangeRange.span.start); - ts.Debug.assert(oldTextPrefix === newTextPrefix); - var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); - var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); - ts.Debug.assert(oldTextSuffix === newTextSuffix); - } - } - } - function createSyntaxCursor(sourceFile) { - var currentArray = sourceFile.statements; - var currentArrayIndex = 0; - ts.Debug.assert(currentArrayIndex < currentArray.length); - var current = currentArray[currentArrayIndex]; - var lastQueriedPosition = -1 /* Value */; - return { - currentNode: function (position) { - // Only compute the current node if the position is different than the last time - // we were asked. The parser commonly asks for the node at the same position - // twice. Once to know if can read an appropriate list element at a certain point, - // and then to actually read and consume the node. - if (position !== lastQueriedPosition) { - // Much of the time the parser will need the very next node in the array that - // we just returned a node from.So just simply check for that case and move - // forward in the array instead of searching for the node again. - if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { - currentArrayIndex++; - current = currentArray[currentArrayIndex]; - } - // If we don't have a node, or the node we have isn't in the right position, - // then try to find a viable node at the position requested. - if (!current || current.pos !== position) { - findHighestListElementThatStartsAtPosition(position); - } - } - // Cache this query so that we don't do any extra work if the parser calls back - // into us. Note: this is very common as the parser will make pairs of calls like - // 'isListElement -> parseListElement'. If we were unable to find a node when - // called with 'isListElement', we don't want to redo the work when parseListElement - // is called immediately after. - lastQueriedPosition = position; - // Either we don'd have a node, or we have a node at the position being asked for. - ts.Debug.assert(!current || current.pos === position); - return current; - } - }; - // Finds the highest element in the tree we can find that starts at the provided position. - // The element must be a direct child of some node list in the tree. This way after we - // return it, we can easily return its next sibling in the list. - function findHighestListElementThatStartsAtPosition(position) { - // Clear out any cached state about the last node we found. - currentArray = undefined; - currentArrayIndex = -1 /* Value */; - current = undefined; - // Recurse into the source file to find the highest node at this position. - forEachChild(sourceFile, visitNode, visitArray); - return; - function visitNode(node) { - if (position >= node.pos && position < node.end) { - // Position was within this node. Keep searching deeper to find the node. - forEachChild(node, visitNode, visitArray); - // don't proceed any further in the search. - return true; - } - // position wasn't in this node, have to keep searching. - return false; - } - function visitArray(array) { - if (position >= array.pos && position < array.end) { - // position was in this array. Search through this array to see if we find a - // viable element. - for (var i = 0; i < array.length; i++) { - var child = array[i]; - if (child) { - if (child.pos === position) { - // Found the right node. We're done. - currentArray = array; - currentArrayIndex = i; - current = child; - return true; - } - else { - if (child.pos < position && position < child.end) { - // Position in somewhere within this child. Search in it and - // stop searching in this array. - forEachChild(child, visitNode, visitArray); - return true; - } - } - } - } - } - // position wasn't in this array, have to keep searching. - return false; - } - } - } - var InvalidPosition; - (function (InvalidPosition) { - InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; - })(InvalidPosition || (InvalidPosition = {})); - })(IncrementalParser || (IncrementalParser = {})); -})(ts || (ts = {})); -/// -/// -/* @internal */ -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) { - // A module is uninstantiated if it contains only - // 1. interface declarations, type alias declarations - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 231 /* TypeAliasDeclaration */) { - return 0 /* NonInstantiated */; - } - else if (ts.isConstEnumDeclaration(node)) { - return 2 /* ConstEnumOnly */; - } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && !(ts.hasModifier(node, 1 /* Export */))) { - return 0 /* NonInstantiated */; - } - else if (node.kind === 234 /* ModuleBlock */) { - var state_1 = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - switch (getModuleInstanceState(n)) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return false; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state_1 = 2 /* ConstEnumOnly */; - return false; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state_1 = 1 /* Instantiated */; - return true; - } - }); - return state_1; - } - else if (node.kind === 233 /* ModuleDeclaration */) { - var body = node.body; - return body ? getModuleInstanceState(body) : 1 /* Instantiated */; - } - else if (node.kind === 71 /* Identifier */ && node.isInJSDocNamespace) { - return 0 /* NonInstantiated */; - } - else { - return 1 /* Instantiated */; - } - } - ts.getModuleInstanceState = getModuleInstanceState; - var ContainerFlags; - (function (ContainerFlags) { - // The current node is not a container, and no container manipulation should happen before - // recursing into it. - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - // The current node is a container. It should be set as the current container (and block- - // container) before recursing into it. The current node does not have locals. Examples: - // - // Classes, ObjectLiterals, TypeLiterals, Interfaces... - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - // The current node is a block-scoped-container. It should be set as the current block- - // container before recursing into it. Examples: - // - // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - // The current node is the container of a control flow path. The current control flow should - // be saved and restored, and a new control flow initialized within the container. - 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"); - binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var languageVersion; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - // state used by control flow analysis - var currentFlow; - var currentBreakTarget; - var currentContinueTarget; - var currentReturnTarget; - var currentTrueTarget; - var currentFalseTarget; - var preSwitchCaseFlow; - var activeLabels; - var hasExplicitReturn; - // state used for emit helpers - var emitFlags; - // If this file is an external module, then it is automatically in strict-mode according to - // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places or if we hit a class/namespace - // or if compiler options contain alwaysStrict. - var inStrictMode; - var symbolCount = 0; - var Symbol; - var classifiableNames; - var unreachableFlow = { flags: 1 /* Unreachable */ }; - var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; - // state used to aggregate transform flags during bind. - var subtreeTransformFlags = 0 /* None */; - var skipTransformFlagAggregation; - function bindSourceFile(f, opts) { - file = f; - options = opts; - languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = ts.createMap(); - symbolCount = 0; - skipTransformFlagAggregation = file.isDeclarationFile; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = 0 /* None */; - subtreeTransformFlags = 0 /* None */; - } - return bindSourceFile; - function bindInStrictMode(file, opts) { - if ((opts.alwaysStrict === undefined ? opts.strict : opts.alwaysStrict) && !file.isDeclarationFile) { - // bind in strict mode source files with alwaysStrict option - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = ts.createMap(); - } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = ts.createMap(); - } - if (symbolFlags & 107455 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 233 /* ModuleDeclaration */)) { - // 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) { - var name = ts.getNameOfDeclaration(node); - if (name) { - if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; - } - 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; - } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); - } - return name.text; - } - switch (node.kind) { - case 152 /* Constructor */: - return "__constructor"; - case 160 /* FunctionType */: - case 155 /* CallSignature */: - return "__call"; - case 161 /* ConstructorType */: - case 156 /* ConstructSignature */: - return "__new"; - case 157 /* IndexSignature */: - return "__index"; - case 244 /* ExportDeclaration */: - return "__export"; - case 243 /* ExportAssignment */: - return node.isExportEquals ? "export=" : "default"; - case 194 /* BinaryExpression */: - switch (ts.getSpecialPropertyAssignmentKind(node)) { - case 2 /* ModuleExports */: - // module.exports = ... - return "export="; - case 1 /* ExportsProperty */: - case 4 /* ThisProperty */: - case 5 /* Property */: - // exports.x = ... or this.y = ... - return node.left.name.text; - case 3 /* PrototypeProperty */: - // className.prototype.methodName = ... - return node.left.expression.name.text; - } - ts.Debug.fail("Unknown binary declaration kind"); - break; - case 228 /* FunctionDeclaration */: - case 229 /* ClassDeclaration */: - return ts.hasModifier(node, 512 /* Default */) ? "default" : undefined; - case 279 /* JSDocFunctionType */: - return ts.isJSDocConstructSignature(node) ? "__new" : "__call"; - case 146 /* Parameter */: - // Parameters with names are handled at the top of this function. Parameters - // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 279 /* JSDocFunctionType */); - var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); - return "arg" + index; - case 290 /* JSDocTypedefTag */: - var parentNode = node.parent && node.parent.parent; - var nameFromParentNode = void 0; - if (parentNode && parentNode.kind === 208 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71 /* Identifier */) { - nameFromParentNode = nameIdentifier.text; - } - } - } - return nameFromParentNode; - } - } - function getDisplayName(node) { - return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); - } - /** - * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. - * @param symbolTable - The symbol table which node will be added to. - * @param parent - node's parent declaration. - * @param node - The declaration to be added to the symbol table - * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. - */ - function declareSymbol(symbolTable, parent, node, includes, excludes) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); - // The exported symbol for an export default function/class node is always named "default" - var name = isDefaultExport && parent ? "default" : getDeclarationName(node); - var symbol; - if (name === undefined) { - symbol = createSymbol(0 /* None */, "__missing"); - } - else { - // Check and see if the symbol table already has a symbol with this name. If not, - // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict - // with the 'excludes' flags we pass in. - // - // If we do get an existing symbol, see if it conflicts with the new symbol we're - // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this - // declaration. - // - // Note that when properties declared in Javascript constructors - // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. - // Always. This allows the common Javascript pattern of overwriting a prototype method - // with an bound instance method of the same type: `this.method = this.method.bind(this)` - // - // If we created a new symbol, either because we didn't have a symbol with this name - // in the symbol table, or we conflicted with an existing symbol, then just add this - // node as the sole declaration of the new symbol. - // - // Otherwise, we'll be merging into a compatible existing symbol (for example when - // you have multiple 'vars' with the same name in the same container). In this case - // just add this node into the declarations list of the symbol. - symbol = symbolTable.get(name); - if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - } - if (name && (includes & 788448 /* Classifiable */)) { - classifiableNames.set(name, name); - } - if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - // Javascript constructor-declared symbols can be discarded in favor of - // prototype symbols like methods. - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - } - else { - if (node.name) { - node.name.parent = node; - } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - if (symbol.declarations && symbol.declarations.length) { - // If the current node is a default export of some sort, then check if - // there are any other default exports that we need to error on. - // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. - if (isDefaultExport) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. - // Error on multiple export default in the following case: - // 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 === 243 /* ExportAssignment */ && !node.isExportEquals))) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); - } - } - } - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; - if (symbolFlags & 8388608 /* Alias */) { - if (node.kind === 246 /* ExportSpecifier */ || (node.kind === 237 /* ImportEqualsDeclaration */ && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - else { - // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, - // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set - // on it. There are 2 main reasons: - // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. - // That means the binder will issue a Duplicate Identifier error if you mix locals and exports - // with the same name in the same container. - // TODO: Make this a more specific error and decouple it from the exclusion logic. - // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, - // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way - // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge - // 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. - var isJSDocTypedefInJSDocNamespace = node.kind === 290 /* JSDocTypedefTag */ && - node.name && - node.name.kind === 71 /* Identifier */ && - node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | - (symbolFlags & 793064 /* Type */ ? 2097152 /* ExportType */ : 0) | - (symbolFlags & 1920 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); - var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - } - // All container nodes are kept on a linked list in declaration order. This list is used by - // the getLocalNameOfContainer function in the type checker to validate that the local name - // used for a container is unique. - function bindContainer(node, containerFlags) { - // Before we recurse into a node's children, we first save the existing parent, container - // and block-container. Then after we pop out of processing the children, we restore - // these saved values. - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - // Depending on what kind of node this is, we may have to adjust the current container - // and block-container. If the current node is a container, then it is automatically - // considered the current block-container as well. Also, for containers that we know - // may contain locals, we proactively initialize the .locals field. We do this because - // it's highly likely that the .locals will be needed to place some child in (for example, - // a parameter, or variable declaration). - // - // However, we do not proactively create the .locals for block-containers because it's - // totally normal and common for block-containers to never actually have a block-scoped - // variable in them. We don't want to end up allocating an object for every 'block' we - // run into when most of them won't be necessary. - // - // Finally, if this is a block-container, then we clear out any existing .locals object - // it may contain within it. This happens in incremental scenarios. Because we can be - // reusing a node from a previous compilation, that node may have had 'locals' created - // for it. We must clear this so we don't accidentally move any stale data forward from - // a previous compilation. - if (containerFlags & 1 /* IsContainer */) { - container = blockScopeContainer = node; - if (containerFlags & 32 /* HasLocals */) { - container.locals = ts.createMap(); - } - addToContainerChain(container); - } - else if (containerFlags & 2 /* IsBlockScopedContainer */) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveCurrentFlow = currentFlow; - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - var saveReturnTarget = currentReturnTarget; - var saveActiveLabels = activeLabels; - var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); - // A non-async IIFE is considered part of the containing control flow. Return statements behave - // similarly to break statements that exit to a label just past the statement body. - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { - currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { - currentFlow.container = node; - } - currentReturnTarget = undefined; - } - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - // Reset all reachability check related flags on node (for incremental scenarios) - node.flags &= ~1408 /* ReachabilityAndEmitFlags */; - if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { - node.flags |= 128 /* HasImplicitReturn */; - if (hasExplicitReturn) - node.flags |= 256 /* HasExplicitReturn */; - } - if (node.kind === 265 /* SourceFile */) { - node.flags |= emitFlags; - } - if (isIIFE) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - } - else { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & 64 /* IsInterface */) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - function bindChildren(node) { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & 536870912 /* HasComputedFlags */) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - function bindEach(nodes) { - if (nodes === undefined) { - return; - } - if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0 /* None */; - var nodeArrayFlags = 0 /* None */; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; - bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; - } - nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - } - function bindEachChild(node) { - ts.forEachChild(node, bind, bindEach); - } - function bindChildrenWorker(node) { - // 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 (ts.isInJavaScriptFile(node) && node.jsDoc) { - ts.forEach(node.jsDoc, bind); - } - if (checkUnreachable(node)) { - bindEachChild(node); - return; - } - switch (node.kind) { - case 213 /* WhileStatement */: - bindWhileStatement(node); - break; - case 212 /* DoStatement */: - bindDoStatement(node); - break; - case 214 /* ForStatement */: - bindForStatement(node); - break; - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - bindForInOrForOfStatement(node); - break; - case 211 /* IfStatement */: - bindIfStatement(node); - break; - case 219 /* ReturnStatement */: - case 223 /* ThrowStatement */: - bindReturnOrThrow(node); - break; - case 218 /* BreakStatement */: - case 217 /* ContinueStatement */: - bindBreakOrContinueStatement(node); - break; - case 224 /* TryStatement */: - bindTryStatement(node); - break; - case 221 /* SwitchStatement */: - bindSwitchStatement(node); - break; - case 235 /* CaseBlock */: - bindCaseBlock(node); - break; - case 257 /* CaseClause */: - bindCaseClause(node); - break; - case 222 /* LabeledStatement */: - bindLabeledStatement(node); - break; - case 192 /* PrefixUnaryExpression */: - bindPrefixUnaryExpressionFlow(node); - break; - case 193 /* PostfixUnaryExpression */: - bindPostfixUnaryExpressionFlow(node); - break; - case 194 /* BinaryExpression */: - bindBinaryExpressionFlow(node); - break; - case 188 /* DeleteExpression */: - bindDeleteExpressionFlow(node); - break; - case 195 /* ConditionalExpression */: - bindConditionalExpressionFlow(node); - break; - case 226 /* VariableDeclaration */: - bindVariableDeclarationFlow(node); - break; - case 181 /* CallExpression */: - bindCallExpressionFlow(node); - break; - case 283 /* JSDocComment */: - bindJSDocComment(node); - break; - case 290 /* JSDocTypedefTag */: - bindJSDocTypedefTag(node); - break; - default: - bindEachChild(node); - break; - } - } - function isNarrowingExpression(expr) { - switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 179 /* PropertyAccessExpression */: - return isNarrowableReference(expr); - case 181 /* CallExpression */: - return hasNarrowableArgument(expr); - case 185 /* ParenthesizedExpression */: - return isNarrowingExpression(expr.expression); - case 194 /* BinaryExpression */: - return isNarrowingBinaryExpression(expr); - case 192 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - } - return false; - } - function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 179 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); - } - function hasNarrowableArgument(expr) { - if (expr.arguments) { - for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === 179 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { - return true; - } - return false; - } - function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 189 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; - } - function isNarrowingBinaryExpression(expr) { - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: - return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: - return isNarrowingExpression(expr.right); - } - return false; - } - function isNarrowableOperand(expr) { - switch (expr.kind) { - case 185 /* ParenthesizedExpression */: - return isNarrowableOperand(expr.expression); - case 194 /* BinaryExpression */: - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: - return isNarrowableOperand(expr.right); - } - } - return isNarrowableReference(expr); - } - function createBranchLabel() { - return { - flags: 4 /* BranchLabel */, - antecedents: undefined - }; - } - function createLoopLabel() { - return { - flags: 8 /* LoopLabel */, - antecedents: undefined - }; - } - function setFlowNodeReferenced(flow) { - // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; - } - function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1 /* Unreachable */) { - return antecedent; - } - if (!expression) { - return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; - } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: flags, - expression: expression, - antecedent: antecedent - }; - } - function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: 128 /* SwitchClause */, - switchStatement: switchStatement, - clauseStart: clauseStart, - clauseEnd: clauseEnd, - antecedent: antecedent - }; - } - function createFlowAssignment(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 16 /* Assignment */, - antecedent: antecedent, - node: node - }; - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { - flags: 256 /* ArrayMutation */, - antecedent: antecedent, - node: node - }; - } - function finishFlowLabel(flow) { - var antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - function isStatementCondition(node) { - var parent = node.parent; - switch (parent.kind) { - case 211 /* IfStatement */: - case 213 /* WhileStatement */: - case 212 /* DoStatement */: - return parent.expression === node; - case 214 /* ForStatement */: - case 195 /* ConditionalExpression */: - return parent.condition === node; - } - return false; - } - function isLogicalExpression(node) { - while (true) { - if (node.kind === 185 /* ParenthesizedExpression */) { - node = node.expression; - } - else if (node.kind === 192 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { - node = node.operand; - } - else { - return node.kind === 194 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); - } - } - } - function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 185 /* ParenthesizedExpression */ || - node.parent.kind === 192 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - function bindCondition(node, trueTarget, falseTarget) { - var saveTrueTarget = currentTrueTarget; - var saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); - } - } - function bindIterativeStatement(node, breakTarget, continueTarget) { - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - function bindWhileStatement(node) { - var preWhileLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - function bindDoStatement(node) { - var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 222 /* LabeledStatement */ - ? ts.lastOrUndefined(activeLabels) - : undefined; - // if do statement is wrapped in labeled statement then target labels for break/continue with or without - // label should be the same - var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); - var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - function bindForStatement(node) { - var preLoopLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindForInOrForOfStatement(node) { - var preLoopLabel = createLoopLabel(); - var postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - if (node.kind === 216 /* ForOfStatement */) { - bind(node.awaitModifier); - } - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== 227 /* VariableDeclarationList */) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindIfStatement(node) { - var thenLabel = createBranchLabel(); - var elseLabel = createBranchLabel(); - var postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - function bindReturnOrThrow(node) { - bind(node.expression); - if (node.kind === 219 /* ReturnStatement */) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - function findActiveLabel(name) { - if (activeLabels) { - for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { - var label = activeLabels_1[_i]; - if (label.name === name) { - return label; - } - } - } - return undefined; - } - function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 218 /* BreakStatement */ ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - function bindBreakOrContinueStatement(node) { - bind(node.label); - if (node.label) { - var activeLabel = findActiveLabel(node.label.text); - if (activeLabel) { - activeLabel.referenced = true; - bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - // TODO: Every statement in try block is potentially an exit point! - bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; - } - if (node.finallyBlock) { - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); - bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block - if (!(currentFlow.flags & 1 /* Unreachable */)) { - if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } - } - if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; - } - } - else { - currentFlow = finishFlowLabel(preFinallyLabel); - } - } - function bindSwitchStatement(node) { - var postSwitchLabel = createBranchLabel(); - bind(node.expression); - var saveBreakTarget = currentBreakTarget; - var savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 258 /* DefaultClause */; }); - // We mark a switch statement as possibly exhaustive if it has no default clause and if all - // case clauses have unreachable end points (e.g. they all return). - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - function bindCaseBlock(node) { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var clauses = node.clauses; - var fallthroughFlow = unreachableFlow; - for (var i = 0; i < clauses.length; i++) { - var clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - var clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - function bindCaseClause(node) { - var saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - bindEach(node.statements); - } - function pushActiveLabel(name, breakTarget, continueTarget) { - var activeLabel = { - name: name, - breakTarget: breakTarget, - continueTarget: continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - function popActiveLabel() { - activeLabels.pop(); - } - function bindLabeledStatement(node) { - var preStatementLabel = createLoopLabel(); - var postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - var activeLabel = pushActiveLabel(node.label.text, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); - } - if (!node.statement || node.statement.kind !== 212 /* DoStatement */) { - // do statement sets current flow inside bindDoStatement - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - } - function bindDestructuringTargetFlow(node) { - if (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { - bindAssignmentTargetFlow(node.left); - } - else { - bindAssignmentTargetFlow(node); - } - } - function bindAssignmentTargetFlow(node) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === 177 /* ArrayLiteralExpression */) { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var e = _a[_i]; - if (e.kind === 198 /* SpreadElement */) { - bindAssignmentTargetFlow(e.expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === 178 /* ObjectLiteralExpression */) { - for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { - var p = _c[_b]; - if (p.kind === 261 /* PropertyAssignment */) { - bindDestructuringTargetFlow(p.initializer); - } - else if (p.kind === 262 /* ShorthandPropertyAssignment */) { - bindAssignmentTargetFlow(p.name); - } - else if (p.kind === 263 /* SpreadAssignment */) { - bindAssignmentTargetFlow(p.expression); - } - } - } - } - function bindLogicalExpression(node, trueTarget, falseTarget) { - var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { - var saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - bindEachChild(node); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - } - function bindPostfixUnaryExpressionFlow(node) { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - function bindBinaryExpressionFlow(node) { - var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - bindEachChild(node); - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 180 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - function bindDeleteExpressionFlow(node) { - bindEachChild(node); - if (node.expression.kind === 179 /* PropertyAccessExpression */) { - bindAssignmentTargetFlow(node.expression); - } - } - function bindConditionalExpressionFlow(node) { - var trueLabel = createBranchLabel(); - var falseLabel = createBranchLabel(); - var postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.questionToken); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.colonToken); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - function bindInitializedVariableFlow(node) { - var name = !ts.isOmittedExpression(node) ? node.name : undefined; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var child = _a[_i]; - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - function bindVariableDeclarationFlow(node) { - bindEachChild(node); - if (node.initializer || node.parent.parent.kind === 215 /* ForInStatement */ || node.parent.parent.kind === 216 /* ForOfStatement */) { - bindInitializedVariableFlow(node); - } - } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 290 /* JSDocTypedefTag */) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - // if the node has a fullName "A.B.C", that means symbol "C" was already bound - // when we visit "fullName"; so when we visit the name "C" as the next child of - // the jsDocTypedefTag, we should skip binding it. - if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { - return; - } - bind(n); - }); - } - function bindCallExpressionFlow(node) { - // If the target of the call expression is a function expression or arrow function we have - // an immediately invoked function expression (IIFE). Initialize the flowNode property to - // the current control flow (which includes evaluation of the IIFE arguments). - var expr = node.expression; - while (expr.kind === 185 /* ParenthesizedExpression */) { - expr = expr.expression; - } - if (expr.kind === 186 /* FunctionExpression */ || expr.kind === 187 /* ArrowFunction */) { - bindEach(node.typeArguments); - bindEach(node.arguments); - bind(node.expression); - } - else { - bindEachChild(node); - } - if (node.expression.kind === 179 /* PropertyAccessExpression */) { - var propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 178 /* ObjectLiteralExpression */: - case 163 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: - case 275 /* JSDocRecordType */: - case 254 /* JsxAttributes */: - return 1 /* IsContainer */; - case 230 /* InterfaceDeclaration */: - return 1 /* IsContainer */ | 64 /* IsInterface */; - case 279 /* JSDocFunctionType */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: - return 1 /* IsContainer */ | 32 /* HasLocals */; - case 265 /* SourceFile */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 151 /* MethodDeclaration */: - if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; - } - // falls through - case 152 /* Constructor */: - case 228 /* FunctionDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 234 /* ModuleBlock */: - return 4 /* IsControlFlowContainer */; - case 149 /* PropertyDeclaration */: - return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 260 /* CatchClause */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - case 235 /* CaseBlock */: - return 2 /* IsBlockScopedContainer */; - case 207 /* Block */: - // do not treat blocks directly inside a function as a block-scoped-container. - // Locals that reside in this block should go to the function locals. Otherwise 'x' - // would not appear to be a redeclaration of a block scoped local in the following - // example: - // - // function foo() { - // var x; - // let x; - // } - // - // If we placed 'var x' into the function locals and 'let x' into the locals of - // the block, then there would be no collision. - // - // By not creating a new block-scoped-container here, we ensure that both 'var x' - // and 'let x' go into the Function-container's locals, and we do get a collision - // conflict. - return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; - } - return 0 /* None */; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - // Just call this directly so that the return type of this function stays "void". - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - function declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes) { - switch (container.kind) { - // Modules, source files, and classes need specialized handling for how their - // members are declared (for example, a member of a class will go into a specific - // symbol table depending on if it is static or not). We defer to specialized - // handlers to take care of declaring these child members. - case 233 /* ModuleDeclaration */: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 265 /* SourceFile */: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 232 /* EnumDeclaration */: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 163 /* TypeLiteral */: - case 178 /* ObjectLiteralExpression */: - case 230 /* InterfaceDeclaration */: - case 275 /* JSDocRecordType */: - case 292 /* JSDocTypeLiteral */: - case 254 /* JsxAttributes */: - // Interface/Object-types always have their children added to the 'members' of - // their container. They are only accessible through an instance of their - // container, and are never in scope otherwise (even inside the body of the - // object / type / interface declaring them). An exception is type parameters, - // which are in scope without qualification (similar to 'locals'). - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 279 /* JSDocFunctionType */: - case 231 /* TypeAliasDeclaration */: - case 172 /* MappedType */: - // All the children of these container types are never visible through another - // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, - // they're only accessed 'lexically' (i.e. from code that exists underneath - // their container in the tree. To accomplish this, we simply add their declared - // symbol to the 'locals' of the container. These symbols can then be found as - // the type checker walks up the containers, checking them for matching names. - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32 /* Static */) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 265 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 265 /* SourceFile */ || body.kind === 234 /* ModuleBlock */)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 244 /* ExportDeclaration */ || stat.kind === 243 /* ExportAssignment */) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular - // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 32 /* ExportContext */; - } - else { - node.flags &= ~32 /* ExportContext */; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1 /* Export */)) { - errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (ts.isExternalModuleAugmentation(node)) { - declareModuleSymbol(node); - } - else { - var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { - var text = node.name.text; - if (ts.hasZeroOrOneAsteriskCharacter(text)) { - pattern = ts.tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 106639 /* ValueModuleExcludes */); - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern: pattern, symbol: symbol }); - } - } - } - else { - var state = declareModuleSymbol(node); - if (state !== 0 /* NonInstantiated */) { - if (node.symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)) { - // if module was already merged with some function, class or non-const enum - // treat is a non-const-enum-only - node.symbol.constEnumOnlyModule = false; - } - else { - var currentModuleIsConstEnumOnly = state === 2 /* ConstEnumOnly */; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - function declareModuleSymbol(node) { - var state = getModuleInstanceState(node); - var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 106639 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); - return state; - } - function bindFunctionOrConstructorType(node) { - // For a given function symbol "<...>(...) => T" we want to generate a symbol identical - // to the one we would get for: { <...>(...): T } - // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable - // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072 /* Signature */); - var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = ts.createMap(); - 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++) { - var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */ || prop.kind === 151 /* MethodDeclaration */ - ? 1 /* Property */ - : 2 /* Accessor */; - var existingKind = seen.get(identifier.text); - if (!existingKind) { - seen.set(identifier.text, currentKind); - continue; - } - if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span_1 = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object"); - } - function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes"); - } - function bindJsxAttribute(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 233 /* ModuleDeclaration */: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 265 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - // falls through - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createMap(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 107455 /* BlockScopedVariableExcludes */); - } - // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized - // check for reserved words used as identifiers in strict mode code. - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && - !ts.isIdentifierName(node) && - !ts.isInAmbientContext(node)) { - // Report error only if there are no parse errors in file - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the - // Catch production is eval or arguments - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { - // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its - // UnaryExpression is a direct reference to a variable, function argument, or function name - var span_2 = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - function isEvalOrArgumentsIdentifier(node) { - return node.kind === 71 /* Identifier */ && - (node.text === "eval" || node.text === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { - var identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); - } - } - } - function getStrictModeEvalOrArgumentsMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - checkStrictModeEvalOrArguments(node, node.name); - } - } - function getStrictModeBlockScopeFunctionDeclarationMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2 /* ES2015 */) { - // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 265 /* SourceFile */ && - blockScopeContainer.kind !== 233 /* ModuleDeclaration */ && - !ts.isFunctionLike(blockScopeContainer)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var errorSpan = ts.getErrorSpanForNode(file, node); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 4 /* Octal */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - function checkStrictModePostfixUnaryExpression(node) { - // Grammar checking - // The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression - // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - function checkStrictModePrefixUnaryExpression(node) { - // Grammar checking - if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - // Grammar checking for withStatement - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function getDestructuringParameterName(node) { - return "__" + ts.indexOf(node.parent.parameters, node); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var saveInStrictMode = inStrictMode; - // Even though in the AST the jsdoc @typedef node belongs to the current node, - // its symbol might be in the same scope with the current node's symbol. Consider: - // - // /** @typedef {string | number} MyType */ - // function foo(); - // - // 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 (ts.isInJavaScriptFile(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 - // destination symbol tables are: - // - // 1) The 'exports' table of the current container's symbol. - // 2) The 'members' table of the current container's symbol. - // 3) The 'locals' table of the current container. - // - // However, not all symbols will end up in any of these tables. 'Anonymous' symbols - // (like TypeLiterals for example) will not be put in any table. - bindWorker(node); - // Then we recurse into the children of the node to bind them as well. For certain - // symbols we do specialized work when we recurse. For example, we'll keep track of - // the current 'container' node when it changes. This helps us know which symbol table - // a local should go into for example. Since terminal nodes are known not to have - // children, as an optimization we don't process those. - if (node.kind > 142 /* LastToken */) { - var saveParent = parent; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags === 0 /* None */) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - function bindJSDocTypedefTagIfAny(node) { - if (!node.jsDoc) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; - } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 290 /* JSDocTypedefTag */) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; - } - } - } - } - function updateStrictModeStatementList(statements) { - if (!inStrictMode) { - for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { - var statement = statements_2[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getTextOfNodeFromSourceText(file.text, node.expression); - // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the - // string to contain unicode escapes (as per ES5). - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - /* Strict mode checks */ - case 71 /* Identifier */: - // 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) { - var parentNode = node.parent; - while (parentNode && parentNode.kind !== 290 /* JSDocTypedefTag */) { - parentNode = parentNode.parent; - } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - break; - } - // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 262 /* ShorthandPropertyAssignment */)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case 179 /* PropertyAccessExpression */: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - break; - case 194 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case 1 /* ExportsProperty */: - bindExportsPropertyAssignment(node); - break; - case 2 /* ModuleExports */: - bindModuleExportsAssignment(node); - break; - case 3 /* PrototypeProperty */: - bindPrototypePropertyAssignment(node); - break; - case 4 /* ThisProperty */: - bindThisPropertyAssignment(node); - break; - case 5 /* Property */: - bindStaticPropertyAssignment(node); - break; - case 0 /* None */: - // Nothing to do - break; - default: - ts.Debug.fail("Unknown special property assignment kind"); - } - return checkStrictModeBinaryExpression(node); - case 260 /* CatchClause */: - return checkStrictModeCatchClause(node); - case 188 /* DeleteExpression */: - return checkStrictModeDeleteExpression(node); - case 8 /* NumericLiteral */: - return checkStrictModeNumericLiteral(node); - case 193 /* PostfixUnaryExpression */: - return checkStrictModePostfixUnaryExpression(node); - case 192 /* PrefixUnaryExpression */: - return checkStrictModePrefixUnaryExpression(node); - case 220 /* WithStatement */: - return checkStrictModeWithStatement(node); - case 169 /* ThisType */: - seenThisKeyword = true; - return; - case 158 /* TypePredicate */: - return checkTypePredicate(node); - case 145 /* TypeParameter */: - return declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 530920 /* TypeParameterExcludes */); - case 146 /* Parameter */: - return bindParameter(node); - case 226 /* VariableDeclaration */: - case 176 /* BindingElement */: - return bindVariableDeclarationOrBindingElement(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 276 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - case 291 /* JSDocPropertyTag */: - return bindJSDocProperty(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 264 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */); - case 263 /* SpreadAssignment */: - case 255 /* JsxSpreadAttribute */: - var root = container; - var hasRest = false; - while (root.parent) { - if (root.kind === 178 /* ObjectLiteralExpression */ && - root.parent.kind === 194 /* BinaryExpression */ && - root.parent.operatorToken.kind === 58 /* EqualsToken */ && - root.parent.left === root) { - hasRest = true; - break; - } - root = root.parent; - } - return; - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - // If this is an ObjectLiteralExpression method, then it sits in the same space - // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes - // so that it will conflict with any other object literal members with the same - // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); - case 228 /* FunctionDeclaration */: - return bindFunctionDeclaration(node); - case 152 /* Constructor */: - return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 153 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */); - case 154 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 279 /* JSDocFunctionType */: - return bindFunctionOrConstructorType(node); - case 163 /* TypeLiteral */: - case 172 /* MappedType */: - case 292 /* JSDocTypeLiteral */: - case 275 /* JSDocRecordType */: - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type"); - case 178 /* ObjectLiteralExpression */: - return bindObjectLiteralExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return bindFunctionExpression(node); - case 181 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - // Members of classes, interfaces, and modules - case 199 /* ClassExpression */: - case 229 /* ClassDeclaration */: - // All classes are automatically in strict mode in ES6. - inStrictMode = true; - return bindClassLikeDeclaration(node); - case 230 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 792968 /* InterfaceExcludes */); - case 290 /* JSDocTypedefTag */: - if (!node.fullName || node.fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - } - break; - case 231 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 793064 /* TypeAliasExcludes */); - case 232 /* EnumDeclaration */: - return bindEnumDeclaration(node); - case 233 /* ModuleDeclaration */: - return bindModuleDeclaration(node); - // Jsx-attributes - case 254 /* JsxAttributes */: - return bindJsxAttributes(node); - case 253 /* JsxAttribute */: - return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); - // Imports and exports - case 237 /* ImportEqualsDeclaration */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: - return declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - case 236 /* NamespaceExportDeclaration */: - return bindNamespaceExportDeclaration(node); - case 239 /* ImportClause */: - return bindImportClause(node); - case 244 /* ExportDeclaration */: - return bindExportDeclaration(node); - case 243 /* ExportAssignment */: - return bindExportAssignment(node); - case 265 /* SourceFile */: - updateStrictModeStatementList(node.statements); - return bindSourceFileIfExternalModule(); - case 207 /* Block */: - if (!ts.isFunctionLike(node.parent)) { - return; - } - // falls through - case 234 /* ModuleBlock */: - return updateStrictModeStatementList(node.statements); - } - } - function checkTypePredicate(node) { - var parameterName = node.parameterName, type = node.type; - if (parameterName && parameterName.kind === 71 /* Identifier */) { - checkStrictModeIdentifier(parameterName); - } - if (parameterName && parameterName.kind === 169 /* ThisType */) { - seenThisKeyword = true; - } - bind(type); - } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } - function bindExportAssignment(node) { - if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); - } - else { - // An export default clause with an expression exports a value - // We want to exclude both class and function here, this is necessary to issue an error when there are both - // default export-assignment and default export function and class declaration. - var flags = node.kind === 243 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) - ? 8388608 /* Alias */ - : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); - } - } - function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); - } - if (node.parent.kind !== 265 /* SourceFile */) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - file.symbol.globalExports = file.symbol.globalExports || ts.createMap(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - } - function bindExportDeclaration(node) { - if (!container.symbol || !container.symbol.exports) { - // Export * in some sort of block construct - bindAnonymousDeclaration(node, 33554432 /* ExportStar */, getDeclarationName(node)); - } - else if (!node.exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 33554432 /* ExportStar */, 0 /* None */); - } - } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 8388608 /* Alias */, 8388608 /* AliasExcludes */); - } - } - function setCommonJsModuleIndicator(node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } - } - } - function bindExportsPropertyAssignment(node) { - // When we create a property via 'exports.foo = bar', the 'exports.foo' property access - // expression is the declaration - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, 4 /* Property */ | 7340032 /* Export */, 0 /* None */); - } - function isExportsOrModuleExportsOrAlias(node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - isNameOfExportsOrModuleExportsAliasDeclaration(node); - } - function isNameOfExportsOrModuleExportsAliasDeclaration(node) { - if (node.kind === 71 /* Identifier */) { - var symbol = lookupSymbolForName(node.text); - if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === 226 /* VariableDeclaration */) { - var declaration = symbol.valueDeclaration; - if (declaration.initializer) { - return isExportsOrModuleExportsOrAliasOrAssignemnt(declaration.initializer); - } - } - } - return false; - } - function isExportsOrModuleExportsOrAliasOrAssignemnt(node) { - return isExportsOrModuleExportsOrAlias(node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignements*/ true) && (isExportsOrModuleExportsOrAliasOrAssignemnt(node.left) || isExportsOrModuleExportsOrAliasOrAssignemnt(node.right))); - } - function bindModuleExportsAssignment(node) { - // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' - // is still pointing to 'module.exports'. - // We do not want to consider this as 'export=' since a module can have only one of these. - // Similarlly we do not want to treat 'module.exports = exports' as an 'export='. - var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || isExportsOrModuleExportsOrAlias(assignedExpression)) { - // Mark it as a module in case there are no other exports in the file - setCommonJsModuleIndicator(node); - return; - } - // 'module.exports = expr' assignment - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 7340032 /* Export */ | 512 /* ValueModule */, 0 /* None */); - } - function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - switch (container.kind) { - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - // Declare a 'member' if the container is an ES5 class or ES6 constructor - container.symbol.members = container.symbol.members || ts.createMap(); - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); - break; - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - // this.foo assignment in a JavaScript class - // Bind this property to the containing class - var containingClass = container.parent; - var symbol = declareSymbol(ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members, containingClass.symbol, node, 4 /* Property */, 0 /* None */); - if (symbol) { - // symbols declared through 'this' property assignements can be overwritten by subsequent method declarations - symbol.isReplaceableByMethod = true; - } - break; - } - } - function bindPrototypePropertyAssignment(node) { - // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. - // Look up the function in the local scope, since prototype assignments should - // follow the function declaration - var leftSideOfAssignment = node.left; - var classPrototype = leftSideOfAssignment.expression; - var constructorFunction = classPrototype.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.text, leftSideOfAssignment, /*isPrototypeProperty*/ true); - } - function bindStaticPropertyAssignment(node) { - // We saw a node of the form 'x.y = z'. Declare a 'member' y on x if x was a function. - // Look up the function in the local scope, since prototype assignments should - // follow the function declaration - var leftSideOfAssignment = node.left; - var target = leftSideOfAssignment.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - target.parent = leftSideOfAssignment; - if (isNameOfExportsOrModuleExportsAliasDeclaration(target)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindPropertyAssignment(target.text, leftSideOfAssignment, /*isPrototypeProperty*/ false); - } - } - function lookupSymbolForName(name) { - return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name)); - } - function bindPropertyAssignment(functionName, propertyAccessExpression, isPrototypeProperty) { - var targetSymbol = lookupSymbolForName(functionName); - if (targetSymbol && ts.isDeclarationOfFunctionOrClassExpression(targetSymbol)) { - targetSymbol = targetSymbol.valueDeclaration.initializer.symbol; - } - if (!targetSymbol || !(targetSymbol.flags & (16 /* Function */ | 32 /* Class */))) { - return; - } - // Set up the members collection if it doesn't exist already - var symbolTable = isPrototypeProperty ? - (targetSymbol.members || (targetSymbol.members = ts.createMap())) : - (targetSymbol.exports || (targetSymbol.exports = ts.createMap())); - // Declare the method/property - declareSymbol(symbolTable, targetSymbol, propertyAccessExpression, 4 /* Property */, 0 /* PropertyExcludes */); - } - function bindCallExpression(node) { - // We're only inspecting call expressions to detect CommonJS modules, so we can skip - // this check if we've already seen the module indicator - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { - setCommonJsModuleIndicator(node); - } - } - function bindClassLikeDeclaration(node) { - if (node.kind === 229 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 899519 /* ClassExcludes */); - } - else { - var bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, 32 /* Class */, bindingName); - // Add name of class expression into the map for semantic classifier - if (node.name) { - classifiableNames.set(node.name.text, node.name.text); - } - } - var symbol = node.symbol; - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the - // type of which is an instantiation of the class type with type Any supplied as a type - // argument for each type parameter. It is an error to explicitly declare a static - // property member with the name 'prototype'. - // - // Note: we check for this here because this class may be merging into a module. The - // module might have an exported variable called 'prototype'. We can't allow that as - // that would clash with the built-in 'prototype' for the class. - var prototypeSymbol = createSymbol(4 /* Property */ | 16777216 /* Prototype */, "prototype"); - var symbolExport = symbol.exports.get(prototypeSymbol.name); - if (symbolExport) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(ts.createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports.set(prototypeSymbol.name, prototypeSymbol); - prototypeSymbol.parent = symbol; - } - function bindEnumDeclaration(node) { - return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */) - : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */); - } - function bindVariableDeclarationOrBindingElement(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (!ts.isBindingPattern(node.name)) { - if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration - // because its parent chain has already been set up, since parents are set before descending into children. - // - // If node is a binding element in parameter declaration, we need to use ParameterExcludes. - // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration - // For example: - // function foo([a,a]) {} // Duplicate Identifier error - // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter - // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107454 /* FunctionScopedVariableExcludes */); - } - } - } - function bindParameter(node) { - 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); - } - if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, getDestructuringParameterName(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); - } - // If this is a property-parameter, then also declare the property symbol into the - // containing class. - if (ts.isParameterPropertyDeclaration(node)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - } - } - function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 106927 /* FunctionExcludes */); - } - } - function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !ts.isInAmbientContext(node)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindJSDocProperty(node) { - return declareSymbolAndAddToSymbolTable(node, 4 /* Property */, 0 /* PropertyExcludes */); - } - // reachability checks - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); - } - function checkUnreachable(node) { - if (!(currentFlow.flags & 1 /* Unreachable */)) { - return false; - } - if (currentFlow === unreachableFlow) { - var reportError = - // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 209 /* EmptyStatement */) || - // report error on class declarations - node.kind === 229 /* ClassDeclaration */ || - // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 233 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 232 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !ts.isInAmbientContext(node) && - (node.kind !== 208 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - } - return true; - } - } - /** - * Computes the transform flags for a node, given the transform flags of its subtree - * - * @param node The node to analyze - * @param subtreeFlags Transform flags computed for this node's subtree - */ - function computeTransformFlagsForNode(node, subtreeFlags) { - var kind = node.kind; - switch (kind) { - case 181 /* CallExpression */: - return computeCallExpression(node, subtreeFlags); - case 182 /* NewExpression */: - return computeNewExpression(node, subtreeFlags); - case 233 /* ModuleDeclaration */: - return computeModuleDeclaration(node, subtreeFlags); - case 185 /* ParenthesizedExpression */: - return computeParenthesizedExpression(node, subtreeFlags); - case 194 /* BinaryExpression */: - return computeBinaryExpression(node, subtreeFlags); - case 210 /* ExpressionStatement */: - return computeExpressionStatement(node, subtreeFlags); - case 146 /* Parameter */: - return computeParameter(node, subtreeFlags); - case 187 /* ArrowFunction */: - return computeArrowFunction(node, subtreeFlags); - case 186 /* FunctionExpression */: - return computeFunctionExpression(node, subtreeFlags); - case 228 /* FunctionDeclaration */: - return computeFunctionDeclaration(node, subtreeFlags); - case 226 /* VariableDeclaration */: - return computeVariableDeclaration(node, subtreeFlags); - case 227 /* VariableDeclarationList */: - return computeVariableDeclarationList(node, subtreeFlags); - case 208 /* VariableStatement */: - return computeVariableStatement(node, subtreeFlags); - case 222 /* LabeledStatement */: - return computeLabeledStatement(node, subtreeFlags); - case 229 /* ClassDeclaration */: - return computeClassDeclaration(node, subtreeFlags); - case 199 /* ClassExpression */: - return computeClassExpression(node, subtreeFlags); - case 259 /* HeritageClause */: - return computeHeritageClause(node, subtreeFlags); - case 260 /* CatchClause */: - return computeCatchClause(node, subtreeFlags); - case 201 /* ExpressionWithTypeArguments */: - return computeExpressionWithTypeArguments(node, subtreeFlags); - case 152 /* Constructor */: - return computeConstructor(node, subtreeFlags); - case 149 /* PropertyDeclaration */: - return computePropertyDeclaration(node, subtreeFlags); - case 151 /* MethodDeclaration */: - return computeMethod(node, subtreeFlags); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return computeAccessor(node, subtreeFlags); - case 237 /* ImportEqualsDeclaration */: - return computeImportEquals(node, subtreeFlags); - case 179 /* PropertyAccessExpression */: - return computePropertyAccess(node, subtreeFlags); - default: - return computeOther(node, kind, subtreeFlags); - } - } - ts.computeTransformFlagsForNode = computeTransformFlagsForNode; - function computeCallExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { - // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; - } - function computeNewExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadElementExpression then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function computeBinaryExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var operatorTokenKind = node.operatorToken.kind; - var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 178 /* ObjectLiteralExpression */) { - // Destructuring object assignments with are ES2015 syntax - // and possibly ESNext if they contain rest - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 177 /* ArrayLiteralExpression */) { - // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { - // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeParameter(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var modifierFlags = ts.getModifierFlags(node); - var name = node.name; - var initializer = node.initializer; - var dotDotDotToken = node.dotDotDotToken; - // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript - // syntax. - if (node.questionToken - || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ - || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If a parameter has an accessibility modifier, then it is TypeScript syntax. - if (modifierFlags & 92 /* ParameterPropertyModifier */) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; - } - // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a parameter has an initializer, a binding pattern or a dotDotDot token, then - // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; - } - function computeParenthesizedExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; - // If the node is synthesized, it means the emitter put the parentheses there, - // not the user. If we didn't want them, the emitter would not have put them - // there. - if (expressionKind === 202 /* AsExpression */ - || expressionKind === 184 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeClassDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - if (modifierFlags & 2 /* Ambient */) { - // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - // An exported declaration may be TypeScript syntax, but is handled by the visitor - // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; - } - function computeClassExpression(node, subtreeFlags) { - // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; - } - function computeHeritageClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - switch (node.token) { - case 85 /* ExtendsKeyword */: - // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 108 /* ImplementsKeyword */: - // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - default: - ts.Debug.fail("Unexpected token for heritage clause"); - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeCatchClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.variableDeclaration && ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; - } - function computeExpressionWithTypeArguments(node, subtreeFlags) { - // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the - // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // If an ExpressionWithTypeArguments contains type arguments, then it - // is TypeScript syntax. - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeConstructor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers and overloads are TypeScript syntax - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; - } - function computeMethod(node, subtreeFlags) { - // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and - // overloads are TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // An async method declaration is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; - } - function computeAccessor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // Decorators, TypeScript-specific modifiers, type annotations, and overloads are - // TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.type - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; - } - function computePropertyDeclaration(node, subtreeFlags) { - // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; - // If the PropertyDeclaration has an initializer, we need to inform its ancestor - // so that it handle the transformation. - if (node.initializer) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeFunctionDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body || (modifierFlags & 2 /* Ambient */)) { - // An ambient declaration is TypeScript syntax. - // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (modifierFlags & 2270 /* TypeScriptModifier */ - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function declaration is ES2017 syntax. - if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionDeclaration is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - // Currently we do not support transforming any other generator fucntions - // down level. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; - } - function computeFunctionExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function expression is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionExpression is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; - } - function computeArrowFunction(node, subtreeFlags) { - // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async arrow function is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; - } - // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; - } - function computePropertyAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - // If a PropertyAccessExpression starts with a super keyword, then it is - // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeVariableDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // Type annotations are TypeScript syntax. - if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeVariableStatement(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var declarationListTransformFlags = node.declarationList.transformFlags; - // An ambient declaration is TypeScript syntax. - if (modifierFlags & 2 /* Ambient */) { - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeLabeledStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ - && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeImportEquals(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // An ImportEqualsDeclaration with a namespace reference is TypeScript. - if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeExpressionStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; - } - function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; - var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2 /* Ambient */) === 0) { - transformFlags |= subtreeFlags; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; - } - function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. - if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; - } - function computeOther(node, kind, subtreeFlags) { - // Mark transformations needed for each node - var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; - switch (kind) { - case 120 /* AsyncKeyword */: - case 191 /* AwaitExpression */: - // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) - transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; - break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 232 /* EnumDeclaration */: - case 264 /* EnumMember */: - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - case 203 /* NonNullExpression */: - case 131 /* ReadonlyKeyword */: - // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - case 249 /* JsxElement */: - case 250 /* JsxSelfClosingElement */: - case 251 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 252 /* JsxClosingElement */: - case 253 /* JsxAttribute */: - case 254 /* JsxAttributes */: - case 255 /* JsxSpreadAttribute */: - case 256 /* JsxExpression */: - // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; - break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 196 /* TemplateExpression */: - case 183 /* TaggedTemplateExpression */: - case 262 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 204 /* MetaProperty */: - // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 9 /* StringLiteral */: - if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 8 /* NumericLiteral */: - if (node.numericLiteralFlags & 48 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 216 /* ForOfStatement */: - // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). - if (node.awaitModifier) { - transformFlags |= 8 /* AssertESNext */; - } - transformFlags |= 192 /* AssertES2015 */; - break; - case 197 /* YieldExpression */: - // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async - // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; - break; - case 119 /* AnyKeyword */: - case 133 /* NumberKeyword */: - case 130 /* NeverKeyword */: - case 134 /* ObjectKeyword */: - case 136 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 158 /* TypePredicate */: - case 159 /* TypeReference */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 162 /* TypeQuery */: - case 163 /* TypeLiteral */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 169 /* ThisType */: - case 170 /* TypeOperator */: - case 171 /* IndexedAccessType */: - case 172 /* MappedType */: - case 173 /* LiteralType */: - // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; - break; - case 144 /* ComputedPropertyName */: - // Even though computed property names are ES6, we don't treat them as such. - // This is so that they can flow through PropertyName transforms unaffected. - // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; - } - break; - case 198 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; - break; - case 263 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; - break; - case 97 /* SuperKeyword */: - // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 99 /* ThisKeyword */: - // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; - break; - case 174 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; - } - excludeFlags = 537396545 /* BindingPatternExcludes */; - break; - case 175 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; - break; - case 176 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; - if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; - } - break; - case 147 /* Decorator */: - // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; - break; - case 178 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { - // If an ObjectLiteralExpression contains a ComputedPropertyName, then it - // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { - // If an ObjectLiteralExpression contains a spread element, then it - // is an ES next node. - transformFlags |= 8 /* AssertESNext */; - } - break; - case 177 /* ArrayLiteralExpression */: - case 182 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 265 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 219 /* ReturnStatement */: - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~excludeFlags; - } - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - /* @internal */ - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 158 /* FirstTypeNode */ && kind <= 173 /* LastTypeNode */) { - return -3 /* TypeExcludes */; - } - switch (kind) { - case 181 /* CallExpression */: - case 182 /* NewExpression */: - case 177 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; - case 233 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; - case 146 /* Parameter */: - return 536872257 /* ParameterExcludes */; - case 187 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; - case 227 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - return 539358529 /* ClassExcludes */; - case 152 /* Constructor */: - return 601015617 /* ConstructorExcludes */; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 133 /* NumberKeyword */: - case 130 /* NeverKeyword */: - case 136 /* StringKeyword */: - case 134 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 145 /* TypeParameter */: - case 148 /* PropertySignature */: - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; - case 178 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; - case 260 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; - case 174 /* ObjectBindingPattern */: - case 175 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; - default: - return 536872257 /* NodeExcludes */; - } - } - ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; -})(ts || (ts = {})); -/// -/// -var ts; -(function (ts) { - function trace(host) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - ts.trace = trace; - /* @internal */ - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - ts.isTraceEnabled = isTraceEnabled; - /** - * Kinds of file that we are currently looking for. - * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript. - */ - var Extensions; - (function (Extensions) { - Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; - Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ - })(Extensions || (Extensions = {})); - /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ - function resolvedTypeScriptOnly(resolved) { - if (!resolved) { - return undefined; - } - ts.Debug.assert(ts.extensionIsTypeScript(resolved.extension)); - return resolved.path; - } - function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations) { - return { - resolvedModule: resolved && { resolvedFileName: resolved.path, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport }, - failedLookupLocations: failedLookupLocations - }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); - function tryReadFromField(fieldName) { - if (!ts.hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - var fileName = jsonContent[fieldName]; - if (typeof fileName !== "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); - } - return; - } - var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); - } - return path; - } - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - if (currentDirectory !== undefined) { - return getDefaultTypeRoots(currentDirectory, host); - } - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - // And if it doesn't exist, tough. - } - var typeRoots; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) { - var atTypes = ts.combinePaths(directory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - return undefined; - }); - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - var resolved = primaryLookup(); - var primary = true; - if (!resolved) { - resolved = secondaryLookup(); - primary = false; - } - var resolvedTypeReferenceDirective; - if (resolved) { - resolved = realpath(resolved, host, traceEnabled); - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolved, primary); - } - resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolved }; - } - return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations }; - function primaryLookup() { - // Check primary library paths - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - return ts.forEach(typeRoots, function (typeRoot) { - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var directoryExists = directoryProbablyExists(candidateDirectory, host); - if (!directoryExists && traceEnabled) { - trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); - } - return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, !directoryExists, moduleResolutionState)); - }); - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - } - function secondaryLookup() { - var resolvedFile; - var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); - if (!resolvedFile && traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - return resolvedFile; - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - } - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; - function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createFileMap(); - var moduleNameToDirectoryMap = ts.createMap(); - return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; - function getOrCreateCacheForDirectory(directoryName) { - var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName); - var perFolderCache = directoryToModuleNameMap.get(path); - if (!perFolderCache) { - perFolderCache = ts.createMap(); - directoryToModuleNameMap.set(path, perFolderCache); - } - return perFolderCache; - } - function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (!moduleHasNonRelativeName(nonRelativeModuleName)) { - return undefined; - } - var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); - if (!perModuleNameCache) { - perModuleNameCache = createPerModuleNameCache(); - moduleNameToDirectoryMap.set(nonRelativeModuleName, perModuleNameCache); - } - return perModuleNameCache; - } - function createPerModuleNameCache() { - var directoryPathMap = ts.createFileMap(); - return { get: get, set: set }; - function get(directory) { - return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); - } - /** - * At first this function add entry directory -> module resolution result to the table. - * Then it computes the set of parent folders for 'directory' that should have the same module resolution result - * and for every parent folder in set it adds entry: parent -> module resolution. . - * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts. - * Set of parent folders that should have the same result will be: - * [ - * /a/b/c/d, /a/b/c, /a/b - * ] - * this means that request for module resolution from file in any of these folder will be immediately found in cache. - */ - function set(directory, result) { - var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); - // if entry is already in cache do nothing - if (directoryPathMap.contains(path)) { - return; - } - directoryPathMap.set(path, result); - var resolvedFileName = result.resolvedModule && result.resolvedModule.resolvedFileName; - // find common prefix between directory and resolved file name - // this common prefix should be the shorted path that has the same resolution - // directory: /a/b/c/d/e - // resolvedFileName: /a/b/foo.d.ts - var commonPrefix = getCommonPrefix(path, resolvedFileName); - var current = path; - while (true) { - var parent = ts.getDirectoryPath(current); - if (parent === current || directoryPathMap.contains(parent)) { - break; - } - directoryPathMap.set(parent, result); - current = parent; - if (current === commonPrefix) { - break; - } - } - } - function getCommonPrefix(directory, resolution) { - if (resolution === undefined) { - return undefined; - } - var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName); - // find first position where directory and resolution differs - var i = 0; - while (i < Math.min(directory.length, resolutionDirectory.length) && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) { - i++; - } - // find last directory separator before position i - var sep = directory.lastIndexOf(ts.directorySeparator, i); - if (sep < 0) { - return undefined; - } - return directory.substr(0, sep); - } - } - } - ts.createModuleResolutionCache = createModuleResolutionCache; - function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var containingDirectory = ts.getDirectoryPath(containingFile); - var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); - var result = perFolderCache && perFolderCache.get(moduleName); - if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); - } - } - else { - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache); - break; - 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); - // put result in per-module name cache - var perModuleNameCache = cache.getOrCreateCacheForModuleName(moduleName); - if (perModuleNameCache) { - perModuleNameCache.set(containingDirectory, result); - } - } - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); - } - else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); - } - } - function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(extensions, candidate_1, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar_1 = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - return ts.forEach(state.compilerOptions.paths[matchedPatternText], function (subst) { - var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have a ".ts" extension; in contrast to an import, which should omit it. - var tsExtension = ts.tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { - var path_1 = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - return path_1 && { path: path_1, extension: tsExtension }; - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - }); - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - /** - * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations. - * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963 - * Throws an error if the module can't be resolved. - */ - /* @internal */ - function resolveJavaScriptModule(moduleName, initialDir, host) { - var _a = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; - 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 }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); - if (result && result.value) { - var _a = result.value, resolved = _a.resolved, isExternalLibraryImport = _a.isExternalLibraryImport; - return createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations); - } - return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - function tryResolve(extensions) { - var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); - if (resolved) { - return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); - } - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); - } - var resolved_1 = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); - // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files. - return resolved_1 && { value: resolved_1.value && { resolved: { path: realpath(resolved_1.value.path, host, traceEnabled), extension: resolved_1.value.extension }, isExternalLibraryImport: true } }; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); - return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); - } - } - } - function realpath(path, host, traceEnabled) { - if (!host.realpath) { - return path; - } - var real = ts.normalizePath(host.realpath(path)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); - } - return real; - } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); - } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { - if (!onlyRecordFailures) { - var parentOfCandidate = ts.getDirectoryPath(candidate); - if (!directoryProbablyExists(parentOfCandidate, state.host)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate); - } - onlyRecordFailures = true; - } - } - var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); - if (resolvedFromFile) { - return resolvedFromFile; - } - } - if (!onlyRecordFailures) { - var candidateExists = directoryProbablyExists(candidate, state.host); - if (!candidateExists) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate); - } - onlyRecordFailures = true; - } - } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - switch (extensions) { - case Extensions.DtsOnly: - return tryExtension(".d.ts", ts.Extension.Dts); - case Extensions.TypeScript: - return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); - case Extensions.JavaScript: - return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); - } - function tryExtension(ext, extension) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, extension: extension }; - } - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocations, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - if (state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - } - } - failedLookupLocations.push(fileName); - return undefined; - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { - if (considerPackageJson === void 0) { considerPackageJson = true; } - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (considerPackageJson) { - var packageJsonPath = pathToPackageJson(candidate); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); - if (fromPackageJson) { - return fromPackageJson; - } - } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - } - } - return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); - } - function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); - if (!file) { - return undefined; - } - var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); - var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); - } - } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - } - /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ - function resolvedIfExtensionMatches(extensions, path) { - var extension = ts.tryGetExtensionFromPath(path); - return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; - } - /** True if `extension` is one of the supported `extensions`. */ - function extensionIsOk(extensions, extension) { - switch (extensions) { - case Extensions.JavaScript: - return extension === ts.Extension.Js || extension === ts.Extension.Jsx; - case Extensions.TypeScript: - return extension === ts.Extension.Ts || extension === ts.Extension.Tsx || extension === ts.Extension.Dts; - case Extensions.DtsOnly: - return extension === ts.Extension.Dts; - } - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state) { - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - return loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - } - function loadModuleFromNodeModules(extensions, moduleName, directory, failedLookupLocations, state, cache) { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); - } - function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { - // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); - } - function loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, typesOnly, cache) { - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - return forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) { - if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host); - if (resolutionFromCache) { - return resolutionFromCache; - } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); - } - }); - } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions, moduleName, directory, failedLookupLocations, state, typesOnly) { - if (typesOnly === void 0) { typesOnly = false; } - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - if (!nodeModulesFolderExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); - } - var packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); - if (packageResult) { - return packageResult; - } - if (extensions !== Extensions.JavaScript) { - var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); - var nodeModulesAtTypesExists = nodeModulesFolderExists; - if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1); - } - nodeModulesAtTypesExists = false; - } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); - } - } - /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(moduleName, state) { - if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, "__"); - if (replaceSlash !== moduleName) { - var mangled = replaceSlash.slice(1); // Take off the "@" - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled); - } - return mangled; - } - } - return moduleName; - } - function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { - var result = cache && cache.get(containingDirectory); - if (result) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache, moduleName); - } - return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, extension: result.resolvedModule.extension } }; - } - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var failedLookupLocations = []; - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); - return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); - function tryResolve(extensions) { - var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, state); - if (resolvedUsingSettings) { - return { value: resolvedUsingSettings }; - } - var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - if (moduleHasNonRelativeName(moduleName)) { - // Climb up parent directories looking for a module. - var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { - var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); - if (resolutionFromCache) { - return resolutionFromCache; - } - var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); - }); - if (resolved_3) { - return resolved_3; - } - if (extensions === Extensions.TypeScript) { - // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFile(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); - } - } - } - ts.classicNameResolver = classicNameResolver; - /** - * LSHost may load a module from a global cache of typings. - * This is the minumum code needed to expose that functionality; the rest is in LSHost. - */ - /* @internal */ - function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); - } - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var failedLookupLocations = []; - var resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); - return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); - } - ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache; - /** - * Wraps value to SearchResult. - * @returns undefined if value is undefined or { value } otherwise - */ - function toSearchResult(value) { - return value !== undefined ? { value: value } : undefined; - } - /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } -})(ts || (ts = {})); -/// -/// -/* @internal */ -var ts; -(function (ts) { - var ambientModuleSymbolRegex = /^".+"$/; - var nextSymbolId = 1; - var nextNodeId = 1; - var nextMergeId = 1; - var nextFlowId = 1; - function getNodeId(node) { - if (!node.id) { - node.id = nextNodeId; - nextNodeId++; - } - return node.id; - } - ts.getNodeId = getNodeId; - function getSymbolId(symbol) { - if (!symbol.id) { - symbol.id = nextSymbolId; - nextSymbolId++; - } - return symbol.id; - } - ts.getSymbolId = getSymbolId; - function createTypeChecker(host, produceDiagnostics) { - // Cancellation that controls whether or not we can cancel in the middle of type checking. - // In general cancelling is *not* safe for the type checker. We might be in the middle of - // computing something, and we will leave our internals in an inconsistent state. Callers - // who set the cancellation token should catch if a cancellation exception occurs, and - // should throw away and create a new TypeChecker. - // - // Currently we only support setting the cancellation token when getting diagnostics. This - // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if - // they no longer need the information (for example, if the user started editing again). - var cancellationToken; - var requestedExternalEmitHelpers; - var externalHelpersModule; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var Type = ts.objectAllocator.getTypeConstructor(); - var Signature = ts.objectAllocator.getSignatureConstructor(); - var typeCount = 0; - var symbolCount = 0; - var enumCount = 0; - var symbolInstantiationDepth = 0; - var emptyArray = []; - var emptySymbols = ts.createMap(); - var compilerOptions = host.getCompilerOptions(); - var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); - var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; - var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; - var strictNullChecks = compilerOptions.strictNullChecks === undefined ? compilerOptions.strict : compilerOptions.strictNullChecks; - var noImplicitAny = compilerOptions.noImplicitAny === undefined ? compilerOptions.strict : compilerOptions.noImplicitAny; - var noImplicitThis = compilerOptions.noImplicitThis === undefined ? compilerOptions.strict : compilerOptions.noImplicitThis; - var emitResolver = createResolver(); - var nodeBuilder = createNodeBuilder(); - var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); - undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); - // for public members that accept a Node or one of its subtypes, we must guard against - // synthetic nodes created during transformations by calling `getParseTreeNode`. - // for most of these, we perform the guard only on `checker` to avoid any possible - // extra cost of calling `getParseTreeNode` when calling these functions from inside the - // checker. - var checker = { - getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; }, - getTypeCount: function () { return typeCount; }, - isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, - isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, - isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; }, - getMergedSymbol: getMergedSymbol, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeOfSymbolAtLocation: function (symbol, location) { - location = ts.getParseTreeNode(location); - return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; - }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); - return getSymbolsOfParameterPropertyDeclaration(parameter, parameterName); - }, - getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, - getPropertiesOfType: getPropertiesOfType, - getPropertyOfType: getPropertyOfType, - getIndexInfoOfType: getIndexInfoOfType, - getSignaturesOfType: getSignaturesOfType, - getIndexTypeOfType: getIndexTypeOfType, - getBaseTypes: getBaseTypes, - getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, - getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); - return node ? getTypeFromTypeNode(node) : unknownType; - }, - getParameterType: getTypeAtPosition, - getReturnTypeOfSignature: getReturnTypeOfSignature, - getNonNullableType: getNonNullableType, - typeToTypeNode: nodeBuilder.typeToTypeNode, - indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, - signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, - getSymbolsInScope: function (location, meaning) { - location = ts.getParseTreeNode(location); - return location ? getSymbolsInScope(location, meaning) : []; - }, - getSymbolAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getSymbolAtLocation(node) : undefined; - }, - getShorthandAssignmentValueSymbol: function (node) { - node = ts.getParseTreeNode(node); - return node ? getShorthandAssignmentValueSymbol(node) : undefined; - }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); - return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; - }, - getTypeAtLocation: function (node) { - node = ts.getParseTreeNode(node); - return node ? getTypeOfNode(node) : unknownType; - }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); - return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; - }, - signatureToString: function (signature, enclosingDeclaration, flags, kind) { - return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind); - }, - typeToString: function (type, enclosingDeclaration, flags) { - return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); - }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); - }, - getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, - getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); - return node ? getContextualType(node) : undefined; - }, - getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); - return node ? getResolvedSignature(node, candidatesOutArray) : undefined; - }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); - return node ? isValidPropertyAccess(node, propertyName) : false; - }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); - return declaration ? getSignatureFromDeclaration(declaration) : undefined; - }, - isImplementationOfOverload: function (node) { - node = ts.getParseTreeNode(node, ts.isFunctionLike); - return node ? isImplementationOfOverload(node) : undefined; - }, - getImmediateAliasedSymbol: function (symbol) { - ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.immediateTarget) { - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); - } - return links.immediateTarget; - }, - getAliasedSymbol: resolveAlias, - getEmitResolver: getEmitResolver, - getExportsOfModule: getExportsOfModuleAsArray, - getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); - return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; - }, - getJsxIntrinsicTagNames: getJsxIntrinsicTagNames, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); - return node ? isOptionalParameter(node) : false; - }, - tryGetMemberInModuleExports: tryGetMemberInModuleExports, - tryFindAmbientModuleWithoutAugmentations: function (moduleName) { - // we deliberately exclude augmentations - // since we are only interested in declarations of the module itself - return tryFindAmbientModule(moduleName, /*withAugmentations*/ false); - }, - getApparentType: getApparentType, - getAllPossiblePropertiesOfType: getAllPossiblePropertiesOfType, - getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, - getSuggestionForNonexistentSymbol: getSuggestionForNonexistentSymbol, - getBaseConstraintOfType: getBaseConstraintOfType, - }; - var tupleTypes = []; - var unionTypes = ts.createMap(); - var intersectionTypes = ts.createMap(); - var literalTypes = ts.createMap(); - var indexedAccessTypes = ts.createMap(); - var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4 /* Property */, "unknown"); - var resolvingSymbol = createSymbol(0, "__resolving__"); - var anyType = createIntrinsicType(1 /* Any */, "any"); - var autoType = createIntrinsicType(1 /* Any */, "any"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 2097152 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(4096 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(4096 /* Null */ | 2097152 /* ContainsWideningType */, "null"); - var stringType = createIntrinsicType(2 /* String */, "string"); - var numberType = createIntrinsicType(4 /* Number */, "number"); - var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); - var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(1024 /* Void */, "void"); - var neverType = createIntrinsicType(8192 /* Never */, "never"); - var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); - var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); - emptyTypeLiteralSymbol.members = ts.createMap(); - var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - emptyGenericType.instantiations = ts.createMap(); - var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated - // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 8388608 /* ContainsAnyFunctionType */; - var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, unknownType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); - var globals = ts.createMap(); - /** - * List of every ambient module with a "*" wildcard. - * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches. - * This is only used if there is no exact match. - */ - var patternAmbientModules; - var globalObjectType; - var globalFunctionType; - var globalArrayType; - var globalReadonlyArrayType; - var globalStringType; - var globalNumberType; - var globalBooleanType; - var globalRegExpType; - var globalThisType; - var anyArrayType; - var autoArrayType; - var anyReadonlyArrayType; - // The library files are only loaded when the feature is used. - // This allows users to just specify library files they want to used through --lib - // and they will not get an error from not having unrelated library files - var deferredGlobalESSymbolConstructorSymbol; - var deferredGlobalESSymbolType; - var deferredGlobalTypedPropertyDescriptorType; - var deferredGlobalPromiseType; - var deferredGlobalPromiseConstructorSymbol; - var deferredGlobalPromiseConstructorLikeType; - var deferredGlobalIterableType; - var deferredGlobalIteratorType; - var deferredGlobalIterableIteratorType; - var deferredGlobalAsyncIterableType; - var deferredGlobalAsyncIteratorType; - var deferredGlobalAsyncIterableIteratorType; - var deferredGlobalTemplateStringsArrayType; - var deferredJsxElementClassType; - var deferredJsxElementType; - var deferredJsxStatelessElementType; - var deferredNodes; - var deferredUnusedIdentifierNodes; - var flowLoopStart = 0; - var flowLoopCount = 0; - var visitedFlowCount = 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 = []; - var flowLoopCaches = []; - var flowLoopNodes = []; - var flowLoopKeys = []; - var flowLoopTypes = []; - var visitedFlowNodes = []; - var visitedFlowTypes = []; - var potentialThisCollisions = []; - 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"; - // The following members encode facts about particular kinds of types for use in the getTypeFacts function. - // The presence of a particular fact means that the given test is true for some (and possibly all) values - // of that kind of type. - 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 /* TypeofEQString */, - "number": 2 /* TypeofEQNumber */, - "boolean": 4 /* TypeofEQBoolean */, - "symbol": 8 /* TypeofEQSymbol */, - "undefined": 16384 /* EQUndefined */, - "object": 16 /* TypeofEQObject */, - "function": 32 /* TypeofEQFunction */ - }); - var typeofNEFacts = ts.createMapFromTemplate({ - "string": 128 /* TypeofNEString */, - "number": 256 /* TypeofNENumber */, - "boolean": 512 /* TypeofNEBoolean */, - "symbol": 1024 /* TypeofNESymbol */, - "undefined": 131072 /* NEUndefined */, - "object": 2048 /* TypeofNEObject */, - "function": 4096 /* TypeofNEFunction */ - }); - var typeofTypesByName = ts.createMapFromTemplate({ - "string": stringType, - "number": numberType, - "boolean": booleanType, - "symbol": esSymbolType, - "undefined": undefinedType - }); - var typeofType = createTypeofType(); - var _jsxNamespace; - var _jsxFactoryEntity; - var _jsxElementPropertiesName; - var _hasComputedJsxElementPropertiesName = false; - var _jsxElementChildrenPropertyName; - var _hasComputedJsxElementChildrenPropertyName = false; - /** Things we lazy load from the JSX namespace */ - var jsxTypes = ts.createMap(); - var JsxNames = { - JSX: "JSX", - IntrinsicElements: "IntrinsicElements", - ElementClass: "ElementClass", - ElementAttributesPropertyNameContainer: "ElementAttributesProperty", - ElementChildrenAttributeNameContainer: "ElementChildrenAttribute", - Element: "Element", - IntrinsicAttributes: "IntrinsicAttributes", - IntrinsicClassAttributes: "IntrinsicClassAttributes" - }; - var subtypeRelation = ts.createMap(); - var assignableRelation = ts.createMap(); - var comparableRelation = ts.createMap(); - var identityRelation = ts.createMap(); - var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - 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(); - return checker; - function getJsxNamespace() { - if (!_jsxNamespace) { - _jsxNamespace = "React"; - if (compilerOptions.jsxFactory) { - _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); - if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; - } - } - else if (compilerOptions.reactNamespace) { - _jsxNamespace = compilerOptions.reactNamespace; - } - } - return _jsxNamespace; - } - function getEmitResolver(sourceFile, cancellationToken) { - // Ensure we have all the type information in place for this file so that all the - // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); - return emitResolver; - } - function error(location, message, arg0, arg1, arg2) { - var diagnostic = location - ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2) - : ts.createCompilerDiagnostic(message, arg0, arg1, arg2); - diagnostics.add(diagnostic); - } - function createSymbol(flags, name) { - symbolCount++; - var symbol = (new Symbol(flags | 134217728 /* Transient */, name)); - symbol.checkFlags = 0; - return symbol; - } - function isTransientSymbol(symbol) { - return (symbol.flags & 134217728 /* Transient */) !== 0; - } - function getExcludedSymbolFlags(flags) { - var result = 0; - if (flags & 2 /* BlockScopedVariable */) - result |= 107455 /* BlockScopedVariableExcludes */; - if (flags & 1 /* FunctionScopedVariable */) - result |= 107454 /* FunctionScopedVariableExcludes */; - if (flags & 4 /* Property */) - result |= 0 /* PropertyExcludes */; - if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; - if (flags & 16 /* Function */) - result |= 106927 /* FunctionExcludes */; - if (flags & 32 /* Class */) - result |= 899519 /* ClassExcludes */; - if (flags & 64 /* Interface */) - result |= 792968 /* InterfaceExcludes */; - if (flags & 256 /* RegularEnum */) - result |= 899327 /* RegularEnumExcludes */; - if (flags & 128 /* ConstEnum */) - result |= 899967 /* ConstEnumExcludes */; - if (flags & 512 /* ValueModule */) - result |= 106639 /* ValueModuleExcludes */; - if (flags & 8192 /* Method */) - result |= 99263 /* MethodExcludes */; - if (flags & 32768 /* GetAccessor */) - result |= 41919 /* GetAccessorExcludes */; - if (flags & 65536 /* SetAccessor */) - result |= 74687 /* SetAccessorExcludes */; - if (flags & 262144 /* TypeParameter */) - result |= 530920 /* TypeParameterExcludes */; - if (flags & 524288 /* TypeAlias */) - result |= 793064 /* TypeAliasExcludes */; - if (flags & 8388608 /* Alias */) - result |= 8388608 /* AliasExcludes */; - return result; - } - function recordMergedSymbol(target, source) { - if (!source.mergeId) { - source.mergeId = nextMergeId; - nextMergeId++; - } - mergedSymbols[source.mergeId] = target; - } - function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags, symbol.name); - result.declarations = symbol.declarations.slice(0); - result.parent = symbol.parent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = ts.cloneMap(symbol.members); - if (symbol.exports) - result.exports = ts.cloneMap(symbol.exports); - recordMergedSymbol(result, symbol); - return result; - } - function mergeSymbol(target, source) { - if (!(target.flags & getExcludedSymbolFlags(source.flags))) { - if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { - // reset flag when merging instantiated module into value module that has only const enums - target.constEnumOnlyModule = false; - } - target.flags |= source.flags; - if (source.valueDeclaration && - (!target.valueDeclaration || - (target.valueDeclaration.kind === 233 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 233 /* ModuleDeclaration */))) { - // other kinds of value declarations take precedence over modules - target.valueDeclaration = source.valueDeclaration; - } - ts.addRange(target.declarations, source.declarations); - if (source.members) { - if (!target.members) - target.members = ts.createMap(); - mergeSymbolTable(target.members, source.members); - } - if (source.exports) { - if (!target.exports) - target.exports = ts.createMap(); - mergeSymbolTable(target.exports, source.exports); - } - recordMergedSymbol(target, source); - } - else if (target.flags & 1024 /* NamespaceModule */) { - 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(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); - }); - } - } - function mergeSymbolTable(target, source) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - } - else { - if (!(targetSymbol.flags & 134217728 /* Transient */)) { - targetSymbol = cloneSymbol(targetSymbol); - target.set(id, targetSymbol); - } - mergeSymbol(targetSymbol, sourceSymbol); - } - }); - } - function mergeModuleAugmentation(moduleName) { - var moduleAugmentation = moduleName.parent; - if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) { - // this is a combined symbol for multiple augmentations within the same file. - // its symbol already has accumulated information for all declarations - // so we need to add it just once - do the work only for first declaration - ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1); - return; - } - if (ts.isGlobalScopeAugmentation(moduleAugmentation)) { - mergeSymbolTable(globals, moduleAugmentation.symbol.exports); - } - else { - // find a module that about to be augmented - // do not validate names of augmentations that are defined in ambient context - var moduleNotFoundError = !ts.isInAmbientContext(moduleName.parent.parent) - ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found - : undefined; - var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); - if (!mainModule) { - return; - } - // obtain item referenced by 'export=' - mainModule = resolveExternalModuleSymbol(mainModule); - if (mainModule.flags & 1920 /* Namespace */) { - // if module symbol has already been merged - it is safe to use it. - // otherwise clone it - mainModule = mainModule.flags & 134217728 /* Transient */ ? mainModule : cloneSymbol(mainModule); - mergeSymbol(mainModule, moduleAugmentation.symbol); - } - else { - error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text); - } - } - } - function addToSymbolTable(target, source, message) { - source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (targetSymbol) { - // Error on redeclarations - ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(id, message)); - } - else { - target.set(id, sourceSymbol); - } - }); - function addDeclarationDiagnostic(id, message) { - return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); }; - } - } - function getSymbolLinks(symbol) { - if (symbol.flags & 134217728 /* Transient */) - return symbol; - var id = getSymbolId(symbol); - return symbolLinks[id] || (symbolLinks[id] = {}); - } - function getNodeLinks(node) { - var nodeId = getNodeId(node); - return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); - } - function getObjectFlags(type) { - return type.flags & 32768 /* Object */ ? type.objectFlags : 0; - } - function isGlobalSourceFile(node) { - return node.kind === 265 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); - } - function getSymbol(symbols, name, meaning) { - if (meaning) { - var symbol = symbols.get(name); - if (symbol) { - ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); - if (symbol.flags & meaning) { - return symbol; - } - if (symbol.flags & 8388608 /* Alias */) { - var target = resolveAlias(symbol); - // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors - if (target === unknownSymbol || target.flags & meaning) { - return symbol; - } - } - } - } - // return undefined if we can't find a symbol. - } - /** - * Get symbols that represent parameter-property-declaration as parameter and as property declaration - * @param parameter a parameterDeclaration node - * @param parameterName a name of the parameter to get the symbols for. - * @return a tuple of two symbols - */ - function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) { - var constructorDeclaration = parameter.parent; - var classDeclaration = parameter.parent.parent; - var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 107455 /* Value */); - var propertySymbol = getSymbol(classDeclaration.symbol.members, parameterName, 107455 /* Value */); - if (parameterSymbol && propertySymbol) { - return [parameterSymbol, propertySymbol]; - } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); - } - function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { - var declarationFile = ts.getSourceFileOfNode(declaration); - var useFile = ts.getSourceFileOfNode(usage); - if (declarationFile !== useFile) { - if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out) || - ts.isInAmbientContext(declaration)) { - // nodes are in different files and order cannot be determined - return true; - } - // declaration is after usage - // can be legal if usage is deferred (i.e. inside function or in initializer of instance property) - if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - return true; - } - var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); - } - if (declaration.pos <= usage.pos) { - // declaration is before usage - if (declaration.kind === 176 /* BindingElement */) { - // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 176 /* BindingElement */); - if (errorBindingElement) { - return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || - declaration.pos < errorBindingElement.pos; - } - // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 226 /* VariableDeclaration */), usage); - } - else if (declaration.kind === 226 /* VariableDeclaration */) { - // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) - return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); - } - return true; - } - // declaration is after usage, but it can still be legal if usage is deferred: - // 1. inside an export specifier - // 2. inside a function - // 3. inside an instance property initializer, a reference to a non-instance property - // 4. inside a static property initializer, a reference to a static method in the same class - // or if usage is in a type context: - // 1. inside a type query (typeof in type position) - if (usage.parent.kind === 246 /* ExportSpecifier */) { - // export specifiers do not use the variable, they only make it available for use - return true; - } - var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); - function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { - var container = ts.getEnclosingBlockScopeContainer(declaration); - switch (declaration.parent.parent.kind) { - case 208 /* VariableStatement */: - case 214 /* ForStatement */: - case 216 /* ForOfStatement */: - // variable statement/for/for-of statement case, - // use site should not be inside variable declaration (initializer of declaration or binding element) - if (isSameScopeDescendentOf(usage, declaration, container)) { - return true; - } - break; - } - switch (declaration.parent.parent.kind) { - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - // ForIn/ForOf case - use site should not be used in expression part - if (isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container)) { - return true; - } - } - return false; - } - function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { - return !!ts.findAncestor(usage, function (current) { - if (current === container) { - return "quit"; - } - if (ts.isFunctionLike(current)) { - return true; - } - var initializerOfProperty = current.parent && - current.parent.kind === 149 /* PropertyDeclaration */ && - current.parent.initializer === current; - if (initializerOfProperty) { - if (ts.getModifierFlags(current.parent) & 32 /* Static */) { - if (declaration.kind === 151 /* MethodDeclaration */) { - return true; - } - } - else { - var isDeclarationInstanceProperty = declaration.kind === 149 /* PropertyDeclaration */ && !(ts.getModifierFlags(declaration) & 32 /* Static */); - if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { - return true; - } - } - } - }); - } - } - // 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, 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; - var errorLocation = location; - var grandparent; - var isInExternalModule = false; - 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 = lookup(location.locals, name, meaning)) { - var useResult = true; - if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) { - // symbol lookup restrictions for function-like declarations - // - Type parameters of a function are in scope in the entire function declaration, including the parameter - // list and return type. However, local types are only in scope in the function body. - // - parameters are only in the scope of function body - // This restriction does not apply to JSDoc comment types because they are parented - // at a higher level than type parameters would normally be - if (meaning & result.flags & 793064 /* Type */ && lastLocation.kind !== 283 /* JSDocComment */) { - useResult = result.flags & 262144 /* TypeParameter */ - ? lastLocation === location.type || - lastLocation.kind === 146 /* Parameter */ || - lastLocation.kind === 145 /* TypeParameter */ - : false; - } - if (meaning & 107455 /* Value */ && result.flags & 1 /* FunctionScopedVariable */) { - // parameters are visible only inside function body, parameter list and return type - // technically for parameter list case here we might mix parameters and variables declared in function, - // however it is detected separately when checking initializers of parameters - // to make sure that they reference no variables declared after them. - useResult = - lastLocation.kind === 146 /* Parameter */ || - (lastLocation === location.type && - result.valueDeclaration.kind === 146 /* Parameter */); - } - } - if (useResult) { - break loop; - } - else { - result = undefined; - } - } - } - switch (location.kind) { - case 265 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) - break; - isInExternalModule = true; - // falls through - case 233 /* ModuleDeclaration */: - var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 265 /* SourceFile */ || ts.isAmbientModule(location)) { - // It's an external module. First see if the module has an export default and if the local - // name of that export default matches. - if (result = moduleExports.get("default")) { - var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { - break loop; - } - result = undefined; - } - // Because of module/namespace merging, a module's exports are in scope, - // yet we never want to treat an export specifier as putting a member in scope. - // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope. - // Two things to note about this: - // 1. We have to check this without calling getSymbol. The problem with calling getSymbol - // on an export specifier is that it might find the export specifier itself, and try to - // resolve it as an alias. This will cause the checker to consider the export specifier - // a circular alias reference when it might not be. - // 2. We check === SymbolFlags.Alias in order to check that the symbol is *purely* - // an alias. If we used &, we'd be throwing out symbols that have non alias aspects, - // which is not the desired behavior. - var moduleExport = moduleExports.get(name); - if (moduleExport && - moduleExport.flags === 8388608 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 246 /* ExportSpecifier */)) { - break; - } - } - if (result = lookup(moduleExports, name, meaning & 8914931 /* ModuleMember */)) { - break loop; - } - break; - case 232 /* EnumDeclaration */: - if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { - break loop; - } - break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - // TypeScript 1.0 spec (April 2014): 8.4.1 - // Initializer expressions for instance member variables are evaluated in the scope - // of the class constructor body but are not permitted to reference parameters or - // local variables of the constructor. This effectively means that entities from outer scopes - // by the same name as a constructor parameter or local variable are inaccessible - // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(ts.getModifierFlags(location) & 32 /* Static */)) { - var ctor = findConstructorDeclaration(location.parent); - if (ctor && ctor.locals) { - if (lookup(ctor.locals, name, meaning & 107455 /* Value */)) { - // Remember the property node, it will be used later to report appropriate error - propertyWithInvalidInitializer = location; - } - } - } - break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - if (result = lookup(getSymbolOfNode(location).members, name, meaning & 793064 /* Type */)) { - if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { - // ignore type parameters not declared in this container - result = undefined; - break; - } - if (lastLocation && ts.getModifierFlags(lastLocation) & 32 /* Static */) { - // TypeScript 1.0 spec (April 2014): 3.4.1 - // The scope of a type parameter extends over the entire declaration with which the type - // parameter list is associated, with the exception of static member declarations in classes. - error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); - return undefined; - } - break loop; - } - if (location.kind === 199 /* ClassExpression */ && meaning & 32 /* Class */) { - var className = location.name; - if (className && name === className.text) { - result = location.symbol; - break loop; - } - } - break; - // It is not legal to reference a class's own type parameters from a computed property name that - // belongs to the class. For example: - // - // function foo() { return '' } - // class C { // <-- Class's own type parameter T - // [foo()]() { } // <-- Reference to T from class's own computed property - // } - // - case 144 /* ComputedPropertyName */: - 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 = 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; - } - } - break; - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - if (meaning & 3 /* Variable */ && name === "arguments") { - result = argumentsSymbol; - break loop; - } - break; - case 186 /* FunctionExpression */: - if (meaning & 3 /* Variable */ && name === "arguments") { - result = argumentsSymbol; - break loop; - } - if (meaning & 16 /* Function */) { - var functionName = location.name; - if (functionName && name === functionName.text) { - result = location.symbol; - break loop; - } - } - break; - case 147 /* Decorator */: - // Decorators are resolved at the class declaration. Resolving at the parameter - // or member would result in looking up locals in the method. - // - // function y() {} - // class C { - // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. - // } - // - if (location.parent && location.parent.kind === 146 /* Parameter */) { - location = location.parent; - } - // - // function y() {} - // class C { - // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. - // } - // - if (location.parent && ts.isClassElement(location.parent)) { - location = location.parent; - } - break; - } - lastLocation = location; - location = location.parent; - } - if (result && nameNotFoundMessage && noUnusedIdentifiers) { - result.isReferenced = true; - } - if (!result) { - result = lookup(globals, name, meaning); - } - if (!result) { - if (nameNotFoundMessage) { - if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && - !checkAndReportErrorForExtendingInterface(errorLocation) && - !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && - !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { - 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; - } - // Perform extra checks only if error reporting was requested - if (nameNotFoundMessage) { - if (propertyWithInvalidInitializer) { - // We have a match, but the reference occurred within a property initializer and the identifier also binds - // to a local variable in the constructor where the code will be emitted. - var propertyName = propertyWithInvalidInitializer.name; - error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return undefined; - } - // Only check for block-scoped variable if we are looking for the - // name with variable meaning - // For example, - // declare module foo { - // interface bar {} - // } - // const foo/*1*/: foo/*2*/.bar; - // The foo at /*1*/ and /*2*/ will share same symbol with two meanings: - // block-scoped variable and namespace module. However, only when we - // try to resolve name in /*1*/ which is used in variable position, - // we want to check for block-scoped - if (meaning & 2 /* BlockScopedVariable */ || - ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 107455 /* Value */) === 107455 /* Value */)) { - var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result); - if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) { - checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation); - } - } - // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { - var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 236 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); - } - } - } - return result; - } - function isTypeParameterSymbolDeclaredInContainer(symbol, container) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (decl.kind === 145 /* TypeParameter */ && decl.parent === container) { - return true; - } - } - return false; - } - function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) { - if ((errorLocation.kind === 71 /* Identifier */ && (isTypeReferenceIdentifier(errorLocation)) || isInTypeQuery(errorLocation))) { - return false; - } - var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true); - var location = container; - while (location) { - if (ts.isClassLike(location.parent)) { - var classSymbol = getSymbolOfNode(location.parent); - if (!classSymbol) { - break; - } - // Check to see if a static member exists. - var constructorType = getTypeOfSymbol(classSymbol); - if (getPropertyOfType(constructorType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg), symbolToString(classSymbol)); - return true; - } - // No static member is present. - // Check if we're in an instance method and look for a relevant instance member. - if (location === container && !(ts.getModifierFlags(location) & 32 /* Static */)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; - if (getPropertyOfType(instanceType, name)) { - error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, typeof nameArg === "string" ? nameArg : ts.declarationNameToString(nameArg)); - return true; - } - } - } - location = location.parent; - } - return false; - } - function checkAndReportErrorForExtendingInterface(errorLocation) { - var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { - error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); - } - return isError; - } - /** - * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, - * but returns undefined if that expression is not an EntityNameExpression. - */ - function getEntityNameForExtendingInterface(node) { - switch (node.kind) { - case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 201 /* ExpressionWithTypeArguments */: - ts.Debug.assert(ts.isEntityNameExpression(node.expression)); - return node.expression; - default: - return undefined; - } - } - function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) { - if (meaning === 1920 /* Namespace */) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 793064 /* Type */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, name); - return true; - } - } - return false; - } - 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); - return true; - } - } - return false; - } - function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) { - if (meaning & (107455 /* Value */ & ~1024 /* NamespaceModule */ & ~793064 /* Type */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, name); - return true; - } - } - else if (meaning & (793064 /* Type */ & ~1024 /* NamespaceModule */ & ~107455 /* Value */)) { - var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~793064 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)); - if (symbol) { - error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, name); - return true; - } - } - return false; - } - function checkResolvedBlockScopedVariable(result, errorLocation) { - ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); - // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 232 /* EnumDeclaration */) ? d : undefined; }); - 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(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - else if (result.flags & 256 /* RegularEnum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); - } - } - } - /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. - * If at any point current node is equal to 'parent' node - return true. - * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. - */ - function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); - } - function getAnyImportSyntax(node) { - if (ts.isAliasSymbolDeclaration(node)) { - if (node.kind === 237 /* ImportEqualsDeclaration */) { - return node; - } - return ts.findAncestor(node, ts.isImportDeclaration); - } - } - function getDeclarationOfAliasSymbol(symbol) { - return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); - } - function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { - return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); - } - return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); - } - function getTargetOfImportClause(node, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); - if (moduleSymbol) { - var exportDefaultSymbol = void 0; - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - exportDefaultSymbol = moduleSymbol; - } - else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); - } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); - } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { - return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - return exportDefaultSymbol; - } - } - function getTargetOfNamespaceImport(node, dontResolveAlias) { - var moduleSpecifier = node.parent.parent.moduleSpecifier; - return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier, dontResolveAlias); - } - // This function creates a synthetic symbol that combines the value side of one symbol with the - // type/namespace side of another symbol. Consider this example: - // - // declare module graphics { - // interface Point { - // x: number; - // y: number; - // } - // } - // declare var graphics: { - // Point: new (x: number, y: number) => graphics.Point; - // } - // declare module "graphics" { - // export = graphics; - // } - // - // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point' - // property with the type/namespace side interface 'Point'. - function combineValueAndTypeSymbols(valueSymbol, typeSymbol) { - if (valueSymbol.flags & (793064 /* Type */ | 1920 /* Namespace */)) { - return valueSymbol; - } - var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); - result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); - result.parent = valueSymbol.parent || typeSymbol.parent; - if (valueSymbol.valueDeclaration) - result.valueDeclaration = valueSymbol.valueDeclaration; - if (typeSymbol.members) - result.members = typeSymbol.members; - if (valueSymbol.exports) - result.exports = valueSymbol.exports; - return result; - } - function getExportOfModule(symbol, name, dontResolveAlias) { - if (symbol.flags & 1536 /* Module */) { - return resolveSymbol(getExportsOfSymbol(symbol).get(name), dontResolveAlias); - } - } - function getPropertyOfVariable(symbol, name) { - if (symbol.flags & 3 /* Variable */) { - var typeAnnotation = symbol.valueDeclaration.type; - if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); - } - } - } - function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); - if (targetSymbol) { - var name = specifier.propertyName || specifier.name; - if (name.text) { - if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - return moduleSymbol; - } - var symbolFromVariable = void 0; - // First check if module was specified with "export=". If so, get the member from the resolved type - if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text); - } - else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); - } - // if symbolFromVariable is export - get its final target - symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - var symbolFromModule = getExportOfModule(targetSymbol, name.text, dontResolveAlias); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.text === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); - } - var symbol = symbolFromModule && symbolFromVariable ? - combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : - symbolFromModule || symbolFromVariable; - if (!symbol) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name)); - } - return symbol; - } - } - } - function getTargetOfImportSpecifier(node, dontResolveAlias) { - return getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias); - } - function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) { - return resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias); - } - function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node, 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); - } - function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { - switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: - return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 239 /* ImportClause */: - return getTargetOfImportClause(node, dontRecursivelyResolve); - case 240 /* NamespaceImport */: - return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 242 /* ImportSpecifier */: - return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 246 /* ExportSpecifier */: - return getTargetOfExportSpecifier(node, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 243 /* ExportAssignment */: - return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 236 /* NamespaceExportDeclaration */: - return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); - } - } - function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && symbol && symbol.flags & 8388608 /* Alias */ && !(symbol.flags & (107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */)); - return shouldResolve ? resolveAlias(symbol) : symbol; - } - function resolveAlias(symbol) { - ts.Debug.assert((symbol.flags & 8388608 /* Alias */) !== 0, "Should only get Alias here."); - var links = getSymbolLinks(symbol); - if (!links.target) { - links.target = resolvingSymbol; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - var target = getTargetOfAliasDeclaration(node); - if (links.target === resolvingSymbol) { - links.target = target || unknownSymbol; - } - else { - error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol)); - } - } - else if (links.target === resolvingSymbol) { - links.target = unknownSymbol; - } - return links.target; - } - function markExportAsReferenced(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target) { - var markAlias = target === unknownSymbol || - ((target.flags & 107455 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target)); - if (markAlias) { - markAliasSymbolAsReferenced(symbol); - } - } - } - // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until - // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of - // the alias as an expression (which recursively takes us back here if the target references another alias). - function markAliasSymbolAsReferenced(symbol) { - var links = getSymbolLinks(symbol); - if (!links.referenced) { - links.referenced = true; - var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - if (node.kind === 243 /* ExportAssignment */) { - // export default - checkExpressionCached(node.expression); - } - else if (node.kind === 246 /* ExportSpecifier */) { - // export { } or export { as foo } - checkExpressionCached(node.propertyName || node.name); - } - else if (ts.isInternalModuleImportEqualsDeclaration(node)) { - // import foo = - checkExpressionCached(node.moduleReference); - } - } - } - // This function is only for imports with entity names - function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { - // There are three things we might try to look for. In the following examples, - // the search term is enclosed in |...|: - // - // import a = |b|; // Namespace - // import a = |b.c|; // Value, type, namespace - // import a = |b.c|.d; // Namespace - if (entityName.kind === 71 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 143 /* QualifiedName */) { - return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); - } - else { - // Case 2 in above example - // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 237 /* ImportEqualsDeclaration */); - return resolveEntityName(entityName, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); - } - } - function getFullyQualifiedName(symbol) { - return symbol.parent ? getFullyQualifiedName(symbol.parent) + "." + symbolToString(symbol) : symbolToString(symbol); - } - /** - * Resolves a qualified name and any involved aliases. - */ - function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) { - if (ts.nodeIsMissing(name)) { - return undefined; - } - var symbol; - if (name.kind === 71 /* Identifier */) { - var message = meaning === 1920 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.text, meaning, ignoreErrors ? undefined : message, name); - if (!symbol) { - return undefined; - } - } - else if (name.kind === 143 /* QualifiedName */ || name.kind === 179 /* PropertyAccessExpression */) { - var left = void 0; - if (name.kind === 143 /* QualifiedName */) { - left = name.left; - } - else if (name.kind === 179 /* PropertyAccessExpression */ && - (name.expression.kind === 185 /* ParenthesizedExpression */ || ts.isEntityNameExpression(name.expression))) { - left = name.expression; - } - else { - // If the expression in property-access expression is not entity-name or parenthsizedExpression (e.g. it is a call expression), it won't be able to successfully resolve the name. - // This is the case when we are trying to do any language service operation in heritage clauses. By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression - // will attempt to checkPropertyAccessExpression to resolve symbol. - // i.e class C extends foo()./*do language service operation here*/B {} - return undefined; - } - var right = name.kind === 143 /* QualifiedName */ ? name.right : name.name; - var namespace = resolveEntityName(left, 1920 /* Namespace */, ignoreErrors, /*dontResolveAlias*/ false, location); - if (!namespace || ts.nodeIsMissing(right)) { - return undefined; - } - else if (namespace === unknownSymbol) { - return namespace; - } - symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); - if (!symbol) { - if (!ignoreErrors) { - error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right)); - } - return undefined; - } - } - else if (name.kind === 185 /* ParenthesizedExpression */) { - // If the expression in parenthesizedExpression is not an entity-name (e.g. it is a call expression), it won't be able to successfully resolve the name. - // This is the case when we are trying to do any language service operation in heritage clauses. - // By return undefined, the getSymbolOfEntityNameOrPropertyAccessExpression will attempt to checkPropertyAccessExpression to resolve symbol. - // i.e class C extends foo()./*do language service operation here*/B {} - return ts.isEntityNameExpression(name.expression) ? - resolveEntityName(name.expression, meaning, ignoreErrors, dontResolveAlias, location) : - undefined; - } - else { - ts.Debug.fail("Unknown entity name kind."); - } - 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) { - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); - } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - if (moduleReferenceExpression.kind !== 9 /* StringLiteral */ && moduleReferenceExpression.kind !== 13 /* NoSubstitutionTemplateLiteral */) { - return; - } - var moduleReferenceLiteral = moduleReferenceExpression; - return resolveExternalModule(location, moduleReferenceLiteral.text, moduleNotFoundError, moduleReferenceLiteral, isForAugmentation); - } - function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) { - if (isForAugmentation === void 0) { isForAugmentation = false; } - // Module names are escaped in our symbol table. However, string literal values aren't. - // Escape the name in the "require(...)" clause to ensure we find the right symbol. - var moduleName = ts.escapeIdentifier(moduleReference); - 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; - } - var isRelative = ts.isExternalModuleNameRelative(moduleName); - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); - var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); - var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); - if (sourceFile) { - if (sourceFile.symbol) { - // merged symbol is module declaration symbol combined with all augmentations - return getMergedSymbol(sourceFile.symbol); - } - if (moduleNotFoundError) { - // report errors only if it was requested - error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName); - } - return undefined; - } - if (patternAmbientModules) { - var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleName); - if (pattern) { - return getMergedSymbol(pattern.symbol); - } - } - // May be an untyped module. If so, ignore resolutionDiagnostic. - if (!isRelative && resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension)) { - if (isForAugmentation) { - var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; - error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); - } - else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. - return undefined; - } - if (moduleNotFoundError) { - // report errors only if it was requested - if (resolutionDiagnostic) { - error(errorNode, resolutionDiagnostic, moduleName, resolvedModule.resolvedFileName); - } - else { - var tsExtension = ts.tryExtractTypeScriptExtension(moduleName); - if (tsExtension) { - var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; - error(errorNode, diag, tsExtension, ts.removeExtension(moduleName, tsExtension)); - } - else { - error(errorNode, moduleNotFoundError, moduleName); - } - } - } - return undefined; - } - // An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, - // and an external module with no 'export =' declaration resolves to the module itself. - function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { - return moduleSymbol && getMergedSymbol(resolveSymbol(moduleSymbol.exports.get("export="), dontResolveAlias)) || moduleSymbol; - } - // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export =' - // 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, moduleReferenceExpression, dontResolveAlias) { - 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)); - } - return symbol; - } - function hasExportAssignmentSymbol(moduleSymbol) { - return moduleSymbol.exports.get("export=") !== undefined; - } - function getExportsOfModuleAsArray(moduleSymbol) { - return symbolsToArray(getExportsOfModule(moduleSymbol)); - } - function getExportsAndPropertiesOfModule(moduleSymbol) { - var exports = getExportsOfModuleAsArray(moduleSymbol); - var exportEquals = resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) { - ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals))); - } - return exports; - } - function tryGetMemberInModuleExports(memberName, moduleSymbol) { - var symbolTable = getExportsOfModule(moduleSymbol); - if (symbolTable) { - return symbolTable.get(memberName); - } - } - function getExportsOfSymbol(symbol) { - return symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; - } - function getExportsOfModule(moduleSymbol) { - var links = getSymbolLinks(moduleSymbol); - return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); - } - /** - * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument - * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables - */ - function extendExportSymbols(target, source, lookupTable, exportNode) { - source && source.forEach(function (sourceSymbol, id) { - if (id === "default") - return; - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - if (lookupTable && exportNode) { - lookupTable.set(id, { - specifierText: ts.getTextOfNode(exportNode.moduleSpecifier) - }); - } - } - else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) { - var collisionTracker = lookupTable.get(id); - if (!collisionTracker.exportsWithDuplicate) { - collisionTracker.exportsWithDuplicate = [exportNode]; - } - else { - collisionTracker.exportsWithDuplicate.push(exportNode); - } - } - }); - } - function getExportsForModule(moduleSymbol) { - var visitedSymbols = []; - // A module defined by an 'export=' consists on one export that needs to be resolved - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - return visit(moduleSymbol) || moduleSymbol.exports; - // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, - // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. - function visit(symbol) { - if (!(symbol && symbol.flags & 1952 /* HasExports */ && !ts.contains(visitedSymbols, symbol))) { - return; - } - visitedSymbols.push(symbol); - var symbols = ts.cloneMap(symbol.exports); - // All export * declarations are collected in an __export symbol by the binder - var exportStars = symbol.exports.get("__export"); - if (exportStars) { - var nestedSymbols = ts.createMap(); - var lookupTable_1 = ts.createMap(); - for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - var exportedSymbols = visit(resolvedModule); - extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node); - } - lookupTable_1.forEach(function (_a, id) { - var exportsWithDuplicate = _a.exportsWithDuplicate; - // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself - if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) { - return; - } - for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) { - var node = exportsWithDuplicate_1[_i]; - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity, lookupTable_1.get(id).specifierText, id)); - } - }); - extendExportSymbols(symbols, nestedSymbols); - } - return symbols; - } - } - function getMergedSymbol(symbol) { - var merged; - return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol; - } - function getSymbolOfNode(node) { - return getMergedSymbol(node.symbol); - } - function getParentOfSymbol(symbol) { - return getMergedSymbol(symbol.parent); - } - function getExportSymbolOfValueSymbolIfExported(symbol) { - return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 - ? getMergedSymbol(symbol.exportSymbol) - : symbol; - } - function symbolIsValue(symbol) { - return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 8388608 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); - } - function findConstructorDeclaration(node) { - var members = node.members; - for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { - var member = members_1[_i]; - if (member.kind === 152 /* Constructor */ && ts.nodeIsPresent(member.body)) { - return member; - } - } - } - function createType(flags) { - var result = new Type(checker, flags); - typeCount++; - result.id = typeCount; - return result; - } - function createIntrinsicType(kind, intrinsicName) { - var type = createType(kind); - type.intrinsicName = intrinsicName; - return type; - } - function createBooleanType(trueFalseTypes) { - var type = getUnionType(trueFalseTypes); - type.flags |= 8 /* Boolean */; - type.intrinsicName = "boolean"; - return type; - } - function createObjectType(objectFlags, symbol) { - var type = createType(32768 /* Object */); - type.objectFlags = objectFlags; - type.symbol = symbol; - return type; - } - function createTypeofType() { - 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 - // with at least two underscores. The @ character indicates that the name is denoted by a well known ES - // Symbol instance. - function isReservedMemberName(name) { - return name.charCodeAt(0) === 95 /* _ */ && - name.charCodeAt(1) === 95 /* _ */ && - name.charCodeAt(2) !== 95 /* _ */ && - name.charCodeAt(2) !== 64 /* at */; - } - function getNamedMembers(members) { - var result; - members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } - } - }); - return result || emptyArray; - } - function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - type.members = members; - type.properties = getNamedMembers(members); - type.callSignatures = callSignatures; - type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; - return type; - } - function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { - return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function forEachSymbolTableInScope(enclosingDeclaration, callback) { - var result; - for (var location = enclosingDeclaration; location; location = location.parent) { - // 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 = callback(location.locals)) { - return result; - } - } - switch (location.kind) { - case 265 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - // falls through - case 233 /* ModuleDeclaration */: - if (result = callback(getSymbolOfNode(location).exports)) { - return result; - } - break; - } - } - return callback(globals); - } - function getQualifiedLeftMeaning(rightMeaning) { - // If we are looking in value space, the parent meaning is value, other wise it is namespace - return rightMeaning === 107455 /* Value */ ? 107455 /* Value */ : 1920 /* Namespace */; - } - function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing) { - function getAccessibleSymbolChainFromSymbolTable(symbols) { - return getAccessibleSymbolChainFromSymbolTableWorker(symbols, []); - } - function getAccessibleSymbolChainFromSymbolTableWorker(symbols, visitedSymbolTables) { - if (ts.contains(visitedSymbolTables, symbols)) { - return undefined; - } - visitedSymbolTables.push(symbols); - var result = trySymbolTable(symbols); - visitedSymbolTables.pop(); - return result; - function canQualifySymbol(symbolFromSymbolTable, meaning) { - // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible - if (!needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning)) { - return true; - } - // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too - var accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); - return !!accessibleParent; - } - function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { - if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) - // and if symbolFromSymbolTable or alias resolution matches the symbol, - // check the symbol can be qualified, it is only then this symbol is accessible - return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && - canQualifySymbol(symbolFromSymbolTable, meaning); - } - } - function trySymbolTable(symbols) { - // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.name))) { - return [symbol]; - } - // Check if symbol is any of the alias - return ts.forEachEntry(symbols, function (symbolFromSymbolTable) { - if (symbolFromSymbolTable.flags & 8388608 /* Alias */ - && symbolFromSymbolTable.name !== "export=" - && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) { - if (!useOnlyExternalAliasing || - // Is this external alias, then use it to name - ts.forEach(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration)) { - var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); - if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { - return [symbolFromSymbolTable]; - } - // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain - // but only if the symbolFromSymbolTable can be qualified - var accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTableWorker(resolvedImportedSymbol.exports, visitedSymbolTables) : undefined; - if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { - return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); - } - } - } - }); - } - } - if (symbol) { - if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - } - } - } - function needsQualification(symbol, enclosingDeclaration, meaning) { - var qualify = false; - forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { - // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.name); - if (!symbolFromSymbolTable) { - // Continue to the next symbol table - return false; - } - // If the symbol with this name is present it should refer to the symbol - if (symbolFromSymbolTable === symbol) { - // No need to qualify - return true; - } - // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 8388608 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 246 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; - if (symbolFromSymbolTable.flags & meaning) { - qualify = true; - return true; - } - // Continue to the next symbol table - return false; - }); - return qualify; - } - function isPropertyOrMethodDeclarationSymbol(symbol) { - if (symbol.declarations && symbol.declarations.length) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - continue; - default: - return false; - } - } - return true; - } - return false; - } - /** - * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested - * - * @param symbol a Symbol to check if accessible - * @param enclosingDeclaration a Node containing reference to the symbol - * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible - * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible - */ - function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); - } - // This could be a symbol that is not exported in the external module - // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); - if (symbolExternalModule) { - var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); - if (symbolExternalModule !== enclosingExternalModule) { - // name from different external module that is not visible - return { - accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbolToString(symbolExternalModule) - }; - } - } - // Just a local name that is not accessible - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - }; - } - return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } - } - function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); - } - function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { - var aliasesToMakeVisible; - if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { - return undefined; - } - return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; - function getIsDeclarationVisible(declaration) { - if (!isDeclarationVisible(declaration)) { - // Mark the unexported alias as visible if its parent is visible - // because these kind of aliases can be used to name types in declaration file - var anyImportSyntax = getAnyImportSyntax(declaration); - if (anyImportSyntax && - !(ts.getModifierFlags(anyImportSyntax) & 1 /* Export */) && - isDeclarationVisible(anyImportSyntax.parent)) { - // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, - // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time - // since we will do the emitting later in trackSymbol. - if (shouldComputeAliasToMakeVisible) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); - } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; - } - } - return true; - } - // Declaration is not visible - return false; - } - return true; - } - } - function isEntityNameVisible(entityName, enclosingDeclaration) { - // get symbol of the first identifier of the entityName - var meaning; - if (entityName.parent.kind === 162 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - // Typeof value - meaning = 107455 /* Value */ | 1048576 /* ExportValue */; - } - else if (entityName.kind === 143 /* QualifiedName */ || entityName.kind === 179 /* PropertyAccessExpression */ || - entityName.parent.kind === 237 /* ImportEqualsDeclaration */) { - // Left identifier from type reference or TypeAlias - // Entity name of the import declaration - meaning = 1920 /* Namespace */; - } - else { - // Type Reference or TypeAlias entity = Identifier - meaning = 793064 /* Type */; - } - var firstIdentifier = getFirstIdentifier(entityName); - var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); - // Verify if the symbol is accessible - return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { - accessibility: 1 /* NotAccessible */, - errorSymbolName: ts.getTextOfNode(firstIdentifier), - errorNode: firstIdentifier - }; - } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); - } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); - } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function typeToString(type, enclosingDeclaration, flags) { - 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) { - 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() { - return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { - 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) { - var context = createNodeBuilderContext(enclosingDeclaration, flags); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; - } - }; - function createNodeBuilderContext(enclosingDeclaration, flags) { - return { - enclosingDeclaration: enclosingDeclaration, - flags: flags, - encounteredError: false, - symbolStack: undefined - }; - } - function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; - if (!type) { - context.encounteredError = true; - return undefined; - } - if (type.flags & 1 /* Any */) { - return ts.createKeywordTypeNode(119 /* AnyKeyword */); - } - if (type.flags & 2 /* String */) { - return ts.createKeywordTypeNode(136 /* StringKeyword */); - } - if (type.flags & 4 /* Number */) { - return ts.createKeywordTypeNode(133 /* NumberKeyword */); - } - if (type.flags & 8 /* Boolean */) { - return ts.createKeywordTypeNode(122 /* BooleanKeyword */); - } - 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.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); - } - if (type.flags & (64 /* NumberLiteral */)) { - return ts.createLiteralTypeNode((ts.createLiteral(type.value))); - } - if (type.flags & 128 /* BooleanLiteral */) { - return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); - } - if (type.flags & 1024 /* Void */) { - return ts.createKeywordTypeNode(105 /* VoidKeyword */); - } - if (type.flags & 2048 /* Undefined */) { - return ts.createKeywordTypeNode(139 /* UndefinedKeyword */); - } - if (type.flags & 4096 /* Null */) { - return ts.createKeywordTypeNode(95 /* NullKeyword */); - } - if (type.flags & 8192 /* Never */) { - return ts.createKeywordTypeNode(130 /* NeverKeyword */); - } - if (type.flags & 512 /* ESSymbol */) { - return ts.createKeywordTypeNode(137 /* SymbolKeyword */); - } - if (type.flags & 16777216 /* NonPrimitive */) { - return ts.createKeywordTypeNode(134 /* ObjectKeyword */); - } - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { - context.encounteredError = true; - } - } - return ts.createThis(); - } - var objectFlags = getObjectFlags(type); - if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - return typeReferenceToTypeNode(type); - } - 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 (!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); - } - 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)) { - context.encounteredError = true; - } - return undefined; - } - } - if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - // The type is an object literal type. - return createAnonymousTypeNode(type); - } - if (type.flags & 262144 /* Index */) { - var indexedType = type.type; - var indexTypeNode = typeToTypeNodeHelper(indexedType, context); - return ts.createTypeOperatorNode(indexTypeNode); - } - if (type.flags & 524288 /* IndexedAccess */) { - var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); - var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); - return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); - } - ts.Debug.fail("Should be unreachable."); - function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 32768 /* Object */)); - var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; - var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - 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; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || - shouldWriteTypeOfFunctionSymbol()) { - 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, context, 793064 /* Type */, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); - } - else { - return ts.createKeywordTypeNode(119 /* AnyKeyword */); - } - } - 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 - if (!context.symbolStack) { - context.symbolStack = []; - } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; - } - } - else { - // Anonymous types without a symbol are never circular. - return createTypeNodeFromObjectType(type); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function createTypeNodeFromObjectType(type) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - return createMappedTypeNodeFromType(type); - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 160 /* FunctionType */, context); - return signatureNode; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 161 /* ConstructorType */, context); - return signatureNode; - } - } - var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; - var members = createTypeNodesFromResolvedType(resolved); - context.flags = savedFlags; - var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); - } - 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) { - 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 = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); - if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { - return ts.createTupleTypeNode(tupleConstituentNodes); - } - } - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { - context.encounteredError = true; - } - return undefined; - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - var qualifiedName = void 0; - if (outerTypeParameters) { - var length_1 = outerTypeParameters.length; - while (i < length_1) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - // 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 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 { - qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); - } - } - } - } - var entityName = undefined; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } - 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 */, context)); - } - for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 156 /* ConstructSignature */, context)); - } - if (resolvedType.stringIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context)); - } - if (resolvedType.numberIndexInfo) { - typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context)); - } - var properties = resolvedType.properties; - if (!properties) { - return typeElements; - } - for (var _d = 0, properties_2 = properties; _d < properties_2.length; _d++) { - var propertySymbol = properties_2[_d]; - var propertyType = getTypeOfSymbol(propertySymbol); - 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 */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - typeElements.push(methodDeclaration); - } - } - else { - 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 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 indexingParameter = ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, name, - /*questionToken*/ undefined, indexerTypeNode, - /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); - return ts.createIndexSignature( - /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : 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 /* 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, context); - } - 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, context) { - var name = symbolToName(type.symbol, context, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); - var defaultParameter = getDefaultFromTypeParameter(type); - var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); - } - 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); - 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, 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 || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { - chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); - ts.Debug.assert(chain && chain.length > 0); - } - else { - chain = [symbol]; - } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(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 typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - 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. */ - function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); - var parentSymbol; - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); - } - } - } - if (accessibleSymbolChain) { - return accessibleSymbolChain; - } - if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || - // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - return [symbol]; - } - } - } - 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; - } - } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - var writer = ts.getSingleLineStringWriter(); - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - var result = writer.string(); - ts.releaseStringWriter(writer); - return result; - } - function formatUnionTypes(types) { - var result = []; - var flags = 0; - for (var i = 0; i < types.length; i++) { - var t = types[i]; - flags |= t.flags; - if (!(t.flags & 6144 /* Nullable */)) { - if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - 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); - } - } - if (flags & 4096 /* Null */) - result.push(nullType); - if (flags & 2048 /* Undefined */) - result.push(undefinedType); - return result || types; - } - function visibilityToString(flags) { - if (flags === 8 /* Private */) { - return "private"; - } - if (flags === 16 /* Protected */) { - return "protected"; - } - return "public"; - } - function getTypeAliasForTypeLiteral(type) { - if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 168 /* ParenthesizedType */; }); - if (node.kind === 231 /* TypeAliasDeclaration */) { - return getSymbolOfNode(node); - } - } - return undefined; - } - function isTopLevelInExternalModuleAugmentation(node) { - return node && node.parent && - node.parent.kind === 234 /* ModuleBlock */ && - ts.isExternalModuleAugmentation(node.parent.parent); - } - function literalTypeToString(type) { - 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]; - 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); - } - switch (declaration.kind) { - case 199 /* ClassExpression */: - return "(Anonymous class)"; - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return "(Anonymous function)"; - } - } - return symbol.name; - } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbol(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = getNameOfSymbol(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - writePunctuation(writer, 21 /* OpenBracketToken */); - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); - } - } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if ( - // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. - endOfChain || - // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 128 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & 16 /* WriteOwnNameForAnyLike */; - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~512 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 16793231 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 16 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - 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 & (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); - } - else if (!(flags & 512 /* InTypeAlias */) && type.aliasSymbol && - isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 262144 /* Index */) { - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 64 /* InElementType */); - } - else if (type.flags & 524288 /* IndexedAccess */) { - writeType(type.objectType, 64 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 64 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.name)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 256 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 64 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - 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 - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - // 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)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 65536 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type, flags); - } - else if (ts.contains(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 - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - 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 - if (!symbolStack) { - symbolStack = []; - } - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return ts.getModifierFlags(declaration) & 32 /* Static */; })); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || - ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 265 /* SourceFile */ || declaration.parent.kind === 234 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 2 /* UseTypeOfFunction */) || - (ts.contains(symbolStack, symbol)); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(type, typeFormatFlags) { - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 67108864 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 64 /* InElementType */) { - return true; - } - else if (flags & 256 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (type.objectFlags & 32 /* Mapped */) { - if (getConstraintTypeFromMappedType(type).flags & (16384 /* TypeParameter */ | 262144 /* Index */)) { - writeMappedType(type); - return; - } - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 8 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 64 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - buildIndexSignatureDisplay(resolved.stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getNullableType(type, 2048 /* Undefined */); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 174 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 175 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 176 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 256 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 2048 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 8 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - if (signature.typePredicate) { - buildTypePredicateDisplay(signature.typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 32 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } - function isDeclarationVisible(node) { - if (node) { - var links = getNodeLinks(node); - if (links.isVisible === undefined) { - links.isVisible = !!determineIfDeclarationIsVisible(); - } - return links.isVisible; - } - return false; - function determineIfDeclarationIsVisible() { - switch (node.kind) { - case 176 /* BindingElement */: - return isDeclarationVisible(node.parent.parent); - case 226 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name) && - !node.name.elements.length) { - // If the binding pattern is empty, this variable declaration is not visible - return false; - } - // falls through - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 228 /* FunctionDeclaration */: - case 232 /* EnumDeclaration */: - case 237 /* ImportEqualsDeclaration */: - // external module augmentation is always visible - if (ts.isExternalModuleAugmentation(node)) { - return true; - } - var parent = getDeclarationContainer(node); - // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 237 /* ImportEqualsDeclaration */ && parent.kind !== 265 /* SourceFile */ && ts.isInAmbientContext(parent))) { - return isGlobalSourceFile(parent); - } - // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - if (ts.getModifierFlags(node) & (8 /* Private */ | 16 /* Protected */)) { - // Private/protected properties/methods are not visible - return false; - } - // Public properties/methods are visible if its parents are visible, so: - // falls through - case 152 /* Constructor */: - case 156 /* ConstructSignature */: - case 155 /* CallSignature */: - case 157 /* IndexSignature */: - case 146 /* Parameter */: - case 234 /* ModuleBlock */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 159 /* TypeReference */: - case 164 /* ArrayType */: - case 165 /* TupleType */: - case 166 /* UnionType */: - case 167 /* IntersectionType */: - case 168 /* ParenthesizedType */: - return isDeclarationVisible(node.parent); - // Default binding, import specifier and namespace import is visible - // only on demand so by default it is not visible - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - return false; - // Type parameters are always visible - case 145 /* TypeParameter */: - // Source file and namespace export are always visible - case 265 /* SourceFile */: - case 236 /* NamespaceExportDeclaration */: - return true; - // Export assignments do not create name bindings outside the module - case 243 /* ExportAssignment */: - return false; - default: - return false; - } - } - } - function collectLinkedAliases(node) { - var exportSymbol; - if (node.parent && node.parent.kind === 243 /* ExportAssignment */) { - 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 */) { - exportSymbol = getTargetOfExportSpecifier(node.parent, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); - } - var result = []; - if (exportSymbol) { - buildVisibleNodeList(exportSymbol.declarations); - } - return result; - function buildVisibleNodeList(declarations) { - ts.forEach(declarations, function (declaration) { - getNodeLinks(declaration).isVisible = true; - var resultNode = getAnyImportSyntax(declaration) || declaration; - if (!ts.contains(result, resultNode)) { - result.push(resultNode); - } - if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { - // Add the referenced top container visible - var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); - var importSymbol = resolveName(declaration, firstIdentifier.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */, undefined, undefined); - if (importSymbol) { - buildVisibleNodeList(importSymbol.declarations); - } - } - }); - } - } - /** - * Push an entry on the type resolution stack. If an entry with the given target and the given property name - * is already on the stack, and no entries in between already have a type, then a circularity has occurred. - * In this case, the result values of the existing entry and all entries pushed after it are changed to false, - * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. - * In order to see if the same query has already been done before, the target object and the propertyName both - * must match the one passed in. - * - * @param target The symbol, type, or signature whose type is being queried - * @param propertyName The property name that should be used to query the target for its type - */ - function pushTypeResolution(target, propertyName) { - var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); - if (resolutionCycleStartIndex >= 0) { - // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { - resolutionResults[i] = false; - } - return false; - } - resolutionTargets.push(target); - resolutionResults.push(/*items*/ true); - resolutionPropertyNames.push(propertyName); - return true; - } - function findResolutionCycleStartIndex(target, propertyName) { - for (var i = resolutionTargets.length - 1; i >= 0; i--) { - if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { - return -1; - } - if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { - return i; - } - } - return -1; - } - function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return getSymbolLinks(target).type; - } - if (propertyName === 2 /* DeclaredType */) { - return getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return target.resolvedReturnType; - } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); - } - // Pop an entry from the type resolution stack and return its associated result value. The result value will - // be true if no circularities were detected, or false if a circularity was found. - function popTypeResolution() { - resolutionTargets.pop(); - resolutionPropertyNames.pop(); - return resolutionResults.pop(); - } - function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { - switch (node.kind) { - case 226 /* VariableDeclaration */: - case 227 /* VariableDeclarationList */: - case 242 /* ImportSpecifier */: - case 241 /* NamedImports */: - case 240 /* NamespaceImport */: - case 239 /* ImportClause */: - return false; - default: - return true; - } - }); - return node && node.parent; - } - function getTypeOfPrototypeProperty(prototype) { - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', - // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. - // It is an error to explicitly declare a static property member with the name 'prototype'. - var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype)); - return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType; - } - // Return the type of the given property in the given type, or undefined if no such property exists - function getTypeOfPropertyOfType(type, name) { - var prop = getPropertyOfType(type, name); - return prop ? getTypeOfSymbol(prop) : undefined; - } - function isTypeAny(type) { - return type && (type.flags & 1 /* Any */) !== 0; - } - // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been - // assigned by contextual typing. - function getTypeForBindingElementParent(node) { - var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); - } - function isComputedNonLiteralName(name) { - return name.kind === 144 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); - } - function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (source.flags & 8192 /* Never */) { - return emptyObjectType; - } - if (source.flags & 65536 /* Union */) { - return mapType(source, function (t) { return getRestType(t, properties, symbol); }); - } - var members = ts.createMap(); - var names = ts.createMap(); - for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { - var name = properties_3[_i]; - names.set(ts.getTextOfPropertyName(name), true); - } - for (var _a = 0, _b = getPropertiesOfType(source); _a < _b.length; _a++) { - var prop = _b[_a]; - var inNamesToRemove = names.has(prop.name); - 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); - } - } - var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); - var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); - return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - /** Return the inferred type for a binding element */ - function getTypeForBindingElement(declaration) { - var pattern = declaration.parent; - var parentType = getTypeForBindingElementParent(pattern.parent); - // If parent has the unknown (error) type, then so does this binding element - if (parentType === unknownType) { - return unknownType; - } - // If no type was specified or inferred for parent, or if the specified or inferred type is any, - // infer from the initializer of the binding element if one is present. Otherwise, go with the - // undefined or any type of the parent. - if (!parentType || isTypeAny(parentType)) { - if (declaration.initializer) { - return checkDeclarationInitializer(declaration); - } - return parentType; - } - var type; - if (pattern.kind === 174 /* ObjectBindingPattern */) { - if (declaration.dotDotDotToken) { - if (!isValidSpreadType(parentType)) { - error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); - return unknownType; - } - var literalMembers = []; - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!element.dotDotDotToken) { - literalMembers.push(element.propertyName || element.name); - } - } - type = getRestType(parentType, literalMembers, declaration.symbol); - } - else { - // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - // computed properties with non-literal names are treated as 'any' - return anyType; - } - if (declaration.initializer) { - getContextualType(declaration.initializer); - } - // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, - // or otherwise the type of the string index signature. - var text = ts.getTextOfPropertyName(name); - type = getTypeOfPropertyOfType(parentType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || - getIndexTypeOfType(parentType, 0 /* String */); - if (!type) { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return unknownType; - } - } - } - else { - // This elementType will be used if the specific property corresponding to this index is not - // present (aka the tuple element property). This call also checks that the parentType is in - // fact an iterable or array (depending on target language). - var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterable*/ false); - if (declaration.dotDotDotToken) { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); - } - else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); - } - return unknownType; - } - } - } - // In strict null checking mode, if a default value of a non-undefined type is specified, remove - // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 2048 /* Undefined */)) { - type = getTypeWithFacts(type, 131072 /* NEUndefined */); - } - return declaration.initializer ? - getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : - type; - } - function getTypeForDeclarationFromJSDocComment(declaration) { - var jsdocType = ts.getJSDocType(declaration); - if (jsdocType) { - return getTypeFromTypeNode(jsdocType); - } - return undefined; - } - function isNullOrUndefined(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 95 /* NullKeyword */ || expr.kind === 71 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; - } - function isEmptyArrayLiteral(node) { - var expr = ts.skipParentheses(node); - return expr.kind === 177 /* ArrayLiteralExpression */ && expr.elements.length === 0; - } - function addOptionality(type, optional) { - return strictNullChecks && optional ? getNullableType(type, 2048 /* Undefined */) : type; - } - // Return the inferred type for a variable, parameter, or property declaration - function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { - if (declaration.flags & 65536 /* JavaScriptFile */) { - // If this is a variable in a JavaScript file, then use the JSDoc type (if it has - // one as its type), otherwise fallback to the below standard TS codepaths to - // try to figure it out. - var type = getTypeForDeclarationFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - // A variable declared in a for..in statement is of type string, or of type keyof T when the - // right hand expression is of a type parameter type. - if (declaration.parent.parent.kind === 215 /* ForInStatement */) { - var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (16384 /* TypeParameter */ | 262144 /* Index */) ? indexType : stringType; - } - if (declaration.parent.parent.kind === 216 /* ForOfStatement */) { - // checkRightHandSideOfForOf will return undefined if the for-of expression type was - // missing properties/signatures required to get its iteratedType (like - // [Symbol.iterator] or next). This may be because we accessed properties from anyType, - // or it may have led to an error inside getElementTypeOfIterable. - var forOfStatement = declaration.parent.parent; - return checkRightHandSideOfForOf(forOfStatement.expression, forOfStatement.awaitModifier) || anyType; - } - if (ts.isBindingPattern(declaration.parent)) { - return getTypeForBindingElement(declaration); - } - // Use type from type annotation if one is present - if (declaration.type) { - var declaredType = getTypeFromTypeNode(declaration.type); - return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); - } - if ((noImplicitAny || declaration.flags & 65536 /* JavaScriptFile */) && - declaration.kind === 226 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !ts.isInAmbientContext(declaration)) { - // If --noImplicitAny is on or the declaration is in a Javascript file, - // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no - // initializer or a 'null' or 'undefined' initializer. - if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { - return autoType; - } - // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array - // literal initializer. - if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { - return autoArrayType; - } - } - if (declaration.kind === 146 /* Parameter */) { - var func = declaration.parent; - // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 154 /* SetAccessor */ && !ts.hasDynamicName(func)) { - var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 153 /* GetAccessor */); - if (getter) { - var getterSignature = getSignatureFromDeclaration(getter); - var thisParameter = getAccessorThisParameter(func); - if (thisParameter && declaration === thisParameter) { - // Use the type from the *getter* - ts.Debug.assert(!thisParameter.type); - return getTypeOfSymbol(getterSignature.thisParameter); - } - return getReturnTypeOfSignature(getterSignature); - } - } - // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.name === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } - if (type) { - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); - } - } - // Use the type of the initializer expression if one is present - if (declaration.initializer) { - var type = checkDeclarationInitializer(declaration); - return addOptionality(type, /*optional*/ declaration.questionToken && includeOptionality); - } - if (ts.isJsxAttribute(declaration)) { - // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true. - // I.e is sugar for - return trueType; - } - // If it is a short-hand property assignment, use the type of the identifier - if (declaration.kind === 262 /* ShorthandPropertyAssignment */) { - return checkIdentifier(declaration.name); - } - // If the declaration specifies a binding pattern, use the type implied by the binding pattern - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true); - } - // No type specified and nothing can be inferred - return undefined; - } - function getWidenedTypeFromJSSpecialPropertyDeclarations(symbol) { - 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 : - declaration.kind === 179 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 194 /* BinaryExpression */) : - undefined; - if (!expression) { - return unknownType; - } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 152 /* Constructor */) { - definedInConstructor = true; - } - else { - definedInMethod = true; - } - } - // 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)); - } - } - else if (!jsDocType) { - // If we don't have an explicit JSDoc type, get the type from the expression. - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); - } - } - 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 - // pattern. Otherwise, it is the type any. - function getTypeFromBindingElement(element, includePatternInType, reportErrors) { - if (element.initializer) { - return checkDeclarationInitializer(element); - } - if (ts.isBindingPattern(element.name)) { - return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); - } - if (reportErrors && noImplicitAny && !declarationBelongsToPrivateAmbientMember(element)) { - reportImplicitAnyError(element, anyType); - } - return anyType; - } - // Return the type implied by an object binding pattern - function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { - var members = ts.createMap(); - var stringIndexInfo; - var hasComputedProperties = false; - ts.forEach(pattern.elements, function (e) { - var name = e.propertyName || e.name; - if (isComputedNonLiteralName(name)) { - // do not include computed properties in the implied type - hasComputedProperties = true; - return; - } - if (e.dotDotDotToken) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); - return; - } - var text = ts.getTextOfPropertyName(name); - var flags = 4 /* Property */ | (e.initializer ? 67108864 /* Optional */ : 0); - var symbol = createSymbol(flags, text); - symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); - symbol.bindingElement = e; - members.set(symbol.name, symbol); - }); - var result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); - if (includePatternInType) { - result.pattern = pattern; - } - if (hasComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } - return result; - } - // Return the type implied by an array binding pattern - function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { - var elements = pattern.elements; - var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; - } - // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); - if (includePatternInType) { - result = cloneTypeReference(result); - result.pattern = pattern; - } - return result; - } - // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself - // and without regard to its context (i.e. without regard any type annotation or initializer associated with the - // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any] - // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is - // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring - // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of - // the parameter. - function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 174 /* ObjectBindingPattern */ - ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) - : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); - } - // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type - // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it - // is a bit more involved. For example: - // - // var [x, s = ""] = [1, "one"]; - // - // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the - // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the - // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. - function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); - if (type) { - if (reportErrors) { - reportErrorsFromWidening(declaration, type); - } - // During a normal type check we'll never get to here with a property assignment (the check of the containing - // object literal uses a different path). We exclude widening only so that language services and type verification - // tools see the actual type. - if (declaration.kind === 261 /* PropertyAssignment */) { - return type; - } - return getWidenedType(type); - } - // Rest parameters default to type any[], other parameters default to type any - type = declaration.dotDotDotToken ? anyArrayType : anyType; - // Report implicit any errors unless this is a private property within an ambient declaration - if (reportErrors && noImplicitAny) { - if (!declarationBelongsToPrivateAmbientMember(declaration)) { - reportImplicitAnyError(declaration, type); - } - } - return type; - } - function declarationBelongsToPrivateAmbientMember(declaration) { - var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 146 /* Parameter */ ? root.parent : root; - return isPrivateWithinAmbient(memberDeclaration); - } - function getTypeOfVariableOrParameterOrProperty(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - // Handle prototype property - if (symbol.flags & 16777216 /* Prototype */) { - return links.type = getTypeOfPrototypeProperty(symbol); - } - // Handle catch clause variables - var declaration = symbol.valueDeclaration; - if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { - return links.type = anyType; - } - // Handle export default expressions - if (declaration.kind === 243 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); - } - if (declaration.flags & 65536 /* JavaScriptFile */ && declaration.kind === 291 /* JSDocPropertyTag */ && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); - } - // Handle variable, parameter or property - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; - } - var type = void 0; - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - if (declaration.kind === 194 /* BinaryExpression */ || - declaration.kind === 179 /* PropertyAccessExpression */ && declaration.parent.kind === 194 /* BinaryExpression */) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); - } - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - return links.type; - } - function getAnnotatedAccessorType(accessor) { - if (accessor) { - if (accessor.kind === 153 /* GetAccessor */) { - return accessor.type && getTypeFromTypeNode(accessor.type); - } - else { - var setterTypeAnnotation = ts.getSetAccessorTypeAnnotationNode(accessor); - return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); - } - } - return undefined; - } - function getAnnotatedAccessorThisParameter(accessor) { - var parameter = getAccessorThisParameter(accessor); - return parameter && parameter.symbol; - } - function getThisTypeOfDeclaration(declaration) { - return getThisTypeOfSignature(getSignatureFromDeclaration(declaration)); - } - function getTypeOfAccessors(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 154 /* SetAccessor */); - if (getter && getter.flags & 65536 /* JavaScriptFile */) { - var jsDocType = getTypeForDeclarationFromJSDocComment(getter); - if (jsDocType) { - return links.type = jsDocType; - } - } - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; - } - var type = void 0; - // First try to see if the user specified a return type on the get-accessor. - var getterReturnType = getAnnotatedAccessorType(getter); - if (getterReturnType) { - type = getterReturnType; - } - else { - // If the user didn't specify a return type, try to use the set-accessor's parameter type. - var setterParameterType = getAnnotatedAccessorType(setter); - if (setterParameterType) { - type = setterParameterType; - } - else { - // If there are no specified types, try to infer it from the body of the get accessor if it exists. - if (getter && getter.body) { - type = getReturnTypeFromBody(getter); - } - else { - if (noImplicitAny) { - if (setter) { - error(setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol)); - } - else { - ts.Debug.assert(!!getter, "there must existed getter as we are current checking either setter or getter in this function"); - error(getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); - } - } - type = anyType; - } - } - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 153 /* GetAccessor */); - error(getter_1, 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, symbolToString(symbol)); - } - } - links.type = type; - } - return links.type; - } - function getBaseTypeVariableOfClass(symbol) { - var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 540672 /* TypeVariable */ ? baseConstructorType : undefined; - } - function getTypeOfFuncClassEnumModule(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { - links.type = anyType; - } - else { - var type = createObjectType(16 /* Anonymous */, symbol); - if (symbol.flags & 32 /* Class */) { - var baseTypeVariable = getBaseTypeVariableOfClass(symbol); - links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; - } - else { - links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? getNullableType(type, 2048 /* Undefined */) : type; - } - } - } - return links.type; - } - function getTypeOfEnumMember(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - links.type = getDeclaredTypeOfEnumMember(symbol); - } - return links.type; - } - function getTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - var targetSymbol = resolveAlias(symbol); - // It only makes sense to get the type of a value symbol. If the result of resolving - // the alias is not a value, then it has no type. To get the type associated with a - // type symbol, call getDeclaredTypeOfSymbol. - // This check is important because without it, a call to getTypeOfSymbol could end - // up recursively calling getTypeOfAlias, causing a stack overflow. - links.type = targetSymbol.flags & 107455 /* Value */ - ? getTypeOfSymbol(targetSymbol) - : unknownType; - } - return links.type; - } - function getTypeOfInstantiatedSymbol(symbol) { - var links = getSymbolLinks(symbol); - if (!links.type) { - if (symbolInstantiationDepth === 100) { - error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = unknownType; - } - else { - if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; - } - symbolInstantiationDepth++; - var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); - symbolInstantiationDepth--; - if (!popTypeResolution()) { - type = reportCircularityError(symbol); - } - links.type = type; - } - } - return links.type; - } - function reportCircularityError(symbol) { - // Check if variable has type annotation that circularly references the variable itself - if (symbol.valueDeclaration.type) { - error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - return unknownType; - } - // Otherwise variable has initializer that circularly references the variable itself - if (noImplicitAny) { - error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); - } - return anyType; - } - function getTypeOfSymbol(symbol) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - return getTypeOfInstantiatedSymbol(symbol); - } - if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { - return getTypeOfVariableOrParameterOrProperty(symbol); - } - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); - } - if (symbol.flags & 8 /* EnumMember */) { - return getTypeOfEnumMember(symbol); - } - if (symbol.flags & 98304 /* Accessor */) { - return getTypeOfAccessors(symbol); - } - if (symbol.flags & 8388608 /* Alias */) { - return getTypeOfAlias(symbol); - } - return unknownType; - } - function isReferenceToType(type, target) { - return type !== undefined - && target !== undefined - && (getObjectFlags(type) & 4 /* Reference */) !== 0 - && type.target === target; - } - function getTargetType(type) { - return getObjectFlags(type) & 4 /* Reference */ ? type.target : type; - } - function hasBaseType(type, checkBase) { - return check(type); - function check(type) { - if (getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { - var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); - } - else if (type.flags & 131072 /* Intersection */) { - return ts.forEach(type.types, check); - } - } - } - // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. - // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set - // in-place and returns the same array. - function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { - var declaration = declarations_3[_i]; - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - if (!typeParameters) { - typeParameters = [tp]; - } - else if (!ts.contains(typeParameters, tp)) { - typeParameters.push(tp); - } - } - return typeParameters; - } - // Appends the outer type parameters of a node to a set of type parameters and returns the resulting set. The function - // allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set in-place and - // returns the same array. - function appendOuterTypeParameters(typeParameters, node) { - while (true) { - node = node.parent; - if (!node) { - return typeParameters; - } - if (node.kind === 229 /* ClassDeclaration */ || node.kind === 199 /* ClassExpression */ || - node.kind === 228 /* FunctionDeclaration */ || node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */ || node.kind === 187 /* ArrowFunction */) { - var declarations = node.typeParameters; - if (declarations) { - return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); - } - } - } - } - // The outer type parameters are those defined by enclosing generic classes, methods, or functions. - function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); - return appendOuterTypeParameters(/*typeParameters*/ undefined, declaration); - } - // The local type parameters are the combined set of type parameters from all declarations of the class, - // interface, or type alias. - function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { - var result; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var node = _a[_i]; - if (node.kind === 230 /* InterfaceDeclaration */ || node.kind === 229 /* ClassDeclaration */ || - node.kind === 199 /* ClassExpression */ || node.kind === 231 /* TypeAliasDeclaration */) { - var declaration = node; - if (declaration.typeParameters) { - result = appendTypeParameters(result, declaration.typeParameters); - } - } - } - return result; - } - // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus - // its locally declared type parameters. - function getTypeParametersOfClassOrInterface(symbol) { - return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol)); - } - // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single - // rest parameter of type any[]. - function isMixinConstructorType(type) { - var signatures = getSignaturesOfType(type, 1 /* Construct */); - if (signatures.length === 1) { - var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getTypeOfParameter(s.parameters[0]) === anyArrayType; - } - return false; - } - function isConstructorType(type) { - if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { - return true; - } - if (type.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); - } - return false; - } - function getBaseTypeNodeOfClass(type) { - return ts.getClassExtendsHeritageClauseElement(type.symbol.valueDeclaration); - } - function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var typeArgCount = ts.length(typeArgumentNodes); - var isJavaScript = ts.isInJavaScriptFile(location); - return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavaScript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); }); - } - function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { - var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; - } - /** - * The base constructor of a class can resolve to - * * undefinedType if the class has no extends clause, - * * unknownType if an error occurred during resolution of the extends expression, - * * nullType if the extends expression is the null value, - * * anyType if the extends expression has type any, or - * * an object type with at least one construct signature. - */ - function getBaseConstructorTypeOfClass(type) { - if (!type.resolvedBaseConstructorType) { - var baseTypeNode = getBaseTypeNodeOfClass(type); - if (!baseTypeNode) { - return type.resolvedBaseConstructorType = undefinedType; - } - if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { - return unknownType; - } - var baseConstructorType = checkExpression(baseTypeNode.expression); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */)) { - // Resolving the members of a class requires us to resolve the base class of that class. - // We force resolution here such that we catch circularities now. - resolveStructuredTypeMembers(baseConstructorType); - } - if (!popTypeResolution()) { - error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = unknownType; - } - if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { - error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); - return type.resolvedBaseConstructorType = unknownType; - } - type.resolvedBaseConstructorType = baseConstructorType; - } - return type.resolvedBaseConstructorType; - } - function getBaseTypes(type) { - if (!type.resolvedBaseTypes) { - if (type.objectFlags & 8 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; - } - else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - if (type.symbol.flags & 32 /* Class */) { - resolveBaseTypesOfClass(type); - } - if (type.symbol.flags & 64 /* Interface */) { - resolveBaseTypesOfInterface(type); - } - } - else { - ts.Debug.fail("type must be class or interface"); - } - } - return type.resolvedBaseTypes; - } - function resolveBaseTypesOfClass(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 1 /* Any */))) { - 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 */ && - areAllOuterTypeParametersApplied(originalBaseType)) { - // When base constructor type is a class with no captured type arguments we know that the constructors all have the same type parameters as the - // 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, typeArgs); - } - else if (baseConstructorType.flags & 1 /* Any */) { - baseType = baseConstructorType; - } - else { - // The class derives from a "class-like" constructor function, check that we have at least one construct signature - // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere - // we check that all instantiated signatures return the same type. - var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode); - if (!constructors.length) { - error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); - return; - } - baseType = getReturnTypeOfSignature(constructors[0]); - } - // In a JS file, you can use the @augments jsdoc tag to specify a base type with type parameters - var valueDecl = type.symbol.valueDeclaration; - if (valueDecl && ts.isInJavaScriptFile(valueDecl)) { - var augTag = ts.getJSDocAugmentsTag(type.symbol.valueDeclaration); - if (augTag) { - baseType = getTypeFromTypeNode(augTag.typeExpression.type); - } - } - if (baseType === unknownType) { - return; - } - if (!isValidBaseType(baseType)) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructor_return_type_0_is_not_a_class_or_interface_type, typeToString(baseType)); - return; - } - if (type === baseType || hasBaseType(baseType, type)) { - error(valueDecl, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); - return; - } - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - function areAllOuterTypeParametersApplied(type) { - // An unapplied type parameter has its symbol still the same as the matching argument symbol. - // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked. - var outerTypeParameters = type.outerTypeParameters; - if (outerTypeParameters) { - var last = outerTypeParameters.length - 1; - var typeArguments = type.typeArguments; - return outerTypeParameters[last].symbol !== typeArguments[last].symbol; - } - return true; - } - // A valid base type is `any`, any non-generic object type or intersection of non-generic - // object types. - function isValidBaseType(type) { - return type.flags & (32768 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 131072 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); - } - function resolveBaseTypesOfInterface(type) { - type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { - for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { - var node = _c[_b]; - var baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { - if (isValidBaseType(baseType)) { - if (type !== baseType && !hasBaseType(baseType, type)) { - if (type.resolvedBaseTypes === emptyArray) { - type.resolvedBaseTypes = [baseType]; - } - else { - type.resolvedBaseTypes.push(baseType); - } - } - else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); - } - } - else { - error(node, ts.Diagnostics.An_interface_may_only_extend_a_class_or_another_interface); - } - } - } - } - } - } - // Returns true if the interface given by the symbol is free of "this" references. Specifically, the result is - // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, - // and if none of the base interfaces have a "this" type. - function isIndependentInterface(symbol) { - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (declaration.kind === 230 /* InterfaceDeclaration */) { - if (declaration.flags & 64 /* ContainsThis */) { - return false; - } - var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); - if (baseTypeNodes) { - for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { - var node = baseTypeNodes_1[_b]; - if (ts.isEntityNameExpression(node.expression)) { - var baseSymbol = resolveEntityName(node.expression, 793064 /* Type */, /*ignoreErrors*/ true); - if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { - return false; - } - } - } - } - } - } - return true; - } - function getDeclaredTypeOfClassOrInterface(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */; - var type = links.declaredType = createObjectType(kind, symbol); - var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); - var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type - // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, - // property types inferred from initializers and method return types inferred from return statements are very hard - // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of - // "this" references. - if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isIndependentInterface(symbol)) { - type.objectFlags |= 4 /* Reference */; - type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters); - type.outerTypeParameters = outerTypeParameters; - type.localTypeParameters = localTypeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); - type.thisType.isThisType = true; - type.thisType.symbol = symbol; - type.thisType.constraint = type; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - // Note that we use the links object as the target here because the symbol object is used as the unique - // identity for resolution of the 'type' property in SymbolLinks. - if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { - return unknownType; - } - var declaration = ts.getDeclarationOfKind(symbol, 290 /* JSDocTypedefTag */); - var type = void 0; - if (declaration) { - if (declaration.jsDocTypeLiteral) { - type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); - } - else { - type = getTypeFromTypeNode(declaration.typeExpression.type); - } - } - else { - declaration = ts.getDeclarationOfKind(symbol, 231 /* TypeAliasDeclaration */); - type = getTypeFromTypeNode(declaration.type); - } - if (popTypeResolution()) { - var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (typeParameters) { - // Initialize the instantiation cache for generic type aliases. The declared type corresponds to - // an instantiation of the type alias with the type parameters supplied as type arguments. - links.typeParameters = typeParameters; - links.instantiations = ts.createMap(); - links.instantiations.set(getTypeListId(typeParameters), type); - } - } - else { - type = unknownType; - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); - } - links.declaredType = type; - } - return links.declaredType; - } - function isLiteralEnumMember(member) { - var expr = member.initializer; - if (!expr) { - return !ts.isInAmbientContext(member); - } - 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 */ && (ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.text)); - } - 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 (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { - return links.enumKind = 1 /* Literal */; - } - if (!isLiteralEnumMember(member)) { - hasNonLiteralMember = true; - } - } - } - } - return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; - } - 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) { - 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); - } - } - } - 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; - } - } - 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)); - if (!links.declaredType) { - links.declaredType = enumType; - } - } - return links.declaredType; - } - function getDeclaredTypeOfTypeParameter(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(16384 /* TypeParameter */); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; - } - function getDeclaredTypeOfAlias(symbol) { - var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; - } - function getDeclaredTypeOfSymbol(symbol) { - if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - return getDeclaredTypeOfClassOrInterface(symbol); - } - if (symbol.flags & 524288 /* TypeAlias */) { - return getDeclaredTypeOfTypeAlias(symbol); - } - if (symbol.flags & 262144 /* TypeParameter */) { - return getDeclaredTypeOfTypeParameter(symbol); - } - if (symbol.flags & 384 /* Enum */) { - return getDeclaredTypeOfEnum(symbol); - } - if (symbol.flags & 8 /* EnumMember */) { - return getDeclaredTypeOfEnumMember(symbol); - } - if (symbol.flags & 8388608 /* Alias */) { - return getDeclaredTypeOfAlias(symbol); - } - return unknownType; - } - // A type reference is considered independent if each type argument is considered independent. - function isIndependentTypeReference(node) { - if (node.typeArguments) { - for (var _i = 0, _a = node.typeArguments; _i < _a.length; _i++) { - var typeNode = _a[_i]; - if (!isIndependentType(typeNode)) { - return false; - } - } - } - return true; - } - // A type is considered independent if it the any, string, number, boolean, symbol, or void keyword, a string - // literal type, an array with an element type that is considered independent, or a type reference that is - // considered independent. - function isIndependentType(node) { - switch (node.kind) { - case 119 /* AnyKeyword */: - case 136 /* StringKeyword */: - case 133 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 137 /* SymbolKeyword */: - case 134 /* ObjectKeyword */: - case 105 /* VoidKeyword */: - case 139 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 130 /* NeverKeyword */: - case 173 /* LiteralType */: - return true; - case 164 /* ArrayType */: - return isIndependentType(node.elementType); - case 159 /* TypeReference */: - return isIndependentTypeReference(node); - } - return false; - } - // A variable-like declaration is considered independent (free of this references) if it has a type annotation - // that specifies an independent type, or if it has no type annotation and no initializer (and thus of type any). - function isIndependentVariableLikeDeclaration(node) { - return node.type && isIndependentType(node.type) || !node.type && !node.initializer; - } - // A function-like declaration is considered independent (free of this references) if it has a return type - // annotation that is considered independent and if each parameter is considered independent. - function isIndependentFunctionLikeDeclaration(node) { - if (node.kind !== 152 /* Constructor */ && (!node.type || !isIndependentType(node.type))) { - return false; - } - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (!isIndependentVariableLikeDeclaration(parameter)) { - return false; - } - } - return true; - } - // Returns true if the class or interface member given by the symbol is free of "this" references. The - // function may return false for symbols that are actually free of "this" references because it is not - // feasible to perform a complete analysis in all cases. In particular, property members with types - // inferred from their initializers and function members with inferred return types are conservatively - // assumed not to be free of "this" references. - function isIndependentMember(symbol) { - if (symbol.declarations && symbol.declarations.length === 1) { - var declaration = symbol.declarations[0]; - if (declaration) { - switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return isIndependentVariableLikeDeclaration(declaration); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - return isIndependentFunctionLikeDeclaration(declaration); - } - } - } - return false; - } - function createSymbolTable(symbols) { - var result = ts.createMap(); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - result.set(symbol.name, symbol); - } - return result; - } - // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, - // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. - function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { - var result = ts.createMap(); - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var symbol = symbols_2[_i]; - result.set(symbol.name, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); - } - return result; - } - function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { - var s = baseSymbols_1[_i]; - if (!symbols.has(s.name)) { - symbols.set(s.name, s); - } - } - } - function resolveDeclaredMembers(type) { - if (!type.declaredProperties) { - var symbol = type.symbol; - type.declaredProperties = getNamedMembers(symbol.members); - type.declaredCallSignatures = getSignaturesOfSymbol(symbol.members.get("__call")); - type.declaredConstructSignatures = getSignaturesOfSymbol(symbol.members.get("__new")); - type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); - type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); - } - return type; - } - function getTypeWithThisArgument(type, thisArgument) { - if (getObjectFlags(type) & 4 /* Reference */) { - var target = type.target; - var typeArguments = type.typeArguments; - if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); - } - } - else if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); - } - return type; - } - function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { - var mapper; - var members; - var callSignatures; - var constructSignatures; - var stringIndexInfo; - var numberIndexInfo; - if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) { - mapper = identityMapper; - members = source.symbol ? source.symbol.members : createSymbolTable(source.declaredProperties); - callSignatures = source.declaredCallSignatures; - constructSignatures = source.declaredConstructSignatures; - stringIndexInfo = source.declaredStringIndexInfo; - numberIndexInfo = source.declaredNumberIndexInfo; - } - else { - mapper = createTypeMapper(typeParameters, typeArguments); - members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1); - callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper); - constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper); - stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper); - numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper); - } - var baseTypes = getBaseTypes(source); - if (baseTypes.length) { - if (source.symbol && members === source.symbol.members) { - members = createSymbolTable(source.declaredProperties); - } - var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { - var baseType = baseTypes_1[_i]; - var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; - addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); - constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); - if (!stringIndexInfo) { - stringIndexInfo = instantiatedBaseType === anyType ? - createIndexInfo(anyType, /*isReadonly*/ false) : - getIndexInfoOfType(instantiatedBaseType, 0 /* String */); - } - numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */); - } - } - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function resolveClassOrInterfaceMembers(type) { - resolveObjectTypeMembers(type, resolveDeclaredMembers(type), emptyArray, emptyArray); - } - function resolveTypeReferenceMembers(type) { - var source = resolveDeclaredMembers(type.target); - var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]); - var typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? - type.typeArguments : ts.concatenate(type.typeArguments, [type]); - resolveObjectTypeMembers(type, source, typeParameters, typeArguments); - } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, typePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); - sig.declaration = declaration; - sig.typeParameters = typeParameters; - sig.parameters = parameters; - sig.thisParameter = thisParameter; - sig.resolvedReturnType = resolvedReturnType; - sig.typePredicate = typePredicate; - sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; - return sig; - } - function cloneSignature(sig) { - return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, sig.resolvedReturnType, sig.typePredicate, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); - } - function getDefaultConstructSignatures(classType) { - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); - if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*typePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; - } - var baseTypeNode = getBaseTypeNodeOfClass(classType); - var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); - var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); - var typeArgCount = ts.length(typeArguments); - var result = []; - for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { - var baseSig = baseSignatures_1[_i]; - var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters); - var typeParamCount = ts.length(baseSig.typeParameters); - if ((isJavaScript || typeArgCount >= minTypeArgumentCount) && typeArgCount <= typeParamCount) { - var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, baseTypeNode)) : cloneSignature(baseSig); - sig.typeParameters = classType.localTypeParameters; - sig.resolvedReturnType = classType; - result.push(sig); - } - } - return result; - } - function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) { - for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { - var s = signatureList_1[_i]; - if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypesIdentical)) { - return s; - } - } - } - function findMatchingSignatures(signatureLists, signature, listIndex) { - if (signature.typeParameters) { - // We require an exact match for generic signatures, so we only return signatures from the first - // signature list and only if they have exact matches in the other signature lists. - if (listIndex > 0) { - return undefined; - } - for (var i = 1; i < signatureLists.length; i++) { - if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) { - return undefined; - } - } - return [signature]; - } - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - // Allow matching non-generic signatures to have excess parameters and different return types - var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true); - if (!match) { - return undefined; - } - if (!ts.contains(result, match)) { - (result || (result = [])).push(match); - } - } - return result; - } - // The signatures of a union type are those signatures that are present in each of the constituent types. - // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional - // parameters and may differ in return types. When signatures differ in return types, the resulting return - // type is the union of the constituent return types. - function getUnionSignatures(types, kind) { - var signatureLists = ts.map(types, function (t) { return getSignaturesOfType(t, kind); }); - var result = undefined; - for (var i = 0; i < signatureLists.length; i++) { - for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { - var signature = _a[_i]; - // Only process signatures with parameter lists that aren't already in the result list - if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true)) { - var unionSignatures = findMatchingSignatures(signatureLists, signature, i); - if (unionSignatures) { - var s = signature; - // Union the result types when more than one signature matches - if (unionSignatures.length > 1) { - s = cloneSignature(signature); - if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { - var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); - s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); - } - // Clear resolved return type we possibly got from cloneSignature - s.resolvedReturnType = undefined; - s.unionSignatures = unionSignatures; - } - (result || (result = [])).push(s); - } - } - } - } - return result || emptyArray; - } - function getUnionIndexInfo(types, kind) { - var indexTypes = []; - var isAnyReadonly = false; - 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; - } - indexTypes.push(indexInfo.type); - isAnyReadonly = isAnyReadonly || indexInfo.isReadonly; - } - return createIndexInfo(getUnionType(indexTypes, /*subtypeReduction*/ true), isAnyReadonly); - } - function resolveUnionTypeMembers(type) { - // The members and properties collections are empty for union types. To get all properties of a union - // type use getPropertiesOfType (only the language service uses this). - var callSignatures = getUnionSignatures(type.types, 0 /* Call */); - var constructSignatures = getUnionSignatures(type.types, 1 /* Construct */); - var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); - var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - function intersectTypes(type1, type2) { - return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]); - } - function intersectIndexInfos(info1, info2) { - return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly); - } - function unionSpreadIndexInfos(info1, info2) { - return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly); - } - function includeMixinType(type, types, index) { - var mixedTypes = []; - for (var i = 0; i < types.length; i++) { - if (i === index) { - mixedTypes.push(type); - } - else if (isMixinConstructorType(types[i])) { - mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0])); - } - } - return getIntersectionType(mixedTypes); - } - function resolveIntersectionTypeMembers(type) { - // The members and properties collections are empty for intersection types. To get all properties of an - // intersection type use getPropertiesOfType (only the language service uses this). - var callSignatures = emptyArray; - var constructSignatures = emptyArray; - var stringIndexInfo; - var numberIndexInfo; - var types = type.types; - var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_3 = function (i) { - var t = type.types[i]; - // When an intersection type contains mixin constructor types, the construct signatures from - // those types are discarded and their return types are mixed into the return types of all - // other construct signatures in the intersection type. For example, the intersection type - // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature - // 'new(s: string) => A & B'. - if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { - var signatures = getSignaturesOfType(t, 1 /* Construct */); - if (signatures.length && mixinCount > 0) { - signatures = ts.map(signatures, function (s) { - var clone = cloneSignature(s); - clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, i); - return clone; - }); - } - constructSignatures = ts.concatenate(constructSignatures, signatures); - } - callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(t, 0 /* Call */)); - stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */)); - numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); - }; - for (var i = 0; i < types.length; i++) { - _loop_3(i); - } - setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - /** - * Converts an AnonymousType to a ResolvedType. - */ - function resolveAnonymousTypeMembers(type) { - var symbol = type.symbol; - if (type.target) { - var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); - var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); - var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); - var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper); - var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else if (symbol.flags & 2048 /* TypeLiteral */) { - var members = symbol.members; - var callSignatures = getSignaturesOfSymbol(members.get("__call")); - var constructSignatures = getSignaturesOfSymbol(members.get("__new")); - var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); - var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */); - setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); - } - else { - // Combinations of function, class, enum and module - var members = emptySymbols; - var constructSignatures = emptyArray; - var stringIndexInfo = undefined; - if (symbol.exports) { - members = getExportsOfSymbol(symbol); - } - if (symbol.flags & 32 /* Class */) { - var classType = getDeclaredTypeOfClassOrInterface(symbol); - constructSignatures = getSignaturesOfSymbol(symbol.members.get("__constructor")); - if (!constructSignatures.length) { - constructSignatures = getDefaultConstructSignatures(classType); - } - var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (32768 /* Object */ | 131072 /* Intersection */ | 540672 /* TypeVariable */)) { - members = createSymbolTable(getNamedMembers(members)); - addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); - } - else if (baseConstructorType === anyType) { - stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); - } - } - var numberIndexInfo = symbol.flags & 384 /* Enum */ ? enumNumberIndexInfo : undefined; - setStructuredTypeMembers(type, members, emptyArray, constructSignatures, stringIndexInfo, numberIndexInfo); - // We resolve the members before computing the signatures because a signature may use - // typeof with a qualified name expression that circularly references the type we are - // in the process of resolving (see issue #6072). The temporarily empty signature list - // will never be observed because a qualified name can't reference signatures. - if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) { - type.callSignatures = getSignaturesOfSymbol(symbol); - } - } - } - /** Resolve the members of a mapped type { [P in K]: T } */ - function resolveMappedTypeMembers(type) { - var members = ts.createMap(); - var stringIndexInfo; - // Resolve upfront such that recursive references see an empty object type. - setStructuredTypeMembers(type, emptySymbols, emptyArray, emptyArray, undefined, undefined); - // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, - // and T as the template type. - var typeParameter = getTypeParameterFromMappedType(type); - var constraintType = getConstraintTypeFromMappedType(type); - var templateType = getTemplateTypeFromMappedType(type); - var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' - var templateReadonly = !!type.declaration.readonlyToken; - var templateOptional = !!type.declaration.questionToken; - if (type.declaration.typeParameter.constraint.kind === 170 /* TypeOperator */) { - // We have a { [P in keyof T]: X } - for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { - var propertySymbol = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); - } - if (getIndexInfoOfType(modifiersType, 0 /* String */)) { - addMemberForKeyType(stringType); - } - } - else { - // First, if the constraint type is a type parameter, obtain the base constraint. Then, - // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 540672 /* TypeVariable */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 262144 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; - forEachType(iterationType, addMemberForKeyType); - } - setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbol) { - // Create a mapper from T to the current iteration type constituent. Then, if the - // mapped type is itself an instantiated type, combine the iteration mapper with the - // instantiation mapper. - var iterationMapper = createTypeMapper([typeParameter], [t]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, iterationMapper) : iterationMapper; - var propType = instantiateType(templateType, templateMapper); - // 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.value; - var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); - var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); - prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 8 /* Readonly */ : 0; - prop.type = propType; - if (propertySymbol) { - prop.syntheticOrigin = propertySymbol; - } - members.set(propName, prop); - } - else if (t.flags & 2 /* String */) { - stringIndexInfo = createIndexInfo(propType, templateReadonly); - } - } - } - function getTypeParameterFromMappedType(type) { - return type.typeParameter || - (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter))); - } - function getConstraintTypeFromMappedType(type) { - return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); - } - function getTemplateTypeFromMappedType(type) { - return type.templateType || - (type.templateType = type.declaration.type ? - instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!type.declaration.questionToken), type.mapper || identityMapper) : - unknownType); - } - function getModifiersTypeFromMappedType(type) { - if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 170 /* TypeOperator */) { - // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check - // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves - // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); - } - else { - // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, - // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T', - // the modifiers type is T. Otherwise, the modifiers type is {}. - var declaredType = getTypeFromMappedTypeNode(type.declaration); - var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 16384 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 262144 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; - } - } - return type.modifiersType; - } - function isGenericMappedType(type) { - if (getObjectFlags(type) & 32 /* Mapped */) { - var constraintType = getConstraintTypeFromMappedType(type); - return maybeTypeOfKind(constraintType, 540672 /* TypeVariable */ | 262144 /* Index */); - } - return false; - } - function resolveStructuredTypeMembers(type) { - if (!type.members) { - if (type.flags & 32768 /* Object */) { - if (type.objectFlags & 4 /* Reference */) { - resolveTypeReferenceMembers(type); - } - else if (type.objectFlags & 3 /* ClassOrInterface */) { - resolveClassOrInterfaceMembers(type); - } - else if (type.objectFlags & 16 /* Anonymous */) { - resolveAnonymousTypeMembers(type); - } - else if (type.objectFlags & 32 /* Mapped */) { - resolveMappedTypeMembers(type); - } - } - else if (type.flags & 65536 /* Union */) { - resolveUnionTypeMembers(type); - } - else if (type.flags & 131072 /* Intersection */) { - resolveIntersectionTypeMembers(type); - } - } - return type; - } - /** Return properties of an object type or an empty array for other types */ - function getPropertiesOfObjectType(type) { - if (type.flags & 32768 /* Object */) { - return resolveStructuredTypeMembers(type).properties; - } - return emptyArray; - } - /** If the given type is an object type and that type has a property by the given name, - * return the symbol for that property. Otherwise return undefined. - */ - function getPropertyOfObjectType(type, name) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - } - } - function getPropertiesOfUnionOrIntersectionType(type) { - if (!type.resolvedProperties) { - var members = ts.createMap(); - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var current = _a[_i]; - for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { - var prop = _c[_b]; - if (!members.has(prop.name)) { - var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.name); - if (combinedProp) { - members.set(prop.name, combinedProp); - } - } - } - // The properties of a union type are those that are present in all constituent types, so - // we only need to check the properties of the first type - if (type.flags & 65536 /* Union */) { - break; - } - } - type.resolvedProperties = getNamedMembers(members); - } - return type.resolvedProperties; - } - function getPropertiesOfType(type) { - type = getApparentType(type); - return type.flags & 196608 /* UnionOrIntersection */ ? - 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) : - getBaseConstraintOfType(type); - } - function getConstraintOfTypeParameter(typeParameter) { - return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; - } - function getConstraintOfIndexedAccess(type) { - var baseObjectType = getBaseConstraintOfType(type.objectType); - var baseIndexType = getBaseConstraintOfType(type.indexType); - return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; - } - function getBaseConstraintOfType(type) { - if (type.flags & (540672 /* TypeVariable */ | 196608 /* UnionOrIntersection */)) { - var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; - } - } - else if (type.flags & 262144 /* Index */) { - return stringType; - } - return undefined; - } - function hasNonCircularBaseConstraint(type) { - return getResolvedBaseConstraint(type) !== circularConstraintType; - } - /** - * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the - * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint - * circularly references the type variable. - */ - function getResolvedBaseConstraint(type) { - var typeStack; - var circular; - if (!type.resolvedBaseConstraint) { - typeStack = []; - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); - } - return type.resolvedBaseConstraint; - function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { - circular = true; - return undefined; - } - typeStack.push(t); - var result = computeBaseConstraint(t); - typeStack.pop(); - return result; - } - function computeBaseConstraint(t) { - if (t.flags & 16384 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; - } - if (t.flags & 196608 /* UnionOrIntersection */) { - var types = t.types; - var baseTypes = []; - 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); - } - } - return t.flags & 65536 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 131072 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : - undefined; - } - if (t.flags & 262144 /* Index */) { - return stringType; - } - if (t.flags & 524288 /* IndexedAccess */) { - var baseObjectType = getBaseConstraint(t.objectType); - var baseIndexType = getBaseConstraint(t.indexType); - var baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; - return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; - } - return t; - } - } - function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); - } - /** - * Gets the default type for a type parameter. - * - * If the type parameter is the result of an instantiation, this gets the instantiated - * default type of its target. If the type parameter has no default type, `undefined` - * is returned. - * - * This function *does not* perform a circularity check. - */ - function getDefaultFromTypeParameter(typeParameter) { - if (!typeParameter.default) { - if (typeParameter.target) { - var targetDefault = getDefaultFromTypeParameter(typeParameter.target); - typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType; - } - else { - var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameter(decl) && decl.default; }); - typeParameter.default = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType; - } - } - return typeParameter.default === noConstraintType ? undefined : typeParameter.default; - } - /** - * For a type parameter, return the base constraint of the type parameter. For the string, number, - * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the - * type itself. Note that the apparent type of a union type is the union type itself. - */ - function getApparentType(type) { - var t = type.flags & 540672 /* TypeVariable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 131072 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 262178 /* StringLike */ ? globalStringType : - t.flags & 84 /* NumberLike */ ? globalNumberType : - t.flags & 136 /* BooleanLike */ ? globalBooleanType : - t.flags & 512 /* ESSymbol */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : - t; - } - function createUnionOrIntersectionProperty(containingType, name) { - var props; - var types = containingType.types; - var isUnion = containingType.flags & 65536 /* Union */; - var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; - // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; - var syntheticFlag = 4 /* SyntheticMethod */; - var checkFlags = 0; - 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 ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; - if (prop && !(modifiers & excludeModifiers)) { - commonFlags &= prop.flags; - if (!props) { - props = [prop]; - } - else if (!ts.contains(props, prop)) { - props.push(prop); - } - checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | - (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | - (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | - (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | - (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); - if (!isMethodLike(prop)) { - syntheticFlag = 2 /* SyntheticProperty */; - } - } - else if (isUnion) { - checkFlags |= 16 /* Partial */; - } - } - } - if (!props) { - return undefined; - } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { - return props[0]; - } - var propTypes = []; - var declarations = []; - var commonType = undefined; - for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { - var prop = props_1[_a]; - if (prop.declarations) { - ts.addRange(declarations, prop.declarations); - } - var type = getTypeOfSymbol(prop); - if (!commonType) { - commonType = type; - } - else if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; - } - propTypes.push(type); - } - var result = createSymbol(4 /* Property */ | commonFlags, name); - result.checkFlags = syntheticFlag | checkFlags; - result.containingType = containingType; - result.declarations = declarations; - result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); - return result; - } - // Return the symbol for a given property in a union or intersection type, or undefined if the property - // does not exist in any constituent type. Note that the returned property may only be present in some - // constituents, in which case the isPartial flag is set when the containing type is union type. We need - // these partial properties when identifying discriminant properties, but otherwise they are filtered out - // and do not appear to be present in the union type. - function getUnionOrIntersectionProperty(type, name) { - var properties = type.propertyCache || (type.propertyCache = ts.createMap()); - var property = properties.get(name); - if (!property) { - property = createUnionOrIntersectionProperty(type, name); - if (property) { - properties.set(name, property); - } - } - return property; - } - function getPropertyOfUnionOrIntersectionType(type, name) { - var property = getUnionOrIntersectionProperty(type, name); - // We need to filter out partial properties in union types - 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 - * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from - * Object and Function as appropriate. - * - * @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, name) { - type = getApparentType(type); - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - var symbol = resolved.members.get(name); - if (symbol && symbolIsValue(symbol)) { - return symbol; - } - if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - var symbol_1 = getPropertyOfObjectType(globalFunctionType, name); - if (symbol_1) { - return symbol_1; - } - } - return getPropertyOfObjectType(globalObjectType, name); - } - if (type.flags & 196608 /* UnionOrIntersection */) { - return getPropertyOfUnionOrIntersectionType(type, name); - } - return undefined; - } - function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; - } - return emptyArray; - } - /** - * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and - * maps primitive types and type parameters are to their apparent types. - */ - function getSignaturesOfType(type, kind) { - return getSignaturesOfStructuredType(getApparentType(type), kind); - } - function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 229376 /* StructuredType */) { - var resolved = resolveStructuredTypeMembers(type); - return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; - } - } - function getIndexTypeOfStructuredType(type, kind) { - var info = getIndexInfoOfStructuredType(type, kind); - return info && info.type; - } - // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and - // maps primitive types and type parameters are to their apparent types. - function getIndexInfoOfType(type, kind) { - return getIndexInfoOfStructuredType(getApparentType(type), kind); - } - // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and - // maps primitive types and type parameters are to their apparent types. - function getIndexTypeOfType(type, kind) { - return getIndexTypeOfStructuredType(getApparentType(type), kind); - } - function getImplicitIndexTypeOfType(type, kind) { - if (isObjectLiteralType(type)) { - var propTypes = []; - for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { - propTypes.push(getTypeOfSymbol(prop)); - } - } - if (propTypes.length) { - return getUnionType(propTypes, /*subtypeReduction*/ true); - } - } - return undefined; - } - function getTypeParametersFromJSDocTemplate(declaration) { - if (declaration.flags & 65536 /* JavaScriptFile */) { - var templateTag = ts.getJSDocTemplateTag(declaration); - if (templateTag) { - return getTypeParametersFromDeclaration(templateTag.typeParameters); - } - } - return undefined; - } - // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual - // type checking functions). - function getTypeParametersFromDeclaration(typeParameterDeclarations) { - var result = []; - ts.forEach(typeParameterDeclarations, function (node) { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); - if (!ts.contains(result, tp)) { - result.push(tp); - } - }); - return result; - } - function symbolsToArray(symbols) { - var result = []; - symbols.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - result.push(symbol); - } - }); - return result; - } - function isJSDocOptionalParameter(node) { - if (node.flags & 65536 /* JavaScriptFile */) { - if (node.type && node.type.kind === 278 /* JSDocOptionalType */) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 278 /* JSDocOptionalType */; - } - } - } - } - } - function tryFindAmbientModule(moduleName, withAugmentations) { - if (ts.isExternalModuleNameRelative(moduleName)) { - return undefined; - } - var symbol = getSymbol(globals, "\"" + moduleName + "\"", 512 /* ValueModule */); - // merged symbol is module declaration symbol combined with all augmentations - return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; - } - function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { - return true; - } - if (node.initializer) { - var signatureDeclaration = node.parent; - var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); - ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; - } - var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); - if (iife) { - return !node.type && - !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; - } - return false; - } - function createTypePredicateFromTypePredicateNode(node) { - if (node.parameterName.kind === 71 /* Identifier */) { - var parameterName = node.parameterName; - return { - kind: 1 /* Identifier */, - parameterName: parameterName ? parameterName.text : undefined, - parameterIndex: parameterName ? getTypePredicateParameterIndex(node.parent.parameters, parameterName) : undefined, - type: getTypeFromTypeNode(node.type) - }; - } - else { - return { - kind: 0 /* This */, - type: getTypeFromTypeNode(node.type) - }; - } - } - /** - * Gets the minimum number of type arguments needed to satisfy all non-optional type - * parameters. - */ - function getMinTypeArgumentCount(typeParameters) { - var minTypeArgumentCount = 0; - if (typeParameters) { - for (var i = 0; i < typeParameters.length; i++) { - if (!getDefaultFromTypeParameter(typeParameters[i])) { - minTypeArgumentCount = i + 1; - } - } - } - return minTypeArgumentCount; - } - /** - * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined - * when a default type is supplied, a new array will be created and returned. - * - * @param typeArguments The supplied type arguments. - * @param typeParameters The requested type parameters. - * @param minTypeArgumentCount The minimum number of required type arguments. - */ - function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, location) { - var numTypeParameters = ts.length(typeParameters); - if (numTypeParameters) { - var numTypeArguments = ts.length(typeArguments); - var isJavaScript = ts.isInJavaScriptFile(location); - if ((isJavaScript || numTypeArguments >= minTypeArgumentCount) && numTypeArguments <= numTypeParameters) { - if (!typeArguments) { - typeArguments = []; - } - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - for (var i = numTypeArguments; i < numTypeParameters; i++) { - typeArguments[i] = isJavaScript ? anyType : emptyObjectType; - } - for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, typeArguments); - var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : isJavaScript ? anyType : emptyObjectType; - } - } - } - return typeArguments; - } - function getSignatureFromDeclaration(declaration) { - var links = getNodeLinks(declaration); - if (!links.resolvedSignature) { - var parameters = []; - var hasLiteralTypes = false; - var minArgumentCount = 0; - var thisParameter = undefined; - var hasThisParameter = void 0; - var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); - var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); - // If this is a JSDoc construct signature, then skip the first parameter in the - // parameter list. The first parameter represents the return type of the construct - // signature. - for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { - var param = declaration.parameters[i]; - var paramSymbol = param.symbol; - // Include parameter symbol instead of property symbol in the signature - if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { - var resolvedSymbol = resolveName(param, paramSymbol.name, 107455 /* Value */, undefined, undefined); - paramSymbol = resolvedSymbol; - } - if (i === 0 && paramSymbol.name === "this") { - hasThisParameter = true; - thisParameter = param.symbol; - } - else { - parameters.push(paramSymbol); - } - if (param.type && param.type.kind === 173 /* LiteralType */) { - hasLiteralTypes = true; - } - // Record a new minimum argument count if this is not an optional parameter - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; - if (!isOptionalParameter_1) { - minArgumentCount = parameters.length; - } - } - // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 153 /* GetAccessor */ || declaration.kind === 154 /* SetAccessor */) && - !ts.hasDynamicName(declaration) && - (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var other = ts.getDeclarationOfKind(declaration.symbol, otherKind); - if (other) { - thisParameter = getAnnotatedAccessorThisParameter(other); - } - } - var classType = declaration.kind === 152 /* Constructor */ ? - getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) - : undefined; - var typeParameters = classType ? classType.localTypeParameters : - declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : - getTypeParametersFromJSDocTemplate(declaration); - var returnType = getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType); - var typePredicate = declaration.type && declaration.type.kind === 158 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : - undefined; - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, ts.hasRestParameter(declaration), hasLiteralTypes); - } - return links.resolvedSignature; - } - function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { - if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); - } - else if (classType) { - return classType; - } - else if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.flags & 65536 /* JavaScriptFile */) { - var type = getReturnTypeFromJSDocComment(declaration); - if (type && type !== unknownType) { - return type; - } - } - // 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 === 153 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(declaration.symbol, 154 /* SetAccessor */); - return getAnnotatedAccessorType(setter); - } - if (ts.nodeIsMissing(declaration.body)) { - return anyType; - } - } - function containsArgumentsReference(declaration) { - var links = getNodeLinks(declaration); - if (links.containsArgumentsReference === undefined) { - if (links.flags & 8192 /* CaptureArguments */) { - links.containsArgumentsReference = true; - } - else { - links.containsArgumentsReference = traverse(declaration.body); - } - } - return links.containsArgumentsReference; - function traverse(node) { - if (!node) - return false; - switch (node.kind) { - case 71 /* Identifier */: - return node.text === "arguments" && ts.isPartOfExpression(node); - case 149 /* PropertyDeclaration */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return node.name.kind === 144 /* ComputedPropertyName */ - && traverse(node.name); - default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); - } - } - } - function getSignaturesOfSymbol(symbol) { - if (!symbol) - return emptyArray; - var result = []; - for (var i = 0; i < symbol.declarations.length; i++) { - var node = symbol.declarations[i]; - switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 279 /* JSDocFunctionType */: - // Don't include signature if node is the implementation of an overloaded function. A node is considered - // an implementation node if it has a body and the previous node is of the same kind and immediately - // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); - } - } - return result; - } - function resolveExternalModuleTypeByLiteral(name) { - var moduleSym = resolveExternalModuleName(name, name); - if (moduleSym) { - var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym); - if (resolvedModuleSymbol) { - return getTypeOfSymbol(resolvedModuleSymbol); - } - } - return anyType; - } - function getThisTypeOfSignature(signature) { - if (signature.thisParameter) { - return getTypeOfSymbol(signature.thisParameter); - } - } - function getReturnTypeOfSignature(signature) { - if (!signature.resolvedReturnType) { - if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { - return unknownType; - } - var type = void 0; - if (signature.target) { - type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); - } - else if (signature.unionSignatures) { - type = getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); - } - else { - type = getReturnTypeFromBody(signature.declaration); - } - if (!popTypeResolution()) { - type = anyType; - if (noImplicitAny) { - var declaration = signature.declaration; - 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); - } - } - } - signature.resolvedReturnType = type; - } - return signature.resolvedReturnType; - } - function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; - } - function getSignatureInstantiation(signature, typeArguments) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters)); - var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); - var id = getTypeListId(typeArguments); - var instantiation = instantiations.get(id); - if (!instantiation) { - instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments)); - } - return instantiation; - } - function createSignatureInstantiation(signature, typeArguments) { - return instantiateSignature(signature, createTypeMapper(signature.typeParameters, typeArguments), /*eraseTypeParameters*/ true); - } - function getErasedSignature(signature) { - if (!signature.typeParameters) - return signature; - if (!signature.erasedSignatureCache) { - signature.erasedSignatureCache = instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true); - } - return signature.erasedSignatureCache; - } - function getOrCreateTypeFromSignature(signature) { - // There are two ways to declare a construct signature, one is by declaring a class constructor - // using the constructor keyword, and the other is declaring a bare construct signature in an - // object type literal or interface (using the new keyword). Each way of declaring a constructor - // will result in a different declaration kind. - if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 152 /* Constructor */ || signature.declaration.kind === 156 /* ConstructSignature */; - var type = createObjectType(16 /* Anonymous */); - type.members = emptySymbols; - type.properties = emptyArray; - type.callSignatures = !isConstructor ? [signature] : emptyArray; - type.constructSignatures = isConstructor ? [signature] : emptyArray; - signature.isolatedSignatureType = type; - } - return signature.isolatedSignatureType; - } - function getIndexSymbol(symbol) { - return symbol.members.get("__index"); - } - function getIndexDeclarationOfSymbol(symbol, kind) { - var syntaxKind = kind === 1 /* Number */ ? 133 /* NumberKeyword */ : 136 /* StringKeyword */; - var indexSymbol = getIndexSymbol(symbol); - if (indexSymbol) { - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var node = decl; - if (node.parameters.length === 1) { - var parameter = node.parameters[0]; - if (parameter && parameter.type && parameter.type.kind === syntaxKind) { - return node; - } - } - } - } - return undefined; - } - function createIndexInfo(type, isReadonly, declaration) { - return { type: type, isReadonly: isReadonly, declaration: declaration }; - } - function getIndexInfoOfSymbol(symbol, kind) { - var declaration = getIndexDeclarationOfSymbol(symbol, kind); - if (declaration) { - return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, (ts.getModifierFlags(declaration) & 64 /* Readonly */) !== 0, declaration); - } - return undefined; - } - function getConstraintDeclaration(type) { - return ts.getDeclarationOfKind(type.symbol, 145 /* TypeParameter */).constraint; - } - function getConstraintFromTypeParameter(typeParameter) { - if (!typeParameter.constraint) { - if (typeParameter.target) { - var targetConstraint = getConstraintOfTypeParameter(typeParameter.target); - typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType; - } - else { - var constraintDeclaration = getConstraintDeclaration(typeParameter); - typeParameter.constraint = constraintDeclaration ? getTypeFromTypeNode(constraintDeclaration) : noConstraintType; - } - } - return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; - } - function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 145 /* TypeParameter */).parent); - } - function getTypeListId(types) { - var result = ""; - if (types) { - var length_4 = types.length; - var i = 0; - while (i < length_4) { - var startId = types[i].id; - var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { - count++; - } - if (result.length) { - result += ","; - } - result += startId; - if (count > 1) { - result += ":" + count; - } - i += count; - } - } - return result; - } - // This function is used to propagate certain flags when creating new object type references and union types. - // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type - // of an object literal or the anyFunctionType. This is because there are operations in the type checker - // 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_4 = types; _i < types_4.length; _i++) { - var type = types_4[_i]; - if (!(type.flags & excludeKinds)) { - result |= type.flags; - } - } - return result & 14680064 /* PropagatingFlags */; - } - function createTypeReference(target, typeArguments) { - var id = getTypeListId(typeArguments); - var type = target.instantiations.get(id); - if (!type) { - type = createObjectType(4 /* Reference */, target.symbol); - target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; - type.target = target; - type.typeArguments = typeArguments; - } - return type; - } - function cloneTypeReference(source) { - var type = createType(source.flags); - type.symbol = source.symbol; - type.objectFlags = source.objectFlags; - type.target = source.target; - type.typeArguments = source.typeArguments; - return type; - } - function getTypeReferenceArity(type) { - return ts.length(type.target.typeParameters); - } - // Get type from reference to class or interface - function getTypeFromClassOrInterfaceReference(node, symbol, typeArgs) { - var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol)); - var typeParameters = type.localTypeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (!ts.isInJavaScriptFile(node) && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */), minTypeArgumentCount, typeParameters.length); - return unknownType; - } - // 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(typeArgs, typeParameters, minTypeArgumentCount, node)); - return createTypeReference(type, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, typeToString(type)); - return unknownType; - } - return type; - } - function getTypeAliasInstantiation(symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var links = getSymbolLinks(symbol); - var typeParameters = links.typeParameters; - var id = getTypeListId(typeArguments); - var instantiation = links.instantiations.get(id); - if (!instantiation) { - links.instantiations.set(id, instantiation = instantiateTypeNoAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters))))); - } - 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, symbol, typeArguments) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeParameters = getSymbolLinks(symbol).typeParameters; - if (typeParameters) { - var numTypeArguments = ts.length(node.typeArguments); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) { - error(node, minTypeArgumentCount === typeParameters.length - ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s - : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); - return unknownType; - } - return getTypeAliasInstantiation(symbol, typeArguments); - } - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return type; - } - // Get type from reference to named type that cannot be generic (enum or type parameter) - function getTypeFromNonGenericTypeReference(node, symbol) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbolToString(symbol)); - return unknownType; - } - return getDeclaredTypeOfSymbol(symbol); - } - function getTypeReferenceName(node) { - switch (node.kind) { - case 159 /* TypeReference */: - return node.typeName; - case 277 /* JSDocTypeReference */: - return node.name; - case 201 /* ExpressionWithTypeArguments */: - // We only support expressions that are simple qualified names. For other - // expressions this produces undefined. - var expr = node.expression; - if (ts.isEntityNameExpression(expr)) { - return expr; - } - } - return undefined; - } - function resolveTypeReferenceName(typeReferenceName) { - if (!typeReferenceName) { - return unknownSymbol; - } - 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, typeArguments); - } - if (symbol.flags & 524288 /* TypeAlias */) { - 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 - // that case, the type of this reference is just the type of the value we resolved - // to. - return getTypeOfSymbol(symbol); - } - return getTypeFromNonGenericTypeReference(node, symbol); - } - function getPrimitiveTypeFromJSDocTypeReference(node) { - if (ts.isIdentifier(node.name)) { - switch (node.name.text) { - case "String": - return stringType; - case "Number": - return numberType; - case "Boolean": - return booleanType; - case "Void": - return voidType; - case "Undefined": - return undefinedType; - case "Null": - return nullType; - case "Object": - return anyType; - case "Function": - return anyFunctionType; - case "Array": - case "array": - return !node.typeArguments || !node.typeArguments.length ? createArrayType(anyType) : undefined; - case "Promise": - case "promise": - return !node.typeArguments || !node.typeArguments.length ? createPromiseType(anyType) : undefined; - } - } - } - function getTypeFromJSDocNullableTypeNode(node) { - var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getUnionType([type, nullType]) : type; - } - function getTypeFromTypeReference(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var symbol = void 0; - var type = void 0; - if (node.kind === 277 /* JSDocTypeReference */) { - type = getPrimitiveTypeFromJSDocTypeReference(node); - if (!type) { - var typeReferenceName = getTypeReferenceName(node); - symbol = resolveTypeReferenceName(typeReferenceName); - type = getTypeReferenceType(node, symbol); - } - } - else { - // We only support expressions that are simple qualified names. For other expressions this produces undefined. - var typeNameOrExpression = node.kind === 159 /* TypeReference */ - ? node.typeName - : ts.isEntityNameExpression(node.expression) - ? node.expression - : undefined; - symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, 793064 /* Type */) || unknownSymbol; - 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. - 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) { - // TypeScript 1.0 spec (April 2014): 3.6.3 - // The expression is processed as an identifier expression (section 4.3) - // or property access expression(section 4.10), - // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); - } - return links.resolvedType; - } - function getTypeOfGlobalSymbol(symbol, arity) { - function getTypeDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; - switch (declaration.kind) { - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 232 /* EnumDeclaration */: - return declaration; - } - } - } - if (!symbol) { - return arity ? emptyGenericType : emptyObjectType; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 32768 /* Object */)) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); - return arity ? emptyGenericType : emptyObjectType; - } - if (ts.length(type.typeParameters) !== arity) { - error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, symbol.name, arity); - return arity ? emptyGenericType : emptyObjectType; - } - return type; - } - function getGlobalValueSymbol(name, reportErrors) { - return getGlobalSymbol(name, 107455 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined); - } - function getGlobalTypeSymbol(name, reportErrors) { - return getGlobalSymbol(name, 793064 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined); - } - function getGlobalSymbol(name, meaning, diagnostic) { - return resolveName(undefined, name, meaning, diagnostic, name); - } - function getGlobalType(name, arity, reportErrors) { - var symbol = getGlobalTypeSymbol(name, reportErrors); - return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined; - } - function getGlobalTypedPropertyDescriptorType() { - return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType; - } - function getGlobalTemplateStringsArrayType() { - return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; - } - function getGlobalESSymbolConstructorSymbol(reportErrors) { - return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); - } - function getGlobalESSymbolType(reportErrors) { - return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType; - } - function getGlobalPromiseType(reportErrors) { - return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalPromiseConstructorSymbol(reportErrors) { - return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors)); - } - function getGlobalPromiseConstructorLikeType(reportErrors) { - return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType; - } - function getGlobalAsyncIterableType(reportErrors) { - return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIteratorType(reportErrors) { - return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalAsyncIterableIteratorType(reportErrors) { - return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableType(reportErrors) { - return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalIteratorType(reportErrors) { - return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalIterableIteratorType(reportErrors) { - return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType; - } - function getGlobalTypeOrUndefined(name, arity) { - if (arity === void 0) { arity = 0; } - var symbol = getGlobalSymbol(name, 793064 /* Type */, /*diagnostic*/ undefined); - return symbol && getTypeOfGlobalSymbol(symbol, arity); - } - /** - * Returns a type that is inside a namespace at the global scope, e.g. - * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type - */ - function getExportedTypeFromNamespace(namespace, name) { - var namespaceSymbol = getGlobalSymbol(namespace, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); - var typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, 793064 /* Type */); - return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); - } - /** - * Instantiates a global type that is generic with some element type, and returns that instantiation. - */ - function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) { - return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType; - } - function createTypedPropertyDescriptorType(propertyType) { - return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]); - } - function createAsyncIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableType(/*reportErrors*/ true), [iteratedType]); - } - function createAsyncIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalAsyncIterableIteratorType(/*reportErrors*/ true), [iteratedType]); - } - function createIterableType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]); - } - function createIterableIteratorType(iteratedType) { - return createTypeFromGenericGlobalType(getGlobalIterableIteratorType(/*reportErrors*/ true), [iteratedType]); - } - function createArrayType(elementType) { - return createTypeFromGenericGlobalType(globalArrayType, [elementType]); - } - function getTypeFromArrayTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); - } - return links.resolvedType; - } - // We represent tuple types as type references to synthesized generic interface types created by - // this function. The types are of the form: - // - // interface Tuple extends Array { 0: T0, 1: T1, 2: T2, ... } - // - // Note that the generic type created by this function has no symbol associated with it. The same - // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity) { - var typeParameters = []; - var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(16384 /* TypeParameter */); - typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */, "" + i); - property.type = typeParameter; - properties.push(property); - } - var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); - type.typeParameters = typeParameters; - type.outerTypeParameters = undefined; - type.localTypeParameters = typeParameters; - type.instantiations = ts.createMap(); - type.instantiations.set(getTypeListId(type.typeParameters), type); - type.target = type; - type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */); - type.thisType.isThisType = true; - type.thisType.constraint = type; - type.declaredProperties = properties; - type.declaredCallSignatures = emptyArray; - type.declaredConstructSignatures = emptyArray; - type.declaredStringIndexInfo = undefined; - type.declaredNumberIndexInfo = undefined; - return type; - } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); - } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); - } - function getTypeFromTupleTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); - } - return links.resolvedType; - } - function binarySearchTypes(types, type) { - var low = 0; - var high = types.length - 1; - var typeId = type.id; - while (low <= high) { - var middle = low + ((high - low) >> 1); - var id = types[middle].id; - if (id === typeId) { - return middle; - } - else if (id > typeId) { - high = middle - 1; - } - else { - low = middle + 1; - } - } - return ~low; - } - function containsType(types, type) { - return binarySearchTypes(types, type) >= 0; - } - function addTypeToUnion(typeSet, type) { - var flags = type.flags; - if (flags & 65536 /* Union */) { - addTypesToUnion(typeSet, type.types); - } - else if (flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (!strictNullChecks && flags & 6144 /* Nullable */) { - if (flags & 2048 /* Undefined */) - typeSet.containsUndefined = true; - if (flags & 4096 /* Null */) - typeSet.containsNull = true; - if (!(flags & 2097152 /* ContainsWideningType */)) - typeSet.containsNonWideningType = true; - } - else if (!(flags & 8192 /* Never */)) { - if (flags & 2 /* String */) - typeSet.containsString = true; - if (flags & 4 /* Number */) - typeSet.containsNumber = true; - if (flags & 96 /* StringOrNumberLiteral */) - typeSet.containsStringOrNumberLiteral = true; - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : binarySearchTypes(typeSet, type); - if (index < 0) { - if (!(flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } - } - } - } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. - function addTypesToUnion(typeSet, types) { - 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_6 = types; _i < types_6.length; _i++) { - var t = types_6[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function isSubtypeOfAny(candidate, types) { - 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; - } - } - return false; - } - function isSetOfLiteralsFromSameEnum(types) { - var first = types[0]; - if (first.flags & 256 /* EnumLiteral */) { - var firstEnum = getParentOfSymbol(first.symbol); - for (var i = 1; i < types.length; i++) { - var other = types[i]; - if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { - return false; - } - } - return true; - } - return false; - } - function removeSubtypes(types) { - if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { - return; - } - var i = types.length; - while (i > 0) { - i--; - if (isSubtypeOfAny(types[i], types)) { - ts.orderedRemoveItemAt(types, i); - } - } - } - function removeRedundantLiteralTypes(types) { - var i = types.length; - while (i > 0) { - i--; - var t = types[i]; - var remove = t.flags & 32 /* StringLiteral */ && types.containsString || - t.flags & 64 /* NumberLiteral */ && types.containsNumber || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 1048576 /* FreshLiteral */ && containsType(types, t.regularType); - if (remove) { - ts.orderedRemoveItemAt(types, i); - } - } - } - // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction - // flag is specified we also reduce the constituent type set to only include types that aren't subtypes - // of other types. Subtype reduction is expensive for large union types and is possible only when union - // types are known not to circularly reference themselves (as is the case with union types created by - // expression constructs such as array literals and the || and ?: operators). Named types can - // circularly reference themselves and therefore cannot be subtype reduced during their declaration. - // For example, "type Item = string | (() => Item" is a named type that circularly references itself. - function getUnionType(types, subtypeReduction, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var typeSet = []; - addTypesToUnion(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (subtypeReduction) { - removeSubtypes(typeSet); - } - else if (typeSet.containsStringOrNumberLiteral) { - removeRedundantLiteralTypes(typeSet); - } - if (typeSet.length === 0) { - return typeSet.containsNull ? typeSet.containsNonWideningType ? nullType : nullWideningType : - typeSet.containsUndefined ? typeSet.containsNonWideningType ? undefinedType : undefinedWideningType : - neverType; - } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); - } - // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return neverType; - } - if (types.length === 1) { - return types[0]; - } - var id = getTypeListId(types); - var type = unionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(65536 /* Union */ | propagatedFlags); - unionTypes.set(id, type); - type.types = types; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromUnionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), /*subtypeReduction*/ false, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function addTypeToIntersection(typeSet, type) { - if (type.flags & 131072 /* Intersection */) { - addTypesToIntersection(typeSet, type.types); - } - else if (type.flags & 1 /* Any */) { - typeSet.containsAny = true; - } - else if (getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - typeSet.containsEmptyObject = true; - } - else if (!(type.flags & 8192 /* Never */) && (strictNullChecks || !(type.flags & 6144 /* Nullable */)) && !ts.contains(typeSet, type)) { - if (type.flags & 32768 /* Object */) { - typeSet.containsObjectType = true; - } - if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { - typeSet.unionIndex = typeSet.length; - } - if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.push(type); - } - } - } - // Add the given types to the given type set. Order is preserved, duplicates are removed, - // and nested types of the given kind are flattened into the set. - function addTypesToIntersection(typeSet, types) { - for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { - var type = types_8[_i]; - addTypeToIntersection(typeSet, type); - } - } - // We normalize combinations of intersection and union types based on the distributive property of the '&' - // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection - // types with union type constituents into equivalent union types with intersection type constituents and - // effectively ensure that union types are always at the top level in type representations. - // - // We do not perform structural deduplication on intersection types. Intersection types are created only by the & - // type operator and we can't reduce those because we want to support recursive intersection types. For example, - // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. - // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution - // for intersections of types with signatures can be deterministic. - function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } - var typeSet = []; - addTypesToIntersection(typeSet, types); - if (typeSet.containsAny) { - return anyType; - } - if (typeSet.containsEmptyObject && !typeSet.containsObjectType) { - typeSet.push(emptyObjectType); - } - if (typeSet.length === 1) { - return typeSet[0]; - } - var unionIndex = typeSet.unionIndex; - if (unionIndex !== undefined) { - // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of - // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionType = typeSet[unionIndex]; - return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex, t)); }), - /*subtypeReduction*/ false, aliasSymbol, aliasTypeArguments); - } - var id = getTypeListId(typeSet); - var type = intersectionTypes.get(id); - if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 6144 /* Nullable */); - type = createType(131072 /* Intersection */ | propagatedFlags); - intersectionTypes.set(id, type); - type.types = typeSet; - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = aliasTypeArguments; - } - return type; - } - function getTypeFromIntersectionTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); - } - return links.resolvedType; - } - function getIndexTypeForGenericType(type) { - if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(262144 /* Index */); - type.resolvedIndexType.type = type; - } - return type.resolvedIndexType; - } - function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.name, "__@") ? - neverType : - getLiteralType(ts.unescapeIdentifier(prop.name)); - } - function getLiteralTypeFromPropertyNames(type) { - return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); - } - function getIndexType(type) { - return maybeTypeOfKind(type, 540672 /* TypeVariable */) ? getIndexTypeForGenericType(type) : - getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : - type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : - getLiteralTypeFromPropertyNames(type); - } - function getIndexTypeOrString(type) { - var indexType = getIndexType(type); - return indexType !== neverType ? indexType : stringType; - } - function getTypeFromTypeOperatorNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexType(getTypeFromTypeNode(node.type)); - } - return links.resolvedType; - } - function createIndexedAccessType(objectType, indexType) { - var type = createType(524288 /* IndexedAccess */); - type.objectType = objectType; - type.indexType = indexType; - return type; - } - function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = indexType.flags & 96 /* StringOrNumberLiteral */ ? - "" + indexType.value : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - ts.getPropertyNameForKnownSymbolName(accessExpression.argumentExpression.name.text) : - undefined; - if (propName !== undefined) { - var prop = getPropertyOfType(objectType, propName); - if (prop) { - if (accessExpression) { - if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { - error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return unknownType; - } - if (cacheSymbol) { - getNodeLinks(accessNode).resolvedSymbol = prop; - } - } - return getTypeOfSymbol(prop); - } - } - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 262178 /* StringLike */ | 84 /* NumberLike */ | 512 /* ESSymbol */)) { - if (isTypeAny(objectType)) { - return anyType; - } - var indexInfo = isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || - getIndexInfoOfType(objectType, 0 /* String */) || - undefined; - if (indexInfo) { - if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); - return unknownType; - } - return indexInfo.type; - } - if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { - if (getIndexTypeOfType(objectType, 1 /* Number */)) { - error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); - } - else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); - } - } - return anyType; - } - } - 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.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)); - } - else { - error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); - } - return unknownType; - } - return anyType; - } - function getIndexedAccessForMappedType(type, indexType, accessNode) { - var accessExpression = accessNode && accessNode.kind === 180 /* ElementAccessExpression */ ? accessNode : undefined; - if (accessExpression && ts.isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; - } - var mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); - var templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); - } - function getIndexedAccessType(objectType, indexType, accessNode) { - // If the index type is generic, if the object type is generic and doesn't originate in an expression, - // or if the object type is a mapped type with a generic constraint, we are performing a higher-order - // index access where we cannot meaningfully access the properties of the object type. Note that for a - // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to - // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved - // eagerly using the constraint type of 'this' at the given location. - if (maybeTypeOfKind(indexType, 540672 /* TypeVariable */ | 262144 /* Index */) || - maybeTypeOfKind(objectType, 540672 /* TypeVariable */) && !(accessNode && accessNode.kind === 180 /* ElementAccessExpression */) || - isGenericMappedType(objectType)) { - if (objectType.flags & 1 /* Any */) { - return objectType; - } - // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes - // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the - // type Box. - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - // Otherwise we defer the operation by creating an indexed access type. - var id = objectType.id + "," + indexType.id; - var type = indexedAccessTypes.get(id); - if (!type) { - indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType)); - } - return type; - } - // In the following we resolve T[K] to the type of the property in T selected by K. - var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 65536 /* Union */ && !(indexType.flags & 8190 /* Primitive */)) { - var propTypes = []; - for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { - var t = _a[_i]; - var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === unknownType) { - return unknownType; - } - propTypes.push(propType); - } - return getUnionType(propTypes); - } - return getPropertyTypeForIndexType(apparentObjectType, indexType, accessNode, /*cacheSymbol*/ true); - } - function getTypeFromIndexedAccessTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getIndexedAccessType(getTypeFromTypeNode(node.objectType), getTypeFromTypeNode(node.indexType), node); - } - return links.resolvedType; - } - function getTypeFromMappedTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = createObjectType(32 /* Mapped */, node.symbol); - type.declaration = node; - type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - // Eagerly resolve the constraint type which forces an error if the constraint type circularly - // references itself through one or more type aliases. - getConstraintTypeFromMappedType(type); - } - return links.resolvedType; - } - function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - // Deferred resolution of members is handled by resolveObjectTypeMembers - var aliasSymbol = getAliasSymbolForTypeNode(node); - if (node.symbol.members.size === 0 && !aliasSymbol) { - links.resolvedType = emptyTypeLiteralType; - } - else { - var type = createObjectType(16 /* Anonymous */, node.symbol); - type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); - links.resolvedType = type; - } - } - return links.resolvedType; - } - function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 231 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; - } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); - return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; - } - /** - * Since the source of spread types are object literals, which are not binary, - * this function should be called in a left folding style, with left = previous result of getSpreadType - * and right = the new element to be spread. - */ - function getSpreadType(left, right) { - if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { - return anyType; - } - left = filterType(left, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (left.flags & 8192 /* Never */) { - return right; - } - right = filterType(right, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (right.flags & 8192 /* Never */) { - return left; - } - if (left.flags & 65536 /* Union */) { - return mapType(left, function (t) { return getSpreadType(t, right); }); - } - if (right.flags & 65536 /* Union */) { - return mapType(right, function (t) { return getSpreadType(left, t); }); - } - if (right.flags & 16777216 /* NonPrimitive */) { - return emptyObjectType; - } - var members = ts.createMap(); - var skippedPrivateMembers = ts.createMap(); - var stringIndexInfo; - var numberIndexInfo; - if (left === emptyObjectType) { - // for the first spread element, left === emptyObjectType, so take the right's string indexer - stringIndexInfo = getIndexInfoOfType(right, 0 /* String */); - numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */); - } - else { - stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */)); - numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */)); - } - for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) { - 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 (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) { - skippedPrivateMembers.set(rightProp.name, true); - } - else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { - members.set(rightProp.name, getNonReadonlySymbol(rightProp)); - } - } - for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) { - var leftProp = _c[_b]; - if (leftProp.flags & 65536 /* SetAccessor */ && !(leftProp.flags & 32768 /* GetAccessor */) - || skippedPrivateMembers.has(leftProp.name) - || isClassMethod(leftProp)) { - continue; - } - if (members.has(leftProp.name)) { - var rightProp = members.get(leftProp.name); - var rightType = getTypeOfSymbol(rightProp); - 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), rightType]); - result.leftSpread = leftProp; - result.rightSpread = rightProp; - result.declarations = declarations; - members.set(leftProp.name, result); - } - } - else { - members.set(leftProp.name, getNonReadonlySymbol(leftProp)); - } - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - } - function getNonReadonlySymbol(prop) { - if (!isReadonlySymbol(prop)) { - return prop; - } - var flags = 4 /* Property */ | (prop.flags & 67108864 /* Optional */); - var result = createSymbol(flags, prop.name); - result.type = getTypeOfSymbol(prop); - result.declarations = prop.declarations; - result.syntheticOrigin = prop; - return result; - } - function isClassMethod(prop) { - return prop.flags & 8192 /* Method */ && ts.find(prop.declarations, function (decl) { return ts.isClassLike(decl.parent); }); - } - function createLiteralType(flags, value, symbol) { - var type = createType(flags); - 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.value, type.symbol); - freshType.regularType = type; - type.freshType = freshType; - } - return type.freshType; - } - return type; - } - function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */ ? type.regularType : type; - } - 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) { - var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); - literalTypes.set(key, type = createLiteralType(flags, value, symbol)); - } - return type; - } - function getTypeFromLiteralTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal)); - } - return links.resolvedType; - } - function getTypeFromJSDocVariadicType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var type = getTypeFromTypeNode(node.type); - links.resolvedType = type ? createArrayType(type) : unknownType; - } - return links.resolvedType; - } - function getTypeFromJSDocTupleType(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - var types = ts.map(node.types, getTypeFromTypeNode); - links.resolvedType = createTupleType(types); - } - return links.resolvedType; - } - function getThisType(node) { - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 230 /* InterfaceDeclaration */)) { - if (!(ts.getModifierFlags(container) & 32 /* Static */) && - (container.kind !== 152 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { - return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; - } - } - error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); - return unknownType; - } - function getTypeFromThisTypeNode(node) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - links.resolvedType = getThisType(node); - } - return links.resolvedType; - } - function getTypeFromTypeNode(node) { - switch (node.kind) { - case 119 /* AnyKeyword */: - case 268 /* JSDocAllType */: - case 269 /* JSDocUnknownType */: - return anyType; - case 136 /* StringKeyword */: - return stringType; - case 133 /* NumberKeyword */: - return numberType; - case 122 /* BooleanKeyword */: - return booleanType; - case 137 /* SymbolKeyword */: - return esSymbolType; - case 105 /* VoidKeyword */: - return voidType; - case 139 /* UndefinedKeyword */: - return undefinedType; - case 95 /* NullKeyword */: - return nullType; - case 130 /* NeverKeyword */: - return neverType; - case 134 /* ObjectKeyword */: - return nonPrimitiveType; - case 169 /* ThisType */: - case 99 /* ThisKeyword */: - return getTypeFromThisTypeNode(node); - case 173 /* LiteralType */: - return getTypeFromLiteralTypeNode(node); - case 293 /* JSDocLiteralType */: - return getTypeFromLiteralTypeNode(node.literal); - case 159 /* TypeReference */: - case 277 /* JSDocTypeReference */: - return getTypeFromTypeReference(node); - case 158 /* TypePredicate */: - return booleanType; - case 201 /* ExpressionWithTypeArguments */: - return getTypeFromTypeReference(node); - case 162 /* TypeQuery */: - return getTypeFromTypeQueryNode(node); - case 164 /* ArrayType */: - case 270 /* JSDocArrayType */: - return getTypeFromArrayTypeNode(node); - case 165 /* TupleType */: - return getTypeFromTupleTypeNode(node); - case 166 /* UnionType */: - case 271 /* JSDocUnionType */: - return getTypeFromUnionTypeNode(node); - case 167 /* IntersectionType */: - return getTypeFromIntersectionTypeNode(node); - case 273 /* JSDocNullableType */: - return getTypeFromJSDocNullableTypeNode(node); - case 168 /* ParenthesizedType */: - case 274 /* JSDocNonNullableType */: - case 281 /* JSDocConstructorType */: - case 282 /* JSDocThisType */: - case 278 /* JSDocOptionalType */: - return getTypeFromTypeNode(node.type); - case 275 /* JSDocRecordType */: - return getTypeFromTypeNode(node.literal); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 163 /* TypeLiteral */: - case 292 /* JSDocTypeLiteral */: - case 279 /* JSDocFunctionType */: - return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 170 /* TypeOperator */: - return getTypeFromTypeOperatorNode(node); - case 171 /* IndexedAccessType */: - return getTypeFromIndexedAccessTypeNode(node); - case 172 /* MappedType */: - return getTypeFromMappedTypeNode(node); - // This function assumes that an identifier or qualified name is a type expression - // Callers should first ensure this by calling isTypeNode - case 71 /* Identifier */: - case 143 /* QualifiedName */: - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - case 272 /* JSDocTupleType */: - return getTypeFromJSDocTupleType(node); - case 280 /* JSDocVariadicType */: - return getTypeFromJSDocVariadicType(node); - default: - return unknownType; - } - } - function instantiateList(items, mapper, instantiator) { - if (items && items.length) { - var result = []; - for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { - var v = items_1[_i]; - result.push(instantiator(v, mapper)); - } - return result; - } - return items; - } - function instantiateTypes(types, mapper) { - return instantiateList(types, mapper, instantiateType); - } - function instantiateSignatures(signatures, mapper) { - return instantiateList(signatures, mapper, instantiateSignature); - } - function instantiateCached(type, mapper, instantiator) { - var instantiations = mapper.instantiations || (mapper.instantiations = []); - return instantiations[type.id] || (instantiations[type.id] = instantiator(type, mapper)); - } - function makeUnaryTypeMapper(source, target) { - return function (t) { return t === source ? target : t; }; - } - function makeBinaryTypeMapper(source1, target1, source2, target2) { - return function (t) { return t === source1 ? target1 : t === source2 ? target2 : t; }; - } - function makeArrayTypeMapper(sources, targets) { - return function (t) { - for (var i = 0; i < sources.length; i++) { - if (t === sources[i]) { - return targets ? targets[i] : anyType; - } - } - return t; - }; - } - function createTypeMapper(sources, targets) { - var mapper = sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : - sources.length === 2 ? makeBinaryTypeMapper(sources[0], targets ? targets[0] : anyType, sources[1], targets ? targets[1] : anyType) : - makeArrayTypeMapper(sources, targets); - mapper.mappedTypes = sources; - return mapper; - } - function createTypeEraser(sources) { - return createTypeMapper(sources, /*targets*/ undefined); - } - /** - * Maps forward-references to later types parameters to the empty object type. - * This is used during inference when instantiating type parameter defaults. - */ - function createBackreferenceMapper(typeParameters, index) { - var mapper = function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; - mapper.mappedTypes = typeParameters; - return mapper; - } - function getInferenceMapper(context) { - if (!context.mapper) { - var mapper = function (t) { - var typeParameters = context.signature.typeParameters; - for (var i = 0; i < typeParameters.length; i++) { - if (t === typeParameters[i]) { - context.inferences[i].isFixed = true; - return getInferredType(context, i); - } - } - return t; - }; - mapper.mappedTypes = context.signature.typeParameters; - mapper.context = context; - context.mapper = mapper; - } - return context.mapper; - } - function identityMapper(type) { - return type; - } - function combineTypeMappers(mapper1, mapper2) { - var mapper = function (t) { return instantiateType(mapper1(t), mapper2); }; - mapper.mappedTypes = ts.concatenate(mapper1.mappedTypes, mapper2.mappedTypes); - return mapper; - } - function createReplacementMapper(source, target, baseMapper) { - var mapper = function (t) { return t === source ? target : baseMapper(t); }; - mapper.mappedTypes = baseMapper.mappedTypes; - return mapper; - } - function cloneTypeParameter(typeParameter) { - var result = createType(16384 /* TypeParameter */); - result.symbol = typeParameter.symbol; - result.target = typeParameter; - return result; - } - function cloneTypePredicate(predicate, mapper) { - if (ts.isIdentifierTypePredicate(predicate)) { - return { - kind: 1 /* Identifier */, - parameterName: predicate.parameterName, - parameterIndex: predicate.parameterIndex, - type: instantiateType(predicate.type, mapper) - }; - } - else { - return { - kind: 0 /* This */, - type: instantiateType(predicate.type, mapper) - }; - } - } - function instantiateSignature(signature, mapper, eraseTypeParameters) { - var freshTypeParameters; - var freshTypePredicate; - if (signature.typeParameters && !eraseTypeParameters) { - // First create a fresh set of type parameters, then include a mapping from the old to the - // new type parameters in the mapper function. Finally store this mapper in the new type - // parameters such that we can use it when instantiating constraints. - freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter); - mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper); - for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) { - var tp = freshTypeParameters_1[_i]; - tp.mapper = mapper; - } - } - if (signature.typePredicate) { - freshTypePredicate = cloneTypePredicate(signature.typePredicate, mapper); - } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); - result.target = signature; - result.mapper = mapper; - return result; - } - function instantiateSymbol(symbol, mapper) { - 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 - // always reference a non-aliases. - symbol = links.target; - mapper = combineTypeMappers(links.mapper, mapper); - } - // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and - // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.name); - result.checkFlags = 1 /* Instantiated */; - result.declarations = symbol.declarations; - result.parent = symbol.parent; - result.target = symbol; - result.mapper = mapper; - if (symbol.valueDeclaration) { - result.valueDeclaration = symbol.valueDeclaration; - } - return result; - } - function instantiateAnonymousType(type, mapper) { - var result = createObjectType(16 /* Anonymous */ | 64 /* Instantiated */, type.symbol); - result.target = type.objectFlags & 64 /* Instantiated */ ? type.target : type; - result.mapper = type.objectFlags & 64 /* Instantiated */ ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function instantiateMappedType(type, mapper) { - // Check if we have a homomorphic mapped type, i.e. a type of the form { [P in keyof T]: X } for some - // type variable T. If so, the mapped type is distributive over a union type and when T is instantiated - // to a union type A | B, we produce { [P in keyof A]: X } | { [P in keyof B]: X }. Furthermore, for - // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a - // union type A | undefined, we produce { [P in keyof A]: X } | undefined. - var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 262144 /* Index */) { - var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 16384 /* TypeParameter */) { - var mappedTypeVariable = instantiateType(typeVariable_1, mapper); - if (typeVariable_1 !== mappedTypeVariable) { - return mapType(mappedTypeVariable, function (t) { - if (isMappableType(t)) { - return instantiateMappedObjectType(type, createReplacementMapper(typeVariable_1, t, mapper)); - } - return t; - }); - } - } - } - return instantiateMappedObjectType(type, mapper); - } - function isMappableType(type) { - return type.flags & (16384 /* TypeParameter */ | 32768 /* Object */ | 131072 /* Intersection */ | 524288 /* IndexedAccess */); - } - function instantiateMappedObjectType(type, mapper) { - var result = createObjectType(32 /* Mapped */ | 64 /* Instantiated */, type.symbol); - result.declaration = type.declaration; - result.mapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; - result.aliasSymbol = type.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper); - return result; - } - function isSymbolInScopeOfMappedTypeParameter(symbol, mapper) { - if (!(symbol.declarations && symbol.declarations.length)) { - return false; - } - var mappedTypes = mapper.mappedTypes; - // Starting with the parent of the symbol's declaration, check if the mapper maps any of - // the type parameters introduced by enclosing declarations. We just pick the first - // declaration since multiple declarations will all have the same parent anyway. - return !!ts.findAncestor(symbol.declarations[0], function (node) { - if (node.kind === 233 /* ModuleDeclaration */ || node.kind === 265 /* SourceFile */) { - return "quit"; - } - switch (node.kind) { - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 152 /* Constructor */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - var declaration = node; - if (declaration.typeParameters) { - for (var _i = 0, _a = declaration.typeParameters; _i < _a.length; _i++) { - var d = _a[_i]; - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(d)))) { - return true; - } - } - } - if (ts.isClassLike(node) || node.kind === 230 /* InterfaceDeclaration */) { - var thisType = getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; - if (thisType && ts.contains(mappedTypes, thisType)) { - return true; - } - } - break; - case 172 /* MappedType */: - if (ts.contains(mappedTypes, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)))) { - return true; - } - break; - case 279 /* JSDocFunctionType */: - var func = node; - for (var _b = 0, _c = func.parameters; _b < _c.length; _b++) { - var p = _c[_b]; - if (ts.contains(mappedTypes, getTypeOfNode(p))) { - return true; - } - } - break; - } - }); - } - function isTopLevelTypeAlias(symbol) { - if (symbol.declarations && symbol.declarations.length) { - var parentKind = symbol.declarations[0].parent.kind; - return parentKind === 265 /* SourceFile */ || parentKind === 234 /* ModuleBlock */; - } - return false; - } - function instantiateType(type, mapper) { - if (type && mapper !== identityMapper) { - // If we are instantiating a type that has a top-level type alias, obtain the instantiation through - // the type alias instead in order to share instantiations for the same type arguments. This can - // dramatically reduce the number of structurally identical types we generate. Note that we can only - // perform this optimization for top-level type aliases. Consider: - // - // function f1(x: T) { - // type Foo = { x: X, t: T }; - // let obj: Foo = { x: x }; - // return obj; - // } - // function f2(x: U) { return f1(x); } - // let z = f2(42); - // - // Above, the declaration of f2 has an inferred return type that is an instantiation of f1's Foo - // equivalent to { x: U, t: U }. When instantiating this return type, we can't go back to Foo's - // cache because all cached instantiations are of the form { x: ???, t: T }, i.e. they have not been - // instantiated for T. Instead, we need to further instantiate the { x: U, t: U } form. - if (type.aliasSymbol && isTopLevelTypeAlias(type.aliasSymbol)) { - if (type.aliasTypeArguments) { - return getTypeAliasInstantiation(type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - return type; - } - return instantiateTypeNoAlias(type, mapper); - } - return type; - } - function instantiateTypeNoAlias(type, mapper) { - if (type.flags & 16384 /* TypeParameter */) { - return mapper(type); - } - if (type.flags & 32768 /* Object */) { - if (type.objectFlags & 16 /* Anonymous */) { - // If the anonymous type originates in a declaration of a function, method, class, or - // interface, in an object type literal, or in an object literal expression, we may need - // to instantiate the type because it might reference a type parameter. We skip instantiation - // if none of the type parameters that are in scope in the type's declaration are mapped by - // the given mapper, however we can only do that analysis if the type isn't itself an - // instantiation. - return type.symbol && - type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && - (type.objectFlags & 64 /* Instantiated */ || isSymbolInScopeOfMappedTypeParameter(type.symbol, mapper)) ? - instantiateCached(type, mapper, instantiateAnonymousType) : type; - } - if (type.objectFlags & 32 /* Mapped */) { - return instantiateCached(type, mapper, instantiateMappedType); - } - if (type.objectFlags & 4 /* Reference */) { - return createTypeReference(type.target, instantiateTypes(type.typeArguments, mapper)); - } - } - if (type.flags & 65536 /* Union */ && !(type.flags & 8190 /* Primitive */)) { - return getUnionType(instantiateTypes(type.types, mapper), /*subtypeReduction*/ false, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(instantiateTypes(type.types, mapper), type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)); - } - if (type.flags & 262144 /* Index */) { - return getIndexType(instantiateType(type.type, mapper)); - } - if (type.flags & 524288 /* IndexedAccess */) { - return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); - } - return type; - } - function instantiateIndexInfo(info, mapper) { - return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); - } - // Returns true if the given expression contains (at any level of nesting) a function or arrow expression - // that is subject to contextual typing. - function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return isContextSensitiveFunctionLikeDeclaration(node); - case 178 /* ObjectLiteralExpression */: - return ts.forEach(node.properties, isContextSensitive); - case 177 /* ArrayLiteralExpression */: - return ts.forEach(node.elements, isContextSensitive); - case 195 /* ConditionalExpression */: - return isContextSensitive(node.whenTrue) || - isContextSensitive(node.whenFalse); - case 194 /* BinaryExpression */: - return node.operatorToken.kind === 54 /* BarBarToken */ && - (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 261 /* PropertyAssignment */: - return isContextSensitive(node.initializer); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - return isContextSensitiveFunctionLikeDeclaration(node); - case 185 /* ParenthesizedExpression */: - return isContextSensitive(node.expression); - case 254 /* JsxAttributes */: - return ts.forEach(node.properties, isContextSensitive); - case 253 /* JsxAttribute */: - // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - return node.initializer && isContextSensitive(node.initializer); - case 256 /* JsxExpression */: - // It is possible to that node.expression is undefined (e.g
) - return node.expression && isContextSensitive(node.expression); - } - return false; - } - function isContextSensitiveFunctionLikeDeclaration(node) { - // Functions with type parameters are not context sensitive. - if (node.typeParameters) { - return false; - } - // Functions with any parameters that lack type annotations are context sensitive. - if (ts.forEach(node.parameters, function (p) { return !p.type; })) { - return true; - } - // For arrow functions we now know we're not context sensitive. - if (node.kind === 187 /* ArrowFunction */) { - return false; - } - // If the first parameter is not an explicit 'this' parameter, then the function has - // an implicit 'this' parameter which is subject to contextual typing. Otherwise we - // know that all parameters (including 'this') have type annotations and nothing is - // subject to contextual typing. - var parameter = ts.firstOrUndefined(node.parameters); - return !(parameter && ts.parameterIsThisKeyword(parameter)); - } - function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); - } - function getTypeWithoutSignatures(type) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.constructSignatures.length) { - var result = createObjectType(16 /* Anonymous */, type.symbol); - result.members = resolved.members; - result.properties = resolved.properties; - result.callSignatures = emptyArray; - result.constructSignatures = emptyArray; - return result; - } - } - else if (type.flags & 131072 /* Intersection */) { - return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); - } - return type; - } - // TYPE CHECKING - function isTypeIdenticalTo(source, target) { - return isTypeRelatedTo(source, target, identityRelation); - } - function compareTypesIdentical(source, target) { - return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */; - } - function compareTypesAssignable(source, target) { - return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */; - } - function isTypeSubtypeOf(source, target) { - return isTypeRelatedTo(source, target, subtypeRelation); - } - function isTypeAssignableTo(source, target) { - return isTypeRelatedTo(source, target, assignableRelation); - } - // A type S is considered to be an instance of a type T if S and T are the same type or if S is a - // subtype of T but not structurally identical to T. This specifically means that two distinct but - // structurally identical types (such as two classes) are not considered instances of each other. - function isTypeInstanceOf(source, target) { - return getTargetType(source) === getTargetType(target) || isTypeSubtypeOf(source, target) && !isTypeIdenticalTo(source, target); - } - /** - * This is *not* a bi-directional relationship. - * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'. - */ - function isTypeComparableTo(source, target) { - return isTypeRelatedTo(source, target, comparableRelation); - } - function areTypesComparable(type1, type2) { - return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); - } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); - } - /** - * This is *not* a bi-directional relationship. - * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'. - */ - function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain); - } - function isSignatureAssignableTo(source, target, ignoreReturnTypes) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, ignoreReturnTypes, /*reportErrors*/ false, - /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; - } - /** - * See signatureRelatedTo, compareSignaturesIdentical - */ - function compareSignaturesRelated(source, target, checkAsCallback, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { - // TODO (drosen): De-duplicate code between related functions. - if (source === target) { - return -1 /* True */; - } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { - return 0 /* False */; - } - // Spec 1.0 Section 3.8.3 & 3.8.4: - // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1 /* True */; - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType && sourceThisType !== voidType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - // void sources are assignable to anything. - var related = compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false) - || compareTypes(targetThisType, sourceThisType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible); - } - return 0 /* False */; - } - result &= related; - } - } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); - var sourceSig = getSingleCallSignature(getNonNullableType(sourceType)); - var targetSig = getSingleCallSignature(getNonNullableType(targetType)); - // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter - // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, - // they naturally relate only contra-variantly). However, if the source and target parameters both have - // function types with a single call signature, we known we are relating two callback parameters. In - // that case it is sufficient to only relate the parameters of the signatures co-variantly because, - // similar to return values, callback parameters are output positions. This means that a Promise, - // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant) - // with respect to T. - var callbacks = sourceSig && targetSig && !sourceSig.typePredicate && !targetSig.typePredicate && - (getFalsyFlags(sourceType) & 6144 /* Nullable */) === (getFalsyFlags(targetType) & 6144 /* Nullable */); - var related = callbacks ? - compareSignaturesRelated(targetSig, sourceSig, /*checkAsCallback*/ true, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : - !checkAsCallback && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); - if (!related) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, sourceParams[i < sourceMax ? i : sourceMax].name, targetParams[i < targetMax ? i : targetMax].name); - } - return 0 /* False */; - } - result &= related; - } - if (!ignoreReturnTypes) { - var targetReturnType = getReturnTypeOfSignature(target); - if (targetReturnType === voidType) { - return result; - } - var sourceReturnType = getReturnTypeOfSignature(source); - // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions - if (target.typePredicate) { - if (source.typePredicate) { - result &= compareTypePredicateRelatedTo(source.typePredicate, target.typePredicate, reportErrors, errorReporter, compareTypes); - } - else if (ts.isIdentifierTypePredicate(target.typePredicate)) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Signature_0_must_have_a_type_predicate, signatureToString(source)); - } - return 0 /* False */; - } - } - else { - // When relating callback signatures, we still need to relate return types bi-variantly as otherwise - // the containing type wouldn't be co-variant. For example, interface Foo { add(cb: () => T): void } - // wouldn't be co-variant for T without this rule. - result &= checkAsCallback && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) || - compareTypes(sourceReturnType, targetReturnType, reportErrors); - } - } - return result; - } - function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { - if (source.kind !== target.kind) { - if (reportErrors) { - errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0 /* False */; - } - if (source.kind === 1 /* Identifier */) { - var sourceIdentifierPredicate = source; - var targetIdentifierPredicate = target; - if (sourceIdentifierPredicate.parameterIndex !== targetIdentifierPredicate.parameterIndex) { - if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, sourceIdentifierPredicate.parameterName, targetIdentifierPredicate.parameterName); - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return 0 /* False */; - } - } - var related = compareTypes(source.type, target.type, reportErrors); - if (related === 0 /* False */ && reportErrors) { - errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); - } - return related; - } - function isImplementationCompatibleWithOverload(implementation, overload) { - var erasedSource = getErasedSignature(implementation); - var erasedTarget = getErasedSignature(overload); - // First see if the return types are compatible in either direction. - var sourceReturnType = getReturnTypeOfSignature(erasedSource); - var targetReturnType = getReturnTypeOfSignature(erasedTarget); - if (targetReturnType === voidType - || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation) - || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) { - return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true); - } - return false; - } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - // If both have rest parameters, get the max and add 1 to - // compensate for the rest parameter. - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - // Return the count for whichever signature doesn't have rest parameters. - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } - function isEmptyResolvedType(t) { - return t.properties.length === 0 && - t.callSignatures.length === 0 && - t.constructSignatures.length === 0 && - !t.stringIndexInfo && - !t.numberIndexInfo; - } - function isEmptyObjectType(type) { - return type.flags & 32768 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 65536 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 131072 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : - false; - } - function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { - if (sourceSymbol === targetSymbol) { - return true; - } - var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); - var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; - } - if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { - enumRelation.set(id, false); - return false; - } - 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(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */)); - } - enumRelation.set(id, false); - return false; - } - } - } - enumRelation.set(id, true); - return true; - } - function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { - var s = source.flags; - var t = target.flags; - if (t & 8192 /* Never */) - return false; - if (t & 1 /* Any */ || s & 8192 /* Never */) - return true; - if (s & 262178 /* StringLike */ && t & 2 /* String */) - return true; - if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && - t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && - source.value === target.value) - return true; - if (s & 84 /* NumberLike */ && t & 4 /* Number */) - return true; - if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && - t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && - source.value === target.value) - return true; - if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) - return true; - if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; - 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 (s & 4096 /* Null */ && (!strictNullChecks || t & 4096 /* Null */)) - return true; - if (s & 32768 /* Object */ && t & 16777216 /* NonPrimitive */) - return true; - if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1 /* 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 & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) - return true; - } - return false; - } - function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { - source = source.regularType; - } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { - target = target.regularType; - } - if (source === target || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { - return true; - } - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - return related === 1 /* Succeeded */; - } - } - if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { - return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); - } - return false; - } - /** - * Checks if 'source' is related to 'target' (e.g.: is a assignable to). - * @param source The left-hand-side of the relation. - * @param target The right-hand-side of the relation. - * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'. - * Used as both to determine which checks are performed and as a cache of previously computed results. - * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used. - * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. - * @param containingMessageChain A chain of errors to prepend any new errors found. - */ - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { - var errorInfo; - var sourceStack; - var targetStack; - var maybeStack; - var expandingFlags; - var depth = 0; - var overflow = false; - ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage); - if (overflow) { - error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); - } - else if (errorInfo) { - if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); - } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - return result !== 0 /* False */; - function reportError(message, arg0, arg1, arg2) { - ts.Debug.assert(!!errorNode); - errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); - } - function reportRelationError(message, source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 128 /* UseFullyQualifiedType */); - } - if (!message) { - if (relation === comparableRelation) { - message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1; - } - else if (sourceType === targetType) { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated; - } - else { - message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1; - } - } - reportError(message, sourceType, targetType); - } - function tryElaborateErrorsForPrimitivesAndObjects(source, target) { - var sourceType = typeToString(source); - var targetType = typeToString(target); - if ((globalStringType === source && stringType === target) || - (globalNumberType === source && numberType === target) || - (globalBooleanType === source && booleanType === target) || - (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) { - reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType); - } - } - function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 196608 /* UnionOrIntersection */)) { - return false; - } - // at this point we know that this is union or intersection type possibly with nullable constituents. - // check if we still will have compound type if we ignore nullable components. - var seenNonNullable = false; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (t.flags & 6144 /* Nullable */) { - continue; - } - if (seenNonNullable) { - return true; - } - seenNonNullable = true; - } - return false; - } - /** - * Compare two types and return - * * Ternary.True if they are related with no assumptions, - * * Ternary.Maybe if they are related with assumptions of other relationships, or - * * Ternary.False if they are not related. - */ - function isRelatedTo(source, target, reportErrors, headMessage) { - var result; - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 1048576 /* FreshLiteral */) { - source = source.regularType; - } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 1048576 /* FreshLiteral */) { - target = target.regularType; - } - // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases - if (source === target) - return -1 /* True */; - if (relation === identityRelation) { - return isIdenticalTo(source, target); - } - if (isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) - return -1 /* True */; - if (getObjectFlags(source) & 128 /* ObjectLiteral */ && source.flags & 1048576 /* FreshLiteral */) { - if (hasExcessProperties(source, target, reportErrors)) { - if (reportErrors) { - reportRelationError(headMessage, source, target); - } - return 0 /* False */; - } - // Above we check for excess properties with respect to the entire target type. When union - // and intersection types are further deconstructed on the target side, we don't want to - // make the check again (as it might fail for a partial target type). Therefore we obtain - // the regular source type and proceed with that. - if (isUnionOrIntersectionTypeWithoutNullableConstituents(target)) { - source = getRegularTypeOfObjectLiteral(source); - } - } - var saveErrorInfo = errorInfo; - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 65536 /* Union */) { - if (relation === comparableRelation) { - result = someTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); - } - else { - result = eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */)); - } - if (result) { - return result; - } - } - else { - if (target.flags & 65536 /* Union */) { - if (result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 8190 /* Primitive */) && !(target.flags & 8190 /* Primitive */))) { - return result; - } - } - else if (target.flags & 131072 /* Intersection */) { - if (result = typeRelatedToEachType(source, target, reportErrors)) { - return result; - } - } - else if (source.flags & 131072 /* Intersection */) { - // Check to see if any constituents of the intersection are immediately related to the target. - // - // Don't report errors though. Checking whether a constituent is related to the source is not actually - // useful and leads to some confusing error messages. Instead it is better to let the below checks - // take care of this, or to not elaborate at all. For instance, - // - // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. - // - // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection - // than to report that 'D' is not assignable to 'A' or 'B'. - // - // - For a primitive type or type parameter (such as 'number = A & B') there is no point in - // breaking the intersection apart. - if (result = someTypeRelatedToType(source, target, /*reportErrors*/ false)) { - return result; - } - } - if (source.flags & 1032192 /* StructuredOrTypeVariable */ || target.flags & 1032192 /* StructuredOrTypeVariable */) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (reportErrors) { - if (source.flags & 32768 /* Object */ && target.flags & 8190 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 32768 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - reportRelationError(headMessage, source, target); - } - return 0 /* False */; - } - function isIdenticalTo(source, target) { - var result; - if (source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */) { - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); - } - if (source.flags & 65536 /* Union */ && target.flags & 65536 /* Union */ || - source.flags & 131072 /* Intersection */ && target.flags & 131072 /* Intersection */) { - if (result = eachTypeRelatedToSomeType(source, target)) { - if (result &= eachTypeRelatedToSomeType(target, source)) { - return result; - } - } - } - return 0 /* False */; - } - function hasExcessProperties(source, target, reportErrors) { - if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { - var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); - if ((relation === assignableRelation || relation === comparableRelation) && - (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { - return false; - } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { - if (reportErrors) { - // We know *exactly* where things went wrong when comparing the types. - // Use this property as the error node as this will be more helpful in - // reasoning about what went wrong. - ts.Debug.assert(!!errorNode); - if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { - // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. - // However, using an object-literal error message will be very confusing to the users so we give different a message. - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); - } - else { - errorNode = prop.valueDeclaration; - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); - } - } - return true; - } - } - } - return false; - } - function eachTypeRelatedToSomeType(source, target) { - var result = -1 /* True */; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { - var sourceType = sourceTypes_1[_i]; - var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function typeRelatedToSomeType(source, target, reportErrors) { - var targetTypes = target.types; - if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { - return -1 /* True */; - } - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var type = targetTypes_1[_i]; - var related = isRelatedTo(source, type, /*reportErrors*/ false); - if (related) { - return related; - } - } - if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); - } - return 0 /* False */; - } - function findMatchingDiscriminantType(source, target) { - var sourceProperties = getPropertiesOfObjectType(source); - if (sourceProperties) { - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProperty = sourceProperties_1[_i]; - if (isDiscriminantProperty(target, sourceProperty.name)) { - var sourceType = getTypeOfSymbol(sourceProperty); - for (var _a = 0, _b = target.types; _a < _b.length; _a++) { - var type = _b[_a]; - var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); - if (targetType && isRelatedTo(sourceType, targetType)) { - return type; - } - } - } - } - } - } - function typeRelatedToEachType(source, target, reportErrors) { - var result = -1 /* True */; - var targetTypes = target.types; - for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { - var targetType = targetTypes_2[_i]; - var related = isRelatedTo(source, targetType, reportErrors); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function someTypeRelatedToType(source, target, reportErrors) { - var sourceTypes = source.types; - if (source.flags & 65536 /* Union */ && containsType(sourceTypes, target)) { - return -1 /* True */; - } - var len = sourceTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); - if (related) { - return related; - } - } - return 0 /* False */; - } - function eachTypeRelatedToType(source, target, reportErrors) { - var result = -1 /* True */; - var sourceTypes = source.types; - for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { - var sourceType = sourceTypes_2[_i]; - var related = isRelatedTo(sourceType, target, reportErrors); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function typeArgumentsRelatedTo(source, target, reportErrors) { - var sources = source.typeArguments || emptyArray; - var targets = target.typeArguments || emptyArray; - if (sources.length !== targets.length && relation === identityRelation) { - return 0 /* False */; - } - var length = sources.length <= targets.length ? sources.length : targets.length; - var result = -1 /* True */; - for (var i = 0; i < length; i++) { - var related = isRelatedTo(sources[i], targets[i], reportErrors); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - // Determine if possibly recursive types are related. First, check if the result is already available in the global cache. - // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true. - // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are - // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion - // and issue an error. Otherwise, actually compare the structure of the two types. - function recursiveTypeRelatedTo(source, target, reportErrors) { - if (overflow) { - return 0 /* False */; - } - var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; - var related = relation.get(id); - if (related !== undefined) { - if (reportErrors && related === 2 /* Failed */) { - // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported - // failure and continue computing the relation such that errors get reported. - relation.set(id, 3 /* FailedAndReported */); - } - else { - return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; - } - } - if (depth > 0) { - for (var i = 0; i < depth; i++) { - // If source and target are already being compared, consider them related with assumptions - if (maybeStack[i].get(id)) { - return 1 /* Maybe */; - } - } - if (depth === 100) { - overflow = true; - return 0 /* False */; - } - } - else { - sourceStack = []; - targetStack = []; - maybeStack = []; - expandingFlags = 0; - } - sourceStack[depth] = source; - targetStack[depth] = target; - maybeStack[depth] = ts.createMap(); - maybeStack[depth].set(id, 1 /* Succeeded */); - depth++; - var saveExpandingFlags = expandingFlags; - if (!(expandingFlags & 1) && isDeeplyNestedType(source, sourceStack, depth)) - expandingFlags |= 1; - if (!(expandingFlags & 2) && isDeeplyNestedType(target, targetStack, depth)) - expandingFlags |= 2; - var result = expandingFlags !== 3 ? structuredTypeRelatedTo(source, target, reportErrors) : 1 /* Maybe */; - expandingFlags = saveExpandingFlags; - depth--; - if (result) { - var maybeCache = maybeStack[depth]; - // If result is definitely true, copy assumptions to global cache, else copy to next level up - var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; - ts.copyEntries(maybeCache, destinationCache); - } - else { - // A false result goes straight into global cache (when something is false under assumptions it - // will also be false without assumptions) - relation.set(id, reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */); - } - return result; - } - function structuredTypeRelatedTo(source, target, reportErrors) { - var result; - var saveErrorInfo = errorInfo; - if (target.flags & 16384 /* TypeParameter */) { - // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. - if (getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { - if (!source.declaration.questionToken) { - var templateType = getTemplateTypeFromMappedType(source); - var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source)); - if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) { - return result; - } - } - } - } - else if (target.flags & 262144 /* Index */) { - // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 262144 /* Index */) { - if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { - return result; - } - } - // A type S is assignable to keyof T if S is assignable to keyof C, where C is the - // constraint of T. - var constraint = getConstraintOfType(target.type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { - return result; - } - } - } - else if (target.flags & 524288 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. - var constraint = getConstraintOfType(target); - if (constraint) { - if (result = isRelatedTo(source, constraint, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - if (source.flags & 16384 /* TypeParameter */) { - // A source type T is related to a target type { [P in keyof T]: X } if T[P] is related to X. - if (getObjectFlags(target) & 32 /* Mapped */ && getConstraintTypeFromMappedType(target) === getIndexType(source)) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else { - var constraint = getConstraintOfTypeParameter(source); - // A type parameter with no constraint is not related to the non-primitive object type. - if (constraint || !(target.flags & 16777216 /* NonPrimitive */)) { - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; - } - // The constraint may need to be further instantiated with its 'this' type. - constraint = getTypeWithThisArgument(constraint, source); - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - } - else if (source.flags & 524288 /* IndexedAccess */) { - // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. - var constraint = getConstraintOfType(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else if (target.flags & 524288 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. - if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { - return result; - } - } - } - else { - if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { - // We have type references to same target type, see if relationship holds for all type arguments - if (result = typeArgumentsRelatedTo(source, target, reportErrors)) { - return result; - } - } - // Even if relationship doesn't hold for unions, intersections, or generic type references, - // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 8190 /* Primitive */); - if (relation !== identityRelation) { - source = getApparentType(source); - } - // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates - // to X. Failing both of those we want to check if the aggregation of A and B's members structurally - // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (32768 /* Object */ | 131072 /* Intersection */) && target.flags & 32768 /* Object */) { - // Report structural errors only if we haven't reported any errors yet - var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isGenericMappedType(source) || isGenericMappedType(target)) { - result = mappedTypeRelatedTo(source, target, reportStructuralErrors); - } - else { - result = propertiesRelatedTo(source, target, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors); - if (result) { - result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors); - if (result) { - result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors); - } - } - } - } - } - if (result) { - errorInfo = saveErrorInfo; - return result; - } - } - } - return 0 /* False */; - } - // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is - // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice - // that S and T are contra-variant whereas X and Y are co-variant. - function mappedTypeRelatedTo(source, target, reportErrors) { - if (isGenericMappedType(target)) { - if (isGenericMappedType(source)) { - var sourceReadonly = !!source.declaration.readonlyToken; - var sourceOptional = !!source.declaration.questionToken; - var targetReadonly = !!target.declaration.readonlyToken; - var targetOptional = !!target.declaration.questionToken; - var modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; - if (modifiersRelated) { - var result_2; - if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); - } - } - } - else if (target.declaration.questionToken && isEmptyObjectType(source)) { - return -1 /* True */; - } - } - else if (relation !== identityRelation) { - var resolved = resolveStructuredTypeMembers(target); - if (isEmptyResolvedType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & 1 /* Any */) { - return -1 /* True */; - } - } - return 0 /* False */; - } - function propertiesRelatedTo(source, target, reportErrors) { - if (relation === identityRelation) { - return propertiesIdenticalTo(source, target); - } - var result = -1 /* True */; - var properties = getPropertiesOfObjectType(target); - var requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & 128 /* ObjectLiteral */); - for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { - var targetProp = properties_4[_i]; - var sourceProp = getPropertyOfType(source, targetProp.name); - if (sourceProp !== targetProp) { - if (!sourceProp) { - if (!(targetProp.flags & 67108864 /* Optional */) || requireOptionalProperties) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); - } - return 0 /* False */; - } - } - else if (!(targetProp.flags & 16777216 /* Prototype */)) { - var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); - var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); - if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - 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)); - } - return 0 /* False */; - } - if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { - if (reportErrors) { - if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { - reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); - } - else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 8 /* Private */ ? source : target), typeToString(sourcePropFlags & 8 /* Private */ ? target : source)); - } - } - return 0 /* False */; - } - } - else if (targetPropFlags & 16 /* Protected */) { - if (!isValidOverrideOf(sourceProp, targetProp)) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); - } - return 0 /* False */; - } - } - else if (sourcePropFlags & 16 /* Protected */) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0 /* False */; - } - var related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); - } - return 0 /* False */; - } - result &= related; - // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 67108864 /* Optional */ && !(targetProp.flags & 67108864 /* Optional */)) { - // TypeScript 1.0 spec (April 2014): 3.8.3 - // S is a subtype of a type T, and T is a supertype of S if ... - // S' and T are object types and, for each member M in T.. - // M is a property and S' contains a property N where - // if M is a required property, N is also a required property - // (M - property in T) - // (N - property in S) - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); - } - return 0 /* False */; - } - } - } - } - return result; - } - function propertiesIdenticalTo(source, target) { - if (!(source.flags & 32768 /* Object */ && target.flags & 32768 /* Object */)) { - return 0 /* False */; - } - var sourceProperties = getPropertiesOfObjectType(source); - var targetProperties = getPropertiesOfObjectType(target); - if (sourceProperties.length !== targetProperties.length) { - return 0 /* False */; - } - var result = -1 /* True */; - for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { - var sourceProp = sourceProperties_2[_i]; - var targetProp = getPropertyOfObjectType(target, sourceProp.name); - if (!targetProp) { - return 0 /* False */; - } - var related = compareProperties(sourceProp, targetProp, isRelatedTo); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function signaturesRelatedTo(source, target, kind, reportErrors) { - if (relation === identityRelation) { - return signaturesIdenticalTo(source, target, kind); - } - if (target === anyFunctionType || source === anyFunctionType) { - return -1 /* True */; - } - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) { - if (isAbstractConstructorType(source) && !isAbstractConstructorType(target)) { - // An abstract constructor type is not assignable to a non-abstract constructor type - // as it would otherwise be possible to new an abstract class. Note that the assignability - // check we perform for an extends clause excludes construct signatures from the target, - // so this check never proceeds. - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); - } - return 0 /* False */; - } - if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) { - return 0 /* False */; - } - } - var result = -1 /* True */; - var saveErrorInfo = errorInfo; - 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 */; - } - result &= related; - } - } - 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 result; - } - /** - * See signatureAssignableTo, compareSignaturesIdentical - */ - function signatureRelatedTo(source, target, reportErrors) { - return compareSignaturesRelated(source, target, /*checkAsCallback*/ false, /*ignoreReturnTypes*/ false, reportErrors, reportError, isRelatedTo); - } - function signaturesIdenticalTo(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - if (sourceSignatures.length !== targetSignatures.length) { - return 0 /* False */; - } - var result = -1 /* True */; - for (var i = 0; i < sourceSignatures.length; i++) { - var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); - if (!related) { - return 0 /* False */; - } - result &= related; - } - return result; - } - function eachPropertyRelatedTo(source, target, kind, reportErrors) { - var result = -1 /* True */; - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (kind === 0 /* String */ || isNumericLiteralName(prop.name)) { - var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); - if (!related) { - if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop)); - } - return 0 /* False */; - } - result &= related; - } - } - return result; - } - function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors) { - var related = isRelatedTo(sourceInfo.type, targetInfo.type, reportErrors); - if (!related && reportErrors) { - reportError(ts.Diagnostics.Index_signatures_are_incompatible); - } - return related; - } - function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors) { - if (relation === identityRelation) { - return indexTypesIdenticalTo(source, target, kind); - } - var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) { - // Index signature of type any permits assignment from everything but primitives - return -1 /* True */; - } - var sourceInfo = getIndexInfoOfType(source, kind) || - kind === 1 /* Number */ && getIndexInfoOfType(source, 0 /* String */); - if (sourceInfo) { - return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors); - } - if (isObjectLiteralType(source)) { - var related = -1 /* True */; - if (kind === 0 /* String */) { - var sourceNumberInfo = getIndexInfoOfType(source, 1 /* Number */); - if (sourceNumberInfo) { - related = indexInfoRelatedTo(sourceNumberInfo, targetInfo, reportErrors); - } - } - if (related) { - related &= eachPropertyRelatedTo(source, targetInfo.type, kind, reportErrors); - } - return related; - } - if (reportErrors) { - reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); - } - return 0 /* False */; - } - function indexTypesIdenticalTo(source, target, indexKind) { - var targetInfo = getIndexInfoOfType(target, indexKind); - var sourceInfo = getIndexInfoOfType(source, indexKind); - if (!sourceInfo && !targetInfo) { - return -1 /* True */; - } - if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) { - return isRelatedTo(sourceInfo.type, targetInfo.type); - } - return 0 /* False */; - } - function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) { - if (!sourceSignature.declaration || !targetSignature.declaration) { - return true; - } - var sourceAccessibility = ts.getModifierFlags(sourceSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; - var targetAccessibility = ts.getModifierFlags(targetSignature.declaration) & 24 /* NonPublicAccessibilityModifier */; - // A public, protected and private signature is assignable to a private signature. - if (targetAccessibility === 8 /* Private */) { - return true; - } - // A public and protected signature is assignable to a protected signature. - if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) { - return true; - } - // Only a public signature is assignable to public signature. - if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) { - return true; - } - if (reportErrors) { - reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility)); - } - return false; - } - } - // 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 (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); - var result = p && forEachProperty(p, callback); - if (result) { - return result; - } - } - return undefined; - } - return callback(prop); - } - // Return the declaring class type of a property or undefined if property not declared in class - function getDeclaringClass(prop) { - return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; - } - // Return true if some underlying source property is declared in a class that derives - // from the given base class. - function isPropertyInClassDerivedFrom(prop, baseClass) { - return forEachProperty(prop, function (sp) { - var sourceClass = getDeclaringClass(sp); - return sourceClass ? hasBaseType(sourceClass, baseClass) : false; - }); - } - // 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 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 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 - function isAbstractConstructorType(type) { - if (getObjectFlags(type) & 16 /* Anonymous */) { - var symbol = type.symbol; - if (symbol && symbol.flags & 32 /* Class */) { - var declaration = getClassLikeDeclarationOfSymbol(symbol); - if (declaration && ts.getModifierFlags(declaration) & 128 /* Abstract */) { - return true; - } - } - } - return false; - } - // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons - // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, - // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely - // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 - // levels, but unequal at some level beyond that. - function isDeeplyNestedType(type, stack, depth) { - // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 32768 /* Object */) { - var symbol = type.symbol; - if (symbol) { - var count = 0; - for (var i = 0; i < depth; i++) { - var t = stack[i]; - if (t.flags & 32768 /* Object */ && t.symbol === symbol) { - count++; - if (count >= 5) - return true; - } - } - } - } - return false; - } - function isPropertyIdenticalTo(sourceProp, targetProp) { - return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */; - } - function compareProperties(sourceProp, targetProp, compareTypes) { - // Two members are considered identical when - // - they are public properties with identical names, optionality, and types, - // - they are private or protected properties originating in the same declaration and having identical types - if (sourceProp === targetProp) { - return -1 /* True */; - } - var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */; - var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */; - if (sourcePropAccessibility !== targetPropAccessibility) { - return 0 /* False */; - } - if (sourcePropAccessibility) { - if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) { - return 0 /* False */; - } - } - else { - if ((sourceProp.flags & 67108864 /* Optional */) !== (targetProp.flags & 67108864 /* Optional */)) { - return 0 /* False */; - } - } - if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) { - return 0 /* False */; - } - return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - function isMatchingSignature(source, target, partialMatch) { - // A source signature matches a target signature if the two signatures have the same number of required, - // optional, and rest parameters. - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { - return true; - } - // A source signature partially matches a target signature if the target signature has no fewer required - // parameters and no more overall parameters than the source signature (where a signature with a rest - // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { - return true; - } - return false; - } - /** - * See signatureRelatedTo, compareSignaturesIdentical - */ - function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) { - // TODO (drosen): De-duplicate code between related functions. - if (source === target) { - return -1 /* True */; - } - if (!(isMatchingSignature(source, target, partialMatch))) { - return 0 /* False */; - } - // Check that the two signatures have the same number of type parameters. We might consider - // also checking that any type parameter constraints match, but that would require instantiating - // the constraints with a common set of type arguments to get relatable entities in places where - // type parameters occur in the constraints. The complexity of doing that doesn't seem worthwhile, - // particularly as we're comparing erased versions of the signatures below. - if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) { - return 0 /* False */; - } - // Spec 1.0 Section 3.8.3 & 3.8.4: - // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N - source = getErasedSignature(source); - target = getErasedSignature(target); - var result = -1 /* True */; - if (!ignoreThisTypes) { - var sourceThisType = getThisTypeOfSignature(source); - if (sourceThisType) { - var targetThisType = getThisTypeOfSignature(target); - if (targetThisType) { - var related = compareTypes(sourceThisType, targetThisType); - if (!related) { - return 0 /* False */; - } - result &= related; - } - } - } - var targetLen = target.parameters.length; - for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); - var related = compareTypes(s, t); - if (!related) { - return 0 /* False */; - } - result &= related; - } - if (!ignoreReturnTypes) { - result &= compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - return result; - } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } - function isSupertypeOfEach(candidate, types) { - 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; - } - return true; - } - function literalTypesWithSameBaseType(types) { - var commonBaseType; - 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; - } - if (baseType === t || baseType !== commonBaseType) { - return false; - } - } - return true; - } - // When the candidate types are all literal types with the same base type, the common - // supertype is a union of those literal types. Otherwise, the common supertype is the - // first type that is a supertype of each of the other types. - function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); - } - function getCommonSupertype(types) { - if (!strictNullChecks) { - return getSupertypeOrUnion(types); - } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (!primaryTypes.length) { - return getUnionType(types, /*subtypeReduction*/ true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - 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 - // to not be the common supertype. So if it weren't for this one downfallType (and possibly others), - // the type in question could have been the common supertype. - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - // types.length - 1 is the maximum score, given that getCommonSupertype returned false - if (bestSupertypeScore === types.length - 1) { - break; - } - } - // In the following errors, the {1} slot is before the {0} slot because checkTypeSubtypeOf supplies the - // subtype as the first argument to the error - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); - } - function isArrayType(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; - } - function isArrayLikeType(type) { - // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, - // or if it is not the undefined or null type and if it is assignable to ReadonlyArray - return getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 6144 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); - } - function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); - } - function isUnitType(type) { - 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 & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : - isUnitType(type); - } - function getBaseTypeOfLiteralType(type) { - 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 & 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; - } - /** - * Check if a Type was written as a tuple type literal. - * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. - */ - function isTupleType(type) { - return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); - } - function getFalsyFlagsOfTypes(types) { - var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; - result |= getFalsyFlags(t); - } - return result; - } - // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null - // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns - // 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.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 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; - } - /** - * Return true if type was inferred from an object literal or written as an object type literal - * with no call or construct signatures. - */ - function isObjectLiteralType(type) { - return type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */)) !== 0 && - getSignaturesOfType(type, 0 /* Call */).length === 0 && - getSignaturesOfType(type, 1 /* Construct */).length === 0; - } - function createSymbolWithType(source, type) { - var symbol = createSymbol(source.flags, source.name); - symbol.declarations = source.declarations; - symbol.parent = source.parent; - symbol.type = type; - symbol.target = source; - if (source.valueDeclaration) { - symbol.valueDeclaration = source.valueDeclaration; - } - return symbol; - } - function transformTypeOfMembers(type, f) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var property = _a[_i]; - var original = getTypeOfSymbol(property); - var updated = f(original); - members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); - } - return members; - } - /** - * If the the provided object literal is subject to the excess properties check, - * create a new that is exempt. Recursively mark object literal members as exempt. - * Leave signatures alone since they are not subject to the check. - */ - function getRegularTypeOfObjectLiteral(type) { - if (!(getObjectFlags(type) & 128 /* ObjectLiteral */ && type.flags & 1048576 /* FreshLiteral */)) { - return type; - } - var regularType = type.regularType; - if (regularType) { - return regularType; - } - var resolved = type; - var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); - var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~1048576 /* FreshLiteral */; - regularNew.objectFlags |= 128 /* ObjectLiteral */; - type.regularType = regularNew; - return regularNew; - } - function getWidenedProperty(prop) { - var original = getTypeOfSymbol(prop); - var widened = getWidenedType(original); - return widened === original ? prop : createSymbolWithType(prop, widened); - } - function getWidenedTypeOfObjectLiteral(type) { - var members = ts.createMap(); - for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { - var prop = _a[_i]; - // Since get accessors already widen their return value there is no need to - // widen accessor based properties here. - members.set(prop.name, prop.flags & 4 /* Property */ ? getWidenedProperty(prop) : prop); - } - var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */); - var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); - return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly)); - } - function getWidenedConstituentType(type) { - return type.flags & 6144 /* Nullable */ ? type : getWidenedType(type); - } - function getWidenedType(type) { - if (type.flags & 6291456 /* RequiresWidening */) { - if (type.flags & 6144 /* Nullable */) { - return anyType; - } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - return getWidenedTypeOfObjectLiteral(type); - } - if (type.flags & 65536 /* Union */) { - return getUnionType(ts.sameMap(type.types, getWidenedConstituentType)); - } - if (isArrayType(type) || isTupleType(type)) { - return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); - } - } - return type; - } - /** - * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' - * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to - * getWidenedType. But in some cases getWidenedType is called without reporting errors - * (type argument inference is an example). - * - * The return value indicates whether an error was in fact reported. The particular circumstances - * are on a best effort basis. Currently, if the null or undefined that causes widening is inside - * an object literal property (arbitrarily deeply), this function reports an error. If no error is - * reported, reportImplicitAnyError is a suitable fallback to report a general error. - */ - function reportWideningErrorsInType(type) { - var errorReported = false; - if (type.flags & 65536 /* Union */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (isArrayType(type) || isTupleType(type)) { - for (var _b = 0, _c = type.typeArguments; _b < _c.length; _b++) { - var t = _c[_b]; - if (reportWideningErrorsInType(t)) { - errorReported = true; - } - } - } - if (getObjectFlags(type) & 128 /* ObjectLiteral */) { - for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { - var p = _e[_d]; - var t = getTypeOfSymbol(p); - if (t.flags & 2097152 /* ContainsWideningType */) { - if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); - } - errorReported = true; - } - } - } - return errorReported; - } - function reportImplicitAnyError(declaration, type) { - var typeAsString = typeToString(getWidenedType(type)); - var diagnostic; - switch (declaration.kind) { - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; - break; - case 146 /* Parameter */: - diagnostic = declaration.dotDotDotToken ? - ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : - ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; - break; - case 176 /* BindingElement */: - diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; - break; - case 228 /* FunctionDeclaration */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - if (!declaration.name) { - error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); - return; - } - diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; - break; - default: - diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; - } - error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); - } - function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { - // Report implicit any error within type if possible, otherwise report error on declaration - if (!reportWideningErrorsInType(type)) { - reportImplicitAnyError(declaration, type); - } - } - } - function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { - callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); - } - } - function createInferenceContext(signature, inferUnionTypes, useAnyForNoInferences) { - var inferences = ts.map(signature.typeParameters, createTypeInferencesObject); - return { - signature: signature, - inferUnionTypes: inferUnionTypes, - inferences: inferences, - inferredTypes: new Array(signature.typeParameters.length), - useAnyForNoInferences: useAnyForNoInferences - }; - } - function createTypeInferencesObject() { - return { - primary: undefined, - secondary: undefined, - topLevel: true, - isFixed: false, - }; - } - // Return true if the given type could possibly reference a type parameter for which - // we perform type inference (i.e. a type parameter of a generic function). We cache - // results for union and intersection types for performance reasons. - function couldContainTypeVariables(type) { - var objectFlags = getObjectFlags(type); - return !!(type.flags & 540672 /* TypeVariable */ || - objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || - objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || - objectFlags & 32 /* Mapped */ || - type.flags & 196608 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); - } - function couldUnionOrIntersectionContainTypeVariables(type) { - if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); - } - return type.couldContainTypeVariables; - } - function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 196608 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); - } - // Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct - // an object type with the same set of properties as the source type, where the type of each - // property is computed by inferring from the source property type to X for the type - // variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for). - function inferTypeForHomomorphicMappedType(source, target) { - var properties = getPropertiesOfType(source); - var indexInfo = getIndexInfoOfType(source, 0 /* String */); - if (properties.length === 0 && !indexInfo) { - return undefined; - } - var typeVariable = getIndexedAccessType(getConstraintTypeFromMappedType(target).type, getTypeParameterFromMappedType(target)); - var typeVariableArray = [typeVariable]; - var typeInferences = createTypeInferencesObject(); - var typeInferencesArray = [typeInferences]; - var templateType = getTemplateTypeFromMappedType(target); - var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; - 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)); - if (!inferredPropType) { - return undefined; - } - var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.name); - inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0; - inferredProp.declarations = prop.declarations; - inferredProp.type = inferredPropType; - members.set(prop.name, inferredProp); - } - if (indexInfo) { - var inferredIndexType = inferTargetType(indexInfo.type); - if (!inferredIndexType) { - return undefined; - } - indexInfo = createIndexInfo(inferredIndexType, readonlyMask && indexInfo.isReadonly); - } - return createAnonymousType(undefined, members, emptyArray, emptyArray, indexInfo, undefined); - function inferTargetType(sourceType) { - typeInferences.primary = undefined; - typeInferences.secondary = undefined; - inferTypes(typeVariableArray, typeInferencesArray, sourceType, templateType); - var inferences = typeInferences.primary || typeInferences.secondary; - return inferences && getUnionType(inferences, /*subtypeReduction*/ true); - } - } - function inferTypesWithContext(context, originalSource, originalTarget) { - inferTypes(context.signature.typeParameters, context.inferences, originalSource, originalTarget); - } - function inferTypes(typeVariables, typeInferences, originalSource, originalTarget) { - var symbolStack; - var visited; - var inferiority = 0; - inferFromTypes(originalSource, originalTarget); - function inferFromTypes(source, target) { - if (!couldContainTypeVariables(target)) { - return; - } - if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) { - // Source and target are types originating in the same generic type alias declaration. - // Simply infer from source type arguments to target type arguments. - var sourceTypes = source.aliasTypeArguments; - var targetTypes = target.aliasTypeArguments; - for (var i = 0; i < sourceTypes.length; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - return; - } - 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. - if (source === target) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - inferFromTypes(t, t); - } - return; - } - // Find each source constituent type that has an identically matching target constituent - // type, and for each such type infer from the type to itself. When inferring from a - // type to itself we effectively find all type parameter occurrences within that type - // and infer themselves as their type arguments. We have special handling for numeric - // and string literals because the number and string types are not represented as unions - // of all their possible values. - var matchingTypes = void 0; - for (var _b = 0, _c = source.types; _b < _c.length; _b++) { - var t = _c[_b]; - if (typeIdenticalToSomeType(t, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t); - inferFromTypes(t, t); - } - else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { - var b = getBaseTypeOfLiteralType(t); - if (typeIdenticalToSomeType(b, target.types)) { - (matchingTypes || (matchingTypes = [])).push(t, b); - } - } - } - // Next, to improve the quality of inferences, reduce the source and target types by - // removing the identically matched constituents. For example, when inferring from - // 'string | string[]' to 'string | T' we reduce the types to 'string[]' and 'T'. - if (matchingTypes) { - source = removeTypesFromUnionOrIntersection(source, matchingTypes); - target = removeTypesFromUnionOrIntersection(target, matchingTypes); - } - } - if (target.flags & 540672 /* TypeVariable */) { - // If target is a type parameter, make an inference, unless the source type contains - // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). - // Because the anyFunctionType is internal, it should not be exposed to the user by adding - // it as an inference candidate. Hopefully, a better candidate will come along that does - // not contain anyFunctionType when we come back to this argument for its second round - // of inference. - if (source.flags & 8388608 /* ContainsAnyFunctionType */) { - return; - } - for (var i = 0; i < typeVariables.length; i++) { - if (target === typeVariables[i]) { - var inferences = typeInferences[i]; - if (!inferences.isFixed) { - // Any inferences that are made to a type parameter in a union type are inferior - // to inferences made to a flat (non-union) type. This is because if we infer to - // T | string[], we really don't know if we should be inferring to T or not (because - // the correct constituent on the target side could be string[]). Therefore, we put - // such inferior inferences into a secondary bucket, and only use them if the primary - // bucket is empty. - var candidates = inferiority ? - inferences.secondary || (inferences.secondary = []) : - inferences.primary || (inferences.primary = []); - if (!ts.contains(candidates, source)) { - candidates.push(source); - } - if (target.flags & 16384 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { - inferences.topLevel = false; - } - } - return; - } - } - } - else if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && source.target === target.target) { - // If source and target are references to the same generic type, infer from type arguments - var sourceTypes = source.typeArguments || emptyArray; - var targetTypes = target.typeArguments || emptyArray; - var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; - for (var i = 0; i < count; i++) { - inferFromTypes(sourceTypes[i], targetTypes[i]); - } - } - else if (target.flags & 196608 /* UnionOrIntersection */) { - var targetTypes = target.types; - var typeVariableCount = 0; - var typeVariable = void 0; - // First infer to each type in union or intersection that isn't a type variable - for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { - var t = targetTypes_3[_d]; - if (t.flags & 540672 /* TypeVariable */ && ts.contains(typeVariables, t)) { - typeVariable = t; - typeVariableCount++; - } - else { - inferFromTypes(source, t); - } - } - // Next, if target containings a single naked type variable, make a secondary inference to that type - // variable. This gives meaningful results for union types in co-variant positions and intersection - // types in contra-variant positions (such as callback parameters). - if (typeVariableCount === 1) { - inferiority++; - inferFromTypes(source, typeVariable); - inferiority--; - } - } - else if (source.flags & 196608 /* UnionOrIntersection */) { - // Source is a union or intersection type, infer from each constituent type - var sourceTypes = source.types; - for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { - var sourceType = sourceTypes_3[_e]; - inferFromTypes(sourceType, target); - } - } - else { - source = getApparentType(source); - if (source.flags & 32768 /* Object */) { - var key = source.id + "," + target.id; - if (visited && visited.get(key)) { - return; - } - (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); - } - } - } - } - function inferFromObjectTypes(source, target) { - if (getObjectFlags(target) & 32 /* Mapped */) { - var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 262144 /* Index */) { - // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, - // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source - // type and then make a secondary inference from that type to T. We make a secondary inference - // such that direct inferences to T get priority over inferences to Partial, for example. - var index = ts.indexOf(typeVariables, constraintType.type); - if (index >= 0 && !typeInferences[index].isFixed) { - var inferredType = inferTypeForHomomorphicMappedType(source, target); - if (inferredType) { - inferiority++; - inferFromTypes(inferredType, typeVariables[index]); - inferiority--; - } - } - return; - } - if (constraintType.flags & 16384 /* TypeParameter */) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. - inferFromTypes(getIndexType(source), constraintType); - inferFromTypes(getUnionType(ts.map(getPropertiesOfType(source), getTypeOfSymbol)), getTemplateTypeFromMappedType(target)); - return; - } - } - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target); - } - function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfObjectType(source, targetProp.name); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); - } - } - } - function inferFromSignatures(source, target, kind) { - var sourceSignatures = getSignaturesOfType(source, kind); - var targetSignatures = getSignaturesOfType(target, kind); - var sourceLen = sourceSignatures.length; - var targetLen = targetSignatures.length; - var len = sourceLen < targetLen ? sourceLen : targetLen; - for (var i = 0; i < len; i++) { - inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); - } - } - function inferFromParameterTypes(source, target) { - return inferFromTypes(source, target); - } - function inferFromSignature(source, target) { - forEachMatchingParameterType(source, target, inferFromParameterTypes); - if (source.typePredicate && target.typePredicate && source.typePredicate.kind === target.typePredicate.kind) { - inferFromTypes(source.typePredicate.type, target.typePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } - } - function inferFromIndexTypes(source, target) { - var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); - if (targetStringIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) || - getImplicitIndexTypeOfType(source, 0 /* String */); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetStringIndexType); - } - } - var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */); - if (targetNumberIndexType) { - var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) || - getIndexTypeOfType(source, 0 /* String */) || - getImplicitIndexTypeOfType(source, 1 /* Number */); - if (sourceIndexType) { - inferFromTypes(sourceIndexType, targetNumberIndexType); - } - } - } - } - function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - /** - * Return a new union or intersection type computed by removing a given set of types - * from a given union or intersection type. - */ - function removeTypesFromUnionOrIntersection(type, typesToRemove) { - var reducedTypes = []; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!typeIdenticalToSomeType(t, typesToRemove)) { - reducedTypes.push(t); - } - } - return type.flags & 65536 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); - } - function getInferenceCandidates(context, index) { - var inferences = context.inferences[index]; - return inferences.primary || inferences.secondary || emptyArray; - } - function hasPrimitiveConstraint(type) { - var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 8190 /* Primitive */ | 262144 /* Index */); - } - function getInferredType(context, index) { - var inferredType = context.inferredTypes[index]; - var inferenceSucceeded; - if (!inferredType) { - var inferences = getInferenceCandidates(context, index); - if (inferences.length) { - // We widen inferred literal types if - // all inferences were made to top-level ocurrences of the type parameter, and - // the type parameter has no constraint or its constraint includes no primitive or literal types, and - // the type parameter was fixed during inference or does not occur at top-level in the return type. - var signature = context.signature; - var widenLiteralTypes = context.inferences[index].topLevel && - !hasPrimitiveConstraint(signature.typeParameters[index]) && - (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - var baseInferences = widenLiteralTypes ? ts.sameMap(inferences, getWidenedLiteralType) : inferences; - // Infer widened union or supertype, or the unknown type for no common supertype - var unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; - } - else { - // Infer either the default or the empty object type when no inferences were - // made. It is important to remember that in this case, inference still - // succeeds, meaning there is no error for not having inference candidates. An - // inference error only occurs when there are *conflicting* candidates, i.e. - // candidates with no common supertype. - var defaultType = getDefaultFromTypeParameter(context.signature.typeParameters[index]); - if (defaultType) { - // Instantiate the default type. Any forward reference to a type - // parameter should be instantiated to the empty object type. - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), getInferenceMapper(context))); - } - else { - inferredType = context.useAnyForNoInferences ? anyType : emptyObjectType; - } - inferenceSucceeded = true; - } - context.inferredTypes[index] = inferredType; - // Only do the constraint check if inference succeeded (to prevent cascading errors) - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, getInferenceMapper(context)); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - context.inferredTypes[index] = inferredType = instantiatedConstraint; - } - } - } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). - // It might be that inference has already failed on a later type parameter on a previous call to inferTypeArguments. - // So if this failure is on preceding type parameter, this type parameter is the new failure index. - context.failedTypeParameterIndex = index; - } - } - return inferredType; - } - function getInferredTypes(context) { - for (var i = 0; i < context.inferredTypes.length; i++) { - getInferredType(context, i); - } - return context.inferredTypes; - } - // EXPRESSION TYPE CHECKING - 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, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; - } - return links.resolvedSymbol; - } - function isInTypeQuery(node) { - // TypeScript 1.0 spec (April 2014): 3.6.3 - // A type query consists of the keyword typeof followed by an expression. - // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 162 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 143 /* QualifiedName */ ? false : "quit"; }); - } - // 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. 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 ? (isApparentTypePosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 99 /* ThisKeyword */) { - return "0"; - } - if (node.kind === 179 /* PropertyAccessExpression */) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + node.name.text; - } - return undefined; - } - function getLeftmostIdentifierOrThis(node) { - switch (node.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - return node; - case 179 /* PropertyAccessExpression */: - return getLeftmostIdentifierOrThis(node.expression); - } - return undefined; - } - function isMatchingReference(source, target) { - switch (source.kind) { - case 71 /* Identifier */: - return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 226 /* VariableDeclaration */ || target.kind === 176 /* BindingElement */) && - getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); - case 99 /* ThisKeyword */: - return target.kind === 99 /* ThisKeyword */; - case 97 /* SuperKeyword */: - return target.kind === 97 /* SuperKeyword */; - case 179 /* PropertyAccessExpression */: - return target.kind === 179 /* PropertyAccessExpression */ && - source.name.text === target.name.text && - isMatchingReference(source.expression, target.expression); - } - return false; - } - function containsMatchingReference(source, target) { - while (source.kind === 179 /* PropertyAccessExpression */) { - source = source.expression; - if (isMatchingReference(source, target)) { - return true; - } - } - return false; - } - // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared - // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property - // a possible discriminant if its type differs in the constituents of containing union type, and if every - // choice is a unit type or a union of unit types. - function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 179 /* PropertyAccessExpression */ && - containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.text); - } - function getDeclaredTypeOfReference(expr) { - if (expr.kind === 71 /* Identifier */) { - return getTypeOfSymbol(getResolvedSymbol(expr)); - } - if (expr.kind === 179 /* PropertyAccessExpression */) { - var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.text); - } - return undefined; - } - function isDiscriminantProperty(type, name) { - if (type && type.flags & 65536 /* Union */) { - var prop = getUnionOrIntersectionProperty(type, name); - if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { - if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); - } - return prop.isDiscriminantProperty; - } - } - return false; - } - function isOrContainsMatchingReference(source, target) { - return isMatchingReference(source, target) || containsMatchingReference(source, target); - } - function hasMatchingArgument(callExpression, reference) { - if (callExpression.arguments) { - for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isOrContainsMatchingReference(reference, argument)) { - return true; - } - } - } - if (callExpression.expression.kind === 179 /* PropertyAccessExpression */ && - isOrContainsMatchingReference(reference, callExpression.expression.expression)) { - return true; - } - return false; - } - function getFlowNodeId(flow) { - if (!flow.id) { - flow.id = nextFlowId; - nextFlowId++; - } - return flow.id; - } - function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 65536 /* Union */)) { - return isTypeAssignableTo(source, target); - } - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isTypeAssignableTo(t, target)) { - return true; - } - } - return false; - } - // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable. - // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean, - // we remove type string. - function getAssignmentReducedType(declaredType, assignedType) { - if (declaredType !== assignedType) { - if (assignedType.flags & 8192 /* Never */) { - return assignedType; - } - var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 8192 /* Never */)) { - return reducedType; - } - } - return declaredType; - } - function getTypeFactsOfTypes(types) { - var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; - result |= getTypeFacts(t); - } - return result; - } - function isFunctionObjectType(type) { - // We do a quick check for a "bind" property before performing the more expensive subtype - // check. This gives us a quicker out in the common case where an object type is not a function. - var resolved = resolveStructuredTypeMembers(type); - return !!(resolved.callSignatures.length || resolved.constructSignatures.length || - resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); - } - function getTypeFacts(type) { - var flags = type.flags; - if (flags & 2 /* String */) { - return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; - } - if (flags & 32 /* StringLiteral */) { - var isEmpty = type.value === ""; - return strictNullChecks ? - 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 */) { - var isZero = type.value === 0; - return strictNullChecks ? - isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : - isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; - } - if (flags & 8 /* Boolean */) { - return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; - } - if (flags & 136 /* BooleanLike */) { - return strictNullChecks ? - type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : - type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; - } - if (flags & 32768 /* Object */) { - return isFunctionObjectType(type) ? - strictNullChecks ? 6164448 /* FunctionStrictFacts */ : 8376288 /* FunctionFacts */ : - strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; - } - if (flags & (1024 /* Void */ | 2048 /* Undefined */)) { - return 2457472 /* UndefinedFacts */; - } - if (flags & 4096 /* Null */) { - return 2340752 /* NullFacts */; - } - if (flags & 512 /* ESSymbol */) { - return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; - } - if (flags & 16777216 /* NonPrimitive */) { - return strictNullChecks ? 6166480 /* ObjectStrictFacts */ : 8378320 /* ObjectFacts */; - } - if (flags & 540672 /* TypeVariable */) { - return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); - } - if (flags & 196608 /* UnionOrIntersection */) { - return getTypeFactsOfTypes(type.types); - } - return 8388607 /* All */; - } - function getTypeWithFacts(type, include) { - return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); - } - function getTypeWithDefault(type, defaultExpression) { - if (defaultExpression) { - var defaultType = getTypeOfExpression(defaultExpression); - return getUnionType([getTypeWithFacts(type, 131072 /* NEUndefined */), defaultType]); - } - return type; - } - function getTypeOfDestructuredProperty(type, name) { - var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || - isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || - getIndexTypeOfType(type, 0 /* String */) || - unknownType; - } - function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || - checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || - unknownType; - } - function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType); - } - function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 177 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 261 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); - return isDestructuringDefaultAssignment ? - getTypeWithDefault(getAssignedType(node), node.right) : - getTypeOfExpression(node.right); - } - function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 194 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 216 /* ForOfStatement */ && parent.parent.initializer === parent; - } - function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); - } - function getAssignedTypeOfSpreadExpression(node) { - return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); - } - function getAssignedTypeOfPropertyAssignment(node) { - return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name); - } - function getAssignedTypeOfShorthandPropertyAssignment(node) { - return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer); - } - function getAssignedType(node) { - var parent = node.parent; - switch (parent.kind) { - case 215 /* ForInStatement */: - return stringType; - case 216 /* ForOfStatement */: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 194 /* BinaryExpression */: - return getAssignedTypeOfBinaryExpression(parent); - case 188 /* DeleteExpression */: - return undefinedType; - case 177 /* ArrayLiteralExpression */: - return getAssignedTypeOfArrayLiteralElement(parent, node); - case 198 /* SpreadElement */: - return getAssignedTypeOfSpreadExpression(parent); - case 261 /* PropertyAssignment */: - return getAssignedTypeOfPropertyAssignment(parent); - case 262 /* ShorthandPropertyAssignment */: - return getAssignedTypeOfShorthandPropertyAssignment(parent); - } - return unknownType; - } - function getInitialTypeOfBindingElement(node) { - var pattern = node.parent; - var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 174 /* ObjectBindingPattern */ ? - getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : - !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : - getTypeOfDestructuredSpreadExpression(parentType); - return getTypeWithDefault(type, node.initializer); - } - function getTypeOfInitializer(node) { - // Return the cached type if one is available. If the type of the variable was inferred - // from its initializer, we'll already have cached the type. Otherwise we compute it now - // without caching such that transient types are reflected. - var links = getNodeLinks(node); - return links.resolvedType || getTypeOfExpression(node); - } - function getInitialTypeOfVariableDeclaration(node) { - if (node.initializer) { - return getTypeOfInitializer(node.initializer); - } - if (node.parent.parent.kind === 215 /* ForInStatement */) { - return stringType; - } - if (node.parent.parent.kind === 216 /* ForOfStatement */) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; - } - return unknownType; - } - function getInitialType(node) { - return node.kind === 226 /* VariableDeclaration */ ? - getInitialTypeOfVariableDeclaration(node) : - getInitialTypeOfBindingElement(node); - } - function getInitialOrAssignedType(node) { - return node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */ ? - getInitialType(node) : - getAssignedType(node); - } - function isEmptyArrayAssignment(node) { - return node.kind === 226 /* VariableDeclaration */ && node.initializer && - isEmptyArrayLiteral(node.initializer) || - node.kind !== 176 /* BindingElement */ && node.parent.kind === 194 /* BinaryExpression */ && - isEmptyArrayLiteral(node.parent.right); - } - function getReferenceCandidate(node) { - switch (node.kind) { - case 185 /* ParenthesizedExpression */: - return getReferenceCandidate(node.expression); - case 194 /* BinaryExpression */: - switch (node.operatorToken.kind) { - case 58 /* EqualsToken */: - return getReferenceCandidate(node.left); - case 26 /* CommaToken */: - return getReferenceCandidate(node.right); - } - } - return node; - } - function getReferenceRoot(node) { - var parent = node.parent; - return parent.kind === 185 /* ParenthesizedExpression */ || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 194 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? - getReferenceRoot(parent) : node; - } - function getTypeOfSwitchClause(clause) { - if (clause.kind === 257 /* CaseClause */) { - var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); - return isUnitType(caseType) ? caseType : undefined; - } - return neverType; - } - function getSwitchClauseTypes(switchStatement) { - var links = getNodeLinks(switchStatement); - if (!links.switchTypes) { - // If all case clauses specify expressions that have unit types, we return an array - // of those unit types. Otherwise we return an empty array. - var types = ts.map(switchStatement.caseBlock.clauses, getTypeOfSwitchClause); - links.switchTypes = !ts.contains(types, undefined) ? types : emptyArray; - } - return links.switchTypes; - } - function eachTypeContainedIn(source, types) { - return source.flags & 65536 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); - } - function isTypeSubsetOf(source, target) { - return source === target || target.flags & 65536 /* Union */ && isTypeSubsetOfUnion(source, target); - } - function isTypeSubsetOfUnion(source, target) { - if (source.flags & 65536 /* Union */) { - for (var _i = 0, _a = source.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (!containsType(target.types, t)) { - return false; - } - } - return true; - } - if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { - return true; - } - return containsType(target.types, source); - } - function forEachType(type, f) { - return type.flags & 65536 /* Union */ ? ts.forEach(type.types, f) : f(type); - } - function filterType(type, f) { - if (type.flags & 65536 /* Union */) { - var types = type.types; - var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); - } - return f(type) ? type : neverType; - } - // Apply a mapping function to a type and return the resulting type. If the source type - // is a union type, the mapping function is applied to each constituent type and a union - // of the resulting types is returned. - function mapType(type, mapper) { - if (!(type.flags & 65536 /* Union */)) { - return mapper(type); - } - var types = type.types; - var mappedType; - var mappedTypes; - 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) { - mappedType = t; - } - else if (!mappedTypes) { - mappedTypes = [mappedType, t]; - } - else { - mappedTypes.push(t); - } - } - } - return mappedTypes ? getUnionType(mappedTypes) : mappedType; - } - function extractTypesOfKind(type, kind) { - return filterType(type, function (t) { return (t.flags & kind) !== 0; }); - } - // Return a new type in which occurrences of the string and number primitive types in - // typeWithPrimitives have been replaced with occurrences of string literals and numeric - // literals in typeWithLiterals, respectively. - function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { - return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : - t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : - t; - }); - } - return typeWithPrimitives; - } - function isIncomplete(flowType) { - return flowType.flags === 0; - } - function getTypeFromFlowType(flowType) { - return flowType.flags === 0 ? flowType.type : flowType; - } - function createFlowType(type, incomplete) { - return incomplete ? { flags: 0, type: type } : type; - } - // An evolving array type tracks the element types that have so far been seen in an - // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving - // array types are ultimately converted into manifest array types (using getFinalArrayType) - // and never escape the getFlowTypeOfReference function. - function createEvolvingArrayType(elementType) { - var result = createObjectType(256 /* EvolvingArray */); - result.elementType = elementType; - return result; - } - function getEvolvingArrayType(elementType) { - return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); - } - // When adding evolving array element types we do not perform subtype reduction. Instead, - // we defer subtype reduction until the evolving array type is finalized into a manifest - // array type. - function addEvolvingArrayElementType(evolvingArrayType, node) { - var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)); - return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); - } - function createFinalArrayType(elementType) { - return elementType.flags & 8192 /* Never */ ? - autoArrayType : - createArrayType(elementType.flags & 65536 /* Union */ ? - getUnionType(elementType.types, /*subtypeReduction*/ true) : - elementType); - } - // We perform subtype reduction upon obtaining the final array type from an evolving array type. - function getFinalArrayType(evolvingArrayType) { - return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); - } - function finalizeEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type; - } - function getElementTypeOfEvolvingArrayType(type) { - return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType; - } - function isEvolvingArrayTypeList(types) { - var hasEvolvingArrayType = false; - 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; - } - hasEvolvingArrayType = true; - } - } - return hasEvolvingArrayType; - } - // At flow control branch or loop junctions, if the type along every antecedent code path - // is an evolving array type, we construct a combined evolving array type. Otherwise we - // finalize all evolving array types. - function getUnionOrEvolvingArrayType(types, subtypeReduction) { - return isEvolvingArrayTypeList(types) ? - getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) : - getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction); - } - // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or - // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. - function isEvolvingArrayOperationTarget(node) { - var root = getReferenceRoot(node); - var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 179 /* PropertyAccessExpression */ && (parent.name.text === "length" || - parent.parent.kind === 181 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 180 /* ElementAccessExpression */ && - parent.expression === root && - parent.parent.kind === 194 /* BinaryExpression */ && - parent.parent.operatorToken.kind === 58 /* EqualsToken */ && - parent.parent.left === parent && - !ts.isAssignmentTarget(parent.parent) && - isTypeAnyOrAllConstituentTypesHaveKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */ | 2048 /* Undefined */); - return isLengthPushOrUnshift || isElementAssignment; - } - function maybeTypePredicateCall(node) { - var links = getNodeLinks(node); - if (links.maybeTypePredicate === undefined) { - links.maybeTypePredicate = getMaybeTypePredicate(node); - } - return links.maybeTypePredicate; - } - function getMaybeTypePredicate(node) { - if (node.expression.kind !== 97 /* SuperKeyword */) { - var funcType = checkNonNullExpression(node.expression); - if (funcType !== silentNeverType) { - var apparentType = getApparentType(funcType); - if (apparentType !== unknownType) { - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - return !!ts.forEach(callSignatures, function (sig) { return sig.typePredicate; }); - } - } - } - return false; - } - function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) { - if (initialType === void 0) { initialType = declaredType; } - var key; - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 17810175 /* Narrowable */)) { - return declaredType; - } - var visitedFlowStart = visitedFlowCount; - var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); - visitedFlowCount = visitedFlowStart; - // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, - // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations - // on empty arrays are possible without implicit any errors and new element types can be inferred without - // type mismatch errors. - var resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent.kind === 203 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 8192 /* Never */) { - return declaredType; - } - return resultType; - function getTypeAtFlowNode(flow) { - while (true) { - if (flow.flags & 1024 /* Shared */) { - // We cache results of flow type resolution for shared nodes that were previously visited in - // the same getFlowTypeOfReference invocation. A node is considered shared when it is the - // antecedent of more than one node. - for (var i = visitedFlowStart; i < visitedFlowCount; i++) { - if (visitedFlowNodes[i] === flow) { - return visitedFlowTypes[i]; - } - } - } - var type = void 0; - if (flow.flags & 4096 /* AfterFinally */) { - // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement - flow.locked = true; - type = getTypeAtFlowNode(flow.antecedent); - flow.locked = false; - } - else if (flow.flags & 2048 /* PreFinally */) { - // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel - // so here just redirect to antecedent - flow = flow.antecedent; - continue; - } - else if (flow.flags & 16 /* Assignment */) { - type = getTypeAtFlowAssignment(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 96 /* Condition */) { - type = getTypeAtFlowCondition(flow); - } - else if (flow.flags & 128 /* SwitchClause */) { - type = getTypeAtSwitchClause(flow); - } - else if (flow.flags & 12 /* Label */) { - if (flow.antecedents.length === 1) { - flow = flow.antecedents[0]; - continue; - } - type = flow.flags & 4 /* BranchLabel */ ? - getTypeAtFlowBranchLabel(flow) : - getTypeAtFlowLoopLabel(flow); - } - else if (flow.flags & 256 /* ArrayMutation */) { - type = getTypeAtFlowArrayMutation(flow); - if (!type) { - flow = flow.antecedent; - continue; - } - } - else if (flow.flags & 2 /* Start */) { - // Check if we should continue with the control flow of the containing function. - var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 179 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { - flow = container.flowNode; - continue; - } - // At the top of the flow we have the initial type. - type = initialType; - } - else { - // Unreachable code errors are reported in the binding phase. Here we - // simply return the non-auto declared type to reduce follow-on errors. - type = convertAutoToAny(declaredType); - } - if (flow.flags & 1024 /* Shared */) { - // Record visited node and the associated type in the cache. - visitedFlowNodes[visitedFlowCount] = flow; - visitedFlowTypes[visitedFlowCount] = type; - visitedFlowCount++; - } - return type; - } - } - function getTypeAtFlowAssignment(flow) { - var node = flow.node; - // Assignments only narrow the computed type if the declared type is a union type. Thus, we - // only need to evaluate the assigned type if the declared type is a union type. - if (isMatchingReference(reference, node)) { - if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) { - var flowType = getTypeAtFlowNode(flow.antecedent); - return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); - } - if (declaredType === autoType || declaredType === autoArrayType) { - if (isEmptyArrayAssignment(node)) { - return getEvolvingArrayType(neverType); - } - var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); - return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; - } - if (declaredType.flags & 65536 /* Union */) { - return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); - } - return declaredType; - } - // We didn't have a direct match. However, if the reference is a dotted name, this - // may be an assignment to a left hand part of the reference. For example, for a - // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case, - // return the declared type. - if (containsMatchingReference(reference, node)) { - return declaredType; - } - // Assignment doesn't affect reference - return undefined; - } - function getTypeAtFlowArrayMutation(flow) { - var node = flow.node; - var expr = node.kind === 181 /* CallExpression */ ? - node.expression.expression : - node.left.expression; - if (isMatchingReference(reference, getReferenceCandidate(expr))) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (getObjectFlags(type) & 256 /* EvolvingArray */) { - var evolvedType_1 = type; - if (node.kind === 181 /* CallExpression */) { - for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { - var arg = _a[_i]; - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); - } - } - else { - var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, 84 /* NumberLike */ | 2048 /* Undefined */)) { - evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); - } - } - return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType)); - } - return flowType; - } - return undefined; - } - function getTypeAtFlowCondition(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - if (type.flags & 8192 /* Never */) { - return flowType; - } - // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by switching to the silent never type which - // doesn't report errors when operators are applied to it. Note that this is the - // *only* place a silent never type is ever generated. - var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0; - var nonEvolvingType = finalizeEvolvingArrayType(type); - var narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); - if (narrowedType === nonEvolvingType) { - return flowType; - } - var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 8192 /* Never */ ? silentNeverType : narrowedType; - return createFlowType(resultType, incomplete); - } - function getTypeAtSwitchClause(flow) { - var flowType = getTypeAtFlowNode(flow.antecedent); - var type = getTypeFromFlowType(flowType); - var expr = flow.switchStatement.expression; - if (isMatchingReference(reference, expr)) { - type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); - } - else if (isMatchingReferenceDiscriminant(expr)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } - return createFlowType(type, isIncomplete(flowType)); - } - function getTypeAtFlowBranchLabel(flow) { - var antecedentTypes = []; - var subtypeReduction = false; - var seenIncomplete = false; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { - // if flow correspond to branch from pre-try to finally and this branch is locked - this means that - // we initially have started following the flow outside the finally block. - // in this case we should ignore this branch. - continue; - } - var flowType = getTypeAtFlowNode(antecedent); - var type = getTypeFromFlowType(flowType); - // If the type at a particular antecedent path is the declared type and the - // reference is known to always be assigned (i.e. when declared and initial types - // are the same), there is no reason to process more antecedents since the only - // possible outcome is subtypes that will be removed in the final union type anyway. - if (type === declaredType && declaredType === initialType) { - return type; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - if (isIncomplete(flowType)) { - seenIncomplete = true; - } - } - return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); - } - function getTypeAtFlowLoopLabel(flow) { - // If we have previously computed the control flow type for the reference at - // this flow loop junction, return the cached type. - var id = getFlowNodeId(flow); - var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap()); - if (!key) { - key = getFlowCacheKey(reference); - } - var cached = cache.get(key); - if (cached) { - return cached; - } - // If this flow loop junction and reference are already being processed, return - // the union of the types computed for each branch so far, marked as incomplete. - // It is possible to see an empty array in cases where loops are nested and the - // back edge of the outer loop reaches an inner loop that is already being analyzed. - // In such cases we restart the analysis of the inner loop, which will then see - // a non-empty in-process array for the outer loop and eventually terminate because - // the first antecedent of a loop junction is always the non-looping control flow - // path that leads to the top. - for (var i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); - } - } - // Add the flow loop junction and reference to the in-process stack and analyze - // each antecedent code path. - var antecedentTypes = []; - var subtypeReduction = false; - var firstAntecedentType; - flowLoopNodes[flowLoopCount] = flow; - flowLoopKeys[flowLoopCount] = key; - flowLoopTypes[flowLoopCount] = antecedentTypes; - for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { - var antecedent = _a[_i]; - flowLoopCount++; - var flowType = getTypeAtFlowNode(antecedent); - flowLoopCount--; - if (!firstAntecedentType) { - firstAntecedentType = flowType; - } - var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis - // was restarted and completed by checkExpressionCached. We can simply pick up - // the resulting type and bail out. - var cached_1 = cache.get(key); - if (cached_1) { - return cached_1; - } - if (!ts.contains(antecedentTypes, type)) { - antecedentTypes.push(type); - } - // If an antecedent type is not a subset of the declared type, we need to perform - // subtype reduction. This happens when a "foreign" type is injected into the control - // flow using the instanceof operator or a user defined type predicate. - if (!isTypeSubsetOf(type, declaredType)) { - subtypeReduction = true; - } - // If the type at a particular antecedent path is the declared type there is no - // reason to process more antecedents since the only possible outcome is subtypes - // that will be removed in the final union type anyway. - if (type === declaredType) { - break; - } - } - // The result is incomplete if the first antecedent (the non-looping control flow path) - // is incomplete. - var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); - if (isIncomplete(firstAntecedentType)) { - return createFlowType(result, /*incomplete*/ true); - } - cache.set(key, result); - return result; - } - function isMatchingReferenceDiscriminant(expr) { - return expr.kind === 179 /* PropertyAccessExpression */ && - declaredType.flags & 65536 /* Union */ && - isMatchingReference(reference, expr.expression) && - isDiscriminantProperty(declaredType, expr.name.text); - } - function narrowTypeByDiscriminant(type, propAccess, narrowType) { - var propName = propAccess.name.text; - var propType = getTypeOfPropertyOfType(type, propName); - var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); - } - function narrowTypeByTruthiness(type, expr, assumeTrue) { - if (isMatchingReference(reference, expr)) { - return getTypeWithFacts(type, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); - } - if (isMatchingReferenceDiscriminant(expr)) { - return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 1048576 /* Truthy */ : 2097152 /* Falsy */); }); - } - if (containsMatchingReferenceDiscriminant(reference, expr)) { - return declaredType; - } - return type; - } - function narrowTypeByBinaryExpression(type, expr, assumeTrue) { - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return narrowTypeByTruthiness(type, expr.left, assumeTrue); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - var operator_1 = expr.operatorToken.kind; - var left_1 = getReferenceCandidate(expr.left); - var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 189 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); - } - if (right_1.kind === 189 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { - return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); - } - if (isMatchingReference(reference, left_1)) { - return narrowTypeByEquality(type, operator_1, right_1, assumeTrue); - } - if (isMatchingReference(reference, right_1)) { - return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); - } - if (isMatchingReferenceDiscriminant(left_1)) { - return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); - } - if (isMatchingReferenceDiscriminant(right_1)) { - return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); }); - } - if (containsMatchingReferenceDiscriminant(reference, left_1) || containsMatchingReferenceDiscriminant(reference, right_1)) { - return declaredType; - } - break; - case 93 /* InstanceOfKeyword */: - return narrowTypeByInstanceof(type, expr, assumeTrue); - case 26 /* CommaToken */: - return narrowType(type, expr.right, assumeTrue); - } - return type; - } - function narrowTypeByEquality(type, operator, value, assumeTrue) { - if (type.flags & 1 /* Any */) { - return type; - } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } - var valueType = getTypeOfExpression(value); - if (valueType.flags & 6144 /* Nullable */) { - if (!strictNullChecks) { - return type; - } - var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; - var facts = doubleEquals ? - assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 95 /* NullKeyword */ ? - assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : - assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; - return getTypeWithFacts(type, facts); - } - if (type.flags & 16810497 /* NotUnionOrUnit */) { - return type; - } - if (assumeTrue) { - var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); - } - if (isUnitType(valueType)) { - var regularType_1 = getRegularTypeOfLiteralType(valueType); - return filterType(type, function (t) { return getRegularTypeOfLiteralType(t) !== regularType_1; }); - } - return type; - } - function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { - // We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands - var target = getReferenceCandidate(typeOfExpr.expression); - if (!isMatchingReference(reference, target)) { - // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, target)) { - return declaredType; - } - return type; - } - if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } - if (assumeTrue && !(type.flags & 65536 /* Union */)) { - // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed - // to one of the primitive types. - var targetType = typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } - } - } - } - var facts = assumeTrue ? - typeofEQFacts.get(literal.text) || 64 /* TypeofEQHostObject */ : - typeofNEFacts.get(literal.text) || 8192 /* TypeofNEHostObject */; - return getTypeWithFacts(type, facts); - } - function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { - // We only narrow if all case expressions specify values with unit types - var switchTypes = getSwitchClauseTypes(switchStatement); - if (!switchTypes.length) { - return type; - } - var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); - var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); - var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : - replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); - if (!hasDefaultClause) { - return caseType; - } - var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 8192 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); - } - function narrowTypeByInstanceof(type, expr, assumeTrue) { - var left = getReferenceCandidate(expr.left); - if (!isMatchingReference(reference, left)) { - // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the - // narrowed type of 'y' to its declared type. - if (containsMatchingReference(reference, left)) { - return declaredType; - } - return type; - } - // Check that right operand is a function type with a prototype property - var rightType = getTypeOfExpression(expr.right); - if (!isTypeSubtypeOf(rightType, globalFunctionType)) { - return type; - } - var targetType; - var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (prototypeProperty) { - // Target type is type of the prototype property - var prototypePropertyType = getTypeOfSymbol(prototypeProperty); - if (!isTypeAny(prototypePropertyType)) { - targetType = prototypePropertyType; - } - } - // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) { - return type; - } - if (!targetType) { - // Target type is type of construct signature - var constructSignatures = void 0; - if (getObjectFlags(rightType) & 2 /* Interface */) { - constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; - } - else if (getObjectFlags(rightType) & 16 /* Anonymous */) { - constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); - } - if (constructSignatures && constructSignatures.length) { - targetType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); - } - } - if (targetType) { - return getNarrowedType(type, targetType, assumeTrue, isTypeInstanceOf); - } - return type; - } - function getNarrowedType(type, candidate, assumeTrue, isRelated) { - if (!assumeTrue) { - return filterType(type, function (t) { return !isRelated(t, candidate); }); - } - // If the current type is a union type, remove all constituents that couldn't be instances of - // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 65536 /* Union */) { - var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 8192 /* Never */)) { - return assignableType; - } - } - // If the candidate type is a subtype of the target type, narrow to the candidate type. - // Otherwise, if the target type is assignable to the candidate type, keep the target type. - // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate - // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the - // two types. - return isTypeSubtypeOf(candidate, type) ? candidate : - isTypeAssignableTo(type, candidate) ? type : - isTypeAssignableTo(candidate, type) ? candidate : - getIntersectionType([type, candidate]); - } - function narrowTypeByTypePredicate(type, callExpression, assumeTrue) { - if (!hasMatchingArgument(callExpression, reference) || !maybeTypePredicateCall(callExpression)) { - return type; - } - var signature = getResolvedSignature(callExpression); - var predicate = signature.typePredicate; - if (!predicate) { - return type; - } - // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; - if (predicateArgument) { - if (isMatchingReference(reference, predicateArgument)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, predicateArgument)) { - return declaredType; - } - } - } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 180 /* ElementAccessExpression */ || invokedExpression.kind === 179 /* PropertyAccessExpression */) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } - return type; - } - // Narrow the given type based on the given expression having the assumed boolean value. The returned type - // will be a subtype or the same type as the argument. - function narrowType(type, expr, assumeTrue) { - switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 179 /* PropertyAccessExpression */: - return narrowTypeByTruthiness(type, expr, assumeTrue); - case 181 /* CallExpression */: - return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 185 /* ParenthesizedExpression */: - return narrowType(type, expr.expression, assumeTrue); - case 194 /* BinaryExpression */: - return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 192 /* PrefixUnaryExpression */: - if (expr.operator === 51 /* ExclamationToken */) { - return narrowType(type, expr.operand, !assumeTrue); - } - break; - } - return type; - } - } - function getTypeOfSymbolAtLocation(symbol, location) { - // If we have an identifier or a property access at the given location, if the location is - // an dotted name expression, and if the location is not an assignment target, obtain the type - // of the expression (which will reflect control flow analysis). If the expression indeed - // resolved to the given symbol, return the narrowed type. - if (location.kind === 71 /* Identifier */) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { - location = location.parent; - } - if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { - var type = getTypeOfExpression(location); - if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { - return type; - } - } - } - // The location isn't a reference to the given symbol, meaning we're being asked - // a hypothetical question of what type the symbol would have if there was a reference - // to it at the given location. Since we have no control flow information for the - // hypothetical reference (control flow information is created and attached by the - // binder), we simply return the declared type of the symbol. - return getTypeOfSymbol(symbol); - } - function getControlFlowContainer(node) { - return ts.findAncestor(node.parent, function (node) { - return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 234 /* ModuleBlock */ || - node.kind === 265 /* SourceFile */ || - node.kind === 149 /* PropertyDeclaration */; - }); - } - // Check if a parameter is assigned anywhere within its declaring function. - function isParameterAssigned(symbol) { - var func = ts.getRootDeclaration(symbol.valueDeclaration).parent; - var links = getNodeLinks(func); - if (!(links.flags & 4194304 /* AssignmentsMarked */)) { - links.flags |= 4194304 /* AssignmentsMarked */; - if (!hasParentWithAssignmentsMarked(func)) { - markParameterAssignments(func); - } - } - return symbol.isAssigned || false; - } - function hasParentWithAssignmentsMarked(node) { - return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 4194304 /* AssignmentsMarked */); }); - } - function markParameterAssignments(node) { - if (node.kind === 71 /* Identifier */) { - if (ts.isAssignmentTarget(node)) { - var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 146 /* Parameter */) { - symbol.isAssigned = true; - } - } - } - else { - ts.forEachChild(node, markParameterAssignments); - } - } - function isConstVariable(symbol) { - return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; - } - /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ - function removeOptionalityFromDeclaredType(declaredType, declaration) { - var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 146 /* Parameter */ && - declaration.initializer && - getFalsyFlags(declaredType) & 2048 /* Undefined */ && - !(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) { - return unknownType; - } - // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. - // Although in down-level emit of arrow function, we emit it using function expression which means that - // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects - // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. - // To avoid that we will give an error to users if they use arguments objects in arrow function so that they - // can explicitly bound arguments objects - if (symbol === argumentsSymbol) { - var container = ts.getContainingFunction(node); - if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 187 /* ArrowFunction */) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); - } - else if (ts.hasModifier(container, 256 /* Async */)) { - error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method); - } - } - getNodeLinks(container).flags |= 8192 /* CaptureArguments */; - return getTypeOfSymbol(symbol); - } - if (symbol.flags & 8388608 /* Alias */ && !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) { - markAliasSymbolAsReferenced(symbol); - } - var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - if (localOrExportSymbol.flags & 32 /* Class */) { - var declaration_1 = localOrExportSymbol.valueDeclaration; - // Due to the emit for class decorators, any reference to the class from inside of the class body - // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind - // behavior of class names in ES6. - if (declaration_1.kind === 229 /* ClassDeclaration */ - && ts.nodeIsDecorated(declaration_1)) { - var container = ts.getContainingClass(node); - while (container !== undefined) { - if (container === declaration_1 && container.name !== node) { - getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; - break; - } - container = ts.getContainingClass(container); - } - } - else if (declaration_1.kind === 199 /* ClassExpression */) { - // When we emit a class expression with static members that contain a reference - // to the constructor in the initializer, we will need to substitute that - // binding with an alias as the class name is not in scope. - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container !== undefined) { - if (container.parent === declaration_1) { - if (container.kind === 149 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { - getNodeLinks(declaration_1).flags |= 8388608 /* ClassWithConstructorReference */; - getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; - } - break; - } - container = ts.getThisContainer(container, /*includeArrowFunctions*/ false); - } - } - } - checkCollisionWithCapturedSuperVariable(node, node); - checkCollisionWithCapturedThisVariable(node, node); - checkCollisionWithCapturedNewTargetVariable(node, node); - checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); - var declaration = localOrExportSymbol.valueDeclaration; - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3 /* Variable */)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); - return unknownType; - } - if (isReadonlySymbol(localOrExportSymbol)) { - error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); - return unknownType; - } - } - // We only narrow variables and parameters occurring in a non-assignment position. For all other - // entities we simply return the declared type. - if (!(localOrExportSymbol.flags & 3 /* Variable */) || assignmentKind === 1 /* Definite */ || !declaration) { - return type; - } - // The declaration container is the innermost function that encloses the declaration of the variable - // or parameter. The flow container is the innermost function starting with which we analyze the control - // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 146 /* Parameter */; - var declarationContainer = getControlFlowContainer(declaration); - var flowContainer = getControlFlowContainer(node); - var isOuterVariable = flowContainer !== declarationContainer; - // When the control flow originates in a function expression or arrow function and we are referencing - // a const variable or parameter from an outer function, we extend the origin of the control flow - // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 186 /* FunctionExpression */ || - flowContainer.kind === 187 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && - (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { - flowContainer = getControlFlowContainer(flowContainer); - } - // We only look for uninitialized variables in strict null checking mode, and only when we can analyze - // the entire control flow graph from the variable's declaration (i.e. when the flow container and - // declaration container are the same). - var assumeInitialized = isParameter || isOuterVariable || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 246 /* ExportSpecifier */) || - ts.isInAmbientContext(declaration); - var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, ts.getRootDeclaration(declaration)) : type) : - type === autoType || type === autoArrayType ? undefinedType : - 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 - // control flow based type does include undefined. - if (type === autoType || type === autoArrayType) { - if (flowType === autoType || flowType === autoArrayType) { - if (noImplicitAny) { - 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); - } - } - else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { - error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - // Return the declared type to reduce follow-on errors - return type; - } - return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; - } - function isInsideFunction(node, threshold) { - return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); }); - } - function checkNestedBlockScopedBinding(node, symbol) { - if (languageVersion >= 2 /* ES2015 */ || - (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 260 /* CatchClause */) { - return; - } - // 1. walk from the use site up to the declaration and check - // if there is anything function like between declaration and use-site (is binding/class is captured in function). - // 2. walk from the declaration up to the boundary of lexical environment and check - // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - var usedInFunction = isInsideFunction(node.parent, container); - var current = container; - var containedInIterationStatement = false; - while (current && !ts.nodeStartsNewLexicalEnvironment(current)) { - if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) { - containedInIterationStatement = true; - break; - } - current = current.parent; - } - if (containedInIterationStatement) { - if (usedInFunction) { - // mark iteration statement as containing block-scoped binding captured in some function - getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */; - } - // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. - // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 214 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 227 /* VariableDeclarationList */).parent === container && - isAssignedInBodyOfForStatement(node, container)) { - getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; - } - // set 'declared inside loop' bit on the block-scoped binding - getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* BlockScopedBindingInLoop */; - } - if (usedInFunction) { - getNodeLinks(symbol.valueDeclaration).flags |= 131072 /* CapturedBlockScopedBinding */; - } - } - function isAssignedInBodyOfForStatement(node, container) { - // skip parenthesized nodes - var current = node; - while (current.parent.kind === 185 /* ParenthesizedExpression */) { - current = current.parent; - } - // check if node is used as LHS in some assignment expression - var isAssigned = false; - if (ts.isAssignmentTarget(current)) { - isAssigned = true; - } - else if ((current.parent.kind === 192 /* PrefixUnaryExpression */ || current.parent.kind === 193 /* PostfixUnaryExpression */)) { - var expr = current.parent; - isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; - } - if (!isAssigned) { - return false; - } - // at this point we know that node is the target of assignment - // now check that modification happens inside the statement part of the ForStatement - return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; }); - } - function captureLexicalThis(node, container) { - getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 149 /* PropertyDeclaration */ || container.kind === 152 /* Constructor */) { - var classNode = container.parent; - getNodeLinks(classNode).flags |= 4 /* CaptureThis */; - } - else { - getNodeLinks(container).flags |= 4 /* CaptureThis */; - } - } - function findFirstSuperCall(n) { - if (ts.isSuperCall(n)) { - return n; - } - else if (ts.isFunctionLike(n)) { - return undefined; - } - return ts.forEachChild(n, findFirstSuperCall); - } - /** - * Return a cached result if super-statement is already found. - * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor - * - * @param constructor constructor-function to look for super statement - */ - function getSuperCallInConstructor(constructor) { - var links = getNodeLinks(constructor); - // Only trying to find super-call if we haven't yet tried to find one. Once we try, we will record the result - if (links.hasSuperCall === undefined) { - links.superCall = findFirstSuperCall(constructor.body); - links.hasSuperCall = links.superCall ? true : false; - } - return links.superCall; - } - /** - * Check if the given class-declaration extends null then return true. - * Otherwise, return false - * @param classDecl a class declaration to check if it extends null - */ - function classDeclarationExtendsNull(classDecl) { - var classSymbol = getSymbolOfNode(classDecl); - var classInstanceType = getDeclaredTypeOfSymbol(classSymbol); - var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType); - return baseConstructorType === nullWideningType; - } - function checkThisBeforeSuper(node, container, diagnosticMessage) { - var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); - // If a containing class does not have extends clause or the class extends null - // skip checking whether super statement is called before "this" accessing. - if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { - var superCall = getSuperCallInConstructor(container); - // We should give an error in the following cases: - // - No super-call - // - "this" is accessing before super-call. - // i.e super(this) - // this.x; super(); - // We want to make sure that super-call is done before accessing "this" so that - // "this" is not accessed as a parameter of the super-call. - if (!superCall || superCall.end > node.pos) { - // In ES6, super inside constructor of class-declaration has to precede "this" accessing - error(node, diagnosticMessage); - } - } - } - function checkThisExpression(node) { - // Stop at the first arrow function so that we can - // tell whether 'this' needs to be captured. - var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); - var needToCaptureLexicalThis = false; - if (container.kind === 152 /* Constructor */) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); - } - // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 187 /* ArrowFunction */) { - container = ts.getThisContainer(container, /* includeArrowFunctions */ false); - // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); - } - switch (container.kind) { - case 233 /* ModuleDeclaration */: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - break; - case 232 /* EnumDeclaration */: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - break; - case 152 /* Constructor */: - if (isInConstructorArgumentInitializer(node, container)) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - } - break; - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - if (ts.getModifierFlags(container) & 32 /* Static */) { - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); - // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks - } - break; - case 144 /* ComputedPropertyName */: - error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); - break; - } - if (needToCaptureLexicalThis) { - captureLexicalThis(node, container); - } - if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { - // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. Check if it's the RHS - // of a x.prototype.y = function [name]() { .... } - if (container.kind === 186 /* FunctionExpression */ && - container.parent.kind === 194 /* BinaryExpression */ && - ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - var className = container.parent // x.prototype.y = f - .left // x.prototype.y - .expression // x.prototype - .expression; // x - var classSymbol = checkExpression(className).symbol; - if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) { - return getInferredClassType(classSymbol); - } - } - var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container); - if (thisType) { - return thisType; - } - } - if (ts.isClassLike(container.parent)) { - var symbol = getSymbolOfNode(container.parent); - var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; - return getFlowTypeOfReference(node, type); - } - if (ts.isInJavaScriptFile(node)) { - var type = getTypeForThisExpressionFromJSDoc(container); - if (type && type !== unknownType) { - return type; - } - } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; - } - function getTypeForThisExpressionFromJSDoc(node) { - var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 279 /* JSDocFunctionType */) { - var jsDocFunctionType = jsdocType; - if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].type.kind === 282 /* JSDocThisType */) { - return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); - } - } - } - function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 146 /* Parameter */; }); - } - function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 181 /* CallExpression */ && node.parent.expression === node; - var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); - var needToCaptureLexicalThis = false; - // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting - if (!isCallExpression) { - while (container && container.kind === 187 /* ArrowFunction */) { - container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); - needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; - } - } - var canUseSuperExpression = isLegalUsageOfSuperExpression(container); - var nodeCheckFlag = 0; - if (!canUseSuperExpression) { - // issue more specific error if super is used in computed property name - // class A { foo() { return "1" }} - // class B { - // [super.foo()]() {} - // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 144 /* ComputedPropertyName */; }); - if (current && current.kind === 144 /* ComputedPropertyName */) { - error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); - } - else if (isCallExpression) { - error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); - } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); - } - else { - error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); - } - return unknownType; - } - if (!isCallExpression && container.kind === 152 /* Constructor */) { - checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class); - } - if ((ts.getModifierFlags(container) & 32 /* Static */) || isCallExpression) { - nodeCheckFlag = 512 /* SuperStatic */; - } - else { - nodeCheckFlag = 256 /* SuperInstance */; - } - getNodeLinks(node).flags |= nodeCheckFlag; - // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference. - // This is due to the fact that we emit the body of an async function inside of a generator function. As generator - // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper - // uses an arrow function, which is permitted to reference `super`. - // - // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property - // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value - // of a property or indexed access, either as part of an assignment expression or destructuring assignment. - // - // The simplest case is reading a value, in which case we will emit something like the following: - // - // // ts - // ... - // async asyncMethod() { - // let x = await super.asyncMethod(); - // return x; - // } - // ... - // - // // js - // ... - // asyncMethod() { - // const _super = name => super[name]; - // return __awaiter(this, arguments, Promise, function *() { - // let x = yield _super("asyncMethod").call(this); - // return x; - // }); - // } - // ... - // - // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases - // are legal in ES6, but also likely less frequent, we emit the same more complex helper for both scenarios: - // - // // ts - // ... - // async asyncMethod(ar: Promise) { - // [super.a, super.b] = await ar; - // } - // ... - // - // // js - // ... - // asyncMethod(ar) { - // const _super = (function (geti, seti) { - // const cache = Object.create(null); - // return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - // })(name => super[name], (name, value) => super[name] = value); - // return __awaiter(this, arguments, Promise, function *() { - // [_super("a").value, _super("b").value] = yield ar; - // }); - // } - // ... - // - // This helper creates an object with a "value" property that wraps the `super` property or indexed access for both get and set. - // This is required for destructuring assignments, as a call expression cannot be used as the target of a destructuring assignment - // while a property access can. - if (container.kind === 151 /* MethodDeclaration */ && ts.getModifierFlags(container) & 256 /* Async */) { - if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { - getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; - } - else { - getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */; - } - } - if (needToCaptureLexicalThis) { - // call expressions are allowed only in constructors so they should always capture correct 'this' - // super property access expressions can also appear in arrow functions - - // in this case they should also use correct lexical this - captureLexicalThis(node.parent, container); - } - if (container.parent.kind === 178 /* ObjectLiteralExpression */) { - if (languageVersion < 2 /* ES2015 */) { - error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); - return unknownType; - } - else { - // for object literal assume that type of 'super' is 'any' - return anyType; - } - } - // at this point the only legal case for parent is ClassLikeDeclaration - var classLikeDeclaration = container.parent; - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); - var baseClassType = classType && getBaseTypes(classType)[0]; - if (!baseClassType) { - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { - error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - } - return unknownType; - } - if (container.kind === 152 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { - // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) - error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); - return unknownType; - } - return nodeCheckFlag === 512 /* SuperStatic */ - ? getBaseConstructorTypeOfClass(classType) - : getTypeWithThisArgument(baseClassType, classType.thisType); - function isLegalUsageOfSuperExpression(container) { - if (!container) { - return false; - } - if (isCallExpression) { - // TS 1.0 SPEC (April 2014): 4.8.1 - // Super calls are only permitted in constructors of derived classes - return container.kind === 152 /* Constructor */; - } - else { - // TS 1.0 SPEC (April 2014) - // 'super' property access is allowed - // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance - // - In a static member function or static member accessor - // topmost container must be something that is directly nested in the class declaration\object literal expression - if (ts.isClassLike(container.parent) || container.parent.kind === 178 /* ObjectLiteralExpression */) { - if (ts.getModifierFlags(container) & 32 /* Static */) { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */; - } - else { - return container.kind === 151 /* MethodDeclaration */ || - container.kind === 150 /* MethodSignature */ || - container.kind === 153 /* GetAccessor */ || - container.kind === 154 /* SetAccessor */ || - container.kind === 149 /* PropertyDeclaration */ || - container.kind === 148 /* PropertySignature */ || - container.kind === 152 /* Constructor */; - } - } - } - return false; - } - } - function getContainingObjectLiteral(func) { - return (func.kind === 151 /* MethodDeclaration */ || - func.kind === 153 /* GetAccessor */ || - func.kind === 154 /* SetAccessor */) && func.parent.kind === 178 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 186 /* FunctionExpression */ && func.parent.kind === 261 /* PropertyAssignment */ ? func.parent.parent : - undefined; - } - function getThisTypeArgument(type) { - return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? type.typeArguments[0] : undefined; - } - function getThisTypeFromContextualType(type) { - return mapType(type, function (t) { - return t.flags & 131072 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); - }); - } - function getContextualThisParameterType(func) { - if (func.kind === 187 /* ArrowFunction */) { - return undefined; - } - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var thisParameter = contextualSignature.thisParameter; - if (thisParameter) { - return getTypeOfSymbol(thisParameter); - } - } - } - if (noImplicitThis) { - var containingLiteral = getContainingObjectLiteral(func); - if (containingLiteral) { - // We have an object literal method. Check if the containing object literal has a contextual type - // that includes a ThisType. If so, T is the contextual type for 'this'. We continue looking in - // any directly enclosing object literals. - var contextualType = getApparentTypeOfContextualType(containingLiteral); - var literal = containingLiteral; - var type = contextualType; - while (type) { - var thisType = getThisTypeFromContextualType(type); - if (thisType) { - return instantiateType(thisType, getContextualMapper(containingLiteral)); - } - if (literal.parent.kind !== 261 /* PropertyAssignment */) { - break; - } - literal = literal.parent.parent; - type = getApparentTypeOfContextualType(literal); - } - // There was no contextual ThisType for the containing object literal, so the contextual type - // for 'this' is the non-null form of the contextual type for the containing object literal or - // the type of the object literal itself. - return contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral); - } - // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the - // contextual type for 'this' is 'obj'. - if (func.parent.kind === 194 /* BinaryExpression */ && func.parent.operatorToken.kind === 58 /* EqualsToken */) { - var target = func.parent.left; - if (target.kind === 179 /* PropertyAccessExpression */ || target.kind === 180 /* ElementAccessExpression */) { - return checkExpressionCached(target.expression); - } - } - } - return undefined; - } - // Return contextual type of parameter or undefined if no contextual type is available - function getContextuallyTypedParameterType(parameter) { - var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; - } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; - } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } - } - } - return undefined; - } - // In a variable, parameter or property declaration with a type annotation, - // the contextual type of an initializer expression is the type of the variable, parameter or property. - // Otherwise, in a parameter declaration of a contextually typed function expression, - // the contextual type of an initializer expression is the contextual type of the parameter. - // Otherwise, in a variable or parameter declaration with a binding pattern name, - // the contextual type of an initializer expression is the type implied by the binding pattern. - // Otherwise, in a binding pattern inside a variable or parameter declaration, - // the contextual type of an initializer expression is the type annotation of the containing declaration, if present. - function getContextualTypeForInitializerExpression(node) { - var declaration = node.parent; - if (node === declaration.initializer) { - if (declaration.type) { - return getTypeFromTypeNode(declaration.type); - } - if (declaration.kind === 146 /* Parameter */) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); - } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 176 /* BindingElement */ && - parentDeclaration.type && - !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); - } - } - } - } - return undefined; - } - function getContextualTypeForReturnExpression(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { - return undefined; - } - var contextualReturnType = getContextualReturnType(func); - return functionFlags & 2 /* Async */ - ? contextualReturnType && getAwaitedTypeOfPromise(contextualReturnType) // Async function - : contextualReturnType; // Regular function - } - return undefined; - } - function getContextualTypeForYieldOperand(node) { - var func = ts.getContainingFunction(node); - if (func) { - var functionFlags = ts.getFunctionFlags(func); - var contextualReturnType = getContextualReturnType(func); - if (contextualReturnType) { - return node.asteriskToken - ? contextualReturnType - : getIteratedTypeOfGenerator(contextualReturnType, (functionFlags & 2 /* Async */) !== 0); - } - } - return undefined; - } - function isInParameterInitializerBeforeContainingFunction(node) { - while (node.parent && !ts.isFunctionLike(node.parent)) { - if (node.parent.kind === 146 /* Parameter */ && node.parent.initializer === node) { - return true; - } - node = node.parent; - } - return false; - } - function getContextualReturnType(functionDecl) { - // If the containing function has a return type annotation, is a constructor, or is a get accessor whose - // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.type || - functionDecl.kind === 152 /* Constructor */ || - functionDecl.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(functionDecl.symbol, 154 /* SetAccessor */))) { - return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); - } - // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature - // and that call signature is non-generic, return statements are contextually typed by the return type of the signature - var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); - if (signature) { - return getReturnTypeOfSignature(signature); - } - return undefined; - } - // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); - if (argIndex >= 0) { - var signature = getResolvedOrAnySignature(callTarget); - return getTypeAtPosition(signature, argIndex); - } - return undefined; - } - function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 183 /* TaggedTemplateExpression */) { - return getContextualTypeForArgument(template.parent, substitutionExpression); - } - return undefined; - } - function getContextualTypeForBinaryOperand(node) { - var binaryExpression = node.parent; - var operator = binaryExpression.operatorToken.kind; - if (operator >= 58 /* FirstAssignment */ && operator <= 70 /* LastAssignment */) { - // Don't do this for special property assignments to avoid circularity - if (ts.getSpecialPropertyAssignmentKind(binaryExpression) !== 0 /* None */) { - return undefined; - } - // In an assignment expression, the right operand is contextually typed by the type of the left operand. - if (node === binaryExpression.right) { - return getTypeOfExpression(binaryExpression.left); - } - } - else if (operator === 54 /* BarBarToken */) { - // When an || expression has a contextual type, the operands are contextually typed by that type. When an || - // expression has no contextual type, the right operand is contextually typed by the type of the left operand. - var type = getContextualType(binaryExpression); - if (!type && node === binaryExpression.right) { - type = getTypeOfExpression(binaryExpression.left); - } - return type; - } - else if (operator === 53 /* AmpersandAmpersandToken */ || operator === 26 /* CommaToken */) { - if (node === binaryExpression.right) { - return getContextualType(binaryExpression); - } - } - return undefined; - } - function getTypeOfPropertyOfContextualType(type, name) { - return mapType(type, function (t) { - var prop = t.flags & 229376 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; - }); - } - function getIndexTypeOfContextualType(type, kind) { - return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }); - } - // Return true if the given contextual type is a tuple-like type - function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 65536 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); - } - // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of - // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one - // exists. Otherwise, it is the type of the string index signature in T, if one exists. - function getContextualTypeForObjectLiteralMethod(node) { - ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return undefined; - } - return getContextualTypeForObjectLiteralElement(node); - } - function getContextualTypeForObjectLiteralElement(element) { - var objectLiteral = element.parent; - var type = getApparentTypeOfContextualType(objectLiteral); - if (type) { - if (!ts.hasDynamicName(element)) { - // For a (non-symbol) computed property, there is no reason to look up the name - // in the type. It will just be "__computed", which does not appear in any - // SymbolTable. - var symbolName = getSymbolOfNode(element).name; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); - if (propertyType) { - return propertyType; - } - } - return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || - getIndexTypeOfContextualType(type, 0 /* String */); - } - return undefined; - } - // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is - // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature, - // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated - // type of T. - function getContextualTypeForElementExpression(node) { - var arrayLiteral = node.parent; - var type = getApparentTypeOfContextualType(arrayLiteral); - if (type) { - var index = ts.indexOf(arrayLiteral.elements, node); - return getTypeOfPropertyOfContextualType(type, "" + index) - || getIndexTypeOfContextualType(type, 1 /* Number */) - || getIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false); - } - return undefined; - } - // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. - function getContextualTypeForConditionalOperand(node) { - var conditional = node.parent; - return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; - } - function getContextualTypeForJsxExpression(node) { - // JSX expression can appear in two position : JSX Element's children or JSX attribute - var jsxAttributes = ts.isJsxAttributeLike(node.parent) ? - node.parent.parent : - node.parent.openingElement.attributes; // node.parent is JsxElement - // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type - // which is a type of the parameter of the signature we are trying out. - // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(jsxAttributes); - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - if (ts.isJsxAttribute(node.parent)) { - // JSX expression is in JSX attribute - return getTypeOfPropertyOfType(attributesType, node.parent.name.text); - } - else if (node.parent.kind === 249 /* JsxElement */) { - // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - return jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfType(attributesType, jsxChildrenPropertyName) : anyType; - } - else { - // JSX expression is in JSX spread attribute - return attributesType; - } - } - function getContextualTypeForJsxAttribute(attribute) { - // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type - // which is a type of the parameter of the signature we are trying out. - // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName - var attributesType = getContextualType(attribute.parent); - if (ts.isJsxAttribute(attribute)) { - if (!attributesType || isTypeAny(attributesType)) { - return undefined; - } - return getTypeOfPropertyOfType(attributesType, attribute.name.text); - } - else { - return attributesType; - } - } - // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily - // be "pushed" onto a node using the contextualType property. - function getApparentTypeOfContextualType(node) { - var type = getContextualType(node); - return type && getApparentType(type); - } - /** - * Woah! Do you really want to use this function? - * - * Unless you're trying to get the *non-apparent* type for a - * value-literal type or you're authoring relevant portions of this algorithm, - * you probably meant to use 'getApparentTypeOfContextualType'. - * Otherwise this may not be very useful. - * - * In cases where you *are* working on this function, you should understand - * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'. - * - * - Use 'getContextualType' when you are simply going to propagate the result to the expression. - * - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type. - * - * @param node the expression whose contextual type will be returned. - * @returns the contextual type of an expression. - */ - function getContextualType(node) { - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return undefined; - } - if (node.contextualType) { - return node.contextualType; - } - var parent = node.parent; - switch (parent.kind) { - case 226 /* VariableDeclaration */: - case 146 /* Parameter */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 176 /* BindingElement */: - return getContextualTypeForInitializerExpression(node); - case 187 /* ArrowFunction */: - case 219 /* ReturnStatement */: - return getContextualTypeForReturnExpression(node); - case 197 /* YieldExpression */: - return getContextualTypeForYieldOperand(parent); - case 181 /* CallExpression */: - case 182 /* NewExpression */: - return getContextualTypeForArgument(parent, node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - return getTypeFromTypeNode(parent.type); - case 194 /* BinaryExpression */: - return getContextualTypeForBinaryOperand(node); - case 261 /* PropertyAssignment */: - case 262 /* ShorthandPropertyAssignment */: - return getContextualTypeForObjectLiteralElement(parent); - case 263 /* SpreadAssignment */: - return getApparentTypeOfContextualType(parent.parent); - case 177 /* ArrayLiteralExpression */: - return getContextualTypeForElementExpression(node); - case 195 /* ConditionalExpression */: - return getContextualTypeForConditionalOperand(node); - case 205 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 196 /* TemplateExpression */); - return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 185 /* ParenthesizedExpression */: - return getContextualType(parent); - case 256 /* JsxExpression */: - return getContextualTypeForJsxExpression(parent); - case 253 /* JsxAttribute */: - case 255 /* JsxSpreadAttribute */: - return getContextualTypeForJsxAttribute(parent); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - return getAttributesTypeFromJsxOpeningLikeElement(parent); - } - return undefined; - } - function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; - } - // If the given type is an object or union type, if that type has a single signature, and if - // that signature is non-generic, return the signature. Otherwise return undefined. - function getNonGenericSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); - if (signatures.length === 1) { - var signature = signatures[0]; - if (!signature.typeParameters && !isAritySmaller(signature, node)) { - return signature; - } - } - } - /** If the contextual signature has fewer parameters than the function expression, do not use it */ - function isAritySmaller(signature, target) { - var targetParameterCount = 0; - for (; targetParameterCount < target.parameters.length; targetParameterCount++) { - var param = target.parameters[targetParameterCount]; - if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) { - break; - } - } - if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { - targetParameterCount--; - } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; - } - function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 186 /* FunctionExpression */ || node.kind === 187 /* ArrowFunction */; - } - function getContextualSignatureForFunctionLikeDeclaration(node) { - // Only function expressions, arrow functions, and object literal methods are contextually typed. - return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node) - ? getContextualSignature(node) - : undefined; - } - function getContextualTypeForFunctionLikeDeclaration(node) { - return ts.isObjectLiteralMethod(node) ? - getContextualTypeForObjectLiteralMethod(node) : - getApparentTypeOfContextualType(node); - } - // Return the contextual signature for a given expression node. A contextual type provides a - // contextual signature if it has a single call signature and if that call signature is non-generic. - // If the contextual type is a union type, get the signature from each type possible and if they are - // all identical ignoring their return type, the result is same signature but with return type as - // union type of return types from these signatures - function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); - if (!type) { - return undefined; - } - if (!(type.flags & 65536 /* Union */)) { - return getNonGenericSignature(type, node); - } - var signatureList; - var types = type.types; - 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) { - // This signature will contribute to contextual union signature - signatureList = [signature]; - } - else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) { - // Signatures aren't identical, do not use - return undefined; - } - else { - // Use this signature for contextual union signature - signatureList.push(signature); - } - } - } - // Result is union of signatures collected (return type is union of return types of this signature set) - var result; - if (signatureList) { - result = cloneSignature(signatureList[0]); - // Clear resolved return type we possibly got from cloneSignature - result.resolvedReturnType = undefined; - result.unionSignatures = signatureList; - } - return result; - } - function checkSpreadExpression(node, checkMode) { - if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 1536 /* SpreadIncludes */); - } - var arrayOrIterableType = checkExpression(node.expression, checkMode); - return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterable*/ false); - } - function hasDefaultValue(node) { - return (node.kind === 176 /* BindingElement */ && !!node.initializer) || - (node.kind === 194 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); - } - function checkArrayLiteral(node, checkMode) { - var elements = node.elements; - var hasSpreadElement = false; - var elementTypes = []; - var inDestructuringPattern = ts.isAssignmentTarget(node); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var e = elements_1[_i]; - if (inDestructuringPattern && e.kind === 198 /* SpreadElement */) { - // Given the following situation: - // var c: {}; - // [...c] = ["", 0]; - // - // c is represented in the tree as a spread element in an array literal. - // But c really functions as a rest element, and its purpose is to provide - // a contextual type for the right hand side of the assignment. Therefore, - // instead of calling checkExpression on "...c", which will give an error - // if c is not iterable/array-like, we need to act as if we are trying to - // get the contextual element type from it. So we do something similar to - // getContextualTypeForElementExpression, which will crucially not error - // if there is no index type / iterated type. - var restArrayType = checkExpression(e.expression, checkMode); - var restElementType = getIndexTypeOfType(restArrayType, 1 /* Number */) || - getIteratedTypeOrElementType(restArrayType, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterable*/ false, /*checkAssignability*/ false); - if (restElementType) { - elementTypes.push(restElementType); - } - } - else { - var type = checkExpressionForMutableLocation(e, checkMode); - elementTypes.push(type); - } - hasSpreadElement = hasSpreadElement || e.kind === 198 /* SpreadElement */; - } - if (!hasSpreadElement) { - // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such - // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); - type.pattern = node; - return type; - } - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - var pattern = contextualType.pattern; - // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting - // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 175 /* ArrayBindingPattern */ || pattern.kind === 177 /* ArrayLiteralExpression */)) { - var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { - elementTypes.push(contextualType.typeArguments[i]); - } - else { - if (patternElement.kind !== 200 /* OmittedExpression */) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - elementTypes.push(unknownType); - } - } - } - if (elementTypes.length) { - return createTupleType(elementTypes); - } - } - } - return createArrayType(elementTypes.length ? - getUnionType(elementTypes, /*subtypeReduction*/ true) : - strictNullChecks ? neverType : undefinedWideningType); - } - function isNumericName(name) { - return name.kind === 144 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); - } - 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), 84 /* NumberLike */); - } - function isTypeAnyOrAllConstituentTypesHaveKind(type, kind) { - return isTypeAny(type) || isTypeOfKind(type, kind); - } - function isInfinityOrNaNString(name) { - return name === "Infinity" || name === "-Infinity" || name === "NaN"; - } - function isNumericLiteralName(name) { - // The intent of numeric names is that - // - they are names with text in a numeric form, and that - // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', - // acquired by applying the abstract 'ToNumber' operation on the name's text. - // - // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. - // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. - // - // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' - // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. - // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names - // because their 'ToString' representation is not equal to their original text. - // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. - // - // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. - // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. - // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. - // - // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. - // This is desired behavior, because when indexing with them as numeric entities, you are indexing - // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. - return (+name).toString() === name; - } - function checkComputedPropertyName(node) { - var links = getNodeLinks(node.expression); - if (!links.resolvedType) { - 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, 84 /* NumberLike */ | 262178 /* StringLike */ | 512 /* ESSymbol */)) { - error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); - } - else { - checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true); - } - } - return links.resolvedType; - } - function getObjectLiteralIndexInfo(propertyNodes, offset, properties, kind) { - var propTypes = []; - for (var i = 0; i < properties.length; i++) { - if (kind === 0 /* String */ || isNumericName(propertyNodes[i + offset].name)) { - propTypes.push(getTypeOfSymbol(properties[i])); - } - } - var unionType = propTypes.length ? getUnionType(propTypes, /*subtypeReduction*/ true) : undefinedType; - return createIndexInfo(unionType, /*isReadonly*/ false); - } - function checkObjectLiteral(node, checkMode) { - var inDestructuringPattern = ts.isAssignmentTarget(node); - // Grammar checking - checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - var propertiesTable = ts.createMap(); - var propertiesArray = []; - var spread = emptyObjectType; - var propagatedFlags = 0; - var contextualType = getApparentTypeOfContextualType(node); - var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 174 /* ObjectBindingPattern */ || contextualType.pattern.kind === 178 /* ObjectLiteralExpression */); - var isJSObjectLiteral = !contextualType && ts.isInJavaScriptFile(node); - var typeFlags = 0; - var patternWithComputedProperties = false; - var hasComputedStringProperty = false; - var hasComputedNumberProperty = false; - var offset = 0; - for (var i = 0; i < node.properties.length; i++) { - var memberDecl = node.properties[i]; - var member = memberDecl.symbol; - if (memberDecl.kind === 261 /* PropertyAssignment */ || - memberDecl.kind === 262 /* ShorthandPropertyAssignment */ || - ts.isObjectLiteralMethod(memberDecl)) { - var type = void 0; - if (memberDecl.kind === 261 /* PropertyAssignment */) { - type = checkPropertyAssignment(memberDecl, checkMode); - } - else if (memberDecl.kind === 151 /* MethodDeclaration */) { - type = checkObjectLiteralMethod(memberDecl, checkMode); - } - else { - ts.Debug.assert(memberDecl.kind === 262 /* ShorthandPropertyAssignment */); - type = checkExpressionForMutableLocation(memberDecl.name, checkMode); - } - typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | member.flags, member.name); - if (inDestructuringPattern) { - // If object literal is an assignment pattern and if the assignment pattern specifies a default value - // for the property, make the property optional. - var isOptional = (memberDecl.kind === 261 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 262 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); - if (isOptional) { - prop.flags |= 67108864 /* Optional */; - } - if (ts.hasDynamicName(memberDecl)) { - patternWithComputedProperties = true; - } - } - else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { - // If object literal is contextually typed by the implied type of a binding pattern, and if the - // binding pattern specifies a default value for the property, make the property optional. - var impliedProp = getPropertyOfType(contextualType, member.name); - if (impliedProp) { - prop.flags |= impliedProp.flags & 67108864 /* Optional */; - } - else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { - error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); - } - } - prop.declarations = member.declarations; - prop.parent = member.parent; - if (member.valueDeclaration) { - prop.valueDeclaration = member.valueDeclaration; - } - prop.type = type; - prop.target = member; - member = prop; - } - else if (memberDecl.kind === 263 /* SpreadAssignment */) { - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(memberDecl, 2 /* Assign */); - } - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - propertiesArray = []; - propertiesTable = ts.createMap(); - hasComputedStringProperty = false; - hasComputedNumberProperty = false; - typeFlags = 0; - } - var type = checkExpression(memberDecl.expression); - if (!isValidSpreadType(type)) { - error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return unknownType; - } - spread = getSpreadType(spread, type); - offset = i + 1; - continue; - } - else { - // TypeScript 1.0 spec (April 2014) - // A get accessor declaration is processed in the same manner as - // an ordinary function declaration(section 6.1) with no parameters. - // A set accessor declaration is processed in the same manner - // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 153 /* GetAccessor */ || memberDecl.kind === 154 /* SetAccessor */); - checkNodeDeferred(memberDecl); - } - if (ts.hasDynamicName(memberDecl)) { - if (isNumericName(memberDecl.name)) { - hasComputedNumberProperty = true; - } - else { - hasComputedStringProperty = true; - } - } - else { - propertiesTable.set(member.name, member); - } - propertiesArray.push(member); - } - // If object literal is contextually typed by the implied type of a binding pattern, augment the result - // type with those properties for which the binding pattern specifies a default value. - if (contextualTypeHasPattern) { - for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 67108864 /* Optional */)) { - error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - propertiesTable.set(prop.name, prop); - propertiesArray.push(prop); - } - } - } - if (spread !== emptyObjectType) { - if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType()); - } - if (spread.flags & 32768 /* Object */) { - // only set the symbol and flags if this is a (fresh) object type - spread.flags |= propagatedFlags; - spread.flags |= 1048576 /* FreshLiteral */; - spread.objectFlags |= 128 /* ObjectLiteral */; - spread.symbol = node.symbol; - } - return spread; - } - return createObjectLiteralType(); - function createObjectLiteralType() { - var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; - var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; - var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 14680064 /* PropagatingFlags */); - result.objectFlags |= 128 /* ObjectLiteral */; - if (patternWithComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } - if (inDestructuringPattern) { - result.pattern = node; - } - if (!(result.flags & 6144 /* Nullable */)) { - propagatedFlags |= (result.flags & 14680064 /* PropagatingFlags */); - } - return result; - } - } - function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 4096 /* Null */ | 2048 /* Undefined */ | 16777216 /* NonPrimitive */) || - type.flags & 32768 /* Object */ && !isGenericMappedType(type) || - type.flags & 196608 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); - } - function checkJsxSelfClosingElement(node) { - checkJsxOpeningLikeElement(node); - return getJsxGlobalElementType() || anyType; - } - function checkJsxElement(node) { - // Check attributes - checkJsxOpeningLikeElement(node.openingElement); - // Perform resolution on the closing tag so that rename/go to definition/etc work - if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { - getIntrinsicTagSymbol(node.closingElement); - } - else { - checkExpression(node.closingElement.tagName); - } - return getJsxGlobalElementType() || anyType; - } - /** - * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers - */ - function isUnhyphenatedJsxName(name) { - // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers - return name.indexOf("-") < 0; - } - /** - * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name - */ - function isJsxIntrinsicIdentifier(tagName) { - // TODO (yuisu): comment - if (tagName.kind === 179 /* PropertyAccessExpression */ || tagName.kind === 99 /* ThisKeyword */) { - return false; - } - else { - return ts.isIntrinsicJsxName(tagName.text); - } - } - /** - * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element. - * - * @param openingLikeElement a JSX opening-like element - * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable - * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property. - * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral, - * which also calls getSpreadType. - */ - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, filter, checkMode) { - var attributes = openingLikeElement.attributes; - 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; - if (ts.isJsxAttribute(attributeDecl)) { - var exprType = attributeDecl.initializer ? - checkExpression(attributeDecl.initializer, checkMode) : - trueType; // is sugar for - var attributeSymbol = createSymbol(4 /* Property */ | 134217728 /* Transient */ | member.flags, member.name); - attributeSymbol.declarations = member.declarations; - attributeSymbol.parent = member.parent; - if (member.valueDeclaration) { - attributeSymbol.valueDeclaration = member.valueDeclaration; - } - attributeSymbol.type = exprType; - 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 */); - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - var exprType = checkExpression(attributeDecl.expression); - if (isTypeAny(exprType)) { - hasSpreadAnyType = true; - } - if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType); - } - else { - typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; - } - } - } - if (!hasSpreadAnyType) { - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - } - attributesArray = getPropertiesOfType(spread); - } - 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 _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 */) { - if (!child.containsOnlyWhiteSpaces) { - childrenTypes.push(stringType); - } - } - else { - childrenTypes.push(checkExpression(child, checkMode)); - } - } - 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 - var childrenPropSymbol = createSymbol(4 /* Property */ | 134217728 /* Transient */, jsxChildrenPropertyName); - childrenPropSymbol.type = childrenTypes.length === 1 ? - childrenTypes[0] : - createArrayType(getUnionType(childrenTypes, /*subtypeReduction*/ false)); - attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); - } - } - 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 - * @param attributesTable a symbol table of attributes property - */ - function createJsxAttributesType(symbol, attributesTable) { - var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; - result.objectFlags |= 128 /* ObjectLiteral */; - return result; - } - } - /** - * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element. - * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used) - * @param node a JSXAttributes to be resolved of its type - */ - function checkJsxAttributes(node, checkMode) { - return createJsxAttributesTypeFromAttributesProperty(node.parent, /*filter*/ undefined, checkMode); - } - function getJsxType(name) { - var jsxType = jsxTypes.get(name); - if (jsxType === undefined) { - jsxTypes.set(name, jsxType = getExportedTypeFromNamespace(JsxNames.JSX, name) || unknownType); - } - return jsxType; - } - /** - * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic - * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic - * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement). - * May also return unknownSymbol if both of these lookups fail. - */ - function getIntrinsicTagSymbol(node) { - var links = getNodeLinks(node); - if (!links.resolvedSymbol) { - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - // Property case - var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.text); - if (intrinsicProp) { - links.jsxFlags |= 1 /* IntrinsicNamedElement */; - return links.resolvedSymbol = intrinsicProp; - } - // Intrinsic string indexer case - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - links.jsxFlags |= 2 /* IntrinsicIndexedElement */; - return links.resolvedSymbol = intrinsicElementsType.symbol; - } - // Wasn't found - error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, node.tagName.text, "JSX." + JsxNames.IntrinsicElements); - return links.resolvedSymbol = unknownSymbol; - } - else { - if (noImplicitAny) { - error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, JsxNames.IntrinsicElements); - } - return links.resolvedSymbol = unknownSymbol; - } - } - return links.resolvedSymbol; - } - /** - * Given a JSX element that is a class element, finds the Element Instance Type. If the - * element is not a class element, or the class element type cannot be determined, returns 'undefined'. - * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). - */ - function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 65536 /* Union */)); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); - return unknownType; - } - } - 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. - * Get a single property from that container if existed. Report an error if there are more than one property. - * - * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer - * if other string is given or the container doesn't exist, return undefined. - */ - function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { - // JSX - var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); - // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol] - var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 793064 /* Type */); - // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type] - var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym); - // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute - var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType); - if (propertiesOfJsxElementAttribPropInterface) { - // Element Attributes has zero properties, so the element attributes type will be the class instance type - if (propertiesOfJsxElementAttribPropInterface.length === 0) { - return ""; - } - else if (propertiesOfJsxElementAttribPropInterface.length === 1) { - return propertiesOfJsxElementAttribPropInterface[0].name; - } - else if (propertiesOfJsxElementAttribPropInterface.length > 1) { - // More than one property on ElementAttributesProperty is an error - error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, nameOfAttribPropContainer); - } - } - return undefined; - } - /// e.g. "props" for React.d.ts, - /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all - /// non-intrinsic elements' attributes type is 'any'), - /// or '' if it has 0 properties (which means every - /// non-intrinsic elements' attributes type is the element instance type) - function getJsxElementPropertiesName() { - if (!_hasComputedJsxElementPropertiesName) { - _hasComputedJsxElementPropertiesName = true; - _jsxElementPropertiesName = getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer); - } - return _jsxElementPropertiesName; - } - function getJsxElementChildrenPropertyname() { - if (!_hasComputedJsxElementChildrenPropertyName) { - _hasComputedJsxElementChildrenPropertyName = true; - _jsxElementChildrenPropertyName = getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer); - } - 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. - * This function assumes that the caller handled other possible element type of the JSX element (e.g. stateful component) - * Unlike tryGetAllJsxStatelessFunctionAttributesType, this function is a default behavior of type-checkers. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature here because we have already resolve the type of JSX Element. - var callSignature = getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, /*candidatesOutArray*/ undefined); - 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); - if (intrinsicAttributes !== unknownType) { - paramType = intersectTypes(intrinsicAttributes, paramType); - } - return paramType; - } - } - } - } - return undefined; - } - /** - * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. - * Return all attributes type of resolved call signature including candidate signatures. - * This function assumes that the caller handled other possible element type of the JSX element. - * This function is a behavior used by language service when looking up completion in JSX element. - * @param openingLikeElement a JSX opening-like element to find attributes type - * @param elementType a type of the opening-like element. This elementType can't be an union type - * @param elemInstanceType an element instance type (the result of newing or invoking this tag) - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global - */ - function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { - // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type - var jsxStatelessElementType = getJsxGlobalStatelessElementType(); - if (jsxStatelessElementType) { - // We don't call getResolvedSignature because here we have already resolve the type of JSX Element. - var candidatesOutArray = []; - getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray); - var result = void 0; - var allMatchingAttributesType = void 0; - for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { - 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++) { - var attribute = _b[_a]; - if (ts.isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.text) && - !getPropertyOfType(paramType, attribute.name.text)) { - shouldBeCandidate = false; - break; - } - } - if (shouldBeCandidate) { - result = intersectTypes(result, paramType); - } - allMatchingAttributesType = intersectTypes(allMatchingAttributesType, paramType); - } - } - // If we can't find any matching, just return everything. - if (!result) { - result = allMatchingAttributesType; - } - // Intersect in JSX.IntrinsicAttributes if it exists - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttributes !== unknownType) { - result = intersectTypes(intrinsicAttributes, result); - } - return result; - } - } - return undefined; - } - /** - * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. - * For instance: - * declare function Foo(attr: { p1: string}): JSX.Element; - * ; // This function will try resolve "Foo" and return an attributes type of "Foo" which is "{ p1: string }" - * - * The function is intended to initially be called from getAttributesTypeFromJsxOpeningLikeElement which already handle JSX-intrinsic-element.. - * This function will try to resolve custom JSX attributes type in following order: string literal, stateless function, and stateful component - * - * @param openingLikeElement a non-intrinsic JSXOPeningLikeElement - * @param shouldIncludeAllStatelessAttributesType a boolean indicating whether to include all attributes types from all stateless function signature - * @param elementType an instance type of the given opening-like element. If undefined, the function will check type openinglikeElement's tagname. - * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global (imported from react.d.ts) - * @return attributes type if able to resolve the type of node - * anyType if there is no type ElementAttributesProperty or there is an error - * emptyObjectType if there is no "prop" in the element instance type - */ - function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (!elementType) { - elementType = checkExpression(openingLikeElement.tagName); - } - if (elementType.flags & 65536 /* Union */) { - var types = elementType.types; - return getUnionType(types.map(function (type) { - return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); - }), /*subtypeReduction*/ true); - } - // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (elementType.flags & 2 /* String */) { - return anyType; - } - else if (elementType.flags & 32 /* StringLiteral */) { - // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type - // For example: - // var CustomTag: "h1" = "h1"; - // Hello World - var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); - if (intrinsicElementsType !== unknownType) { - var stringLiteralTypeName = elementType.value; - var intrinsicProp = getPropertyOfType(intrinsicElementsType, stringLiteralTypeName); - if (intrinsicProp) { - return getTypeOfSymbol(intrinsicProp); - } - var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */); - if (indexSignatureType) { - return indexSignatureType; - } - error(openingLikeElement, ts.Diagnostics.Property_0_does_not_exist_on_type_1, stringLiteralTypeName, "JSX." + JsxNames.IntrinsicElements); - } - // If we need to report an error, we already done so here. So just return any to prevent any more error downstream - return anyType; - } - // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); - // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. - // Otherwise get only attributes type from the signature picked by choose-overload logic. - var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? - tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) : - defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType); - if (statelessAttributesType) { - return statelessAttributesType; - } - // Issue an error if this return type isn't assignable to JSX.ElementClass - if (elementClassType) { - checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); - } - if (isTypeAny(elemInstanceType)) { - return elemInstanceType; - } - var propsName = getJsxElementPropertiesName(); - if (propsName === undefined) { - // There is no type ElementAttributesProperty, return 'any' - return anyType; - } - else if (propsName === "") { - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - return elemInstanceType; - } - else { - var attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); - if (!attributesType) { - // There is no property named 'props' on this instance type - return emptyObjectType; - } - else if (isTypeAny(attributesType) || (attributesType === unknownType)) { - // Props is of type 'any' or unknown - return attributesType; - } - else { - // Normal case -- add in IntrinsicClassElements and IntrinsicElements - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - if (typeParams) { - if (typeParams.length === 1) { - apparentAttributesType = intersectTypes(createTypeReference(intrinsicClassAttribs, [elemInstanceType]), apparentAttributesType); - } - } - else { - apparentAttributesType = intersectTypes(attributesType, intrinsicClassAttribs); - } - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; - } - } - } - /** - * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. - * The function is intended to be called from a function which has checked that the opening element is an intrinsic element. - * @param node an intrinsic JSX opening-like element - */ - function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) { - ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName)); - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var symbol = getIntrinsicTagSymbol(node); - if (links.jsxFlags & 1 /* IntrinsicNamedElement */) { - return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol); - } - else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) { - return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; - } - else { - return links.resolvedJsxElementAttributesType = unknownType; - } - } - return links.resolvedJsxElementAttributesType; - } - /** - * Get attributes type of the given custom opening-like JSX element. - * This function is intended to be called from a caller that handles intrinsic JSX element already. - * @param node a custom JSX opening-like element - * @param shouldIncludeAllStatelessAttributesType a boolean value used by language service to get all possible attributes type from an overload stateless function component - */ - function getCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType) { - var links = getNodeLinks(node); - if (!links.resolvedJsxElementAttributesType) { - var elemClassType = getJsxGlobalElementClassType(); - return links.resolvedJsxElementAttributesType = resolveCustomJsxElementAttributesType(node, shouldIncludeAllStatelessAttributesType, /*elementType*/ undefined, elemClassType); - } - return links.resolvedJsxElementAttributesType; - } - /** - * Get all possible attributes type, especially from an overload stateless function component, of the given JSX opening-like element. - * This function is called by language service (see: completions-tryGetGlobalSymbols). - * @param node a JSX opening-like element to get attributes type for - */ - function getAllAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - // Because in language service, the given JSX opening-like element may be incomplete and therefore, - // we can't resolve to exact signature if the element is a stateless function component so the best thing to do is return all attributes type from all overloads. - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ true); - } - } - /** - * Get the attributes type, which indicates the attributes that are valid on the given JSXOpeningLikeElement. - * @param node a JSXOpeningLikeElement node - * @return an attributes type of the given node - */ - function getAttributesTypeFromJsxOpeningLikeElement(node) { - if (isJsxIntrinsicIdentifier(node.tagName)) { - return getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - } - else { - return getCustomJsxElementAttributesType(node, /*shouldIncludeAllStatelessAttributesType*/ false); - } - } - /** - * Given a JSX attribute, returns the symbol for the corresponds property - * of the element attributes type. Will return unknownSymbol for attributes - * that have no matching element attributes type property. - */ - function getJsxAttributePropertySymbol(attrib) { - var attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent); - var prop = getPropertyOfType(attributesType, attrib.name.text); - return prop || unknownSymbol; - } - function getJsxGlobalElementClassType() { - if (!deferredJsxElementClassType) { - deferredJsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); - } - return deferredJsxElementClassType; - } - function getJsxGlobalElementType() { - if (!deferredJsxElementType) { - deferredJsxElementType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.Element); - } - return deferredJsxElementType; - } - function getJsxGlobalStatelessElementType() { - if (!deferredJsxStatelessElementType) { - var jsxElementType = getJsxGlobalElementType(); - if (jsxElementType) { - deferredJsxStatelessElementType = getUnionType([jsxElementType, nullType]); - } - } - return deferredJsxStatelessElementType; - } - /** - * Returns all the properties of the Jsx.IntrinsicElements interface - */ - function getJsxIntrinsicTagNames() { - var intrinsics = getJsxType(JsxNames.IntrinsicElements); - return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; - } - function checkJsxPreconditions(errorNode) { - // Preconditions for using JSX - if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) { - error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided); - } - if (getJsxGlobalElementType() === undefined) { - if (noImplicitAny) { - error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist); - } - } - } - function checkJsxOpeningLikeElement(node) { - checkGrammarJsxElement(node); - checkJsxPreconditions(node); - // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import. - // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error. - var reactRefErr = compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined; - var reactNamespace = getJsxNamespace(); - var reactSym = resolveName(node.tagName, reactNamespace, 107455 /* Value */, reactRefErr, reactNamespace); - if (reactSym) { - // Mark local symbol as referenced here because it might not have been marked - // if jsx emit was not react as there wont be error being emitted - reactSym.isReferenced = true; - // If react symbol is alias, mark it as refereced - if (reactSym.flags & 8388608 /* Alias */ && !isConstEnumOrConstEnumOnlyModule(resolveAlias(reactSym))) { - markAliasSymbolAsReferenced(reactSym); - } - } - 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" - * Check assignablity between given attributes property, "source attributes", and the "target attributes" - * @param openingLikeElement an opening-like JSX element to check its JSXAttributes - */ - function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { - // The function involves following steps: - // 1. Figure out expected attributes type by resolving tagName of the JSX opening-like element, targetAttributesType. - // During these steps, we will try to resolve the tagName as intrinsic name, stateless function, stateful component (in the order) - // 2. Solved JSX attributes type given by users, sourceAttributesType, which is by resolving "attributes" property of the JSX opening-like element. - // 3. Check if the two are assignable to each other - // targetAttributesType is a type of an attributes from resolving tagName of an opening-like JSX element. - var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? - getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : - getCustomJsxElementAttributesType(openingLikeElement, /*shouldIncludeAllStatelessAttributesType*/ false); - // sourceAttributesType is a type of an attributes properties. - // i.e
- // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, function (attribute) { - return isUnhyphenatedJsxName(attribute.name) || !!(getPropertyOfType(targetAttributesType, attribute.name)); - }); - // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. - // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. - if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || sourceAttributesType.properties.length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); - } - else { - // 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) { - if (node.expression) { - var type = checkExpression(node.expression, checkMode); - if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) { - error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type, node.toString(), typeToString(type)); - } - return type; - } - else { - return unknownType; - } - } - // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized - // '.prototype' property as well as synthesized tuple index properties. - function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 149 /* PropertyDeclaration */; - } - function getDeclarationNodeFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; - } - function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); - } - /** - * Check whether the requested property access is valid. - * Returns true if node is a valid property access, and false otherwise. - * @param node The node to be checked. - * @param left The left hand side of the property access (e.g.: the super in `super.foo`). - * @param type The type of left. - * @param prop The symbol for the right hand side of the property access. - */ - function checkPropertyAccessibility(node, left, type, prop) { - var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 179 /* PropertyAccessExpression */ || node.kind === 226 /* VariableDeclaration */ ? - node.name : - node.right; - 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; - } - if (left.kind === 97 /* SuperKeyword */) { - // TS 1.0 spec (April 2014): 4.8.2 - // - In a constructor, instance member function, instance member accessor, or - // instance member variable initializer where this references a derived class instance, - // a super property access is permitted and must specify a public instance member function of the base class. - // - In a static member function or static member accessor - // where this references the constructor function object of a derived class, - // a super property access is permitted and must specify a public static member function of the base class. - if (languageVersion < 2 /* ES2015 */) { - var hasNonMethodDeclaration = forEachProperty(prop, function (p) { - var propKind = getDeclarationKindFromSymbol(p); - return propKind !== 151 /* MethodDeclaration */ && propKind !== 150 /* MethodSignature */; - }); - if (hasNonMethodDeclaration) { - error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); - return false; - } - } - if (flags & 128 /* Abstract */) { - // A method cannot be accessed in a super property access if the method is abstract. - // This error could mask a private property access error. But, a member - // cannot simultaneously be private and abstract, so this will trigger an - // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - } - // Public properties are otherwise accessible. - if (!(flags & 24 /* NonPublicAccessibilityModifier */)) { - return true; - } - // Property is known to be private or protected at this point - // Private property is accessible if the property is within the declaring class - if (flags & 8 /* Private */) { - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); - return false; - } - return true; - } - // Property is known to be protected at this point - // All protected properties of a supertype are accessible in a super access - if (left.kind === 97 /* SuperKeyword */) { - return true; - } - // Find the first enclosing class that has the declaring classes of the protected constituents - // of the property as base classes - var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { - var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; - }); - // A protected property is accessible if the property is within the declaring class or classes derived from it - if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); - return false; - } - // No further restrictions for static properties - if (flags & 32 /* Static */) { - return true; - } - // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { - // get the original type -- represented as the type constraint of the 'this' type - type = getConstraintOfTypeParameter(type); - } - if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); - return false; - } - return true; - } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); - } - function checkNonNullType(type, errorNode) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 6144 /* Nullable */; - if (kind) { - error(errorNode, kind & 2048 /* Undefined */ ? kind & 4096 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); - var t = getNonNullableType(type); - return t.flags & (6144 /* Nullable */ | 8192 /* Never */) ? unknownType : t; - } - return type; - } - function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); - } - function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); - } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var type = checkNonNullExpression(left); - if (isTypeAny(type) || type === silentNeverType) { - return type; - } - var apparentType = getApparentType(getWidenedType(type)); - if (apparentType === unknownType || (type.flags & 16384 /* TypeParameter */ && isTypeAny(apparentType))) { - // handle cases when type is Type parameter with invalid or any constraint - return apparentType; - } - var prop = getPropertyOfType(apparentType, right.text); - if (!prop) { - var stringIndexType = getIndexTypeOfType(apparentType, 0 /* String */); - if (stringIndexType) { - return stringIndexType; - } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); - } - return unknownType; - } - if (prop.valueDeclaration) { - if (isInPropertyInitializer(node) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, right.text); - } - if (prop.valueDeclaration.kind === 229 /* ClassDeclaration */ && - node.parent && node.parent.kind !== 159 /* TypeReference */ && - !ts.isInAmbientContext(prop.valueDeclaration) && - !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, right.text); - } - } - markPropertyAsReferenced(prop); - getNodeLinks(node).resolvedSymbol = prop; - checkPropertyAccessibility(node, left, apparentType, prop); - var propType = getDeclaredOrApparentType(prop, node); - var assignmentKind = ts.getAssignmentTargetKind(node); - if (assignmentKind) { - if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, right.text); - return unknownType; - } - } - // Only compute control flow type if this is a property access expression that isn't an - // assignment target, and the referenced property was declared as a variable, property, - // accessor, or optional method. - if (node.kind !== 179 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && - !(prop.flags & 8192 /* Method */ && propType.flags & 65536 /* Union */)) { - return propType; - } - 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 - : node.left; - var type = checkExpression(left); - if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop) { - return checkPropertyAccessibility(node, left, type, prop); - } - } - return true; - } - /** - * Return the symbol of the for-in variable declared or referenced by the given for-in statement. - */ - function getForInVariableSymbol(node) { - var initializer = node.initializer; - if (initializer.kind === 227 /* VariableDeclarationList */) { - var variable = initializer.declarations[0]; - if (variable && !ts.isBindingPattern(variable.name)) { - return getSymbolOfNode(variable); - } - } - else if (initializer.kind === 71 /* Identifier */) { - return getResolvedSymbol(initializer); - } - return undefined; - } - /** - * Return true if the given type is considered to have numeric property names. - */ - function hasNumericPropertyNames(type) { - return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */); - } - /** - * Return true if given node is an expression consisting of an identifier (possibly parenthesized) - * that references a for-in variable for an object with numeric property names. - */ - function isForInVariableForNumericPropertyNames(expr) { - var e = ts.skipParentheses(expr); - if (e.kind === 71 /* Identifier */) { - var symbol = getResolvedSymbol(e); - if (symbol.flags & 3 /* Variable */) { - var child = expr; - var node = expr.parent; - while (node) { - if (node.kind === 215 /* ForInStatement */ && - child === node.statement && - getForInVariableSymbol(node) === symbol && - hasNumericPropertyNames(getTypeOfExpression(node.expression))) { - return true; - } - child = node; - node = node.parent; - } - } - } - return false; - } - function checkIndexedAccess(node) { - var objectType = checkNonNullExpression(node.expression); - var indexExpression = node.argumentExpression; - if (!indexExpression) { - var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 182 /* NewExpression */ && node.parent.expression === node) { - var start = ts.skipTrivia(sourceFile.text, node.expression.end); - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); - } - else { - var start = node.end - "]".length; - var end = node.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); - } - return unknownType; - } - var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); - if (objectType === unknownType || objectType === silentNeverType) { - return objectType; - } - if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { - error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); - return unknownType; - } - return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); - } - function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === unknownType) { - // There is already an error, so no need to report one. - return false; - } - if (!ts.isWellKnownSymbolSyntactically(expression)) { - return false; - } - // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 512 /* ESSymbol */) === 0) { - if (reportError) { - error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); - } - return false; - } - // The name is Symbol., so make sure Symbol actually resolves to the - // global Symbol object - var leftHandSide = expression.expression; - var leftHandSideSymbol = getResolvedSymbol(leftHandSide); - if (!leftHandSideSymbol) { - return false; - } - var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true); - if (!globalESSymbol) { - // Already errored when we tried to look up the symbol - return false; - } - if (leftHandSideSymbol !== globalESSymbol) { - if (reportError) { - error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object); - } - return false; - } - 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); - } - else if (node.kind !== 147 /* Decorator */) { - ts.forEach(node.arguments, function (argument) { - checkExpression(argument); - }); - } - return anySignature; - } - function resolveErrorCall(node) { - resolveUntypedCall(node); - return unknownSignature; - } - // Re-order candidate signatures into the result array. Assumes the result array to be empty. - // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order - // A nit here is that we reorder only signatures that belong to the same symbol, - // so order how inherited signatures are processed is still preserved. - // interface A { (x: string): void } - // interface B extends A { (x: 'foo'): string } - // const b: B; - // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] - function reorderCandidates(signatures, result) { - var lastParent; - var lastSymbol; - var cutoffIndex = 0; - var index; - var specializedIndex = -1; - var spliceIndex; - ts.Debug.assert(!result.length); - 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) { - if (lastParent && parent === lastParent) { - index++; - } - else { - lastParent = parent; - index = cutoffIndex; - } - } - else { - // current declaration belongs to a different symbol - // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex - index = cutoffIndex = result.length; - lastParent = parent; - } - lastSymbol = symbol; - // specialized signatures always need to be placed before non-specialized signatures regardless - // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { - specializedIndex++; - spliceIndex = specializedIndex; - // The cutoff index always needs to be greater than or equal to the specialized signature index - // in order to prevent non-specialized signatures from being added before a specialized - // signature. - cutoffIndex++; - } - else { - spliceIndex = index; - } - result.splice(spliceIndex, 0, signature); - } - } - function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 198 /* SpreadElement */) { - return i; - } - } - return -1; - } - function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) - var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments - var isDecorator; - var spreadArgIndex = -1; - if (ts.isJsxOpeningLikeElement(node)) { - // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". - return true; - } - if (node.kind === 183 /* TaggedTemplateExpression */) { - var tagExpression = node; - // Even if the call is incomplete, we'll have a missing expression as our last argument, - // so we can say the count is just the arg list length - argCount = args.length; - typeArguments = undefined; - if (tagExpression.template.kind === 196 /* TemplateExpression */) { - // If a tagged template expression lacks a tail literal, the call is incomplete. - // Specifically, a template only can end in a TemplateTail or a Missing literal. - var templateExpression = tagExpression.template; - var lastSpan = ts.lastOrUndefined(templateExpression.templateSpans); - ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. - callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; - } - else { - // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, - // then this might actually turn out to be a TemplateHead in the future; - // so we consider the call to be incomplete. - var templateLiteral = tagExpression.template; - ts.Debug.assert(templateLiteral.kind === 13 /* NoSubstitutionTemplateLiteral */); - callIsIncomplete = !!templateLiteral.isUnterminated; - } - } - else if (node.kind === 147 /* Decorator */) { - isDecorator = true; - typeArguments = undefined; - argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); - } - else { - var callExpression = node; - if (!callExpression.arguments) { - // This only happens when we have something of the form: 'new C' - ts.Debug.assert(callExpression.kind === 182 /* NewExpression */); - return signature.minArgumentCount === 0; - } - argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; - // If we are missing the close parenthesis, the call is incomplete. - callIsIncomplete = callExpression.arguments.end === callExpression.end; - typeArguments = callExpression.typeArguments; - spreadArgIndex = getSpreadArgumentIndex(args); - } - // If the user supplied type arguments, but the number of type arguments does not match - // the declared number of type parameters, the call has an incorrect arity. - var numTypeParameters = ts.length(signature.typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || - (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { - return false; - } - // 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) || spreadArgIndex >= signature.minArgumentCount; - } - // Too many arguments implies incorrect arity. - if (!signature.hasRestParameter && argCount > signature.parameters.length) { - return false; - } - // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= signature.minArgumentCount; - return callIsIncomplete || hasEnoughArguments; - } - // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. - function getSingleCallSignature(type) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && - resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - return resolved.callSignatures[0]; - } - } - return undefined; - } - // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) - function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper) { - var context = createInferenceContext(signature, /*inferUnionTypes*/ true, /*useAnyForNoInferences*/ false); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { - // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypesWithContext(context, instantiateType(source, contextualMapper), target); - }); - return getSignatureInstantiation(signature, getInferredTypes(context)); - } - function inferTypeArguments(node, signature, args, excludeArgument, context) { - var typeParameters = signature.typeParameters; - var inferenceMapper = getInferenceMapper(context); - // Clear out all the inference results from the last time inferTypeArguments was called on this context - for (var i = 0; i < typeParameters.length; i++) { - // As an optimization, we don't have to clear (and later recompute) inferred types - // for type parameters that have already been fixed on the previous call to inferTypeArguments. - // It would be just as correct to reset all of them. But then we'd be repeating the same work - // for the type parameters that were fixed, namely the work done by getInferredType. - if (!context.inferences[i].isFixed) { - context.inferredTypes[i] = undefined; - } - } - // On this call to inferTypeArguments, we may get more inferences for certain type parameters that were not - // fixed last time. This means that a type parameter that failed inference last time may succeed this time, - // or vice versa. Therefore, the failedTypeParameterIndex is useless if it points to an unfixed type parameter, - // because it may change. So here we reset it. However, getInferredType will not revisit any type parameters - // that were previously fixed. So if a fixed type parameter failed previously, it will fail again because - // it will contain the exact same set of inferences. So if we reset the index from a fixed type parameter, - // we will lose information that we won't recover this time around. - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } - var thisType = getThisTypeOfSignature(signature); - if (thisType) { - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - inferTypesWithContext(context, thisArgumentType, thisType); - } - // We perform two passes over the arguments. In the first pass we infer from all arguments, but use - // wildcards for all context sensitive function expressions. - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - // For context sensitive arguments we pass the identityMapper, which is a signal to treat all - // context sensitive function expressions as wildcards - var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; - argType = checkExpressionWithContextualType(arg, paramType, mapper); - } - inferTypesWithContext(context, argType, paramType); - } - } - // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this - // time treating function expressions normally (which may cause previously inferred type arguments to be fixed - // as we construct types for contextually typed parameters) - // Decorators will not have `excludeArgument`, as their arguments cannot be contextually typed. - // Tagged template expressions will always have `undefined` for `excludeArgument[0]`. - if (excludeArgument) { - for (var i = 0; i < argCount; i++) { - // No need to check for omitted args and template expressions, their exclusion value is always undefined - if (excludeArgument[i] === false) { - var arg = args[i]; - var paramType = getTypeAtPosition(signature, i); - inferTypesWithContext(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); - } - } - } - getInferredTypes(context); - } - function checkTypeArguments(signature, typeArgumentNodes, typeArgumentTypes, reportErrors, headMessage) { - var typeParameters = signature.typeParameters; - var typeArgumentsAreAssignable = true; - var mapper; - for (var i = 0; i < typeArgumentNodes.length; i++) { - if (typeArgumentsAreAssignable /* so far */) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - var errorInfo = void 0; - var typeArgumentHeadMessage = ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; - if (reportErrors && headMessage) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, typeArgumentHeadMessage); - typeArgumentHeadMessage = headMessage; - } - if (!mapper) { - mapper = createTypeMapper(typeParameters, typeArgumentTypes); - } - var typeArgument = typeArgumentTypes[i]; - typeArgumentsAreAssignable = checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo); - } - } - } - return typeArgumentsAreAssignable; - } - /** - * Check if the given signature can possibly be a signature called by the JSX opening-like element. - * @param node a JSX opening-like element we are trying to figure its call signature - * @param signature a candidate signature we are trying whether it is a call signature - * @param relation a relationship to check parameter and argument type - * @param excludeArgument - */ - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation) { - // JSX opening-like element has correct arity for stateless-function component if the one of the following condition is true: - // 1. callIsIncomplete - // 2. attributes property has same number of properties as the parameter object type. - // We can figure that out by resolving attributes property and check number of properties in the resolved type - // If the call has correct arity, we will then check if the argument type and parameter type is assignable - var callIsIncomplete = node.attributes.end === node.end; // If we are missing the close "/>", the call is incomplete - if (callIsIncomplete) { - return true; - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - // Stateless function components can have maximum of three arguments: "props", "context", and "updater". - // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props, - // can be specified by users through attributes property. - var paramType = getTypeAtPosition(signature, 0); - var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); - var argProperties = getPropertiesOfType(attributesType); - for (var _i = 0, argProperties_1 = argProperties; _i < argProperties_1.length; _i++) { - var arg = argProperties_1[_i]; - if (!getPropertyOfType(paramType, arg.name) && isUnhyphenatedJsxName(arg.name)) { - return false; - } - } - return checkTypeRelatedTo(attributesType, paramType, relation, /*errorNode*/ undefined, headMessage); - } - function checkApplicableSignature(node, args, signature, relation, excludeArgument, reportErrors) { - if (ts.isJsxOpeningLikeElement(node)) { - return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); - } - var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 182 /* NewExpression */) { - // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType - // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. - // If the expression is a new expression, then the check is skipped. - var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; - var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; - var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { - return false; - } - } - var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; - var argCount = getEffectiveArgumentCount(node, args, signature); - for (var i = 0; i < argCount; i++) { - var arg = getEffectiveArgument(node, args, i); - // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 200 /* OmittedExpression */) { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - var argType = getEffectiveArgumentType(node, i); - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - } - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { - return false; - } - } - } - return true; - } - /** - * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. - */ - function getThisArgumentOfCall(node) { - if (node.kind === 181 /* CallExpression */) { - var callee = node.expression; - if (callee.kind === 179 /* PropertyAccessExpression */) { - return callee.expression; - } - else if (callee.kind === 180 /* ElementAccessExpression */) { - return callee.expression; - } - } - } - /** - * Returns the effective arguments for an expression that works like a function invocation. - * - * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. - * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution - * expressions, where the first element of the list is `undefined`. - * If 'node' is a Decorator, the argument list will be `undefined`, and its arguments and types - * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. - */ - function getEffectiveCallArguments(node) { - var args; - if (node.kind === 183 /* TaggedTemplateExpression */) { - var template = node.template; - args = [undefined]; - if (template.kind === 196 /* TemplateExpression */) { - ts.forEach(template.templateSpans, function (span) { - args.push(span.expression); - }); - } - } - else if (node.kind === 147 /* Decorator */) { - // For a decorator, we return undefined as we will determine - // the number and types of arguments for a decorator using - // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. - return undefined; - } - else if (ts.isJsxOpeningLikeElement(node)) { - args = node.attributes.properties.length > 0 ? [node.attributes] : emptyArray; - } - else { - args = node.arguments || emptyArray; - } - return args; - } - /** - * Returns the effective argument count for a node that works like a function invocation. - * If 'node' is a Decorator, the number of arguments is derived from the decoration - * target and the signature: - * If 'node.target' is a class declaration or class expression, the effective argument - * count is 1. - * If 'node.target' is a parameter declaration, the effective argument count is 3. - * If 'node.target' is a property declaration, the effective argument count is 2. - * If 'node.target' is a method or accessor declaration, the effective argument count - * is 3, although it can be 2 if the signature only accepts two arguments, allowing - * us to match a property decorator. - * Otherwise, the argument count is the length of the 'args' array. - */ - function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 147 /* Decorator */) { - switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) - return 1; - case 149 /* PropertyDeclaration */: - // A property declaration decorator will have two arguments (see - // `PropertyDecorator` in core.d.ts) - return 2; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - // A method or accessor declaration decorator will have two or three arguments (see - // `PropertyDecorator` and `MethodDecorator` in core.d.ts) - // If we are emitting decorators for ES3, we will only pass two arguments. - if (languageVersion === 0 /* ES3 */) { - return 2; - } - // If the method decorator signature only accepts a target and a key, we will only - // type check those arguments. - return signature.parameters.length >= 3 ? 3 : 2; - case 146 /* Parameter */: - // A parameter declaration decorator will have three arguments (see - // `ParameterDecorator` in core.d.ts) - return 3; - } - } - else { - return args.length; - } - } - /** - * Returns the effective type of the first argument to a decorator. - * If 'node' is a class declaration or class expression, the effective argument type - * is the type of the static side of the class. - * If 'node' is a parameter declaration, the effective argument type is either the type - * of the static or instance side of the class for the parameter's parent method, - * depending on whether the method is declared static. - * For a constructor, the type is always the type of the static side of the class. - * If 'node' is a property, method, or accessor declaration, the effective argument - * type is the type of the static or instance side of the parent class for class - * element, depending on whether the element is declared static. - */ - function getEffectiveDecoratorFirstArgumentType(node) { - // The first argument to a decorator is its `target`. - if (node.kind === 229 /* ClassDeclaration */) { - // For a class decorator, the `target` is the type of the class (e.g. the - // "static" or "constructor" side of the class) - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - if (node.kind === 146 /* Parameter */) { - // For a parameter decorator, the `target` is the parent type of the - // parameter's containing method. - node = node.parent; - if (node.kind === 152 /* Constructor */) { - var classSymbol = getSymbolOfNode(node); - return getTypeOfSymbol(classSymbol); - } - } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // For a property or method decorator, the `target` is the - // "static"-side type of the parent of the member if the member is - // declared "static"; otherwise, it is the "instance"-side type of the - // parent of the member. - return getParentTypeOfClassElement(node); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - /** - * Returns the effective type for the second argument to a decorator. - * If 'node' is a parameter, its effective argument type is one of the following: - * If 'node.parent' is a constructor, the effective argument type is 'any', as we - * will emit `undefined`. - * If 'node.parent' is a member with an identifier, numeric, or string literal name, - * the effective argument type will be a string literal type for the member name. - * If 'node.parent' is a computed property name, the effective argument type will - * either be a symbol type or the string type. - * If 'node' is a member with an identifier, numeric, or string literal name, the - * effective argument type will be a string literal type for the member name. - * If 'node' is a computed property name, the effective argument type will either - * be a symbol type or the string type. - * A class decorator does not have a second argument type. - */ - function getEffectiveDecoratorSecondArgumentType(node) { - // The second argument to a decorator is its `propertyKey` - if (node.kind === 229 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return unknownType; - } - if (node.kind === 146 /* Parameter */) { - node = node.parent; - if (node.kind === 152 /* Constructor */) { - // For a constructor parameter decorator, the `propertyKey` will be `undefined`. - return anyType; - } - // For a non-constructor parameter decorator, the `propertyKey` will be either - // a string or a symbol, based on the name of the parameter's containing method. - } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // The `propertyKey` for a property or method decorator will be a - // string literal type if the member name is an identifier, number, or string; - // otherwise, if the member name is a computed property name it will - // be either string or symbol. - var element = node; - switch (element.name.kind) { - case 71 /* Identifier */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - return getLiteralType(element.name.text); - case 144 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(element.name); - if (isTypeOfKind(nameType, 512 /* ESSymbol */)) { - return nameType; - } - else { - return stringType; - } - default: - ts.Debug.fail("Unsupported property name."); - return unknownType; - } - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - /** - * Returns the effective argument type for the third argument to a decorator. - * If 'node' is a parameter, the effective argument type is the number type. - * If 'node' is a method or accessor, the effective argument type is a - * `TypedPropertyDescriptor` instantiated with the type of the member. - * Class and property decorators do not have a third effective argument. - */ - function getEffectiveDecoratorThirdArgumentType(node) { - // The third argument to a decorator is either its `descriptor` for a method decorator - // or its `parameterIndex` for a parameter decorator - if (node.kind === 229 /* ClassDeclaration */) { - ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 146 /* Parameter */) { - // The `parameterIndex` for a parameter decorator is always a number - return numberType; - } - if (node.kind === 149 /* PropertyDeclaration */) { - ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return unknownType; - } - if (node.kind === 151 /* MethodDeclaration */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` - // for the type of the member. - var propertyType = getTypeOfNode(node); - return createTypedPropertyDescriptorType(propertyType); - } - ts.Debug.fail("Unsupported decorator target."); - return unknownType; - } - /** - * Returns the effective argument type for the provided argument to a decorator. - */ - function getEffectiveDecoratorArgumentType(node, argIndex) { - if (argIndex === 0) { - return getEffectiveDecoratorFirstArgumentType(node.parent); - } - else if (argIndex === 1) { - return getEffectiveDecoratorSecondArgumentType(node.parent); - } - else if (argIndex === 2) { - return getEffectiveDecoratorThirdArgumentType(node.parent); - } - ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return unknownType; - } - /** - * Gets the effective argument type for an argument in a call expression. - */ - function getEffectiveArgumentType(node, argIndex) { - // Decorators provide special arguments, a tagged template expression provides - // a special first argument, and string literals get string literal types - // unless we're reporting errors - if (node.kind === 147 /* Decorator */) { - return getEffectiveDecoratorArgumentType(node, argIndex); - } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { - return getGlobalTemplateStringsArrayType(); - } - // This is not a synthetic argument, so we return 'undefined' - // to signal that the caller needs to check the argument. - return undefined; - } - /** - * Gets the effective argument expression for an argument in a call expression. - */ - function getEffectiveArgument(node, args, argIndex) { - // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 147 /* Decorator */ || - (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */)) { - return undefined; - } - return args[argIndex]; - } - /** - * Gets the error node to use when reporting errors for an effective argument. - */ - function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 147 /* Decorator */) { - // For a decorator, we use the expression of the decorator for error reporting. - return node.expression; - } - else if (argIndex === 0 && node.kind === 183 /* TaggedTemplateExpression */) { - // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. - return node.template; - } - else { - return arg; - } - } - function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 183 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 147 /* Decorator */; - var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); - var typeArguments; - if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { - typeArguments = node.typeArguments; - // We already perform checking on the type arguments on the class declaration itself. - if (node.expression.kind !== 97 /* SuperKeyword */) { - ts.forEach(typeArguments, checkSourceElement); - } - } - if (signatures.length === 1) { - var declaration = signatures[0].declaration; - if (declaration && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration)) { - if (containsArgumentsReference(declaration)) { - var signatureWithRest = cloneSignature(signatures[0]); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); - syntheticArgsSymbol.type = anyArrayType; - syntheticArgsSymbol.isRestParameter = true; - signatureWithRest.parameters = ts.concatenate(signatureWithRest.parameters, [syntheticArgsSymbol]); - signatureWithRest.hasRestParameter = true; - signatures = [signatureWithRest]; - } - } - } - var candidates = candidatesOutArray || []; - // reorderCandidates fills up the candidates array directly - reorderCandidates(signatures, candidates); - if (!candidates.length) { - diagnostics.add(ts.createDiagnosticForNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures)); - return resolveErrorCall(node); - } - var args = getEffectiveCallArguments(node); - // The following applies to any value of 'excludeArgument[i]': - // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. - // - undefined: the argument at 'i' is *not* susceptible to permanent contextual typing. - // - false: the argument at 'i' *was* and *has been* permanently contextually typed. - // - // The idea is that we will perform type argument inference & assignability checking once - // without using the susceptible parameters that are functions, and once more for each of those - // parameters, contextually typing each as we go along. - // - // For a tagged template, then the first argument be 'undefined' if necessary - // because it represents a TemplateStringsArray. - // - // For a decorator, no arguments are susceptible to contextual typing due to the fact - // decorators are applied to a declaration by the emitter, and not to an expression. - var excludeArgument; - if (!isDecorator) { - // We do not need to call `getEffectiveArgumentCount` here as it only - // applies when calculating the number of arguments for a decorator. - for (var i = isTaggedTemplate ? 1 : 0; i < args.length; i++) { - if (isContextSensitive(args[i])) { - if (!excludeArgument) { - excludeArgument = new Array(args.length); - } - excludeArgument[i] = true; - } - } - } - // The following variables are captured and modified by calls to chooseOverload. - // If overload resolution or type argument inference fails, we want to report the - // best error possible. The best error is one which says that an argument was not - // assignable to a parameter. This implies that everything else about the overload - // was fine. So if there is any overload that is only incorrect because of an - // argument, we will report an error on that one. - // - // function foo(s: string) {} - // function foo(n: number) {} // Report argument error on this overload - // function foo() {} - // foo(true); - // - // If none of the overloads even made it that far, there are two possibilities. - // There was a problem with type arguments for some overload, in which case - // report an error on that. Or none of the overloads even had correct arity, - // in which case give an arity error. - // - // function foo(x: T, y: T) {} // Report type argument inference error - // function foo() {} - // foo(0, true); - // - var candidateForArgumentError; - var candidateForTypeArgumentError; - var resultOfFailedInference; - var result; - // If we are in signature help, a trailing comma indicates that we intend to provide another argument, - // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 /* CallExpression */ && node.arguments.hasTrailingComma; - // Section 4.12.1: - // if the candidate list contains one or more signatures for which the type of each argument - // expression is a subtype of each corresponding parameter type, the return type of the first - // of those signatures becomes the return type of the function call. - // Otherwise, the return type of the first signature in the candidate list becomes the return - // type of the function call. - // - // Whether the call is an error is determined by assignability of the arguments. The subtype pass - // is just important for choosing the best signature. So in the case where there is only one - // signature, the subtype pass is useless. So skipping it is an optimization. - if (candidates.length > 1) { - result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); - } - if (!result) { - // Reinitialize these pointers for round two - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; - result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); - } - if (result) { - return result; - } - // No signatures were applicable. Now report errors based on the last applicable signature with - // no arguments excluded from assignability checks. - // If candidate is undefined, it means that no candidates had a suitable arity. In that case, - // skip the checkApplicableSignature check. - if (candidateForArgumentError) { - if (isJsxOpeningOrSelfClosingElement) { - // We do not report any error here because any error will be handled in "resolveCustomJsxElementAttributesType". - return candidateForArgumentError; - } - // excludeArgument is undefined, in this case also equivalent to [undefined, undefined, ...] - // The importance of excludeArgument is to prevent us from typing function expression parameters - // in arguments too early. If possible, we'd like to only type them once we know the correct - // overload. However, this matters for the case where the call is correct. When the call is - // an error, we don't need to exclude any arguments, although it would cause no harm to do so. - checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); - } - else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ 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(/*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 (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } - } - 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. - // Pick the first candidate that matches the arity. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }); - // f({ | - if (!produceDiagnostics) { - 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)); - } - return candidate; - } - } - } - return resolveErrorCall(node); - function chooseOverload(candidates, relation, signatureHelpTrailingComma) { - if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } - for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { - var originalCandidate = candidates_2[_i]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { - continue; - } - var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, /*inferUnionTypes*/ false, /*useAnyForNoInferences*/ ts.isInJavaScriptFile(node)) - : undefined; - while (true) { - candidate = originalCandidate; - if (candidate.typeParameters) { - var typeArgumentTypes = void 0; - if (typeArguments) { - typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); - } - else { - inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentTypes = inferenceContext.inferredTypes; - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; - } - candidate = getSignatureInstantiation(candidate, typeArgumentTypes); - } - if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { - break; - } - var index = excludeArgument ? ts.indexOf(excludeArgument, /*value*/ true) : -1; - if (index < 0) { - return candidate; - } - excludeArgument[index] = false; - } - // A post-mortem of this iteration of the loop. The signature was not applicable, - // so we want to track it as a candidate for reporting an error. If the candidate - // had no type parameters, or had no issues related to type arguments, we can - // report an error based on the arguments. If there was an issue with type - // arguments, then we can only report an error based on the type arguments. - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } - } - return undefined; - } - } - function resolveCallExpression(node, candidatesOutArray) { - if (node.expression.kind === 97 /* SuperKeyword */) { - var superType = checkSuperExpression(node.expression); - if (superType !== unknownType) { - // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated - // with the type arguments specified in the extends clause. - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); - if (baseTypeNode) { - var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); - return resolveCall(node, baseConstructors, candidatesOutArray); - } - } - return resolveUntypedCall(node); - } - var funcType = checkNonNullExpression(node.expression); - if (funcType === silentNeverType) { - return silentNeverSignature; - } - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - // Another error has already been reported - return resolveErrorCall(node); - } - // Technically, this signatures list may be incomplete. We are taking the apparent type, - // but we are not including call signatures that may have been added to the Object or - // Function interface, since they have none by default. This is a bit of a leap of faith - // that the user will not add any. - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - // TS 1.0 Spec: 4.12 - // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual - // types are provided for the argument expressions, and the result is always of type Any. - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - // The unknownType indicates that an error already occurred (and was reported). No - // need to report another error in this case. - if (funcType !== unknownType && node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call. - // TypeScript employs overload resolution in typed function calls in order to support functions - // with multiple call signatures. - if (!callSignatures.length) { - if (constructSignatures.length) { - error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); - } - else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - } - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - /** - * TS 1.0 spec: 4.12 - * If FuncExpr is of type Any, or of an object type that has no call or construct signatures - * but is a subtype of the Function interface, the call is an untyped function call. - */ - function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - if (isTypeAny(funcType)) { - return true; - } - if (isTypeAny(apparentFuncType) && funcType.flags & 16384 /* TypeParameter */) { - return true; - } - if (!numCallSignatures && !numConstructSignatures) { - // We exclude union types because we may have a union of function types that happen to have - // no common signatures. - if (funcType.flags & 65536 /* Union */) { - return false; - } - return isTypeAssignableTo(funcType, globalFunctionType); - } - return false; - } - function resolveNewExpression(node, candidatesOutArray) { - if (node.arguments && languageVersion < 1 /* ES5 */) { - var spreadIndex = getSpreadArgumentIndex(node.arguments); - if (spreadIndex >= 0) { - error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); - } - } - var expressionType = checkNonNullExpression(node.expression); - if (expressionType === silentNeverType) { - return silentNeverSignature; - } - // If expressionType's apparent type(section 3.8.1) is an object type with one or - // more construct signatures, the expression is processed in the same manner as a - // function call, but using the construct signatures as the initial set of candidate - // signatures for overload resolution. The result type of the function call becomes - // the result type of the operation. - expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { - // Another error has already been reported - return resolveErrorCall(node); - } - // If the expression is a class of abstract type, then it cannot be instantiated. - // Note, only class declarations can be declared abstract. - // In the case of a merged class-module or class-interface declaration, - // 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(ts.getNameOfDeclaration(valueDecl))); - return resolveErrorCall(node); - } - // TS 1.0 spec: 4.11 - // If expressionType is of type Any, Args can be any argument - // list and the result of the operation is of type Any. - if (isTypeAny(expressionType)) { - if (node.typeArguments) { - error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); - } - return resolveUntypedCall(node); - } - // Technically, this signatures list may be incomplete. We are taking the apparent type, - // but we are not including construct signatures that may have been added to the Object or - // Function interface, since they have none by default. This is a bit of a leap of faith - // that the user will not add any. - var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */); - if (constructSignatures.length) { - if (!isConstructorAccessible(node, constructSignatures[0])) { - return resolveErrorCall(node); - } - return resolveCall(node, constructSignatures, candidatesOutArray); - } - // If expressionType's apparent type is an object type with no construct signatures but - // one or more call signatures, the expression is processed as a function call. A compile-time - // error occurs if the result of the function call is not Void. The type of the result of the - // operation is Any. It is an error to have a Void this type. - var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */); - if (callSignatures.length) { - var signature = resolveCall(node, callSignatures, candidatesOutArray); - if (getReturnTypeOfSignature(signature) !== voidType) { - error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); - } - if (getThisTypeOfSignature(signature) === voidType) { - error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void); - } - return signature; - } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); - return resolveErrorCall(node); - } - function isConstructorAccessible(node, signature) { - if (!signature || !signature.declaration) { - return true; - } - var declaration = signature.declaration; - var modifiers = ts.getModifierFlags(declaration); - // Public constructor is accessible. - if (!(modifiers & 24 /* NonPublicAccessibilityModifier */)) { - return true; - } - var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol); - var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol); - // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) - if (!isNodeWithinClass(node, declaringClassDeclaration)) { - var containingClass = ts.getContainingClass(node); - if (containingClass) { - var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); - } - } - if (modifiers & 8 /* Private */) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - if (modifiers & 16 /* Protected */) { - error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass)); - } - return false; - } - return true; - } - function resolveTaggedTemplateExpression(node, candidatesOutArray) { - var tagType = checkExpression(node.tag); - var apparentType = getApparentType(tagType); - if (apparentType === unknownType) { - // Another error has already been reported - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray); - } - /** - * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression. - */ - function getDiagnosticHeadMessageForDecoratorResolution(node) { - switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 146 /* Parameter */: - return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 149 /* PropertyDeclaration */: - return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; - } - } - /** - * Resolves a decorator as if it were a call expression. - */ - function resolveDecorator(node, candidatesOutArray) { - var funcType = checkExpression(node.expression); - var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { - return resolveErrorCall(node); - } - var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); - var constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */); - if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { - return resolveUntypedCall(node); - } - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); - errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - return resolveErrorCall(node); - } - return resolveCall(node, callSignatures, candidatesOutArray, headMessage); - } - /** - * This function is similar to getResolvedSignature but is exclusively for trying to resolve JSX stateless-function component. - * The main reason we have to use this function instead of getResolvedSignature because, the caller of this function will already check the type of openingLikeElement's tagName - * and pass the type as elementType. The elementType can not be a union (as such case should be handled by the caller of this function) - * Note: at this point, we are still not sure whether the opening-like element is a stateless function component or not. - * @param openingLikeElement an opening-like JSX element to try to resolve as JSX stateless function - * @param elementType an element type of the opneing-like element by checking opening-like element's tagname. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - */ - function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 65536 /* Union */)); - var callSignature = resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - return callSignature; - } - /** - * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. - * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible - * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. - * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures - */ - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 65536 /* Union */) { - var types = elementType.types; - var result = void 0; - 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; - } - var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); - if (callSignatures && callSignatures.length > 0) { - var callSignature = void 0; - callSignature = resolveCall(openingLikeElement, callSignatures, candidatesOutArray); - return callSignature; - } - return undefined; - } - function resolveSignature(node, candidatesOutArray) { - switch (node.kind) { - case 181 /* CallExpression */: - return resolveCallExpression(node, candidatesOutArray); - case 182 /* NewExpression */: - return resolveNewExpression(node, candidatesOutArray); - case 183 /* TaggedTemplateExpression */: - return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 147 /* Decorator */: - return resolveDecorator(node, candidatesOutArray); - case 251 /* JsxOpeningElement */: - case 250 /* JsxSelfClosingElement */: - // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray); - } - ts.Debug.fail("Branch in 'resolveSignature' should be unreachable."); - } - /** - * Resolve a signature of a given call-like expression. - * @param node a call-like expression to try resolve a signature for - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a signature of the call-like expression or undefined if one can't be found - */ - function getResolvedSignature(node, candidatesOutArray) { - var links = getNodeLinks(node); - // If getResolvedSignature has already been called, we will have cached the resolvedSignature. - // However, it is possible that either candidatesOutArray was not passed in the first time, - // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work - // to correctly fill the candidatesOutArray. - var cached = links.resolvedSignature; - if (cached && cached !== resolvingSignature && !candidatesOutArray) { - return cached; - } - links.resolvedSignature = resolvingSignature; - var result = resolveSignature(node, candidatesOutArray); - // If signature resolution originated in control flow type analysis (for example to compute the - // assigned type in a flow assignment) we don't cache the result as it may be based on temporary - // types from the control flow analysis. - links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached; - return result; - } - function getResolvedOrAnySignature(node) { - // If we're already in the process of resolving the given signature, don't resolve again as - // that could cause infinite recursion. Instead, return anySignature. - return getNodeLinks(node).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(node); - } - function getInferredClassType(symbol) { - var links = getSymbolLinks(symbol); - if (!links.inferredClassType) { - links.inferredClassType = createAnonymousType(symbol, symbol.members, emptyArray, emptyArray, /*stringIndexType*/ undefined, /*numberIndexType*/ undefined); - } - return links.inferredClassType; - } - /** - * Syntactically and semantically checks a call or new expression. - * @param node The call/new expression to be checked. - * @returns On success, the expression's signature's return type. On failure, anyType. - */ - function checkCallExpression(node) { - // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true - checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - var signature = getResolvedSignature(node); - if (node.expression.kind === 97 /* SuperKeyword */) { - return voidType; - } - if (node.kind === 182 /* NewExpression */) { - var declaration = signature.declaration; - if (declaration && - declaration.kind !== 152 /* Constructor */ && - declaration.kind !== 156 /* ConstructSignature */ && - declaration.kind !== 161 /* ConstructorType */ && - !ts.isJSDocConstructSignature(declaration)) { - // When resolved signature is a call signature (and not a construct signature) the result type is any, unless - // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations - // in a JS file - // Note:JS inferred classes might come from a variable declaration instead of a function declaration. - // In this case, using getResolvedSymbol directly is required to avoid losing the members from the declaration. - var funcSymbol = node.expression.kind === 71 /* Identifier */ ? - getResolvedSymbol(node.expression) : - checkExpression(node.expression).symbol; - if (funcSymbol && ts.isDeclarationOfFunctionOrClassExpression(funcSymbol)) { - funcSymbol = getSymbolOfNode(funcSymbol.valueDeclaration.initializer); - } - if (funcSymbol && funcSymbol.members && funcSymbol.flags & 16 /* Function */) { - return getInferredClassType(funcSymbol); - } - else if (noImplicitAny) { - error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); - } - return anyType; - } - } - // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (ts.isInJavaScriptFile(node) && isCommonJsRequire(node)) { - return resolveExternalModuleTypeByLiteral(node.arguments[0]); - } - return getReturnTypeOfSignature(signature); - } - function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - return false; - } - // Make sure require is not a local function - var resolvedRequire = resolveName(node.expression, node.expression.text, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (!resolvedRequire) { - // project does not contain symbol named 'require' - assume commonjs require - return true; - } - // project includes symbol named 'require' - make sure that it it ambient and local non-alias - if (resolvedRequire.flags & 8388608 /* Alias */) { - return false; - } - var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 228 /* FunctionDeclaration */ - : resolvedRequire.flags & 3 /* Variable */ - ? 226 /* VariableDeclaration */ - : 0 /* Unknown */; - if (targetDeclarationKind !== 0 /* Unknown */) { - var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); - // function/variable declaration should be ambient - return ts.isInAmbientContext(decl); - } - return false; - } - function checkTaggedTemplateExpression(node) { - return getReturnTypeOfSignature(getResolvedSignature(node)); - } - function checkAssertion(node) { - var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(node.expression))); - checkSourceElement(node.type); - var targetType = getTypeFromTypeNode(node.type); - if (produceDiagnostics && targetType !== unknownType) { - var widenedType = getWidenedType(exprType); - if (!isTypeComparableTo(targetType, widenedType)) { - checkTypeComparableTo(exprType, targetType, node, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); - } - } - return targetType; - } - function checkNonNullAssertion(node) { - return getNonNullableType(checkExpression(node.expression)); - } - function checkMetaProperty(node) { - checkGrammarMetaProperty(node); - var container = ts.getNewTargetContainer(node); - if (!container) { - error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); - return unknownType; - } - else if (container.kind === 152 /* Constructor */) { - var symbol = getSymbolOfNode(container.parent); - return getTypeOfSymbol(symbol); - } - else { - var symbol = getSymbolOfNode(container); - return getTypeOfSymbol(symbol); - } - } - function getTypeOfParameter(symbol) { - var type = getTypeOfSymbol(symbol); - if (strictNullChecks) { - var declaration = symbol.valueDeclaration; - if (declaration && declaration.initializer) { - return getNullableType(type, 2048 /* Undefined */); - } - } - return type; - } - function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; - } - function getTypeOfFirstParameterOfSignature(signature) { - return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; - } - function assignContextualParameterTypes(signature, context, mapper, checkMode) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); - if (checkMode === 2 /* Inferential */) { - for (var i = 0; i < len; i++) { - var declaration = signature.parameters[i].valueDeclaration; - if (declaration.type) { - inferTypesWithContext(mapper.context, getTypeFromTypeNode(declaration.type), getTypeAtPosition(context, i)); - } - } - } - if (context.thisParameter) { - var parameter = signature.thisParameter; - if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { - if (!parameter) { - signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined); - } - assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper, checkMode); - } - } - for (var i = 0; i < len; i++) { - var parameter = signature.parameters[i]; - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeAtPosition(context, i); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - var parameter = ts.lastOrUndefined(signature.parameters); - if (!parameter.valueDeclaration.type) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); - assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper, checkMode); - } - } - } - // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push - // the destructured type into the contained binding elements. - function assignBindingElementTypes(node) { - if (ts.isBindingPattern(node.name)) { - for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (!ts.isOmittedExpression(element)) { - if (element.name.kind === 71 /* Identifier */) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); - } - assignBindingElementTypes(element); - } - } - } - } - function assignTypeToParameterAndFixTypeParameters(parameter, contextualType, mapper, checkMode) { - 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 && - (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(name); - } - assignBindingElementTypes(parameter.valueDeclaration); - } - else if (checkMode === 2 /* Inferential */) { - // Even if the parameter already has a type, it might be because it was given a type while - // processing the function as an argument to a prior signature during overload resolution. - // If this was the case, it may have caused some type parameters to be fixed. So here, - // we need to ensure that type parameters at the same positions get fixed again. This is - // done by calling instantiateType to attach the mapper to the contextualType, and then - // calling inferTypes to force a walk of contextualType so that all the correct fixing - // happens. The choice to pass in links.type may seem kind of arbitrary, but it serves - // to make sure that all the correct positions in contextualType are reached by the walk. - // Here is an example: - // - // interface Base { - // baseProp; - // } - // interface Derived extends Base { - // toBase(): Base; - // } - // - // var derived: Derived; - // - // declare function foo(x: T, func: (p: T) => T): T; - // declare function foo(x: T, func: (p: T) => T): T; - // - // var result = foo(derived, d => d.toBase()); - // - // We are typing d while checking the second overload. But we've already given d - // a type (Derived) from the first overload. However, we still want to fix the - // T in the second overload so that we do not infer Base as a candidate for T - // (inferring Base would make type argument inference inconsistent between the two - // overloads). - inferTypesWithContext(mapper.context, links.type, instantiateType(contextualType, mapper)); - } - } - function getReturnTypeFromJSDocComment(func) { - var returnTag = ts.getJSDocReturnTag(func); - if (returnTag && returnTag.typeExpression) { - return getTypeFromTypeNode(returnTag.typeExpression.type); - } - return undefined; - } - function createPromiseType(promisedType) { - // creates a `Promise` type where `T` is the promisedType argument - var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); - if (globalPromiseType !== emptyGenericType) { - // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type - promisedType = getAwaitedType(promisedType) || emptyObjectType; - return createTypeReference(globalPromiseType, [promisedType]); - } - return emptyObjectType; - } - function createPromiseReturnType(func, promisedType) { - var promiseType = createPromiseType(promisedType); - if (promiseType === emptyObjectType) { - error(func, ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); - return unknownType; - } - else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { - error(func, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - return promiseType; - } - function getReturnTypeFromBody(func, checkMode) { - var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (!func.body) { - return unknownType; - } - var functionFlags = ts.getFunctionFlags(func); - var type; - if (func.body.kind !== 207 /* Block */) { - type = checkExpressionCached(func.body, checkMode); - if (functionFlags & 2 /* Async */) { - // 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 should be unwrapped to its awaited type, which we will wrap in - // the native Promise type later in this function. - type = checkAwaitedType(type, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - } - else { - var types = void 0; - if (functionFlags & 1 /* Generator */) { - types = ts.concatenate(checkAndAggregateYieldOperandTypes(func, checkMode), checkAndAggregateReturnExpressionTypes(func, checkMode)); - if (!types || types.length === 0) { - var iterableIteratorAny = functionFlags & 2 /* Async */ - ? createAsyncIterableIteratorType(anyType) // AsyncGenerator function - : createIterableIteratorType(anyType); // Generator function - if (noImplicitAny) { - error(func.asteriskToken, ts.Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); - } - return iterableIteratorAny; - } - } - else { - types = checkAndAggregateReturnExpressionTypes(func, checkMode); - if (!types) { - // For an async function, the return type will not be never, but rather a Promise for never. - return functionFlags & 2 /* Async */ - ? createPromiseReturnType(func, neverType) // Async function - : neverType; // Normal function - } - if (types.length === 0) { - // For an async function, the return type will not be void, but rather a Promise for void. - return functionFlags & 2 /* Async */ - ? createPromiseReturnType(func, voidType) // Async function - : voidType; // Normal function - } - } - // Return a union of the return expression types. - type = getUnionType(types, /*subtypeReduction*/ true); - if (functionFlags & 1 /* Generator */) { - type = functionFlags & 2 /* Async */ - ? createAsyncIterableIteratorType(type) // AsyncGenerator function - : createIterableIteratorType(type); // Generator function - } - } - if (!contextualSignature) { - reportErrorsFromWidening(func, type); - } - if (isUnitType(type) && - !(contextualSignature && - isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { - type = getWidenedLiteralType(type); - } - var widenedType = getWidenedType(type); - // 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 /* AsyncGenerator */) === 2 /* Async */ - ? createPromiseReturnType(func, widenedType) // Async function - : widenedType; // Generator function, AsyncGenerator function, or normal function - } - function checkAndAggregateYieldOperandTypes(func, checkMode) { - var aggregatedTypes = []; - var functionFlags = ts.getFunctionFlags(func); - ts.forEachYieldExpression(func.body, function (yieldExpression) { - var expr = yieldExpression.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (yieldExpression.asteriskToken) { - // A yield* expression effectively yields everything that its operand yields - type = checkIteratedTypeOrElementType(type, yieldExpression.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); - } - if (functionFlags & 2 /* Async */) { - type = checkAwaitedType(type, expr, yieldExpression.asteriskToken - ? ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member - : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - }); - return aggregatedTypes; - } - function isExhaustiveSwitchStatement(node) { - if (!node.possiblyExhaustive) { - return false; - } - var type = getTypeOfExpression(node.expression); - if (!isLiteralType(type)) { - return false; - } - var switchTypes = getSwitchClauseTypes(node); - if (!switchTypes.length) { - return false; - } - return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); - } - function functionHasImplicitReturn(func) { - if (!(func.flags & 128 /* HasImplicitReturn */)) { - return false; - } - var lastStatement = ts.lastOrUndefined(func.body.statements); - if (lastStatement && lastStatement.kind === 221 /* SwitchStatement */ && isExhaustiveSwitchStatement(lastStatement)) { - return false; - } - return true; - } - function checkAndAggregateReturnExpressionTypes(func, checkMode) { - var functionFlags = ts.getFunctionFlags(func); - var aggregatedTypes = []; - var hasReturnWithNoExpression = functionHasImplicitReturn(func); - var hasReturnOfTypeNever = false; - ts.forEachReturnStatement(func.body, function (returnStatement) { - var expr = returnStatement.expression; - if (expr) { - var type = checkExpressionCached(expr, checkMode); - if (functionFlags & 2 /* Async */) { - // 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 should be unwrapped to its awaited type, which should be wrapped in - // the native Promise type by the caller. - type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - if (type.flags & 8192 /* Never */) { - hasReturnOfTypeNever = true; - } - else if (!ts.contains(aggregatedTypes, type)) { - aggregatedTypes.push(type); - } - } - else { - hasReturnWithNoExpression = true; - } - }); - if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || - func.kind === 186 /* FunctionExpression */ || func.kind === 187 /* ArrowFunction */)) { - return undefined; - } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { - if (!ts.contains(aggregatedTypes, undefinedType)) { - aggregatedTypes.push(undefinedType); - } - } - return aggregatedTypes; - } - /** - * TypeScript Specification 1.0 (6.3) - July 2014 - * An explicitly typed function whose return type isn't the Void type, - * the Any type, or a union type containing the Void or Any type as a constituent - * must have at least one return statement somewhere in its body. - * An exception to this rule is if the function implementation consists of a single 'throw' statement. - * - * @param returnType - return type of the function, can be undefined if return type is not explicitly specified - */ - function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { - if (!produceDiagnostics) { - return; - } - // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 1024 /* Void */)) { - return; - } - // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (ts.nodeIsMissing(func.body) || func.body.kind !== 207 /* Block */ || !functionHasImplicitReturn(func)) { - return; - } - var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 8192 /* Never */) { - error(func.type, ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); - } - else if (returnType && !hasExplicitReturn) { - // minimal check: function has syntactic return type annotation and no explicit return statements in the body - // this function does not conform to the specification. - // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); - } - else if (returnType && strictNullChecks && !isTypeAssignableTo(undefinedType, returnType)) { - error(func.type, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined); - } - else if (compilerOptions.noImplicitReturns) { - if (!returnType) { - // If return type annotation is omitted check if function has any explicit return statements. - // If it does not have any - its inferred return type is void - don't do any checks. - // Otherwise get inferred return type from function body and report error only if it is not void / anytype - if (!hasExplicitReturn) { - return; - } - var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func)); - if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) { - return; - } - } - error(func.type || func, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - // Grammar checking - var hasGrammarError = checkGrammarFunctionLikeDeclaration(node); - if (!hasGrammarError && node.kind === 186 /* FunctionExpression */) { - checkGrammarForGenerator(node); - } - // The identityMapper object is used to indicate that function expressions are wildcards - if (checkMode === 1 /* SkipContextSensitive */ && isContextSensitive(node)) { - checkNodeDeferred(node); - return anyFunctionType; - } - var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); - var contextSensitive = isContextSensitive(node); - var mightFixTypeParameters = contextSensitive && checkMode === 2 /* Inferential */; - // Check if function expression is contextually typed and assign parameter types if so. - // See the comment in assignTypeToParameterAndFixTypeParameters to understand why we need to - // check mightFixTypeParameters. - if (mightFixTypeParameters || !(links.flags & 1024 /* ContextChecked */)) { - var contextualSignature = getContextualSignature(node); - // If a type check is started at a function expression that is an argument of a function call, obtaining the - // contextual type may recursively get back to here during overload resolution of the call. If so, we will have - // already assigned contextual types. - var contextChecked = !!(links.flags & 1024 /* ContextChecked */); - if (mightFixTypeParameters || !contextChecked) { - links.flags |= 1024 /* ContextChecked */; - if (contextualSignature) { - var signature = getSignaturesOfType(type, 0 /* Call */)[0]; - if (contextSensitive) { - assignContextualParameterTypes(signature, contextualSignature, getContextualMapper(node), checkMode); - } - if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { - var returnType = getReturnTypeFromBody(node, checkMode); - if (!signature.resolvedReturnType) { - signature.resolvedReturnType = returnType; - } - } - } - if (!contextChecked) { - checkSignatureDeclaration(node); - checkNodeDeferred(node); - } - } - } - if (produceDiagnostics && node.kind !== 151 /* MethodDeclaration */) { - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - } - return type; - } - function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var functionFlags = ts.getFunctionFlags(node); - var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : - getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function - if ((functionFlags & 1 /* Generator */) === 0) { - // return is not necessary in the body of generators - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (node.body) { - if (!node.type) { - // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors - // we need. An example is the noImplicitAny errors resulting from widening the return expression - // of a function. Because checking of function expression bodies is deferred, there was never an - // appropriate time to do this during the main walk of the file (see the comment at the top of - // checkFunctionExpressionBodies). So it must be done now. - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - if (node.body.kind === 207 /* Block */) { - checkSourceElement(node.body); - } - else { - // 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 we - // should not be checking assignability of a promise to the return type. Instead, we need to - // check assignability of the awaited type of the expression body against the promised type of - // its return type annotation. - var exprType = checkExpression(node.body); - if (returnOrPromisedType) { - 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); - } - else { - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); - } - } - } - registerForUnusedIdentifiersCheck(node); - } - } - function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAnyOrAllConstituentTypesHaveKind(type, 84 /* NumberLike */)) { - error(operand, diagnostic); - return false; - } - return true; - } - function isReadonlySymbol(symbol) { - // The following symbols are considered read-only: - // Properties with a 'readonly' modifier - // Variables declared with 'const' - // Get accessors without matching set accessors - // Enum members - // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - 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 */); - } - function isReferenceToReadonlyEntity(expr, symbol) { - if (isReadonlySymbol(symbol)) { - // Allow assignments to readonly properties within constructors of the same class declaration. - if (symbol.flags & 4 /* Property */ && - (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) && - expr.expression.kind === 99 /* ThisKeyword */) { - // Look for if this is the constructor for the class that `symbol` is a property of. - var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 152 /* Constructor */)) - return true; - // If func.parent is a class and symbol is a (readonly) property of that class, or - // if func is a constructor and symbol is a (readonly) parameter property declared in it, - // then symbol is writeable here. - return !(func.parent === symbol.valueDeclaration.parent || func === symbol.valueDeclaration.parent); - } - return true; - } - return false; - } - function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 179 /* PropertyAccessExpression */ || expr.kind === 180 /* ElementAccessExpression */) { - var node = ts.skipParentheses(expr.expression); - if (node.kind === 71 /* Identifier */) { - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol.flags & 8388608 /* Alias */) { - var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 240 /* NamespaceImport */; - } - } - } - return false; - } - function checkReferenceExpression(expr, invalidReferenceMessage) { - // References are combinations of identifiers, parentheses, and property accesses. - var node = ts.skipParentheses(expr); - if (node.kind !== 71 /* Identifier */ && node.kind !== 179 /* PropertyAccessExpression */ && node.kind !== 180 /* ElementAccessExpression */) { - error(expr, invalidReferenceMessage); - return false; - } - return true; - } - function checkDeleteExpression(node) { - checkExpression(node.expression); - var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 179 /* PropertyAccessExpression */ && expr.kind !== 180 /* ElementAccessExpression */) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); - return booleanType; - } - var links = getNodeLinks(expr); - var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol); - if (symbol && isReadonlySymbol(symbol)) { - error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property); - } - return booleanType; - } - function checkTypeOfExpression(node) { - checkExpression(node.expression); - return typeofType; - } - function checkVoidExpression(node) { - checkExpression(node.expression); - return undefinedWideningType; - } - function checkAwaitExpression(node) { - // Grammar checking - if (produceDiagnostics) { - if (!(node.flags & 16384 /* AwaitContext */)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - var operandType = checkExpression(node.expression); - return checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - function checkPrefixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - if (node.operator === 38 /* MinusToken */ && node.operand.kind === 8 /* NumericLiteral */) { - return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text)); - } - switch (node.operator) { - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 512 /* ESSymbol */)) { - error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); - } - return numberType; - case 51 /* ExclamationToken */: - var facts = getTypeFacts(operandType) & (1048576 /* Truthy */ | 2097152 /* Falsy */); - return facts === 1048576 /* Truthy */ ? falseType : - facts === 2097152 /* Falsy */ ? trueType : - booleanType; - case 43 /* PlusPlusToken */: - case 44 /* MinusMinusToken */: - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - return unknownType; - } - function checkPostfixUnaryExpression(node) { - var operandType = checkExpression(node.operand); - if (operandType === silentNeverType) { - return silentNeverType; - } - var ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), ts.Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); - if (ok) { - // run check only if former checks succeeded to avoid reporting cascading errors - checkReferenceExpression(node.operand, ts.Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access); - } - return numberType; - } - // Return true if type might be of the given kind. A union or intersection type might be of a given - // kind if at least one constituent type is of the given kind. - function maybeTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 196608 /* UnionOrIntersection */) { - var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; - if (maybeTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - // Return true if type is of the given kind. A union type is of a given kind if all constituent types - // are of the given kind. An intersection type is of a given kind if at least one constituent type is - // of the given kind. - function isTypeOfKind(type, kind) { - if (type.flags & kind) { - return true; - } - if (type.flags & 65536 /* Union */) { - var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; - if (!isTypeOfKind(t, kind)) { - return false; - } - } - return true; - } - if (type.flags & 131072 /* Intersection */) { - var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; - if (isTypeOfKind(t, kind)) { - return true; - } - } - } - return false; - } - function isConstEnumObjectType(type) { - return getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); - } - function isConstEnumSymbol(symbol) { - return (symbol.flags & 128 /* ConstEnum */) !== 0; - } - function checkInstanceOfExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - // TypeScript 1.0 spec (April 2014): 4.15.4 - // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, - // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature. - // The result is always of the Boolean primitive type. - // NOTE: do not raise error if leftType is unknown as related error was already reported - if (isTypeOfKind(leftType, 8190 /* Primitive */)) { - error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - // NOTE: do not raise error if right is unknown as related error was already reported - if (!(isTypeAny(rightType) || - getSignaturesOfType(rightType, 0 /* Call */).length || - getSignaturesOfType(rightType, 1 /* Construct */).length || - isTypeSubtypeOf(rightType, globalFunctionType))) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type); - } - return booleanType; - } - function checkInExpression(left, right, leftType, rightType) { - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - // TypeScript 1.0 spec (April 2014): 4.15.5 - // 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, 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 */)) { - error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - return booleanType; - } - function checkObjectLiteralAssignment(node, sourceType) { - var properties = node.properties; - for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { - var p = properties_7[_i]; - checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); - } - return sourceType; - } - /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ - function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 261 /* PropertyAssignment */ || property.kind === 262 /* ShorthandPropertyAssignment */) { - var name = property.name; - if (name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var text = ts.getTextOfPropertyName(name); - var type = isTypeAny(objectLiteralType) - ? objectLiteralType - : getTypeOfPropertyOfType(objectLiteralType, text) || - isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || - getIndexTypeOfType(objectLiteralType, 0 /* String */); - if (type) { - if (property.kind === 262 /* ShorthandPropertyAssignment */) { - return checkDestructuringAssignment(property, type); - } - else { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.initializer, type); - } - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); - } - } - else if (property.kind === 263 /* SpreadAssignment */) { - if (languageVersion < 5 /* ESNext */) { - checkExternalEmitHelpers(property, 4 /* Rest */); - } - var nonRestNames = []; - if (allProperties) { - for (var i = 0; i < allProperties.length - 1; i++) { - nonRestNames.push(allProperties[i].name); - } - } - var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); - return checkDestructuringAssignment(property.expression, type); - } - else { - error(property, ts.Diagnostics.Property_assignment_expected); - } - } - function checkArrayLiteralAssignment(node, sourceType, checkMode) { - if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512 /* Read */); - } - // This elementType will be used if the specific property corresponding to this index is not - // present (aka the tuple element property). This call also checks that the parentType is in - // fact an iterable or array (depending on target language). - var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType; - var elements = node.elements; - for (var i = 0; i < elements.length; i++) { - checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); - } - return sourceType; - } - function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { - var elements = node.elements; - var element = elements[elementIndex]; - if (element.kind !== 200 /* OmittedExpression */) { - if (element.kind !== 198 /* SpreadElement */) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; - if (type) { - return checkDestructuringAssignment(element, type, checkMode); - } - else { - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } - } - } - else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - else { - var restExpression = element.expression; - if (restExpression.kind === 194 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); - } - } - } - } - return undefined; - } - function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { - var target; - if (exprOrAssignment.kind === 262 /* ShorthandPropertyAssignment */) { - var prop = exprOrAssignment; - if (prop.objectAssignmentInitializer) { - // In strict null checking mode, if a default value of a non-undefined type is specified, remove - // undefined from the final type. - if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 2048 /* Undefined */)) { - sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); - } - checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); - } - target = exprOrAssignment.name; - } - else { - target = exprOrAssignment; - } - if (target.kind === 194 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { - checkBinaryExpression(target, checkMode); - target = target.left; - } - if (target.kind === 178 /* ObjectLiteralExpression */) { - return checkObjectLiteralAssignment(target, sourceType); - } - if (target.kind === 177 /* ArrayLiteralExpression */) { - return checkArrayLiteralAssignment(target, sourceType, checkMode); - } - return checkReferenceAssignment(target, sourceType, checkMode); - } - function checkReferenceAssignment(target, sourceType, checkMode) { - var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 263 /* SpreadAssignment */ ? - ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : - ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; - if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); - } - return sourceType; - } - /** - * This is a *shallow* check: An expression is side-effect-free if the - * evaluation of the expression *itself* cannot produce side effects. - * For example, x++ / 3 is side-effect free because the / operator - * does not have side effects. - * The intent is to "smell test" an expression for correctness in positions where - * its value is discarded (e.g. the left side of the comma operator). - */ - function isSideEffectFree(node) { - node = ts.skipParentheses(node); - switch (node.kind) { - case 71 /* Identifier */: - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 183 /* TaggedTemplateExpression */: - case 196 /* TemplateExpression */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 139 /* UndefinedKeyword */: - case 186 /* FunctionExpression */: - case 199 /* ClassExpression */: - case 187 /* ArrowFunction */: - case 177 /* ArrayLiteralExpression */: - case 178 /* ObjectLiteralExpression */: - case 189 /* TypeOfExpression */: - case 203 /* NonNullExpression */: - case 250 /* JsxSelfClosingElement */: - case 249 /* JsxElement */: - return true; - case 195 /* ConditionalExpression */: - return isSideEffectFree(node.whenTrue) && - isSideEffectFree(node.whenFalse); - case 194 /* BinaryExpression */: - if (ts.isAssignmentOperator(node.operatorToken.kind)) { - return false; - } - return isSideEffectFree(node.left) && - isSideEffectFree(node.right); - case 192 /* PrefixUnaryExpression */: - case 193 /* PostfixUnaryExpression */: - // Unary operators ~, !, +, and - have no side effects. - // The rest do. - switch (node.operator) { - case 51 /* ExclamationToken */: - case 37 /* PlusToken */: - case 38 /* MinusToken */: - case 52 /* TildeToken */: - return true; - } - return false; - // Some forms listed here for clarity - case 190 /* VoidExpression */: // Explicit opt-out - case 184 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 202 /* AsExpression */: // Not SEF, but can produce useful type warnings - default: - return false; - } - } - function isTypeEqualityComparableTo(source, target) { - return (target.flags & 6144 /* Nullable */) !== 0 || isTypeComparableTo(source, target); - } - function getBestChoiceType(type1, type2) { - var firstAssignableToSecond = isTypeAssignableTo(type1, type2); - var secondAssignableToFirst = isTypeAssignableTo(type2, type1); - return secondAssignableToFirst && !firstAssignableToSecond ? type1 : - firstAssignableToSecond && !secondAssignableToFirst ? type2 : - getUnionType([type1, type2], /*subtypeReduction*/ true); - } - function checkBinaryExpression(node, checkMode) { - return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); - } - function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { - var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 178 /* ObjectLiteralExpression */ || left.kind === 177 /* ArrayLiteralExpression */)) { - return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); - } - var leftType = checkExpression(left, checkMode); - var rightType = checkExpression(right, checkMode); - switch (operator) { - case 39 /* AsteriskToken */: - case 40 /* AsteriskAsteriskToken */: - case 61 /* AsteriskEqualsToken */: - case 62 /* AsteriskAsteriskEqualsToken */: - case 41 /* SlashToken */: - case 63 /* SlashEqualsToken */: - case 42 /* PercentToken */: - case 64 /* PercentEqualsToken */: - case 38 /* MinusToken */: - case 60 /* MinusEqualsToken */: - case 45 /* LessThanLessThanToken */: - case 65 /* LessThanLessThanEqualsToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 66 /* GreaterThanGreaterThanEqualsToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - case 67 /* GreaterThanGreaterThanGreaterThanEqualsToken */: - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - var suggestedOperator = void 0; - // if a user tries to apply a bitwise operator to 2 boolean operands - // try and return them a helpful suggestion - if ((leftType.flags & 136 /* BooleanLike */) && - (rightType.flags & 136 /* BooleanLike */) && - (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { - error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); - } - else { - // otherwise just check each operand separately and report errors as normal - var leftOk = checkArithmeticOperandType(left, leftType, ts.Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - var rightOk = checkArithmeticOperandType(right, rightType, ts.Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - if (leftOk && rightOk) { - checkAssignmentOperator(numberType); - } - } - return numberType; - case 37 /* PlusToken */: - case 59 /* PlusEqualsToken */: - if (leftType === silentNeverType || rightType === silentNeverType) { - return silentNeverType; - } - if (!isTypeOfKind(leftType, 1 /* Any */ | 262178 /* StringLike */) && !isTypeOfKind(rightType, 1 /* Any */ | 262178 /* StringLike */)) { - leftType = checkNonNullType(leftType, left); - rightType = checkNonNullType(rightType, right); - } - var resultType = void 0; - 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; - } - else { - if (isTypeOfKind(leftType, 262178 /* StringLike */) || isTypeOfKind(rightType, 262178 /* StringLike */)) { - // If one or both operands are of the String primitive type, the result is of the String primitive type. - resultType = stringType; - } - else if (isTypeAny(leftType) || isTypeAny(rightType)) { - // Otherwise, the result is of type Any. - // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we. - resultType = leftType === unknownType || rightType === unknownType ? unknownType : anyType; - } - // Symbols are not allowed at all in arithmetic expressions - if (resultType && !checkForDisallowedESSymbolOperand(operator)) { - return resultType; - } - } - if (!resultType) { - reportOperatorError(); - return anyType; - } - if (operator === 59 /* PlusEqualsToken */) { - checkAssignmentOperator(resultType); - } - return resultType; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - if (checkForDisallowedESSymbolOperand(operator)) { - leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left)); - rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right)); - if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) { - reportOperatorError(); - } - } - return booleanType; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - var leftIsLiteral = isLiteralType(leftType); - var rightIsLiteral = isLiteralType(rightType); - if (!leftIsLiteral || !rightIsLiteral) { - leftType = leftIsLiteral ? getBaseTypeOfLiteralType(leftType) : leftType; - rightType = rightIsLiteral ? getBaseTypeOfLiteralType(rightType) : rightType; - } - if (!isTypeEqualityComparableTo(leftType, rightType) && !isTypeEqualityComparableTo(rightType, leftType)) { - reportOperatorError(); - } - return booleanType; - case 93 /* InstanceOfKeyword */: - return checkInstanceOfExpression(left, right, leftType, rightType); - case 92 /* InKeyword */: - return checkInExpression(left, right, leftType, rightType); - case 53 /* AmpersandAmpersandToken */: - return getTypeFacts(leftType) & 1048576 /* Truthy */ ? - getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : - leftType; - case 54 /* BarBarToken */: - return getTypeFacts(leftType) & 2097152 /* Falsy */ ? - getBestChoiceType(removeDefinitelyFalsyTypes(leftType), rightType) : - leftType; - case 58 /* EqualsToken */: - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); - case 26 /* CommaToken */: - if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { - error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); - } - return rightType; - } - function isEvalNode(node) { - return node.kind === 71 /* Identifier */ && node.text === "eval"; - } - // Return true if there was no error, false if there was an error. - function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 512 /* ESSymbol */) ? left : - maybeTypeOfKind(rightType, 512 /* ESSymbol */) ? right : - undefined; - if (offendingSymbolOperand) { - error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); - return false; - } - return true; - } - function getSuggestedBooleanOperator(operator) { - switch (operator) { - case 49 /* BarToken */: - case 69 /* BarEqualsToken */: - return 54 /* BarBarToken */; - case 50 /* CaretToken */: - case 70 /* CaretEqualsToken */: - return 35 /* ExclamationEqualsEqualsToken */; - case 48 /* AmpersandToken */: - case 68 /* AmpersandEqualsToken */: - return 53 /* AmpersandAmpersandToken */; - default: - return undefined; - } - } - function checkAssignmentOperator(valueType) { - if (produceDiagnostics && operator >= 58 /* FirstAssignment */ && operator <= 70 /* LastAssignment */) { - // TypeScript 1.0 spec (April 2014): 4.17 - // An assignment of the form - // VarExpr = ValueExpr - // requires VarExpr to be classified as a reference - // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) - // and the type of the non - compound operation to be assignable to the type of VarExpr. - if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { - // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported - checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); - } - } - } - function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); - } - } - function isYieldExpressionInClass(node) { - var current = node; - var parent = node.parent; - while (parent) { - if (ts.isFunctionLike(parent) && current === parent.body) { - return false; - } - else if (ts.isClassLike(current)) { - return true; - } - current = parent; - parent = parent.parent; - } - return false; - } - function checkYieldExpression(node) { - // Grammar checking - if (produceDiagnostics) { - if (!(node.flags & 4096 /* YieldContext */) || isYieldExpressionInClass(node)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body); - } - if (isInParameterInitializerBeforeContainingFunction(node)) { - error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer); - } - } - if (node.expression) { - var func = ts.getContainingFunction(node); - // If the user's code is syntactically correct, the func should always have a star. After all, - // we are in a yield context. - var functionFlags = func && ts.getFunctionFlags(func); - if (node.asteriskToken) { - // 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 */); - } - // Generator functions prior to ES2015 require the __values helper - if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && - languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 256 /* Values */); - } - } - if (functionFlags & 1 /* Generator */) { - var expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); - var expressionElementType = void 0; - var nodeIsYieldStar = !!node.asteriskToken; - if (nodeIsYieldStar) { - expressionElementType = checkIteratedTypeOrElementType(expressionType, node.expression, /*allowStringInput*/ false, (functionFlags & 2 /* Async */) !== 0); - } - // There is no point in doing an assignability check if the function - // has no explicit return type because the return type is directly computed - // from the yield expressions. - if (func.type) { - var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(func.type), (functionFlags & 2 /* Async */) !== 0) || anyType; - if (nodeIsYieldStar) { - checkTypeAssignableTo(functionFlags & 2 /* Async */ - ? getAwaitedType(expressionElementType, node.expression, ts.Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionElementType, signatureElementType, node.expression, - /*headMessage*/ undefined); - } - else { - checkTypeAssignableTo(functionFlags & 2 /* Async */ - ? getAwaitedType(expressionType, node.expression, ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member) - : expressionType, signatureElementType, node.expression, - /*headMessage*/ undefined); - } - } - } - } - // Both yield and yield* expressions have type 'any' - return anyType; - } - function checkConditionalExpression(node, checkMode) { - checkExpression(node.condition); - var type1 = checkExpression(node.whenTrue, checkMode); - var type2 = checkExpression(node.whenFalse, checkMode); - return getBestChoiceType(type1, type2); - } - function checkLiteralExpression(node) { - if (node.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(node); - } - switch (node.kind) { - case 9 /* StringLiteral */: - return getFreshTypeOfLiteralType(getLiteralType(node.text)); - case 8 /* NumericLiteral */: - return getFreshTypeOfLiteralType(getLiteralType(+node.text)); - case 101 /* TrueKeyword */: - return trueType; - case 86 /* FalseKeyword */: - return falseType; - } - } - function checkTemplateExpression(node) { - // We just want to check each expressions, but we are unconcerned with - // the type of each expression, as any value may be coerced into a string. - // It is worth asking whether this is what we really want though. - // A place where we actually *are* concerned with the expressions' types are - // in tagged templates. - ts.forEach(node.templateSpans, function (templateSpan) { - checkExpression(templateSpan.expression); - }); - return stringType; - } - function checkExpressionWithContextualType(node, contextualType, contextualMapper) { - var saveContextualType = node.contextualType; - var saveContextualMapper = node.contextualMapper; - node.contextualType = contextualType; - node.contextualMapper = contextualMapper; - var checkMode = contextualMapper === identityMapper ? 1 /* SkipContextSensitive */ : - contextualMapper ? 2 /* Inferential */ : 0 /* Normal */; - var result = checkExpression(node, checkMode); - node.contextualType = saveContextualType; - node.contextualMapper = saveContextualMapper; - return result; - } - function checkExpressionCached(node, checkMode) { - var links = getNodeLinks(node); - if (!links.resolvedType) { - // When computing a type that we're going to cache, we need to ignore any ongoing control flow - // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart - // to the top of the stack ensures all transient types are computed from a known point. - var saveFlowLoopStart = flowLoopStart; - flowLoopStart = flowLoopCount; - links.resolvedType = checkExpression(node, checkMode); - flowLoopStart = saveFlowLoopStart; - } - return links.resolvedType; - } - function isTypeAssertion(node) { - node = ts.skipParentheses(node); - return node.kind === 184 /* TypeAssertionExpression */ || node.kind === 202 /* AsExpression */; - } - function checkDeclarationInitializer(declaration) { - var type = getTypeOfExpression(declaration.initializer, /*cache*/ true); - return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || - ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration) || - isTypeAssertion(declaration.initializer) ? type : getWidenedLiteralType(type); - } - function isLiteralContextualType(contextualType) { - if (contextualType) { - if (contextualType.flags & 540672 /* TypeVariable */) { - var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - // If the type parameter is constrained to the base primitive type we're checking for, - // consider this a literal context. For example, given a type parameter 'T extends string', - // this causes us to infer string literal types for T. - if (constraint.flags & (2 /* String */ | 4 /* Number */ | 8 /* Boolean */ | 16 /* Enum */)) { - return true; - } - contextualType = constraint; - } - return maybeTypeOfKind(contextualType, (224 /* Literal */ | 262144 /* Index */)); - } - return false; - } - function checkExpressionForMutableLocation(node, checkMode) { - var type = checkExpression(node, checkMode); - return isTypeAssertion(node) || isLiteralContextualType(getContextualType(node)) ? type : getWidenedLiteralType(type); - } - function checkPropertyAssignment(node, checkMode) { - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - } - return checkExpressionForMutableLocation(node.initializer, checkMode); - } - function checkObjectLiteralMethod(node, checkMode) { - // Grammar checking - checkGrammarMethod(node); - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - } - var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) { - if (checkMode === 2 /* Inferential */) { - var signature = getSingleCallSignature(type); - if (signature && signature.typeParameters) { - var contextualType = getApparentTypeOfContextualType(node); - if (contextualType) { - var contextualSignature = getSingleCallSignature(contextualType); - if (contextualSignature && !contextualSignature.typeParameters) { - return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, getContextualMapper(node))); - } - } - } - } - return type; - } - /** - * Returns the type of an expression. Unlike checkExpression, this function is simply concerned - * with computing the type and may not fully check all contained sub-expressions for errors. - * A cache argument of true indicates that if the function performs a full type check, it is ok - * to cache the result. - */ - function getTypeOfExpression(node, cache) { - // Optimize for the common case of a call to a function with a single non-generic call - // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 181 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - var funcType = checkNonNullExpression(node.expression); - var signature = getSingleCallSignature(funcType); - if (signature && !signature.typeParameters) { - return getReturnTypeOfSignature(signature); - } - } - // Otherwise simply call checkExpression. Ideally, the entire family of checkXXX functions - // should have a parameter that indicates whether full error checking is required such that - // we can perform the optimizations locally. - return cache ? checkExpressionCached(node) : checkExpression(node); - } - /** - * Returns the type of an expression. Unlike checkExpression, this function is simply concerned - * with computing the type and may not fully check all contained sub-expressions for errors. - * It is intended for uses where you know there is no contextual type, - * and requesting the contextual type might cause a circularity or other bad behaviour. - * It sets the contextual type of the node to any before calling getTypeOfExpression. - */ - function getContextFreeTypeOfExpression(node) { - var saveContextualType = node.contextualType; - node.contextualType = anyType; - var type = getTypeOfExpression(node); - node.contextualType = saveContextualType; - return type; - } - // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When - // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the - // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in - // conjunction with the generic contextual type. When contextualMapper is equal to the identityMapper function - // object, it serves as an indicator that all contained function and arrow expressions should be considered to - // have the wildcard function type; this form of type check is used during overload resolution to exclude - // contextually typed function and arrow expressions in the initial phase. - function checkExpression(node, checkMode) { - var type; - if (node.kind === 143 /* QualifiedName */) { - type = checkQualifiedName(node); - } - else { - var uninstantiatedType = checkExpressionWorker(node, checkMode); - type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode); - } - if (isConstEnumObjectType(type)) { - // enum object type for const enums are only permitted in: - // - 'left' in property access - // - 'object' in indexed access - // - target in rhs of import statement - var ok = (node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); - if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); - } - } - return type; - } - function checkExpressionWorker(node, checkMode) { - switch (node.kind) { - case 71 /* Identifier */: - return checkIdentifier(node); - case 99 /* ThisKeyword */: - return checkThisExpression(node); - case 97 /* SuperKeyword */: - return checkSuperExpression(node); - case 95 /* NullKeyword */: - return nullWideningType; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - return checkLiteralExpression(node); - case 196 /* TemplateExpression */: - return checkTemplateExpression(node); - case 13 /* NoSubstitutionTemplateLiteral */: - return stringType; - case 12 /* RegularExpressionLiteral */: - return globalRegExpType; - case 177 /* ArrayLiteralExpression */: - return checkArrayLiteral(node, checkMode); - case 178 /* ObjectLiteralExpression */: - return checkObjectLiteral(node, checkMode); - case 179 /* PropertyAccessExpression */: - return checkPropertyAccessExpression(node); - case 180 /* ElementAccessExpression */: - return checkIndexedAccess(node); - case 181 /* CallExpression */: - case 182 /* NewExpression */: - return checkCallExpression(node); - case 183 /* TaggedTemplateExpression */: - return checkTaggedTemplateExpression(node); - case 185 /* ParenthesizedExpression */: - return checkExpression(node.expression, checkMode); - case 199 /* ClassExpression */: - return checkClassExpression(node); - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 189 /* TypeOfExpression */: - return checkTypeOfExpression(node); - case 184 /* TypeAssertionExpression */: - case 202 /* AsExpression */: - return checkAssertion(node); - case 203 /* NonNullExpression */: - return checkNonNullAssertion(node); - case 204 /* MetaProperty */: - return checkMetaProperty(node); - case 188 /* DeleteExpression */: - return checkDeleteExpression(node); - case 190 /* VoidExpression */: - return checkVoidExpression(node); - case 191 /* AwaitExpression */: - return checkAwaitExpression(node); - case 192 /* PrefixUnaryExpression */: - return checkPrefixUnaryExpression(node); - case 193 /* PostfixUnaryExpression */: - return checkPostfixUnaryExpression(node); - case 194 /* BinaryExpression */: - return checkBinaryExpression(node, checkMode); - case 195 /* ConditionalExpression */: - return checkConditionalExpression(node, checkMode); - case 198 /* SpreadElement */: - return checkSpreadExpression(node, checkMode); - case 200 /* OmittedExpression */: - return undefinedWideningType; - case 197 /* YieldExpression */: - return checkYieldExpression(node); - case 256 /* JsxExpression */: - return checkJsxExpression(node, checkMode); - case 249 /* JsxElement */: - return checkJsxElement(node); - case 250 /* JsxSelfClosingElement */: - return checkJsxSelfClosingElement(node); - case 254 /* JsxAttributes */: - return checkJsxAttributes(node, checkMode); - case 251 /* JsxOpeningElement */: - ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); - } - return unknownType; - } - // DECLARATION AND STATEMENT TYPE CHECKING - function checkTypeParameter(node) { - // Grammar Checking - if (node.expression) { - grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); - } - checkSourceElement(node.constraint); - checkSourceElement(node.default); - var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!hasNonCircularBaseConstraint(typeParameter)) { - error(node.constraint, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); - } - var constraintType = getConstraintOfTypeParameter(typeParameter); - var defaultType = getDefaultFromTypeParameter(typeParameter); - if (constraintType && defaultType) { - checkTypeAssignableTo(defaultType, getTypeWithThisArgument(constraintType, defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); - } - } - function checkParameter(node) { - // Grammar checking - // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the - // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code - // or if its FunctionBody is strict code(11.1.5). - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkVariableLikeDeclaration(node); - var func = ts.getContainingFunction(node); - if (ts.getModifierFlags(node) & 92 /* ParameterPropertyModifier */) { - func = ts.getContainingFunction(node); - if (!(func.kind === 152 /* Constructor */ && ts.nodeIsPresent(func.body))) { - error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); - } - } - if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { - error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); - } - if (node.name.text === "this") { - if (ts.indexOf(func.parameters, node) !== 0) { - error(node, ts.Diagnostics.A_this_parameter_must_be_the_first_parameter); - } - if (func.kind === 152 /* Constructor */ || func.kind === 156 /* ConstructSignature */ || func.kind === 161 /* ConstructorType */) { - error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); - } - } - // Only check rest parameter type if it's not a binding pattern. Since binding patterns are - // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { - error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); - } - } - function getTypePredicateParameterIndex(parameterList, parameter) { - if (parameterList) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 71 /* Identifier */ && - param.name.text === parameter.text) { - return i; - } - } - } - return -1; - } - function checkTypePredicate(node) { - var parent = getTypePredicateParent(node); - if (!parent) { - // The parent must not be valid. - error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); - return; - } - var typePredicate = getSignatureFromDeclaration(parent).typePredicate; - if (!typePredicate) { - return; - } - var parameterName = node.parameterName; - if (ts.isThisTypePredicate(typePredicate)) { - getTypeFromThisTypeNode(parameterName); - } - else { - if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { - error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); - } - else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, - /*headMessage*/ undefined, leadingError); - } - } - else if (parameterName) { - var hasReportedError = false; - for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name = _a[_i].name; - if (ts.isBindingPattern(name) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) { - hasReportedError = true; - break; - } - } - if (!hasReportedError) { - error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName); - } - } - } - } - function getTypePredicateParent(node) { - switch (node.parent.kind) { - case 187 /* ArrowFunction */: - case 155 /* CallSignature */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 160 /* FunctionType */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - var parent = node.parent; - if (node === parent.type) { - return parent; - } - } - } - function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) { - for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (ts.isOmittedExpression(element)) { - continue; - } - var name = element.name; - if (name.kind === 71 /* Identifier */ && - name.text === predicateVariableName) { - error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); - return true; - } - else if (name.kind === 175 /* ArrayBindingPattern */ || - name.kind === 174 /* ObjectBindingPattern */) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { - return true; - } - } - } - } - function checkSignatureDeclaration(node) { - // Grammar checking - if (node.kind === 157 /* IndexSignature */) { - checkGrammarIndexSignature(node); - } - else if (node.kind === 160 /* FunctionType */ || node.kind === 228 /* FunctionDeclaration */ || node.kind === 161 /* ConstructorType */ || - node.kind === 155 /* CallSignature */ || node.kind === 152 /* Constructor */ || - node.kind === 156 /* ConstructSignature */) { - checkGrammarFunctionLikeDeclaration(node); - } - var functionFlags = ts.getFunctionFlags(node); - 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 */); - } - // Async functions prior to ES2017 require the __awaiter helper - if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - } - // 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 */); - } - } - checkTypeParameters(node.typeParameters); - ts.forEach(node.parameters, checkParameter); - if (node.type) { - checkSourceElement(node.type); - } - if (produceDiagnostics) { - checkCollisionWithArgumentsInGeneratedCode(node); - if (noImplicitAny && !node.type) { - switch (node.kind) { - case 156 /* ConstructSignature */: - error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - case 155 /* CallSignature */: - error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); - break; - } - } - if (node.type) { - var functionFlags_1 = ts.getFunctionFlags(node); - 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); - } - else { - var generatorElementType = getIteratedTypeOfGenerator(returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType; - var iterableIteratorInstantiation = functionFlags_1 & 2 /* Async */ - ? createAsyncIterableIteratorType(generatorElementType) // AsyncGenerator function - : createIterableIteratorType(generatorElementType); // Generator function - // Naively, one could check that IterableIterator is assignable to the return type annotation. - // However, that would not catch the error in the following case. - // - // interface BadGenerator extends Iterable, Iterator { } - // function* g(): BadGenerator { } // Iterable and Iterator have different types! - // - checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); - } - } - else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); - } - } - if (noUnusedIdentifiers && !node.body) { - checkUnusedTypeParameters(node); - } - } - } - 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++) { - var member = _a[_i]; - if (member.kind === 152 /* Constructor */) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var param = _c[_b]; - if (ts.isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, param.name.text, 3 /* Property */); - } - } - } - else { - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; - var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { - switch (member.kind) { - case 153 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); - break; - case 154 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); - break; - case 149 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); - break; - case 151 /* MethodDeclaration */: - addName(names, member.name, memberName, 4 /* Method */); - break; - } - } - } - } - function addName(names, location, name, meaning) { - var prev = names.get(name); - if (prev) { - if (prev & 4 /* Method */) { - if (meaning !== 4 /* Method */) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - } - else if (prev & meaning) { - error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location)); - } - else { - names.set(name, prev | meaning); - } - } - else { - names.set(name, meaning); - } - } - } - /** - * Static members being set on a constructor function may conflict with built-in properties - * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable - * built-in properties. This check issues a transpile error when a class has a static - * member with the same name as a non-writable built-in property. - * - * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3 - * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5 - * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor - * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances - */ - function checkClassForStaticPropertyNameConflicts(node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var memberNameNode = member.name; - var isStatic = ts.getModifierFlags(member) & 32 /* Static */; - if (isStatic && memberNameNode) { - var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode); - switch (memberName) { - case "name": - case "length": - case "caller": - case "arguments": - case "prototype": - var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; - var className = getNameOfSymbol(getSymbolOfNode(node)); - error(memberNameNode, message, memberName, className); - break; - } - } - } - } - function checkObjectTypeForDuplicateDeclarations(node) { - var names = ts.createMap(); - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 148 /* PropertySignature */) { - var memberName = void 0; - switch (member.name.kind) { - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - case 71 /* Identifier */: - memberName = member.name.text; - break; - default: - continue; - } - if (names.get(memberName)) { - error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); - error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); - } - else { - names.set(memberName, true); - } - } - } - } - function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 230 /* InterfaceDeclaration */) { - var nodeSymbol = getSymbolOfNode(node); - // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration - // to prevent this run check only for the first declaration of a given kind - if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { - return; - } - } - // TypeScript 1.0 spec (April 2014) - // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. - // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration - var indexSymbol = getIndexSymbol(getSymbolOfNode(node)); - if (indexSymbol) { - var seenNumericIndexer = false; - var seenStringIndexer = false; - for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var declaration = decl; - if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type.kind) { - case 136 /* StringKeyword */: - if (!seenStringIndexer) { - seenStringIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_string_index_signature); - } - break; - case 133 /* NumberKeyword */: - if (!seenNumericIndexer) { - seenNumericIndexer = true; - } - else { - error(declaration, ts.Diagnostics.Duplicate_number_index_signature); - } - break; - } - } - } - } - } - function checkPropertyDeclaration(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarProperty(node) || checkGrammarComputedPropertyName(node.name); - checkVariableLikeDeclaration(node); - } - function checkMethodDeclaration(node) { - // Grammar checking - checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); - // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration - checkFunctionOrMethodDeclaration(node); - // Abstract methods cannot have an implementation. - // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (ts.getModifierFlags(node) & 128 /* Abstract */ && node.body) { - error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); - } - } - function checkConstructorDeclaration(node) { - // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function. - checkSignatureDeclaration(node); - // Grammar check for checking only related to constructorDeclaration - checkGrammarConstructorTypeParameters(node) || checkGrammarConstructorTypeAnnotation(node); - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - var symbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); - // Only type check the symbol once - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(symbol); - } - // exit early in the case of signature - super checks are not relevant to them - if (ts.nodeIsMissing(node.body)) { - return; - } - if (!produceDiagnostics) { - return; - } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } - function markThisReferencesAsErrors(n) { - if (n.kind === 99 /* ThisKeyword */) { - error(n, ts.Diagnostics.this_cannot_be_referenced_in_current_location); - } - else if (n.kind !== 186 /* FunctionExpression */ && n.kind !== 228 /* FunctionDeclaration */) { - ts.forEachChild(n, markThisReferencesAsErrors); - } - } - function isInstancePropertyWithInitializer(n) { - return n.kind === 149 /* PropertyDeclaration */ && - !(ts.getModifierFlags(n) & 32 /* Static */) && - !!n.initializer; - } - // TS 1.0 spec (April 2014): 8.3.2 - // Constructors of classes with no extends clause may not contain super calls, whereas - // constructors of derived classes must contain at least one super call somewhere in their function body. - var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { - captureLexicalThis(node.parent, containingClassDecl); - var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); - var superCall = getSuperCallInConstructor(node); - if (superCall) { - if (classExtendsNull) { - error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); - } - // The first statement in the body of a constructor (excluding prologue directives) must be a super call - // if both of the following are true: - // - The containing class is a derived class. - // - The constructor declares parameter properties - // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return ts.getModifierFlags(p) & 92 /* ParameterPropertyModifier */; }); - // Skip past any prologue directives to find the first statement - // to ensure that it was a super call. - if (superCallShouldBeFirst) { - var statements = node.body.statements; - var superCallStatement = void 0; - for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) { - var statement = statements_3[_i]; - if (statement.kind === 210 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { - superCallStatement = statement; - break; - } - if (!ts.isPrologueDirective(statement)) { - break; - } - } - if (!superCallStatement) { - error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); - } - } - } - else if (!classExtendsNull) { - error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); - } - } - } - function checkAccessorDeclaration(node) { - if (produceDiagnostics) { - // Grammar checking accessors - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - checkDecorators(node); - checkSignatureDeclaration(node); - if (node.kind === 153 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { - if (!(node.flags & 256 /* HasExplicitReturn */)) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); - } - } - } - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - // TypeScript 1.0 spec (April 2014): 8.4.3 - // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 153 /* GetAccessor */ ? 154 /* SetAccessor */ : 153 /* GetAccessor */; - var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); - if (otherAccessor) { - if ((ts.getModifierFlags(node) & 28 /* AccessibilityModifier */) !== (ts.getModifierFlags(otherAccessor) & 28 /* AccessibilityModifier */)) { - error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); - } - if (ts.hasModifier(node, 128 /* Abstract */) !== ts.hasModifier(otherAccessor, 128 /* Abstract */)) { - error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract); - } - // TypeScript 1.0 spec (April 2014): 4.5 - // If both accessors include type annotations, the specified types must be identical. - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type); - checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type); - } - } - var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 153 /* GetAccessor */) { - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); - } - } - checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); - } - function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { - var firstType = getAnnotatedType(first); - var secondType = getAnnotatedType(second); - if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) { - error(first, message); - } - } - function checkMissingDeclaration(node) { - checkDecorators(node); - } - function checkTypeArgumentConstraints(typeParameters, typeArgumentNodes) { - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - var typeArguments; - var mapper; - var result = true; - for (var i = 0; i < typeParameters.length; i++) { - var constraint = getConstraintOfTypeParameter(typeParameters[i]); - if (constraint) { - if (!typeArguments) { - typeArguments = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, minTypeArgumentCount); - mapper = createTypeMapper(typeParameters, typeArguments); - } - var typeArgument = typeArguments[i]; - result = result && checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), typeArgumentNodes[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); - } - } - return result; - } - function checkTypeReferenceNode(node) { - checkGrammarTypeArguments(node, node.typeArguments); - var type = getTypeFromTypeReference(node); - if (type !== unknownType) { - if (node.typeArguments) { - // Do type argument local checks only if referenced type is successfully resolved - ts.forEach(node.typeArguments, checkSourceElement); - if (produceDiagnostics) { - var symbol = getNodeLinks(node).resolvedSymbol; - var typeParameters = symbol.flags & 524288 /* TypeAlias */ ? getSymbolLinks(symbol).typeParameters : type.target.localTypeParameters; - checkTypeArgumentConstraints(typeParameters, node.typeArguments); - } - } - 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)); - } - } - } - function checkTypeQuery(node) { - getTypeFromTypeQueryNode(node); - } - function checkTypeLiteral(node) { - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - checkObjectTypeForDuplicateDeclarations(node); - } - } - function checkArrayType(node) { - checkSourceElement(node.elementType); - } - function checkTupleType(node) { - // Grammar checking - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); - } - ts.forEach(node.elementTypes, checkSourceElement); - } - function checkUnionOrIntersectionType(node) { - ts.forEach(node.types, checkSourceElement); - } - function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 524288 /* IndexedAccess */)) { - return type; - } - // Check if the index type is assignable to 'keyof T' for the object type. - var objectType = type.objectType; - var indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - return type; - } - // 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, 84 /* NumberLike */)) { - var constraint = getBaseConstraintOfType(objectType); - if (constraint && getIndexInfoOfType(constraint, 1 /* Number */)) { - return type; - } - } - error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); - return type; - } - function checkIndexedAccessType(node) { - checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); - } - function checkMappedType(node) { - checkSourceElement(node.typeParameter); - checkSourceElement(node.type); - var type = getTypeFromMappedTypeNode(node); - var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); - } - function isPrivateWithinAmbient(node) { - return (ts.getModifierFlags(node) & 8 /* Private */) && ts.isInAmbientContext(node); - } - function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = ts.getCombinedModifierFlags(n); - // children of classes (even ambient classes) should not be marked as ambient or export - // because those flags have no useful semantics there. - if (n.parent.kind !== 230 /* InterfaceDeclaration */ && - n.parent.kind !== 229 /* ClassDeclaration */ && - n.parent.kind !== 199 /* ClassExpression */ && - ts.isInAmbientContext(n)) { - if (!(flags & 2 /* Ambient */)) { - // It is nested in an ambient context, which means it is automatically exported - flags |= 1 /* Export */; - } - flags |= 2 /* Ambient */; - } - return flags & flagsToCheck; - } - function checkFunctionOrConstructorSymbol(symbol) { - if (!produceDiagnostics) { - return; - } - function getCanonicalOverload(overloads, implementation) { - // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration - // Error on all deviations from this canonical set of flags - // The caveat is that if some overloads are defined in lib.d.ts, we don't want to - // report the errors on those. To achieve this, we will say that the implementation is - // the canonical signature only if it is in the same container as the first overload - var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; - return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; - } - function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) { - // Error if some overloads have a flag that is not shared by all overloads. To find the - // deviations, we XOR someOverloadFlags with allOverloadFlags - var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; - if (someButNotAllOverloadFlags !== 0) { - var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); - ts.forEach(overloads, function (o) { - var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; - if (deviation & 1 /* Export */) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - } - else if (deviation & 2 /* Ambient */) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - } - else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - } - else if (deviation & 128 /* Abstract */) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); - } - }); - } - } - function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) { - if (someHaveQuestionToken !== allHaveQuestionToken) { - var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation)); - ts.forEach(overloads, function (o) { - var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; - if (deviation) { - error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); - } - }); - } - } - var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */; - var someNodeFlags = 0 /* None */; - var allNodeFlags = flagsToCheck; - var someHaveQuestionToken = false; - var allHaveQuestionToken = true; - var hasOverloads = false; - var bodyDeclaration; - var lastSeenNonAmbientDeclaration; - var previousDeclaration; - var declarations = symbol.declarations; - var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0; - function reportImplementationExpectedError(node) { - if (node.name && ts.nodeIsMissing(node.name)) { - return; - } - var seen = false; - var subsequentNode = ts.forEachChild(node.parent, function (c) { - if (seen) { - return c; - } - else { - seen = c === node; - } - }); - // We may be here because of some extra nodes between overloads that could not be parsed into a valid node. - // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here. - if (subsequentNode && subsequentNode.pos === node.end) { - if (subsequentNode.kind === node.kind) { - var errorNode_1 = subsequentNode.name || subsequentNode; - // TODO(jfreeman): These are methods, so handle computed name case - if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { - var reportError = (node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */) && - (ts.getModifierFlags(node) & 32 /* Static */) !== (ts.getModifierFlags(subsequentNode) & 32 /* Static */); - // we can get here in two cases - // 1. mixed static and instance class members - // 2. something with the same name was defined before the set of overloads that prevents them from merging - // here we'll report error only for the first case since for second we should already report error in binder - if (reportError) { - var diagnostic = ts.getModifierFlags(node) & 32 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; - error(errorNode_1, diagnostic); - } - return; - } - else if (ts.nodeIsPresent(subsequentNode.body)) { - error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); - return; - } - } - } - var errorNode = node.name || node; - if (isConstructor) { - error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); - } - else { - // Report different errors regarding non-consecutive blocks of declarations depending on whether - // the node in question is abstract. - if (ts.getModifierFlags(node) & 128 /* Abstract */) { - error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); - } - else { - error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration); - } - } - } - var duplicateFunctionDeclaration = false; - var multipleConstructorImplementation = false; - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var current = declarations_5[_i]; - var node = current; - var inAmbientContext = ts.isInAmbientContext(node); - var inAmbientContextOrInterface = node.parent.kind === 230 /* InterfaceDeclaration */ || node.parent.kind === 163 /* TypeLiteral */ || inAmbientContext; - if (inAmbientContextOrInterface) { - // check if declarations are consecutive only if they are non-ambient - // 1. ambient declarations can be interleaved - // i.e. this is legal - // declare function foo(); - // declare function bar(); - // declare function foo(); - // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one - previousDeclaration = undefined; - } - if (node.kind === 228 /* FunctionDeclaration */ || node.kind === 151 /* MethodDeclaration */ || node.kind === 150 /* MethodSignature */ || node.kind === 152 /* Constructor */) { - var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); - someNodeFlags |= currentNodeFlags; - allNodeFlags &= currentNodeFlags; - someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); - allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - if (ts.nodeIsPresent(node.body) && bodyDeclaration) { - if (isConstructor) { - multipleConstructorImplementation = true; - } - else { - duplicateFunctionDeclaration = true; - } - } - else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { - reportImplementationExpectedError(previousDeclaration); - } - if (ts.nodeIsPresent(node.body)) { - if (!bodyDeclaration) { - bodyDeclaration = node; - } - } - else { - hasOverloads = true; - } - previousDeclaration = node; - if (!inAmbientContextOrInterface) { - lastSeenNonAmbientDeclaration = node; - } - } - } - if (multipleConstructorImplementation) { - ts.forEach(declarations, function (declaration) { - error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed); - }); - } - if (duplicateFunctionDeclaration) { - ts.forEach(declarations, function (declaration) { - error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); - }); - } - // Abstract methods can't have an implementation -- in particular, they don't need one. - if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(ts.getModifierFlags(lastSeenNonAmbientDeclaration) & 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) { - reportImplementationExpectedError(lastSeenNonAmbientDeclaration); - } - if (hasOverloads) { - checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags); - checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); - if (bodyDeclaration) { - var signatures = getSignaturesOfSymbol(symbol); - var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - 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; - } - } - } - } - } - function checkExportsOnMergedDeclarations(node) { - if (!produceDiagnostics) { - return; - } - // if localSymbol is defined on node then node itself is exported - check is required - var symbol = node.localSymbol; - if (!symbol) { - // local symbol is undefined => this declaration is non-exported. - // however symbol might contain other declarations that are exported - symbol = getSymbolOfNode(node); - if (!(symbol.flags & 7340032 /* Export */)) { - // this is a pure local symbol (all declarations are non-exported) - no need to check anything - return; - } - } - // run the check only for the first declaration in the list - if (ts.getDeclarationOfKind(symbol, node.kind) !== node) { - return; - } - // we use SymbolFlags.ExportValue, SymbolFlags.ExportType and SymbolFlags.ExportNamespace - // to denote disjoint declarationSpaces (without making new enum type). - var exportedDeclarationSpaces = 0 /* None */; - var nonExportedDeclarationSpaces = 0 /* None */; - var defaultExportedDeclarationSpaces = 0 /* None */; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var d = _a[_i]; - var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */); - if (effectiveDeclarationFlags & 1 /* Export */) { - if (effectiveDeclarationFlags & 512 /* Default */) { - defaultExportedDeclarationSpaces |= declarationSpaces; - } - else { - exportedDeclarationSpaces |= declarationSpaces; - } - } - else { - nonExportedDeclarationSpaces |= declarationSpaces; - } - } - // Spaces for anything not declared a 'default export'. - var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; - var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; - var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; - if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { - // declaration spaces for exported and non-exported declarations intersect - 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(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(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); - } - } - } - function getDeclarationSpaces(d) { - switch (d.kind) { - case 230 /* InterfaceDeclaration */: - return 2097152 /* ExportType */; - case 233 /* ModuleDeclaration */: - return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ - ? 4194304 /* ExportNamespace */ | 1048576 /* ExportValue */ - : 4194304 /* ExportNamespace */; - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - return 2097152 /* ExportType */ | 1048576 /* ExportValue */; - case 237 /* ImportEqualsDeclaration */: - var result_3 = 0; - var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); - return result_3; - default: - return 1048576 /* ExportValue */; - } - } - } - function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage) { - var promisedType = getPromisedTypeOfPromise(type, errorNode); - return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage); - } - /** - * Gets the "promised type" of a promise. - * @param type The type of the promise. - * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback. - */ - function getPromisedTypeOfPromise(promise, errorNode) { - // - // { // promise - // then( // thenFunction - // onfulfilled: ( // onfulfilledParameterType - // value: T // valueParameterType - // ) => any - // ): any; - // } - // - if (isTypeAny(promise)) { - return undefined; - } - var typeAsPromise = promise; - if (typeAsPromise.promisedTypeOfPromise) { - return typeAsPromise.promisedTypeOfPromise; - } - if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { - return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; - } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); - if (isTypeAny(thenFunction)) { - return undefined; - } - var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray; - if (thenSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method); - } - return undefined; - } - var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 524288 /* NEUndefinedOrNull */); - if (isTypeAny(onfulfilledParameterType)) { - return undefined; - } - var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */); - if (onfulfilledParameterSignatures.length === 0) { - if (errorNode) { - error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback); - } - return undefined; - } - return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), /*subtypeReduction*/ true); - } - /** - * Gets the "awaited type" of a type. - * @param type The type to await. - * @remarks The "awaited type" of an expression is its "promised type" if the expression is a - * Promise-like type; otherwise, it is the type of the expression. This is used to reflect - * The runtime behavior of the `await` keyword. - */ - function checkAwaitedType(type, errorNode, diagnosticMessage) { - return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; - } - function getAwaitedType(type, errorNode, diagnosticMessage) { - var typeAsAwaitable = type; - if (typeAsAwaitable.awaitedTypeOfType) { - return typeAsAwaitable.awaitedTypeOfType; - } - if (isTypeAny(type)) { - return typeAsAwaitable.awaitedTypeOfType = type; - } - if (type.flags & 65536 /* Union */) { - var types = void 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var constituentType = _a[_i]; - types = ts.append(types, getAwaitedType(constituentType, errorNode, diagnosticMessage)); - } - if (!types) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = getUnionType(types, /*subtypeReduction*/ true); - } - var promisedType = getPromisedTypeOfPromise(type); - if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { - // Verify that we don't have a bad actor in the form of a promise whose - // promised type is the same as the promise type, or a mutually recursive - // promise. If so, we return undefined as we cannot guess the shape. If this - // were the actual case in the JavaScript, this Promise would never resolve. - // - // An example of a bad actor with a singly-recursive promise type might - // be: - // - // interface BadPromise { - // then( - // onfulfilled: (value: BadPromise) => any, - // onrejected: (error: any) => any): BadPromise; - // } - // The above interface will pass the PromiseLike check, and return a - // promised type of `BadPromise`. Since this is a self reference, we - // don't want to keep recursing ad infinitum. - // - // An example of a bad actor in the form of a mutually-recursive - // promise type might be: - // - // interface BadPromiseA { - // then( - // onfulfilled: (value: BadPromiseB) => any, - // onrejected: (error: any) => any): BadPromiseB; - // } - // - // interface BadPromiseB { - // then( - // onfulfilled: (value: BadPromiseA) => any, - // onrejected: (error: any) => any): BadPromiseA; - // } - // - if (errorNode) { - error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); - } - return undefined; - } - // Keep track of the type we're about to unwrap to avoid bad recursive promise types. - // See the comments above for more information. - awaitedTypeStack.push(type.id); - var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage); - awaitedTypeStack.pop(); - if (!awaitedType) { - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = awaitedType; - } - // The type was not a promise, so it could not be unwrapped any further. - // As long as the type does not have a callable "then" property, it is - // safe to return the type; otherwise, an error will be reported in - // the call to getNonThenableType and we will return undefined. - // - // An example of a non-promise "thenable" might be: - // - // await { then(): void {} } - // - // The "thenable" does not match the minimal definition for a promise. When - // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise - // will never settle. We treat this as an error to help flag an early indicator - // of a runtime problem. If the user wants to return this value from an async - // function, they would need to wrap it in some other value. If they want it to - // be treated as a promise, they can cast to . - var thenFunction = getTypeOfPropertyOfType(type, "then"); - if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { - if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); - error(errorNode, diagnosticMessage); - } - return undefined; - } - return typeAsAwaitable.awaitedTypeOfType = type; - } - /** - * Checks the return type of an async function to ensure it is a compatible - * Promise implementation. - * - * This checks that an async function has a valid Promise-compatible return type, - * and returns the *awaited type* of the promise. An async function has a valid - * Promise-compatible return type if the resolved value of the return type has a - * construct signature that takes in an `initializer` function that in turn supplies - * a `resolve` function as one of its arguments and results in an object with a - * callable `then` signature. - * - * @param node The signature to check - */ - function checkAsyncFunctionReturnType(node) { - // As part of our emit for an async function, we will need to emit the entity name of - // the return type annotation as an expression. To meet the necessary runtime semantics - // for __awaiter, we must also check that the type of the declaration (e.g. the static - // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`. - // - // An example might be (from lib.es6.d.ts): - // - // interface Promise { ... } - // interface PromiseConstructor { - // new (...): Promise; - // } - // declare var Promise: PromiseConstructor; - // - // When an async function declares a return type annotation of `Promise`, we - // need to get the type of the `Promise` variable declaration above, which would - // be `PromiseConstructor`. - // - // The same case applies to a class: - // - // declare class Promise { - // constructor(...); - // then(...): Promise; - // } - // - var returnType = getTypeFromTypeNode(node.type); - if (languageVersion >= 2 /* ES2015 */) { - if (returnType === unknownType) { - return unknownType; - } - var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); - if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { - // The promise type was not a valid type reference to the global promise type, so we - // report an error and return the unknown type. - error(node.type, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return unknownType; - } - } - else { - // Always mark the type node as referenced if it points to a value - markTypeNodeAsReferenced(node.type); - if (returnType === unknownType) { - return unknownType; - } - var promiseConstructorName = ts.getEntityNameFromTypeNode(node.type); - if (promiseConstructorName === undefined) { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return unknownType; - } - var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 107455 /* Value */, /*ignoreErrors*/ true); - var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; - if (promiseConstructorType === unknownType) { - if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.text === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { - error(node.type, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); - } - else { - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - } - return unknownType; - } - var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); - if (globalPromiseConstructorLikeType === emptyObjectType) { - // If we couldn't resolve the global PromiseConstructorLike type we cannot verify - // compatibility with __awaiter. - error(node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node.type, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return unknownType; - } - // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - var collidingSymbol = getSymbol(node.locals, rootName.text, 107455 /* Value */); - if (collidingSymbol) { - error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, rootName.text, ts.entityNameToString(promiseConstructorName)); - return unknownType; - } - } - // Get and return the awaited type of the return type. - return checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - } - /** Check a decorator */ - function checkDecorator(node) { - var signature = getResolvedSignature(node); - var returnType = getReturnTypeOfSignature(signature); - if (returnType.flags & 1 /* Any */) { - return; - } - var expectedReturnType; - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - var errorInfo; - switch (node.parent.kind) { - case 229 /* ClassDeclaration */: - var classSymbol = getSymbolOfNode(node.parent); - var classConstructorType = getTypeOfSymbol(classSymbol); - expectedReturnType = getUnionType([classConstructorType, voidType]); - break; - case 146 /* Parameter */: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); - break; - case 149 /* PropertyDeclaration */: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); - break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - var methodType = getTypeOfNode(node.parent); - var descriptorType = createTypedPropertyDescriptorType(methodType); - expectedReturnType = getUnionType([descriptorType, voidType]); - break; - } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); - } - /** - * If a TypeNode can be resolved to a value symbol imported from an external module, it is - * marked as referenced to prevent import elision. - */ - function markTypeNodeAsReferenced(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 - && rootSymbol.flags & 8388608 /* Alias */ - && symbolIsValue(rootSymbol) - && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { - 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; - } - /** Check the decorators of a node */ - function checkDecorators(node) { - if (!node.decorators) { - return; - } - // skip this check for nodes that cannot have decorators. These should have already had an error reported by - // checkGrammarDecorators. - if (!ts.nodeCanBeDecorated(node)) { - return; - } - if (!compilerOptions.experimentalDecorators) { - error(node, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning); - } - var firstDecorator = node.decorators[0]; - checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 146 /* Parameter */) { - checkExternalEmitHelpers(firstDecorator, 32 /* Param */); - } - if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); - // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. - switch (node.kind) { - case 229 /* ClassDeclaration */: - var constructor = ts.getFirstConstructorWithBody(node); - if (constructor) { - for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - } - break; - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - case 149 /* PropertyDeclaration */: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); - break; - case 146 /* Parameter */: - markDecoratorMedataDataTypeNodeAsReferenced(node.type); - break; - } - } - ts.forEach(node.decorators, checkDecorator); - } - function checkFunctionDeclaration(node) { - if (produceDiagnostics) { - checkFunctionOrMethodDeclaration(node) || checkGrammarForGenerator(node); - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function checkFunctionOrMethodDeclaration(node) { - checkDecorators(node); - checkSignatureDeclaration(node); - var functionFlags = ts.getFunctionFlags(node); - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name && node.name.kind === 144 /* ComputedPropertyName */) { - // This check will account for methods in class/interface declarations, - // as well as accessors in classes/object literals - checkComputedPropertyName(node.name); - } - if (!ts.hasDynamicName(node)) { - // first we want to check the local symbol that contain this declaration - // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol - // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode - var symbol = getSymbolOfNode(node); - var localSymbol = node.localSymbol || symbol; - // Since the javascript won't do semantic analysis like typescript, - // if the javascript file comes before the typescript file and both contain same name functions, - // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - var firstDeclaration = ts.forEach(localSymbol.declarations, - // Get first non javascript function declaration - function (declaration) { return declaration.kind === node.kind && !ts.isSourceFileJavaScript(ts.getSourceFileOfNode(declaration)) ? - declaration : undefined; }); - // Only type check the symbol once - if (node === firstDeclaration) { - checkFunctionOrConstructorSymbol(localSymbol); - } - if (symbol.parent) { - // run check once for the first declaration - if (ts.getDeclarationOfKind(symbol, node.kind) === node) { - // run check on export symbol to check that modifiers agree across all exported declarations - checkFunctionOrConstructorSymbol(symbol); - } - } - } - checkSourceElement(node.body); - if ((functionFlags & 1 /* Generator */) === 0) { - var returnOrPromisedType = node.type && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(node.type)); // normal function - checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); - } - if (produceDiagnostics && !node.type) { - // Report an implicit any error if there is no body, no explicit return type, and node is not a private method - // in an ambient context - if (noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { - reportImplicitAnyError(node, anyType); - } - if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(node.body)) { - // A generator with a body and no type annotation can still cause errors. It can error if the - // yielded values have no common supertype, or it can give an implicit any error if it has no - // yielded values. The only way to trigger these errors is to try checking its return type. - getReturnTypeOfSignature(getSignatureFromDeclaration(node)); - } - } - registerForUnusedIdentifiersCheck(node); - } - function registerForUnusedIdentifiersCheck(node) { - if (deferredUnusedIdentifierNodes) { - deferredUnusedIdentifierNodes.push(node); - } - } - function checkUnusedIdentifiers() { - if (deferredUnusedIdentifierNodes) { - for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { - var node = deferredUnusedIdentifierNodes_1[_i]; - switch (node.kind) { - case 265 /* SourceFile */: - case 233 /* ModuleDeclaration */: - checkUnusedModuleMembers(node); - break; - case 229 /* ClassDeclaration */: - case 199 /* ClassExpression */: - checkUnusedClassMembers(node); - checkUnusedTypeParameters(node); - break; - case 230 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node); - break; - case 207 /* Block */: - case 235 /* CaseBlock */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - checkUnusedLocalsAndParameters(node); - break; - case 152 /* Constructor */: - case 186 /* FunctionExpression */: - case 228 /* FunctionDeclaration */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - if (node.body) { - checkUnusedLocalsAndParameters(node); - } - checkUnusedTypeParameters(node); - break; - case 150 /* MethodSignature */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - case 157 /* IndexSignature */: - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - checkUnusedTypeParameters(node); - break; - } - } - } - } - function checkUnusedLocalsAndParameters(node) { - if (node.parent.kind !== 230 /* InterfaceDeclaration */ && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - 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(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(ts.getNameOfDeclaration(d) || d, local.name); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } - function errorUnusedLocal(node, name) { - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration = ts.getRootDeclaration(node.parent); - if (declaration.kind === 226 /* VariableDeclaration */ && - (declaration.parent.parent.kind === 215 /* ForInStatement */ || - declaration.parent.parent.kind === 216 /* ForOfStatement */)) { - return; - } - } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - error(node, ts.Diagnostics._0_is_declared_but_never_used, name); - } - } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { - return node.kind === 71 /* Identifier */ && node.text.charCodeAt(0) === 95 /* _ */; - } - function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 151 /* MethodDeclaration */ || member.kind === 149 /* PropertyDeclaration */) { - if (!member.symbol.isReferenced && ts.getModifierFlags(member) & 8 /* Private */) { - error(member.name, ts.Diagnostics._0_is_declared_but_never_used, member.symbol.name); - } - } - else if (member.kind === 152 /* Constructor */) { - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.getModifierFlags(parameter) & 8 /* Private */) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_never_used, parameter.symbol.name); - } - } - } - } - } - } - } - function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - if (node.typeParameters) { - // Only report errors on the last declaration for the type parameter container; - // this ensures that all uses have been accounted for. - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } - for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { - var typeParameter = _a[_i]; - if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_never_used, typeParameter.symbol.name); - } - } - } - } - } - function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !ts.isInAmbientContext(node)) { - node.locals.forEach(function (local) { - if (!local.isReferenced && !local.exportSymbol) { - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); - } - } - } - }); - } - } - function checkBlock(node) { - // Grammar checking for SyntaxKind.Block - if (node.kind === 207 /* Block */) { - checkGrammarStatementInAmbientContext(node); - } - ts.forEach(node.statements, checkSourceElement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkCollisionWithArgumentsInGeneratedCode(node) { - // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasDeclaredRestParameter(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { - return; - } - ts.forEach(node.parameters, function (p) { - if (p.name && !ts.isBindingPattern(p.name) && p.name.text === argumentsSymbol.name) { - error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); - } - }); - } - function needCollisionCheckForIdentifier(node, identifier, name) { - if (!(identifier && identifier.text === name)) { - return false; - } - if (node.kind === 149 /* PropertyDeclaration */ || - node.kind === 148 /* PropertySignature */ || - node.kind === 151 /* MethodDeclaration */ || - node.kind === 150 /* MethodSignature */ || - node.kind === 153 /* GetAccessor */ || - node.kind === 154 /* SetAccessor */) { - // it is ok to have member named '_super' or '_this' - member access is always qualified - return false; - } - if (ts.isInAmbientContext(node)) { - // ambient context - no codegen impact - return false; - } - var root = ts.getRootDeclaration(node); - if (root.kind === 146 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { - // just an overload - no codegen impact - return false; - } - return true; - } - function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { - potentialThisCollisions.push(node); - } - } - function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { - potentialNewTargetCollisions.push(node); - } - } - // this function will run after checking the source file so 'CaptureThis' is correct for all nodes - function checkIfThisIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { - var isDeclaration_1 = node.kind !== 71 /* Identifier */; - if (isDeclaration_1) { - 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); - } - return true; - } - }); - } - function checkIfNewTargetIsCapturedInEnclosingScope(node) { - ts.findAncestor(node, function (current) { - if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { - var isDeclaration_2 = node.kind !== 71 /* Identifier */; - if (isDeclaration_2) { - 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); - } - return true; - } - }); - } - function checkCollisionWithCapturedSuperVariable(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "_super")) { - return; - } - // bubble up and find containing type - var enclosingClass = ts.getContainingClass(node); - // if containing type was not found or it is ambient - exit (no codegen) - if (!enclosingClass || ts.isInAmbientContext(enclosingClass)) { - return; - } - if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71 /* Identifier */; - if (isDeclaration_3) { - error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); - } - else { - error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); - } - } - } - function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - // No need to check for require or exports for ES6 modules and later - if (modulekind >= ts.ModuleKind.ES2015) { - return; - } - if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { - return; - } - // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { - return; - } - // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent - var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { - // If the declaration happens to be in external module, report error that require and exports are reserved keywords - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { - return; - } - // Uninstantiated modules shouldnt do this check - if (node.kind === 233 /* ModuleDeclaration */ && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { - return; - } - // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent - var parent = getDeclarationContainer(node); - if (parent.kind === 265 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { - // If the declaration happens to be in external module, report error that Promise is a reserved identifier. - error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); - } - } - function checkVarDeclaredNamesNotShadowed(node) { - // - ScriptBody : StatementList - // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList - // also occurs in the VarDeclaredNames of StatementList. - // - Block : { StatementList } - // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList - // also occurs in the VarDeclaredNames of StatementList. - // Variable declarations are hoisted to the top of their function scope. They can shadow - // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition - // by the binder as the declaration scope is different. - // A non-initialized declaration is a no-op as the block declaration will resolve before the var - // declaration. the problem is if the declaration has an initializer. this will act as a write to the - // block declared value. this is fine for let, but not const. - // Only consider declarations with initializers, uninitialized const declarations will not - // step on a let/const variable. - // Do not consider const and const declarations, as duplicate block-scoped declarations - // are handled by the binder. - // We are only looking for const declarations that step on let\const declarations from a - // different scope. e.g.: - // { - // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration - // const x = 0; // symbol for this declaration will be 'symbol' - // } - // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { - return; - } - // skip variable declarations that don't have initializers - // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern - // so we'll always treat binding elements as initialized - if (node.kind === 226 /* VariableDeclaration */ && !node.initializer) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol.flags & 1 /* FunctionScopedVariable */) { - var localDeclarationSymbol = resolveName(node, node.name.text, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); - if (localDeclarationSymbol && - localDeclarationSymbol !== symbol && - localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 227 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 208 /* VariableStatement */ && varDeclList.parent.parent - ? varDeclList.parent.parent - : undefined; - // names of block-scoped and function scoped variables can collide only - // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) - var namesShareScope = container && - (container.kind === 207 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 234 /* ModuleBlock */ || - container.kind === 233 /* ModuleDeclaration */ || - container.kind === 265 /* SourceFile */); - // here we know that function scoped variable is shadowed by block scoped one - // if they are defined in the same scope - binder has already reported redeclaration error - // otherwise if variable has an initializer - show error that initialization will fail - // since LHS will be block scoped name instead of function scoped - if (!namesShareScope) { - var name = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); - } - } - } - } - } - // Check that a parameter initializer contains no references to parameters declared to the right of itself - function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 146 /* Parameter */) { - return; - } - var func = ts.getContainingFunction(node); - visit(node.initializer); - function visit(n) { - if (ts.isTypeNode(n) || ts.isDeclarationName(n)) { - // do not dive in types - // skip declaration names (i.e. in object literal expressions) - return; - } - if (n.kind === 179 /* PropertyAccessExpression */) { - // skip property names in property access expression - return visit(n.expression); - } - else if (n.kind === 71 /* Identifier */) { - // check FunctionLikeDeclaration.locals (stores parameters\function local variable) - // if it contains entry with a specified name - var symbol = resolveName(n, n.text, 107455 /* Value */ | 8388608 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { - return; - } - if (symbol.valueDeclaration === node) { - error(n, ts.Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, ts.declarationNameToString(node.name)); - return; - } - // locals map for function contain both parameters and function locals - // so we need to do a bit of extra work to check if reference is legal - var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 146 /* Parameter */ || - symbol.valueDeclaration.kind === 176 /* BindingElement */) { - // it is ok to reference parameter in initializer if either - // - parameter is located strictly on the left of current parameter declaration - if (symbol.valueDeclaration.pos < node.pos) { - return; - } - // - parameter is wrapped in function-like entity - if (ts.findAncestor(n, function (current) { - if (current === node.initializer) { - return "quit"; - } - return ts.isFunctionLike(current.parent) || - // computed property names/initializers in instance property declaration of class like entities - // are executed in constructor and thus deferred - (current.parent.kind === 149 /* PropertyDeclaration */ && - !(ts.hasModifier(current.parent, 32 /* Static */)) && - ts.isClassLike(current.parent.parent)); - })) { - return; - } - // fall through to report error - } - error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); - } - } - else { - return ts.forEachChild(n, visit); - } - } - } - function convertAutoToAny(type) { - return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; - } - // Check variable, parameter, or property declaration - function checkVariableLikeDeclaration(node) { - checkDecorators(node); - checkSourceElement(node.type); - // For a computed property, just check the initializer and exit - // Do not use hasDynamicName here, because that returns false for well known symbols. - // We want to perform checkComputedPropertyName for all computed properties, including - // well known symbols. - if (node.name.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.name); - if (node.initializer) { - checkExpressionCached(node.initializer); - } - } - if (node.kind === 176 /* BindingElement */) { - if (node.parent.kind === 174 /* ObjectBindingPattern */ && languageVersion < 5 /* ESNext */) { - checkExternalEmitHelpers(node, 4 /* Rest */); - } - // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 144 /* ComputedPropertyName */) { - checkComputedPropertyName(node.propertyName); - } - // check private/protected variable access - var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); - var name = node.propertyName || node.name; - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); - markPropertyAsReferenced(property); - if (parent.initializer && property) { - checkPropertyAccessibility(parent, parent.initializer, parentType, property); - } - } - // For a binding pattern, check contained binding elements - if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 175 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { - checkExternalEmitHelpers(node, 512 /* Read */); - } - ts.forEach(node.name.elements, checkSourceElement); - } - // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 146 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { - error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); - return; - } - // For a binding pattern, validate the initializer and exit - if (ts.isBindingPattern(node.name)) { - // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); - checkParameterInitializer(node); - } - return; - } - var symbol = getSymbolOfNode(node); - var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); - if (node === symbol.valueDeclaration) { - // Node is the primary declaration of the symbol, just validate the initializer - // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 215 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, /*headMessage*/ undefined); - checkParameterInitializer(node); - } - } - else { - // Node is a secondary declaration, check that type is identical to primary declaration and check that - // initializer is consistent with type associated with the node - var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { - error(node.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(node.name), typeToString(type), typeToString(declarationType)); - } - if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); - } - if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - 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)); - } - } - if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */) { - // We know we don't have a binding pattern or computed name here - checkExportsOnMergedDeclarations(node); - if (node.kind === 226 /* VariableDeclaration */ || node.kind === 176 /* BindingElement */) { - checkVarDeclaredNamesNotShadowed(node); - } - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - } - function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 146 /* Parameter */ && right.kind === 226 /* VariableDeclaration */) || - (left.kind === 226 /* VariableDeclaration */ && right.kind === 146 /* Parameter */)) { - // Differences in optionality between parameters and variables are allowed. - return true; - } - if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) { - return false; - } - var interestingFlags = 8 /* Private */ | - 16 /* Protected */ | - 256 /* Async */ | - 128 /* Abstract */ | - 64 /* Readonly */ | - 32 /* Static */; - return (ts.getModifierFlags(left) & interestingFlags) === (ts.getModifierFlags(right) & interestingFlags); - } - function checkVariableDeclaration(node) { - checkGrammarVariableDeclaration(node); - return checkVariableLikeDeclaration(node); - } - function checkBindingElement(node) { - checkGrammarBindingElement(node); - return checkVariableLikeDeclaration(node); - } - function checkVariableStatement(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); - ts.forEach(node.declarationList.declarations, checkSourceElement); - } - function checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) { - // We only disallow modifier on a method declaration if it is a property of object-literal-expression - if (node.modifiers && node.parent.kind === 178 /* ObjectLiteralExpression */) { - if (ts.getFunctionFlags(node) & 2 /* Async */) { - if (node.modifiers.length > 1) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); - } - } - } - function checkExpressionStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - } - function checkIfStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 209 /* EmptyStatement */) { - error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); - } - checkSourceElement(node.elseStatement); - } - function checkDoStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkSourceElement(node.statement); - checkExpression(node.expression); - } - function checkWhileStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkExpression(node.expression); - checkSourceElement(node.statement); - } - function checkForStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 227 /* VariableDeclarationList */) { - checkGrammarVariableDeclarationList(node.initializer); - } - } - if (node.initializer) { - if (node.initializer.kind === 227 /* VariableDeclarationList */) { - ts.forEach(node.initializer.declarations, checkVariableDeclaration); - } - else { - checkExpression(node.initializer); - } - } - if (node.condition) - checkExpression(node.condition); - if (node.incrementor) - checkExpression(node.incrementor); - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForOfStatement(node) { - checkGrammarForInOrForOfStatement(node); - if (node.kind === 216 /* ForOfStatement */) { - if (node.awaitModifier) { - 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 (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { - // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled - checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); - } - } - // Check the LHS and RHS - // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS - // via checkRightHandSideOfForOf. - // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. - // Then check that the RHS is assignable to it. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { - checkForInOrForOfVariableDeclaration(node); - } - else { - var varExpr = node.initializer; - var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); - // There may be a destructuring assignment on the left side - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { - // iteratedType may be undefined. In this case, we still want to check the structure of - // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like - // to short circuit the type relation checking as much as possible, so we pass the unknownType. - checkDestructuringAssignment(varExpr, iteratedType || unknownType); - } - else { - var leftType = checkExpression(varExpr); - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access); - // iteratedType will be undefined if the rightType was missing properties/signatures - // required to get its iteratedType (like [Symbol.iterator] or next). This may be - // because we accessed properties from anyType, or it may have led to an error inside - // getElementTypeOfIterable. - if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); - } - } - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInStatement(node) { - // Grammar checking - checkGrammarForInOrForOfStatement(node); - var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 - // In a 'for-in' statement of the form - // for (let VarDecl in Expr) Statement - // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, - // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 227 /* VariableDeclarationList */) { - var variable = node.initializer.declarations[0]; - if (variable && ts.isBindingPattern(variable.name)) { - error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - checkForInOrForOfVariableDeclaration(node); - } - else { - // In a 'for-in' statement of the form - // for (Var in Expr) Statement - // Var must be an expression classified as a reference of type Any or the String primitive type, - // and Expr must be an expression of type Any, an object type, or a type parameter type. - var varExpr = node.initializer; - var leftType = checkExpression(varExpr); - if (varExpr.kind === 177 /* ArrayLiteralExpression */ || varExpr.kind === 178 /* ObjectLiteralExpression */) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); - } - else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { - error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); - } - else { - // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access); - } - } - // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved - // in this case error about missing name is already reported - do not report extra one - if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, 32768 /* Object */ | 540672 /* TypeVariable */ | 16777216 /* NonPrimitive */)) { - error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); - } - checkSourceElement(node.statement); - if (node.locals) { - registerForUnusedIdentifiersCheck(node); - } - } - function checkForInOrForOfVariableDeclaration(iterationStatement) { - var variableDeclarationList = iterationStatement.initializer; - // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. - if (variableDeclarationList.declarations.length >= 1) { - var decl = variableDeclarationList.declarations[0]; - checkVariableDeclaration(decl); - } - } - function checkRightHandSideOfForOf(rhsExpression, awaitModifier) { - var expressionType = checkNonNullExpression(rhsExpression); - return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true, awaitModifier !== undefined); - } - function checkIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable) { - if (isTypeAny(inputType)) { - return inputType; - } - return getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, /*checkAssignability*/ true) || anyType; - } - /** - * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment - * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type - * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. - */ - function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterable, checkAssignability) { - var uplevelIteration = languageVersion >= 2 /* ES2015 */; - var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; - // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 - // or higher, when inside of an async generator or for-await-if, or when - // downlevelIteration is requested. - if (uplevelIteration || downlevelIteration || allowAsyncIterable) { - // We only report errors for an invalid iterable type in ES2015 or higher. - var iteratedType = getIteratedTypeOfIterable(inputType, uplevelIteration ? errorNode : undefined, allowAsyncIterable, allowAsyncIterable, checkAssignability); - if (iteratedType || uplevelIteration) { - return iteratedType; - } - } - var arrayType = inputType; - var reportedError = false; - var hasStringConstituent = false; - // If strings are permitted, remove any string-like constituents from the array type. - // This allows us to find other non-string element types from an array unioned with - // a string. - if (allowStringInput) { - if (arrayType.flags & 65536 /* Union */) { - // After we remove all types that are StringLike, we will know if there was a string constituent - // based on whether the result of filter is a new array. - var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 262178 /* StringLike */); }); - if (filteredTypes !== arrayTypes) { - arrayType = getUnionType(filteredTypes, /*subtypeReduction*/ true); - } - } - else if (arrayType.flags & 262178 /* StringLike */) { - arrayType = neverType; - } - hasStringConstituent = arrayType !== inputType; - if (hasStringConstituent) { - if (languageVersion < 1 /* ES5 */) { - if (errorNode) { - error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher); - reportedError = true; - } - } - // Now that we've removed all the StringLike types, if no constituents remain, then the entire - // arrayOrStringType was a string. - if (arrayType.flags & 8192 /* Never */) { - return stringType; - } - } - } - if (!isArrayLikeType(arrayType)) { - if (errorNode && !reportedError) { - // Which error we report depends on whether we allow strings or if there was a - // string constituent. For example, if the input type is number | string, we - // want to say that number is not an array type. But if the input was just - // number and string input is allowed, we want to say that number is not an - // array type or a string type. - var diagnostic = !allowStringInput || hasStringConstituent - ? downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type - : downlevelIteration - ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; - error(errorNode, diagnostic, typeToString(arrayType)); - } - return hasStringConstituent ? stringType : undefined; - } - var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); - if (hasStringConstituent && arrayElementType) { - // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 262178 /* StringLike */) { - return stringType; - } - return getUnionType([arrayElementType, stringType], /*subtypeReduction*/ true); - } - return arrayElementType; - } - /** - * We want to treat type as an iterable, and get the type it is an iterable of. The iterable - * must have the following structure (annotated with the names of the variables below): - * - * { // iterable - * [Symbol.iterator]: { // iteratorMethod - * (): Iterator - * } - * } - * - * For an async iterable, we expect the following structure: - * - * { // iterable - * [Symbol.asyncIterator]: { // iteratorMethod - * (): AsyncIterator - * } - * } - * - * T is the type we are after. At every level that involves analyzing return types - * of signatures, we union the return types of all the signatures. - * - * Another thing to note is that at any step of this process, we could run into a dead end, - * meaning either the property is missing, or we run into the anyType. If either of these things - * happens, we return undefined to signal that we could not find the iterated type. If a property - * is missing, and the previous step did not result in 'any', then we also give an error if the - * caller requested it. Then the caller can decide what to do in the case where there is no iterated - * type. This is different from returning anyType, because that would signify that we have matched the - * whole pattern and that T (above) is 'any'. - * - * For a **for-of** statement, `yield*` (in a normal generator), spread, array - * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()` - * method. - * - * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method. - * - * For a **for-await-of** statement or a `yield*` in an async generator we will look for - * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method. - */ - function getIteratedTypeOfIterable(type, errorNode, isAsyncIterable, allowNonAsyncIterables, checkAssignability) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterable = type; - if (isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable) { - return isAsyncIterable ? typeAsIterable.iteratedTypeOfAsyncIterable : typeAsIterable.iteratedTypeOfIterable; - } - if (isAsyncIterable) { - // As an optimization, if the type is an instantiation of the global `AsyncIterable` - // or the global `AsyncIterableIterator` then just grab its type argument. - if (isReferenceToType(type, getGlobalAsyncIterableType(/*reportErrors*/ false)) || - isReferenceToType(type, getGlobalAsyncIterableIteratorType(/*reportErrors*/ false))) { - return typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0]; - } - } - if (!isAsyncIterable || allowNonAsyncIterables) { - // As an optimization, if the type is an instantiation of the global `Iterable` or - // `IterableIterator` then just grab its type argument. - if (isReferenceToType(type, getGlobalIterableType(/*reportErrors*/ false)) || - isReferenceToType(type, getGlobalIterableIteratorType(/*reportErrors*/ false))) { - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = type.typeArguments[0] - : typeAsIterable.iteratedTypeOfIterable = type.typeArguments[0]; - } - } - var iteratorMethodSignatures; - var isNonAsyncIterable = false; - if (isAsyncIterable) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0 /* Call */); - } - if (!isAsyncIterable || (allowNonAsyncIterables && !ts.some(iteratorMethodSignatures))) { - var iteratorMethod = getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")); - if (isTypeAny(iteratorMethod)) { - return undefined; - } - iteratorMethodSignatures = iteratorMethod && getSignaturesOfType(iteratorMethod, 0 /* Call */); - isNonAsyncIterable = true; - } - if (ts.some(iteratorMethodSignatures)) { - var iteratorMethodReturnType = getUnionType(ts.map(iteratorMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); - var iteratedType = getIteratedTypeOfIterator(iteratorMethodReturnType, errorNode, /*isAsyncIterator*/ !isNonAsyncIterable); - if (checkAssignability && errorNode && iteratedType) { - // If `checkAssignability` was specified, we were called from - // `checkIteratedTypeOrElementType`. As such, we need to validate that - // the type passed in is actually an Iterable. - checkTypeAssignableTo(type, isNonAsyncIterable - ? createIterableType(iteratedType) - : createAsyncIterableType(iteratedType), errorNode); - } - return isAsyncIterable - ? typeAsIterable.iteratedTypeOfAsyncIterable = iteratedType - : typeAsIterable.iteratedTypeOfIterable = iteratedType; - } - if (errorNode) { - error(errorNode, isAsyncIterable - ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); - } - return undefined; - } - /** - * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on - * Iterators instead of Iterables. Here is the structure: - * - * { // iterator - * next: { // nextMethod - * (): { // nextResult - * value: T // nextValue - * } - * } - * } - * - * For an async iterator, we expect the following structure: - * - * { // iterator - * next: { // nextMethod - * (): PromiseLike<{ // nextResult - * value: T // nextValue - * }> - * } - * } - */ - function getIteratedTypeOfIterator(type, errorNode, isAsyncIterator) { - if (isTypeAny(type)) { - return undefined; - } - var typeAsIterator = type; - if (isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator) { - return isAsyncIterator ? typeAsIterator.iteratedTypeOfAsyncIterator : typeAsIterator.iteratedTypeOfIterator; - } - // As an optimization, if the type is an instantiation of the global `Iterator` (for - // a non-async iterator) or the global `AsyncIterator` (for an async-iterator) then - // just grab its type argument. - var getIteratorType = isAsyncIterator ? getGlobalAsyncIteratorType : getGlobalIteratorType; - if (isReferenceToType(type, getIteratorType(/*reportErrors*/ false))) { - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = type.typeArguments[0] - : typeAsIterator.iteratedTypeOfIterator = type.typeArguments[0]; - } - // Both async and non-async iterators must have a `next` method. - var nextMethod = getTypeOfPropertyOfType(type, "next"); - if (isTypeAny(nextMethod)) { - return undefined; - } - var nextMethodSignatures = nextMethod ? getSignaturesOfType(nextMethod, 0 /* Call */) : emptyArray; - if (nextMethodSignatures.length === 0) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.An_async_iterator_must_have_a_next_method - : ts.Diagnostics.An_iterator_must_have_a_next_method); - } - return undefined; - } - var nextResult = getUnionType(ts.map(nextMethodSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); - if (isTypeAny(nextResult)) { - return undefined; - } - // For an async iterator, we must get the awaited type of the return type. - if (isAsyncIterator) { - nextResult = getAwaitedTypeOfPromise(nextResult, errorNode, ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property); - if (isTypeAny(nextResult)) { - return undefined; - } - } - var nextValue = nextResult && getTypeOfPropertyOfType(nextResult, "value"); - if (!nextValue) { - if (errorNode) { - error(errorNode, isAsyncIterator - ? ts.Diagnostics.The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property - : ts.Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); - } - return undefined; - } - return isAsyncIterator - ? typeAsIterator.iteratedTypeOfAsyncIterator = nextValue - : typeAsIterator.iteratedTypeOfIterator = nextValue; - } - /** - * A generator may have a return type of `Iterator`, `Iterable`, or - * `IterableIterator`. An async generator may have a return type of `AsyncIterator`, - * `AsyncIterable`, or `AsyncIterableIterator`. This function can be used to extract - * the iterated type from this return type for contextual typing and verifying signatures. - */ - function getIteratedTypeOfGenerator(returnType, isAsyncGenerator) { - if (isTypeAny(returnType)) { - return undefined; - } - return getIteratedTypeOfIterable(returnType, /*errorNode*/ undefined, isAsyncGenerator, /*allowNonAsyncIterables*/ false, /*checkAssignability*/ false) - || getIteratedTypeOfIterator(returnType, /*errorNode*/ undefined, isAsyncGenerator); - } - function checkBreakOrContinueStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node) || checkGrammarBreakOrContinueStatement(node); - // TODO: Check that target label is valid - } - function isGetAccessorWithAnnotatedSetAccessor(node) { - return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); - } - function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - 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 */); - } - function checkReturnStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - var functionBlock = ts.getContainingFunction(node); - if (!functionBlock) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); - } - } - var func = ts.getContainingFunction(node); - if (func) { - var signature = getSignatureFromDeclaration(func); - var returnType = getReturnTypeOfSignature(signature); - if (strictNullChecks || node.expression || returnType.flags & 8192 /* Never */) { - var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; - var functionFlags = ts.getFunctionFlags(func); - if (functionFlags & 1 /* Generator */) { - // A generator does not need its return expressions checked against its return type. - // Instead, the yield expressions are checked against the element type. - // TODO: Check return expressions of generators when return type tracking is added - // for generators. - return; - } - if (func.kind === 154 /* SetAccessor */) { - if (node.expression) { - error(node, ts.Diagnostics.Setters_cannot_return_a_value); - } - } - else if (func.kind === 152 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { - error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); - } - } - else if (func.type || isGetAccessorWithAnnotatedSetAccessor(func)) { - if (functionFlags & 2 /* Async */) { - var promisedType = getPromisedTypeOfPromise(returnType); - var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - if (promisedType) { - // If the function has a return type, but promisedType is - // undefined, an error will be reported in checkAsyncFunctionReturnType - // so we don't need to report one here. - checkTypeAssignableTo(awaitedType, promisedType, node); - } - } - else { - checkTypeAssignableTo(exprType, returnType, node); - } - } - } - else if (func.kind !== 152 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) { - // The function has a return type, but the return statement doesn't have an expression. - error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); - } - } - } - function checkWithStatement(node) { - // Grammar checking for withStatement - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.flags & 16384 /* AwaitContext */) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block); - } - } - checkExpression(node.expression); - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; - var end = node.statement.pos; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); - } - } - function checkSwitchStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - var firstDefaultClause; - var hasDuplicateDefaultClause = false; - var expressionType = checkExpression(node.expression); - var expressionIsLiteral = isLiteralType(expressionType); - ts.forEach(node.caseBlock.clauses, function (clause) { - // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 258 /* DefaultClause */ && !hasDuplicateDefaultClause) { - if (firstDefaultClause === undefined) { - firstDefaultClause = clause; - } - else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); - hasDuplicateDefaultClause = true; - } - } - if (produceDiagnostics && clause.kind === 257 /* CaseClause */) { - var caseClause = clause; - // TypeScript 1.0 spec (April 2014): 5.9 - // In a 'switch' statement, each 'case' expression must be of a type that is comparable - // to or from the type of the 'switch' expression. - var caseType = checkExpression(caseClause.expression); - var caseIsLiteral = isLiteralType(caseType); - var comparedExpressionType = expressionType; - if (!caseIsLiteral || !expressionIsLiteral) { - caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType; - comparedExpressionType = getBaseTypeOfLiteralType(expressionType); - } - if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) { - // expressionType is not comparable to caseType, try the reversed check and report errors if it fails - checkTypeComparableTo(caseType, comparedExpressionType, caseClause.expression, /*headMessage*/ undefined); - } - } - ts.forEach(clause.statements, checkSourceElement); - }); - if (node.caseBlock.locals) { - registerForUnusedIdentifiersCheck(node.caseBlock); - } - } - function checkLabeledStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - ts.findAncestor(node.parent, function (current) { - if (ts.isFunctionLike(current)) { - return "quit"; - } - if (current.kind === 222 /* LabeledStatement */ && current.label.text === node.label.text) { - var sourceFile = ts.getSourceFileOfNode(node); - grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); - return true; - } - }); - } - // ensure that label is unique - checkSourceElement(node.statement); - } - function checkThrowStatement(node) { - // Grammar checking - if (!checkGrammarStatementInAmbientContext(node)) { - if (node.expression === undefined) { - grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here); - } - } - if (node.expression) { - checkExpression(node.expression); - } - } - function checkTryStatement(node) { - // Grammar checking - checkGrammarStatementInAmbientContext(node); - checkBlock(node.tryBlock); - var catchClause = node.catchClause; - if (catchClause) { - // Grammar checking - if (catchClause.variableDeclaration) { - if (catchClause.variableDeclaration.type) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation); - } - else if (catchClause.variableDeclaration.initializer) { - grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer); - } - else { - var blockLocals_1 = catchClause.block.locals; - if (blockLocals_1) { - ts.forEachKey(catchClause.locals, function (caughtName) { - var blockLocal = blockLocals_1.get(caughtName); - if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) { - grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName); - } - }); - } - } - } - checkBlock(catchClause.block); - } - if (node.finallyBlock) { - checkBlock(node.finallyBlock); - } - } - function checkIndexConstraints(type) { - var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); - var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); - var stringIndexType = getIndexTypeOfType(type, 0 /* String */); - var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); - if (stringIndexType || numberIndexType) { - ts.forEach(getPropertiesOfObjectType(type), function (prop) { - var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); - }); - if (getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; - for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { - var member = _a[_i]; - // Only process instance properties with computed names here. - // Static properties cannot be in conflict with indexers, - // and properties with literal names were already checked. - if (!(ts.getModifierFlags(member) & 32 /* Static */) && ts.hasDynamicName(member)) { - var propType = getTypeOfSymbol(member.symbol); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); - } - } - } - } - var errorNode; - if (stringIndexType && numberIndexType) { - errorNode = declaredNumberIndexer || declaredStringIndexer; - // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer - if (!errorNode && (getObjectFlags(type) & 2 /* Interface */)) { - var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); }); - errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; - } - } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { - error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); - } - function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { - return; - } - var propDeclaration = prop.valueDeclaration; - // index is numeric and property name is not valid numeric literal - 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 us to rule out cases when both property and indexer are inherited from the base class - var errorNode; - if (propDeclaration && - (propDeclaration.kind === 194 /* BinaryExpression */ || - ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || - prop.parent === containingType.symbol)) { - errorNode = propDeclaration; - } - else if (indexDeclaration) { - errorNode = indexDeclaration; - } - else if (getObjectFlags(containingType) & 2 /* Interface */) { - // for interfaces property and indexer might be inherited from different bases - // check if any base class already has both property and indexer. - // check should be performed only if 'type' is the first type that brings property\indexer together - var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; - } - if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 /* String */ - ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 - : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; - error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); - } - } - } - function checkTypeNameIsReserved(name, message) { - // TS 1.0 spec (April 2014): 3.6.1 - // The predefined type keywords are reserved and cannot be used as names of user defined types. - switch (name.text) { - case "any": - case "number": - case "boolean": - case "string": - case "symbol": - case "void": - case "object": - error(name, message, name.text); - } - } - /** - * Check each type parameter and check that type parameters have no duplicate type parameter declarations - */ - function checkTypeParameters(typeParameterDeclarations) { - if (typeParameterDeclarations) { - var seenDefault = false; - for (var i = 0; i < typeParameterDeclarations.length; i++) { - var node = typeParameterDeclarations[i]; - checkTypeParameter(node); - if (produceDiagnostics) { - if (node.default) { - seenDefault = true; - } - else if (seenDefault) { - error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); - } - for (var j = 0; j < i; j++) { - if (typeParameterDeclarations[j].symbol === node.symbol) { - error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); - } - } - } - } - } - } - /** Check that type parameter lists are identical across multiple declarations */ - function checkTypeParameterListsIdentical(symbol) { - if (symbol.declarations.length === 1) { - return; - } - var links = getSymbolLinks(symbol); - if (!links.typeParametersChecked) { - links.typeParametersChecked = true; - var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol); - if (declarations.length <= 1) { - return; - } - var type = getDeclaredTypeOfSymbol(symbol); - if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { - // Report an error on every conflicting declaration. - var name = symbolToString(symbol); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; - error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name); - } - } - } - } - function areTypeParametersIdentical(declarations, typeParameters) { - var maxTypeArgumentCount = ts.length(typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - // If this declaration has too few or too many type parameters, we report an error - var numTypeParameters = ts.length(declaration.typeParameters); - if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { - return false; - } - for (var i = 0; i < numTypeParameters; i++) { - var source = declaration.typeParameters[i]; - var target = typeParameters[i]; - // If the type parameter node does not have the same as the resolved type - // parameter at this position, we report an error. - if (source.name.text !== target.symbol.name) { - return false; - } - // If the type parameter node does not have an identical constraint as the resolved - // type parameter at this position, we report an error. - var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); - if ((sourceConstraint || targetConstraint) && - (!sourceConstraint || !targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint))) { - return false; - } - // If the type parameter node has a default and it is not identical to the default - // for the type parameter at this position, we report an error. - var sourceDefault = source.default && getTypeFromTypeNode(source.default); - var targetDefault = getDefaultFromTypeParameter(target); - if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) { - return false; - } - } - } - return true; - } - function checkClassExpression(node) { - checkClassLikeDeclaration(node); - checkNodeDeferred(node); - return getTypeOfSymbol(getSymbolOfNode(node)); - } - function checkClassExpressionDeferred(node) { - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassDeclaration(node) { - if (!node.name && !(ts.getModifierFlags(node) & 512 /* Default */)) { - grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); - } - checkClassLikeDeclaration(node); - ts.forEach(node.members, checkSourceElement); - registerForUnusedIdentifiersCheck(node); - } - function checkClassLikeDeclaration(node) { - checkGrammarClassLikeDeclaration(node); - checkDecorators(node); - if (node.name) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkTypeParameters(node.typeParameters); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - var staticType = getTypeOfSymbol(symbol); - checkTypeParameterListsIdentical(symbol); - checkClassForDuplicateDeclarations(node); - // Only check for reserved static identifiers on non-ambient context. - if (!ts.isInAmbientContext(node)) { - checkClassForStaticPropertyNameConflicts(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); - } - var baseTypes = getBaseTypes(type); - if (baseTypes.length && produceDiagnostics) { - var baseType_1 = baseTypes[0]; - var baseConstructorType = getBaseConstructorTypeOfClass(type); - var staticBaseType = getApparentType(baseConstructorType); - checkBaseTypeAccessibility(staticBaseType, baseTypeNode); - checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { - ts.forEach(baseTypeNode.typeArguments, checkSourceElement); - for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { - var constructor = _a[_i]; - if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { - break; - } - } - } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); - checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 540672 /* TypeVariable */ && !isMixinConstructorType(staticType)) { - error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); - } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 540672 /* TypeVariable */)) { - // When the static base type is a "class-like" constructor function (but not actually a class), we verify - // that all instantiated base constructor signatures return the same type. We can simply compare the type - // references (as opposed to checking the structure of the types) because elsewhere we have already checked - // that the base type is a class or interface type (and not, for example, an anonymous object type). - var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (ts.forEach(constructors, function (sig) { return getReturnTypeOfSignature(sig) !== baseType_1; })) { - error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type); - } - } - checkKindsOfPropertyMemberOverrides(type, baseType_1); - } - } - var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); - if (implementedTypeNodes) { - for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { - var typeRefNode = implementedTypeNodes_1[_b]; - if (!ts.isEntityNameExpression(typeRefNode.expression)) { - error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(typeRefNode); - if (produceDiagnostics) { - var t = getTypeFromTypeNode(typeRefNode); - if (t !== unknownType) { - if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_implements_interface_1); - } - else { - error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); - } - } - } - } - } - if (produceDiagnostics) { - checkIndexConstraints(type); - checkTypeForDuplicateIndexSignatures(node); - } - } - function checkBaseTypeAccessibility(type, node) { - var signatures = getSignaturesOfType(type, 1 /* Construct */); - if (signatures.length) { - var declaration = signatures[0].declaration; - if (declaration && ts.getModifierFlags(declaration) & 8 /* Private */) { - var typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!isNodeWithinClass(node, typeClassDeclaration)) { - error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol)); - } - } - } - } - 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 ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; - } - function getClassLikeDeclarationOfSymbol(symbol) { - return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); - } - function getClassOrInterfaceDeclarationsOfSymbol(symbol) { - return ts.filter(symbol.declarations, function (d) { - return d.kind === 229 /* ClassDeclaration */ || d.kind === 230 /* InterfaceDeclaration */; - }); - } - function checkKindsOfPropertyMemberOverrides(type, baseType) { - // TypeScript 1.0 spec (April 2014): 8.2.3 - // A derived class inherits all members from its base class it doesn't override. - // Inheritance means that a derived class implicitly contains all non - overridden members of the base class. - // Both public and private property members are inherited, but only public property members can be overridden. - // A property member in a derived class is said to override a property member in a base class - // when the derived class property member has the same name and kind(instance or static) - // as the base class property member. - // The type of an overriding property member must be assignable(section 3.8.4) - // to the type of the overridden property member, or otherwise a compile - time error occurs. - // Base class instance member functions can be overridden by derived class instance member functions, - // but not by other kinds of members. - // Base class instance member variables and accessors can be overridden by - // derived class instance member variables and accessors, but not by other kinds of members. - // NOTE: assignability is checked in checkClassDeclaration - var baseProperties = getPropertiesOfType(baseType); - for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { - var baseProperty = baseProperties_1[_i]; - var base = getTargetSymbol(baseProperty); - if (base.flags & 16777216 /* Prototype */) { - continue; - } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - 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, - // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated* - // type declaration, derived and base resolve to the same symbol even in the case of generic classes. - if (derived === base) { - // derived class inherits base without override/redeclaration - var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - // It is an error to inherit an abstract member without implementing it or being declared abstract. - // If there is no declaration for the derived class (as in the case of class expressions), - // then the class cannot be declared abstract. - if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(ts.getModifierFlags(derivedClassDecl) & 128 /* Abstract */))) { - if (derivedClassDecl.kind === 199 /* ClassExpression */) { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); - } - else { - error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType)); - } - } - } - else { - // derived overrides base. - 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 (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; - } - var errorMessage = void 0; - if (isMethodLike(base)) { - if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; - } - } - else if (base.flags & 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; - } - else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; - } - error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); - } - } - } - } - function isAccessor(kind) { - return kind === 153 /* GetAccessor */ || kind === 154 /* SetAccessor */; - } - function checkInheritedPropertiesAreIdentical(type, typeNode) { - var baseTypes = getBaseTypes(type); - if (baseTypes.length < 2) { - return true; - } - var seen = ts.createMap(); - ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.name, { prop: p, containingType: type }); }); - var ok = true; - for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { - var base = baseTypes_2[_i]; - var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0, properties_8 = properties; _a < properties_8.length; _a++) { - var prop = properties_8[_a]; - var existing = seen.get(prop.name); - if (!existing) { - seen.set(prop.name, { prop: prop, containingType: base }); - } - else { - var isInheritedProperty = existing.containingType !== type; - if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { - ok = false; - var typeName1 = typeToString(existing.containingType); - var typeName2 = typeToString(base); - var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo)); - } - } - } - } - return ok; - } - function checkInterfaceDeclaration(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); - checkTypeParameters(node.typeParameters); - if (produceDiagnostics) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - checkTypeParameterListsIdentical(symbol); - // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 230 /* InterfaceDeclaration */); - if (node === firstInterfaceDecl) { - var type = getDeclaredTypeOfSymbol(symbol); - var typeWithThis = getTypeWithThisArgument(type); - // run subsequent checks only if first set succeeded - if (checkInheritedPropertiesAreIdentical(type, node.name)) { - for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) { - var baseType = _a[_i]; - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1); - } - checkIndexConstraints(type); - } - } - checkObjectTypeForDuplicateDeclarations(node); - } - ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) { - if (!ts.isEntityNameExpression(heritageElement.expression)) { - error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments); - } - checkTypeReferenceNode(heritageElement); - }); - ts.forEach(node.members, checkSourceElement); - if (produceDiagnostics) { - checkTypeForDuplicateIndexSignatures(node); - registerForUnusedIdentifiersCheck(node); - } - } - function checkTypeAliasDeclaration(node) { - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); - checkTypeParameters(node.typeParameters); - checkSourceElement(node.type); - } - function computeEnumMemberValues(node) { - var nodeLinks = getNodeLinks(node); - if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) { - nodeLinks.flags |= 16384 /* EnumValuesComputed */; - var autoValue = 0; - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - var value = computeMemberValue(member, autoValue); - getNodeLinks(member).enumMemberValue = value; - autoValue = typeof value === "number" ? value + 1 : undefined; - } - } - } - 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); - } - } - 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; - } - } - 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; - case 47 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right; - case 45 /* LessThanLessThanToken */: return left << right; - case 50 /* CaretToken */: return left ^ right; - case 39 /* AsteriskToken */: return left * right; - case 41 /* SlashToken */: return left / right; - case 37 /* PlusToken */: return left + right; - case 38 /* MinusToken */: return left - right; - case 42 /* PercentToken */: return left % right; - } - } - 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); - } - } - 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; - } - // Grammar checking - checkGrammarDecorators(node) || checkGrammarModifiers(node); - checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkExportsOnMergedDeclarations(node); - computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && ts.isInAmbientContext(node)) { - error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); - } - // Spec 2014 - Section 9.3: - // It isn't possible for one enum declaration to continue the automatic numbering sequence of another, - // and when an enum type has multiple declarations, only one declaration is permitted to omit a value - // for the first member. - // - // Only perform this check once per symbol - var enumSymbol = getSymbolOfNode(node); - var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind); - if (node === firstDeclaration) { - if (enumSymbol.declarations.length > 1) { - // check that const is placed\omitted on all enum declarations - ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); - } - }); - } - var seenEnumMissingInitialInitializer_1 = false; - ts.forEach(enumSymbol.declarations, function (declaration) { - // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 232 /* EnumDeclaration */) { - return false; - } - var enumDeclaration = declaration; - if (!enumDeclaration.members.length) { - return false; - } - var firstEnumMember = enumDeclaration.members[0]; - if (!firstEnumMember.initializer) { - if (seenEnumMissingInitialInitializer_1) { - error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); - } - else { - seenEnumMissingInitialInitializer_1 = true; - } - } - }); - } - } - function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { - var declarations = symbol.declarations; - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; - if ((declaration.kind === 229 /* ClassDeclaration */ || - (declaration.kind === 228 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !ts.isInAmbientContext(declaration)) { - return declaration; - } - } - return undefined; - } - function inSameLexicalScope(node1, node2) { - var container1 = ts.getEnclosingBlockScopeContainer(node1); - var container2 = ts.getEnclosingBlockScopeContainer(node2); - if (isGlobalSourceFile(container1)) { - return isGlobalSourceFile(container2); - } - else if (isGlobalSourceFile(container2)) { - return false; - } - else { - return container1 === container2; - } - } - function checkModuleDeclaration(node) { - if (produceDiagnostics) { - // Grammar checking - var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = ts.isInAmbientContext(node); - if (isGlobalAugmentation && !inAmbientContext) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); - } - var isAmbientExternalModule = ts.isAmbientModule(node); - var contextErrorMessage = isAmbientExternalModule - ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file - : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; - if (checkGrammarModuleElementContext(node, contextErrorMessage)) { - // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node)) { - if (!inAmbientContext && node.name.kind === 9 /* StringLiteral */) { - grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - } - if (ts.isIdentifier(node.name)) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - } - checkExportsOnMergedDeclarations(node); - var symbol = getSymbolOfNode(node); - // The following checks only apply on a non-ambient instantiated module declaration. - if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 - && !inAmbientContext - && ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { - var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); - if (firstNonAmbientClassOrFunc) { - if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); - } - else if (node.pos < firstNonAmbientClassOrFunc.pos) { - error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged); - } - } - // if the module merges with a class declaration in the same lexical scope, - // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 229 /* ClassDeclaration */); - if (mergedClass && - inSameLexicalScope(node, mergedClass)) { - getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; - } - } - if (isAmbientExternalModule) { - if (ts.isExternalModuleAugmentation(node)) { - // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module) - // otherwise we'll be swamped in cascading errors. - // We can detect if augmentation was applied using following rules: - // - augmentation for a global scope is always applied - // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728 /* Transient */); - if (checkBody && node.body) { - // body of ambient external module is always a module block - for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - checkModuleAugmentationElement(statement, isGlobalAugmentation); - } - } - } - else if (isGlobalSourceFile(node.parent)) { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else if (ts.isExternalModuleNameRelative(node.name.text)) { - error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name); - } - } - else { - if (isGlobalAugmentation) { - error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations); - } - else { - // Node is not an augmentation and is not located on the script level. - // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited. - error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces); - } - } - } - } - if (node.body) { - checkSourceElement(node.body); - if (!ts.isGlobalScopeAugmentation(node)) { - registerForUnusedIdentifiersCheck(node); - } - } - } - function checkModuleAugmentationElement(node, isGlobalAugmentation) { - switch (node.kind) { - case 208 /* VariableStatement */: - // error each individual name in variable statement instead of marking the entire variable statement - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - checkModuleAugmentationElement(decl, isGlobalAugmentation); - } - break; - case 243 /* ExportAssignment */: - case 244 /* ExportDeclaration */: - grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); - break; - case 237 /* ImportEqualsDeclaration */: - case 238 /* ImportDeclaration */: - grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); - break; - case 176 /* BindingElement */: - case 226 /* VariableDeclaration */: - var name = node.name; - if (ts.isBindingPattern(name)) { - for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { - var el = _c[_b]; - // mark individual names in binding pattern - checkModuleAugmentationElement(el, isGlobalAugmentation); - } - break; - } - // falls through - case 229 /* ClassDeclaration */: - case 232 /* EnumDeclaration */: - case 228 /* FunctionDeclaration */: - case 230 /* InterfaceDeclaration */: - case 233 /* ModuleDeclaration */: - case 231 /* TypeAliasDeclaration */: - if (isGlobalAugmentation) { - return; - } - var symbol = getSymbolOfNode(node); - if (symbol) { - // module augmentations cannot introduce new names on the top level scope of the module - // this is done it two steps - // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error - // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 134217728 /* Transient */); - if (!reportError) { - // symbol should not originate in augmentation - reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); - } - } - break; - } - } - function getFirstIdentifier(node) { - switch (node.kind) { - case 71 /* Identifier */: - return node; - case 143 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 71 /* Identifier */); - return node; - case 179 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 71 /* Identifier */); - return node; - } - } - function checkExternalImportOrExportDeclaration(node) { - var moduleName = ts.getExternalModuleName(node); - if (!ts.nodeIsMissing(moduleName) && moduleName.kind !== 9 /* StringLiteral */) { - error(moduleName, ts.Diagnostics.String_literal_expected); - return false; - } - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 244 /* ExportDeclaration */ ? - ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : - ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); - return false; - } - if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) { - // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration - // no need to do this again. - if (!isTopLevelInExternalModuleAugmentation(node)) { - // TypeScript 1.0 spec (April 2013): 12.1.6 - // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference - // other external modules only through top - level external module names. - // Relative external module names are not permitted. - error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name); - return false; - } - } - return true; - } - function checkAliasSymbol(node) { - var symbol = getSymbolOfNode(node); - var target = resolveAlias(symbol); - if (target !== unknownSymbol) { - // For external modules symbol represent local symbol for an alias. - // This local symbol will merge any other local declarations (excluding other aliases) - // and symbol.flags will contains combined representation for all merged declaration. - // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have, - // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export* - // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names). - var excludedMeanings = (symbol.flags & (107455 /* Value */ | 1048576 /* ExportValue */) ? 107455 /* Value */ : 0) | - (symbol.flags & 793064 /* Type */ ? 793064 /* Type */ : 0) | - (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); - if (target.flags & excludedMeanings) { - var message = node.kind === 246 /* ExportSpecifier */ ? - ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : - 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) { - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); - checkAliasSymbol(node); - } - function checkImportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); - } - if (checkExternalImportOrExportDeclaration(node)) { - var importClause = node.importClause; - if (importClause) { - if (importClause.name) { - checkImportBinding(importClause); - } - if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 240 /* NamespaceImport */) { - checkImportBinding(importClause.namedBindings); - } - else { - ts.forEach(importClause.namedBindings.elements, checkImportBinding); - } - } - } - } - } - function checkImportEqualsDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { - // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. - return; - } - checkGrammarDecorators(node) || checkGrammarModifiers(node); - if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { - checkImportBinding(node); - if (ts.getModifierFlags(node) & 1 /* Export */) { - markExportAsReferenced(node); - } - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - var target = resolveAlias(getSymbolOfNode(node)); - if (target !== unknownSymbol) { - if (target.flags & 107455 /* Value */) { - // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); - if (!(resolveEntityName(moduleName, 107455 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { - error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); - } - } - if (target.flags & 793064 /* Type */) { - checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0); - } - } - } - else { - if (modulekind === ts.ModuleKind.ES2015 && !ts.isInAmbientContext(node)) { - // Import equals declaration is deprecated in es6 or above - grammarErrorOnNode(node, ts.Diagnostics.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); - } - } - } - } - function checkExportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { - // If we hit an export in an illegal context, just bail out to avoid cascading errors. - return; - } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); - } - if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { - if (node.exportClause) { - // export { x, y } - // export { x, y } from "foo" - ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 234 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 234 /* ModuleBlock */ && - !node.moduleSpecifier && ts.isInAmbientContext(node); - if (node.parent.kind !== 265 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { - error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); - } - } - else { - // export * from "foo" - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); - } - } - } - } - function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 265 /* SourceFile */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 233 /* ModuleDeclaration */; - if (!isInAppropriateContext) { - grammarErrorOnFirstToken(node, errorMessage); - } - return !isInAppropriateContext; - } - function checkExportSpecifier(node) { - checkAliasSymbol(node); - if (!node.parent.parent.moduleSpecifier) { - var exportedName = node.propertyName || node.name; - // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - var symbol = resolveName(exportedName, exportedName.text, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */, - /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, exportedName.text); - } - else { - markExportAsReferenced(node); - } - } - } - function checkExportAssignment(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) { - // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. - return; - } - var container = node.parent.kind === 265 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 233 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { - if (node.isExportEquals) { - error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); - } - else { - error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); - } - return; - } - // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && ts.getModifierFlags(node) !== 0) { - grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); - } - if (node.expression.kind === 71 /* Identifier */) { - markExportAsReferenced(node); - } - else { - checkExpressionCached(node.expression); - } - checkExternalModuleExports(container); - if (node.isExportEquals && !ts.isInAmbientContext(node)) { - if (modulekind === ts.ModuleKind.ES2015) { - // export assignment is not supported in es6 modules - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); - } - else if (modulekind === ts.ModuleKind.System) { - // system modules does not support export assignment - grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); - } - } - } - function hasExportedMembers(moduleSymbol) { - return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; }); - } - function checkExternalModuleExports(node) { - var moduleSymbol = getSymbolOfNode(node); - var links = getSymbolLinks(moduleSymbol); - if (!links.exportsChecked) { - var exportEqualsSymbol = moduleSymbol.exports.get("export="); - if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { - var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration)) { - error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); - } - } - // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - exports && exports.forEach(function (_a, id) { - var declarations = _a.declarations, flags = _a.flags; - if (id === "__export") { - return; - } - // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. - // (TS Exceptions: namespaces, function overloads, enums, and interfaces) - if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) { - return; - } - var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverload); - if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) { - // it is legal to merge type alias with other values - // so count should be either 1 (just type alias) or 2 (type alias + merged value) - return; - } - if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; - if (isNotOverload(declaration)) { - diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, id)); - } - } - } - }); - links.exportsChecked = true; - } - function isNotOverload(declaration) { - return (declaration.kind !== 228 /* FunctionDeclaration */ && declaration.kind !== 151 /* MethodDeclaration */) || - !!declaration.body; - } - } - function checkSourceElement(node) { - if (!node) { - return; - } - var kind = node.kind; - if (cancellationToken) { - // Only bother checking on a few construct kinds. We don't want to be excessively - // hitting the cancellation token on every node we check. - switch (kind) { - case 233 /* ModuleDeclaration */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 228 /* FunctionDeclaration */: - cancellationToken.throwIfCancellationRequested(); - } - } - switch (kind) { - case 145 /* TypeParameter */: - return checkTypeParameter(node); - case 146 /* Parameter */: - return checkParameter(node); - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - return checkPropertyDeclaration(node); - case 160 /* FunctionType */: - case 161 /* ConstructorType */: - case 155 /* CallSignature */: - case 156 /* ConstructSignature */: - return checkSignatureDeclaration(node); - case 157 /* IndexSignature */: - return checkSignatureDeclaration(node); - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - return checkMethodDeclaration(node); - case 152 /* Constructor */: - return checkConstructorDeclaration(node); - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - return checkAccessorDeclaration(node); - case 159 /* TypeReference */: - return checkTypeReferenceNode(node); - case 158 /* TypePredicate */: - return checkTypePredicate(node); - case 162 /* TypeQuery */: - return checkTypeQuery(node); - case 163 /* TypeLiteral */: - return checkTypeLiteral(node); - case 164 /* ArrayType */: - return checkArrayType(node); - case 165 /* TupleType */: - return checkTupleType(node); - case 166 /* UnionType */: - case 167 /* IntersectionType */: - return checkUnionOrIntersectionType(node); - case 168 /* ParenthesizedType */: - case 170 /* TypeOperator */: - return checkSourceElement(node.type); - case 171 /* IndexedAccessType */: - return checkIndexedAccessType(node); - case 172 /* MappedType */: - return checkMappedType(node); - case 228 /* FunctionDeclaration */: - return checkFunctionDeclaration(node); - case 207 /* Block */: - case 234 /* ModuleBlock */: - return checkBlock(node); - case 208 /* VariableStatement */: - return checkVariableStatement(node); - case 210 /* ExpressionStatement */: - return checkExpressionStatement(node); - case 211 /* IfStatement */: - return checkIfStatement(node); - case 212 /* DoStatement */: - return checkDoStatement(node); - case 213 /* WhileStatement */: - return checkWhileStatement(node); - case 214 /* ForStatement */: - return checkForStatement(node); - case 215 /* ForInStatement */: - return checkForInStatement(node); - case 216 /* ForOfStatement */: - return checkForOfStatement(node); - case 217 /* ContinueStatement */: - case 218 /* BreakStatement */: - return checkBreakOrContinueStatement(node); - case 219 /* ReturnStatement */: - return checkReturnStatement(node); - case 220 /* WithStatement */: - return checkWithStatement(node); - case 221 /* SwitchStatement */: - return checkSwitchStatement(node); - case 222 /* LabeledStatement */: - return checkLabeledStatement(node); - case 223 /* ThrowStatement */: - return checkThrowStatement(node); - case 224 /* TryStatement */: - return checkTryStatement(node); - case 226 /* VariableDeclaration */: - return checkVariableDeclaration(node); - case 176 /* BindingElement */: - return checkBindingElement(node); - case 229 /* ClassDeclaration */: - return checkClassDeclaration(node); - case 230 /* InterfaceDeclaration */: - return checkInterfaceDeclaration(node); - case 231 /* TypeAliasDeclaration */: - return checkTypeAliasDeclaration(node); - case 232 /* EnumDeclaration */: - return checkEnumDeclaration(node); - case 233 /* ModuleDeclaration */: - return checkModuleDeclaration(node); - case 238 /* ImportDeclaration */: - return checkImportDeclaration(node); - case 237 /* ImportEqualsDeclaration */: - return checkImportEqualsDeclaration(node); - case 244 /* ExportDeclaration */: - return checkExportDeclaration(node); - case 243 /* ExportAssignment */: - return checkExportAssignment(node); - case 209 /* EmptyStatement */: - checkGrammarStatementInAmbientContext(node); - return; - case 225 /* DebuggerStatement */: - checkGrammarStatementInAmbientContext(node); - return; - case 247 /* MissingDeclaration */: - return checkMissingDeclaration(node); - } - } - // Function and class expression bodies are checked after all statements in the enclosing body. This is - // to ensure constructs like the following are permitted: - // const foo = function () { - // const s = foo(); - // return "hello"; - // } - // Here, performing a full type check of the body of the function expression whilst in the process of - // determining the type of foo would cause foo to be given type any because of the recursive reference. - // Delaying the type check of the body ensures foo has been assigned a type. - function checkNodeDeferred(node) { - if (deferredNodes) { - deferredNodes.push(node); - } - } - function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; - switch (node.kind) { - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - checkFunctionExpressionOrObjectLiteralMethodDeferred(node); - break; - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - checkAccessorDeclaration(node); - break; - case 199 /* ClassExpression */: - checkClassExpressionDeferred(node); - break; - } - } - } - function checkSourceFile(node) { - ts.performance.mark("beforeCheck"); - checkSourceFileWorker(node); - ts.performance.mark("afterCheck"); - ts.performance.measure("Check", "beforeCheck", "afterCheck"); - } - // Fully type check a source file and collect the relevant diagnostics. - function checkSourceFileWorker(node) { - var links = getNodeLinks(node); - if (!(links.flags & 1 /* TypeChecked */)) { - // If skipLibCheck is enabled, skip type checking if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip type checking if file contains a - // '/// ' directive. - if (compilerOptions.skipLibCheck && node.isDeclarationFile || compilerOptions.skipDefaultLibCheck && node.hasNoDefaultLib) { - return; - } - // Grammar checking - checkGrammarSourceFile(node); - potentialThisCollisions.length = 0; - potentialNewTargetCollisions.length = 0; - deferredNodes = []; - deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; - ts.forEach(node.statements, checkSourceElement); - checkDeferredNodes(); - if (ts.isExternalModule(node)) { - registerForUnusedIdentifiersCheck(node); - } - if (!node.isDeclarationFile) { - checkUnusedIdentifiers(); - } - deferredNodes = undefined; - deferredUnusedIdentifierNodes = undefined; - if (ts.isExternalOrCommonJsModule(node)) { - checkExternalModuleExports(node); - } - if (potentialThisCollisions.length) { - ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope); - potentialThisCollisions.length = 0; - } - if (potentialNewTargetCollisions.length) { - ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope); - potentialNewTargetCollisions.length = 0; - } - links.flags |= 1 /* TypeChecked */; - } - } - function getDiagnostics(sourceFile, ct) { - try { - // Record the cancellation token so it can be checked later on during checkSourceElement. - // Do this in a finally block so we can ensure that it gets reset back to nothing after - // this call is done. - cancellationToken = ct; - return getDiagnosticsWorker(sourceFile); - } - finally { - cancellationToken = undefined; - } - } - function getDiagnosticsWorker(sourceFile) { - throwIfNonDiagnosticsProducing(); - if (sourceFile) { - // Some global diagnostics are deferred until they are needed and - // may not be reported in the firt call to getGlobalDiagnostics. - // We should catch these changes and report them. - var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; - checkSourceFile(sourceFile); - var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); - var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); - if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { - // If the arrays are not the same reference, new diagnostics were added. - var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics); - return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics); - } - else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) { - // If the arrays are the same reference, but the length has changed, a single - // new diagnostic was added as DiagnosticCollection attempts to reuse the - // same array. - return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics); - } - return semanticDiagnostics; - } - // Global diagnostics are always added when a file is not provided to - // getDiagnostics - ts.forEach(host.getSourceFiles(), checkSourceFile); - return diagnostics.getDiagnostics(); - } - function getGlobalDiagnostics() { - throwIfNonDiagnosticsProducing(); - return diagnostics.getGlobalDiagnostics(); - } - function throwIfNonDiagnosticsProducing() { - if (!produceDiagnostics) { - throw new Error("Trying to get diagnostics from a type checker that does not produce them."); - } - } - // Language service support - function isInsideWithStatementBody(node) { - if (node) { - while (node.parent) { - if (node.parent.kind === 220 /* WithStatement */ && node.parent.statement === node) { - return true; - } - node = node.parent; - } - } - return false; - } - function getSymbolsInScope(location, meaning) { - if (isInsideWithStatementBody(location)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return []; - } - var symbols = ts.createMap(); - var memberFlags = 0 /* None */; - populateSymbols(); - return symbolsToArray(symbols); - function populateSymbols() { - while (location) { - if (location.locals && !isGlobalSourceFile(location)) { - copySymbols(location.locals, meaning); - } - switch (location.kind) { - case 265 /* SourceFile */: - if (!ts.isExternalOrCommonJsModule(location)) { - break; - } - // falls through - case 233 /* ModuleDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8914931 /* ModuleMember */); - break; - case 232 /* EnumDeclaration */: - copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); - break; - case 199 /* ClassExpression */: - var className = location.name; - if (className) { - copySymbol(location.symbol, meaning); - } - // falls through - // this fall-through is necessary because we would like to handle - // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - // If we didn't come from static member of class or interface, - // add the type parameters into the symbol table - // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. - // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 32 /* Static */)) { - copySymbols(getSymbolOfNode(location).members, meaning & 793064 /* Type */); - } - break; - case 186 /* FunctionExpression */: - var funcName = location.name; - if (funcName) { - copySymbol(location.symbol, meaning); - } - break; - } - if (ts.introducesArgumentsExoticObject(location)) { - copySymbol(argumentsSymbol, meaning); - } - memberFlags = ts.getModifierFlags(location); - location = location.parent; - } - copySymbols(globals, meaning); - } - /** - * Copy the given symbol into symbol tables if the symbol has the given meaning - * and it doesn't already existed in the symbol table - * @param key a key for storing in symbol table; if undefined, use symbol.name - * @param symbol the symbol to be added into symbol table - * @param meaning meaning of symbol to filter by before adding to symbol table - */ - function copySymbol(symbol, meaning) { - if (symbol.flags & meaning) { - var id = symbol.name; - // We will copy all symbol regardless of its reserved name because - // symbolsToArray will check whether the key is a reserved name and - // it will not copy symbol with reserved name to the array - if (!symbols.has(id)) { - symbols.set(id, symbol); - } - } - } - function copySymbols(source, meaning) { - if (meaning) { - source.forEach(function (symbol) { - copySymbol(symbol, meaning); - }); - } - } - } - function isTypeDeclarationName(name) { - return name.kind === 71 /* Identifier */ && - isTypeDeclaration(name.parent) && - name.parent.name === name; - } - function isTypeDeclaration(node) { - switch (node.kind) { - case 145 /* TypeParameter */: - case 229 /* ClassDeclaration */: - case 230 /* InterfaceDeclaration */: - case 231 /* TypeAliasDeclaration */: - case 232 /* EnumDeclaration */: - return true; - } - } - // True if the given identifier is part of a type reference - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 143 /* QualifiedName */) { - node = node.parent; - } - return node.parent && (node.parent.kind === 159 /* TypeReference */ || node.parent.kind === 277 /* JSDocTypeReference */); - } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 179 /* PropertyAccessExpression */) { - node = node.parent; - } - return node.parent && node.parent.kind === 201 /* ExpressionWithTypeArguments */; - } - function forEachEnclosingClass(node, callback) { - var result; - while (true) { - node = ts.getContainingClass(node); - if (!node) - break; - if (result = callback(node)) - break; - } - return result; - } - function isNodeWithinClass(node, classDeclaration) { - return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); - } - function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 143 /* QualifiedName */) { - nodeOnRightSide = nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 237 /* ImportEqualsDeclaration */) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; - } - if (nodeOnRightSide.parent.kind === 243 /* ExportAssignment */) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; - } - return undefined; - } - function isInRightSideOfImportOrExportAssignment(node) { - return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined; - } - function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) { - var specialPropertyAssignmentKind = ts.getSpecialPropertyAssignmentKind(entityName.parent.parent); - switch (specialPropertyAssignmentKind) { - case 1 /* ExportsProperty */: - case 3 /* PrototypeProperty */: - return getSymbolOfNode(entityName.parent); - case 4 /* ThisProperty */: - case 2 /* ModuleExports */: - case 5 /* Property */: - return getSymbolOfNode(entityName.parent.parent); - } - } - function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { - if (ts.isDeclarationName(entityName)) { - return getSymbolOfNode(entityName.parent); - } - if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 179 /* PropertyAccessExpression */ && - entityName.parent === entityName.parent.parent.left) { - // Check if this is a special property assignment - var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); - if (specialPropertyAssignmentSymbol) { - return specialPropertyAssignmentSymbol; - } - } - if (entityName.parent.kind === 243 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, - /*all meanings*/ 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); - } - if (entityName.kind !== 179 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { - // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 237 /* ImportEqualsDeclaration */); - ts.Debug.assert(importEqualsDeclaration !== undefined); - return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); - } - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { - entityName = entityName.parent; - } - if (isHeritageClauseElementIdentifier(entityName)) { - var meaning = 0 /* None */; - // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 201 /* ExpressionWithTypeArguments */) { - meaning = 793064 /* Type */; - // In a class 'extends' clause we are also looking for a value. - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { - meaning |= 107455 /* Value */; - } - } - else { - meaning = 1920 /* Namespace */; - } - meaning |= 8388608 /* Alias */; - var entityNameSymbol = resolveEntityName(entityName, meaning); - if (entityNameSymbol) { - return entityNameSymbol; - } - } - if (ts.isPartOfExpression(entityName)) { - if (ts.nodeIsMissing(entityName)) { - // Missing entity name. - return undefined; - } - if (entityName.kind === 71 /* Identifier */) { - if (ts.isJSXTagName(entityName) && isJsxIntrinsicIdentifier(entityName)) { - return getIntrinsicTagSymbol(entityName.parent); - } - return resolveEntityName(entityName, 107455 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); - } - else if (entityName.kind === 179 /* PropertyAccessExpression */) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkPropertyAccessExpression(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - else if (entityName.kind === 143 /* QualifiedName */) { - var symbol = getNodeLinks(entityName).resolvedSymbol; - if (!symbol) { - checkQualifiedName(entityName); - } - return getNodeLinks(entityName).resolvedSymbol; - } - } - else if (isTypeReferenceIdentifier(entityName)) { - var meaning = (entityName.parent.kind === 159 /* TypeReference */ || entityName.parent.kind === 277 /* JSDocTypeReference */) ? 793064 /* Type */ : 1920 /* Namespace */; - return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); - } - else if (entityName.parent.kind === 253 /* JsxAttribute */) { - return getJsxAttributePropertySymbol(entityName.parent); - } - if (entityName.parent.kind === 158 /* TypePredicate */) { - return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); - } - // Do we want to return undefined here? - return undefined; - } - function getSymbolAtLocation(node) { - if (node.kind === 265 /* SourceFile */) { - return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; - } - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return undefined; - } - if (isDeclarationNameOrImportPropertyName(node)) { - // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(node.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); - } - if (node.kind === 71 /* Identifier */) { - if (isInRightSideOfImportOrExportAssignment(node)) { - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - } - else if (node.parent.kind === 176 /* BindingElement */ && - node.parent.parent.kind === 174 /* ObjectBindingPattern */ && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); - var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.text); - if (propertyDeclaration) { - return propertyDeclaration; - } - } - } - switch (node.kind) { - case 71 /* Identifier */: - case 179 /* PropertyAccessExpression */: - case 143 /* QualifiedName */: - return getSymbolOfEntityNameOrPropertyAccessExpression(node); - case 99 /* ThisKeyword */: - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - if (ts.isFunctionLike(container)) { - var sig = getSignatureFromDeclaration(container); - if (sig.thisParameter) { - return sig.thisParameter; - } - } - // falls through - case 97 /* SuperKeyword */: - var type = ts.isPartOfExpression(node) ? getTypeOfExpression(node) : getTypeFromTypeNode(node); - return type.symbol; - case 169 /* ThisType */: - return getTypeFromTypeNode(node).symbol; - case 123 /* ConstructorKeyword */: - // constructor keyword for an overload, should take us to the definition if it exist - var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 152 /* Constructor */) { - return constructorDeclaration.parent.symbol; - } - return undefined; - case 9 /* StringLiteral */: - // External module name in an import declaration - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { - return resolveExternalModuleName(node, node); - } - // falls through - case 8 /* NumericLiteral */: - // index access - if (node.parent.kind === 180 /* ElementAccessExpression */ && node.parent.argumentExpression === node) { - var objectType = getTypeOfExpression(node.parent.expression); - if (objectType === unknownType) - return undefined; - var apparentType = getApparentType(objectType); - if (apparentType === unknownType) - return undefined; - return getPropertyOfType(apparentType, node.text); - } - break; - } - return undefined; - } - function getShorthandAssignmentValueSymbol(location) { - // The function returns a value symbol of an identifier in the short-hand property assignment. - // This is necessary as an identifier in short-hand property assignment can contains two meaning: - // property name and property value. - if (location && location.kind === 262 /* ShorthandPropertyAssignment */) { - return resolveEntityName(location.name, 107455 /* Value */ | 8388608 /* Alias */); - } - return undefined; - } - /** Returns the target of an export specifier without following aliases */ - function getExportSpecifierLocalTargetSymbol(node) { - return node.parent.parent.moduleSpecifier ? - getExternalModuleMember(node.parent.parent, node) : - resolveEntityName(node.propertyName || node.name, 107455 /* Value */ | 793064 /* Type */ | 1920 /* Namespace */ | 8388608 /* Alias */); - } - function getTypeOfNode(node) { - if (isInsideWithStatementBody(node)) { - // We cannot answer semantic questions within a with block, do not proceed any further - return unknownType; - } - if (ts.isPartOfTypeNode(node)) { - var typeFromTypeNode = getTypeFromTypeNode(node); - if (typeFromTypeNode && ts.isExpressionWithTypeArgumentsInClassImplementsClause(node)) { - var containingClass = ts.getContainingClass(node); - var classType = getTypeOfNode(containingClass); - typeFromTypeNode = getTypeWithThisArgument(typeFromTypeNode, classType.thisType); - } - return typeFromTypeNode; - } - if (ts.isPartOfExpression(node)) { - return getRegularTypeOfExpression(node); - } - if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(node)) { - // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the - // extends clause of a class. We handle that case here. - var classNode = ts.getContainingClass(node); - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classNode)); - var baseType = getBaseTypes(classType)[0]; - return baseType && getTypeWithThisArgument(baseType, classType.thisType); - } - if (isTypeDeclaration(node)) { - // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - var symbol = getSymbolOfNode(node); - return getDeclaredTypeOfSymbol(symbol); - } - if (isTypeDeclarationName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); - } - if (ts.isDeclaration(node)) { - // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - var symbol = getSymbolOfNode(node); - return getTypeOfSymbol(symbol); - } - if (isDeclarationNameOrImportPropertyName(node)) { - var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); - } - if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); - } - if (isInRightSideOfImportOrExportAssignment(node)) { - var symbol = getSymbolAtLocation(node); - var declaredType = symbol && getDeclaredTypeOfSymbol(symbol); - return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); - } - return unknownType; - } - // Gets the type of object literal or array literal of destructuring assignment. - // { a } from - // for ( { a } of elems) { - // } - // [ a ] from - // [a] = [ some array ...] - function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 178 /* ObjectLiteralExpression */ || expr.kind === 177 /* ArrayLiteralExpression */); - // If this is from "for of" - // for ( { a } of elems) { - // } - if (expr.parent.kind === 216 /* ForOfStatement */) { - var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - // If this is from "for" initializer - // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 194 /* BinaryExpression */) { - var iteratedType = getTypeOfExpression(expr.parent.right); - return checkDestructuringAssignment(expr, iteratedType || unknownType); - } - // If this is from nested object binding pattern - // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 261 /* PropertyAssignment */) { - var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); - } - // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 177 /* ArrayLiteralExpression */); - // [{ property1: p1, property2 }] = elems; - var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterable*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); - } - // Gets the property symbol corresponding to the property in destructuring assignment - // 'property1' from - // for ( { property1: a } of elems) { - // } - // 'property1' at location 'a' from: - // [a] = [ property1, property2 ] - function getPropertySymbolOfDestructuringAssignment(location) { - // Get the type of the object or array literal and then look for property of given name in the type - var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); - return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); - } - function getRegularTypeOfExpression(expr) { - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) { - expr = expr.parent; - } - return getRegularTypeOfLiteralType(getTypeOfExpression(expr)); - } - /** - * Gets either the static or instance type of a class element, based on - * whether the element is declared as "static". - */ - function getParentTypeOfClassElement(node) { - var classSymbol = getSymbolOfNode(node.parent); - return ts.getModifierFlags(node) & 32 /* Static */ - ? getTypeOfSymbol(classSymbol) - : getDeclaredTypeOfSymbol(classSymbol); - } - // Return the list of properties of the given type, augmented with properties from Function - // if the type has call or construct signatures - function getAugmentedPropertiesOfType(type) { - type = getApparentType(type); - var propsByName = createSymbolTable(getPropertiesOfType(type)); - if (getSignaturesOfType(type, 0 /* Call */).length || getSignaturesOfType(type, 1 /* Construct */).length) { - ts.forEach(getPropertiesOfType(globalFunctionType), function (p) { - if (!propsByName.has(p.name)) { - propsByName.set(p.name, p); - } - }); - } - return getNamedMembers(propsByName); - } - function getRootSymbols(symbol) { - 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_4.push(symbol); - } - }); - return symbols_4; - } - else if (symbol.flags & 134217728 /* Transient */) { - if (symbol.leftSpread) { - var links = symbol; - return getRootSymbols(links.leftSpread).concat(getRootSymbols(links.rightSpread)); - } - if (symbol.syntheticOrigin) { - return getRootSymbols(symbol.syntheticOrigin); - } - var target = void 0; - var next = symbol; - while (next = getSymbolLinks(next).target) { - target = next; - } - if (target) { - return [target]; - } - } - return [symbol]; - } - // Emitter support - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var isPropertyName_1 = node.parent.kind === 179 /* PropertyAccessExpression */ && node.parent.name === node; - return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; - } - } - return false; - } - function moduleExportsSomeValue(moduleReferenceExpression) { - var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression); - if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { - // If the module is not found or is shorthand, assume that it may export a value. - return true; - } - var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol); - // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment - // otherwise it will return moduleSymbol itself - moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); - var symbolLinks = getSymbolLinks(moduleSymbol); - if (symbolLinks.exportsSomeValue === undefined) { - // for export assignments - check if resolved symbol for RHS is itself a value - // otherwise - check if at least one export is value - symbolLinks.exportsSomeValue = hasExportAssignment - ? !!(moduleSymbol.flags & 107455 /* Value */) - : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue); - } - return symbolLinks.exportsSomeValue; - function isValue(s) { - s = resolveSymbol(s); - return s && !!(s.flags & 107455 /* Value */); - } - } - function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; - } - // When resolved as an expression identifier, if the given node references an exported entity, return the declaration - // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - // When resolving the export container for the name of a module or enum - // declaration, we need to start resolution at the declaration's container. - // Otherwise, we could incorrectly resolve the export container as the - // declaration if it contains an exported member with the same name. - var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node)); - if (symbol) { - if (symbol.flags & 1048576 /* ExportValue */) { - // If we reference an exported entity within the same module declaration, then whether - // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the - // kinds that we do NOT prefix. - var exportSymbol = getMergedSymbol(symbol.exportSymbol); - if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */) { - return undefined; - } - symbol = exportSymbol; - } - var parentSymbol_1 = getParentOfSymbol(symbol); - if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 265 /* SourceFile */) { - var symbolFile = parentSymbol_1.valueDeclaration; - var referenceFile = ts.getSourceFileOfNode(node); - // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. - var symbolIsUmdExport = symbolFile !== referenceFile; - return symbolIsUmdExport ? undefined : symbolFile; - } - return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; }); - } - } - } - } - // When resolved as an expression identifier, if the given node references an import, return the declaration of - // that import. Otherwise, return undefined. - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && symbol.flags & 8388608 /* Alias */) { - return getDeclarationOfAliasSymbol(symbol); - } - } - return undefined; - } - function isSymbolOfDeclarationWithCollidingName(symbol) { - if (symbol.flags & 418 /* BlockScoped */) { - var links = getSymbolLinks(symbol); - if (links.isDeclarationWithCollidingName === undefined) { - var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); - if (ts.isStatementWithLocals(container)) { - var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.name, 107455 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { - // redeclaration - always should be renamed - links.isDeclarationWithCollidingName = true; - } - else if (nodeLinks_1.flags & 131072 /* CapturedBlockScopedBinding */) { - // binding is captured in the function - // should be renamed if: - // - binding is not top level - top level bindings never collide with anything - // AND - // - binding is not declared in loop, should be renamed to avoid name reuse across siblings - // let a, b - // { let x = 1; a = () => x; } - // { let x = 100; b = () => x; } - // console.log(a()); // should print '1' - // console.log(b()); // should print '100' - // OR - // - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body - // * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly - // * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus - // they will not collide with anything - var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; - var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 207 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); - links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); - } - else { - links.isDeclarationWithCollidingName = false; - } - } - } - return links.isDeclarationWithCollidingName; - } - return false; - } - // When resolved as an expression identifier, if the given node references a nested block scoped entity with - // a name that either hides an existing name or might hide it when compiled downlevel, - // return the declaration of that entity. Otherwise, return undefined. - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); - if (node) { - var symbol = getReferencedValueSymbol(node); - if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { - return symbol.valueDeclaration; - } - } - } - return undefined; - } - // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an - // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); - if (node) { - var symbol = getSymbolOfNode(node); - if (symbol) { - return isSymbolOfDeclarationWithCollidingName(symbol); - } - } - return false; - } - function isValueAliasDeclaration(node) { - switch (node.kind) { - case 237 /* ImportEqualsDeclaration */: - case 239 /* ImportClause */: - case 240 /* NamespaceImport */: - case 242 /* ImportSpecifier */: - case 246 /* ExportSpecifier */: - return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 244 /* ExportDeclaration */: - var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 243 /* ExportAssignment */: - return node.expression - && node.expression.kind === 71 /* Identifier */ - ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) - : true; - } - return false; - } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 265 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { - // parent is not source file or it is not reference to internal module - return false; - } - var isValue = isAliasResolvedToValue(getSymbolOfNode(node)); - return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference); - } - function isAliasResolvedToValue(symbol) { - var target = resolveAlias(symbol); - if (target === unknownSymbol) { - return true; - } - // const enums and modules that contain only const enums are not considered values from the emit perspective - // unless 'preserveConstEnums' option is set to true - return target.flags & 107455 /* Value */ && - (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); - } - function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; - } - function isReferencedAliasDeclaration(node, checkChildren) { - if (ts.isAliasSymbolDeclaration(node)) { - var symbol = getSymbolOfNode(node); - if (symbol && getSymbolLinks(symbol).referenced) { - return true; - } - } - if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); - } - return false; - } - function isImplementationOfOverload(node) { - if (ts.nodeIsPresent(node.body)) { - var symbol = getSymbolOfNode(node); - var signaturesOfSymbol = getSignaturesOfSymbol(symbol); - // If this function body corresponds to function with multiple signature, it is implementation of overload - // e.g.: function foo(a: string): string; - // function foo(a: number): number; - // function foo(a: any) { // This is implementation of the overloads - // return a; - // } - return signaturesOfSymbol.length > 1 || - // If there is single signature for the symbol, it is overload if that signature isn't coming from the node - // e.g.: function foo(a: string): string; - // function foo(a: any) { // This is implementation of the overloads - // return a; - // } - (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); - } - return false; - } - function isRequiredInitializedParameter(parameter) { - return strictNullChecks && - !isOptionalParameter(parameter) && - parameter.initializer && - !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); - } - function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; - } - function getEnumMemberValue(node) { - computeEnumMemberValues(node.parent); - return getNodeLinks(node).enumMemberValue; - } - function canHaveConstantValue(node) { - switch (node.kind) { - case 264 /* EnumMember */: - case 179 /* PropertyAccessExpression */: - case 180 /* ElementAccessExpression */: - return true; - } - return false; - } - function getConstantValue(node) { - if (node.kind === 264 /* EnumMember */) { - return getEnumMemberValue(node); - } - var symbol = getNodeLinks(node).resolvedSymbol; - if (symbol && (symbol.flags & 8 /* EnumMember */)) { - // inline property\index accesses only for const enums - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); - } - } - return undefined; - } - function isFunctionType(type) { - return type.flags & 32768 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; - } - function getTypeReferenceSerializationKind(typeName, location) { - // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - var valueSymbol = resolveEntityName(typeName, 107455 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); - // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - var typeSymbol = resolveEntityName(typeName, 793064 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location); - if (valueSymbol && valueSymbol === typeSymbol) { - var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false); - if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) { - return ts.TypeReferenceSerializationKind.Promise; - } - var constructorType = getTypeOfSymbol(valueSymbol); - if (constructorType && isConstructorType(constructorType)) { - return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; - } - } - // We might not be able to resolve type symbol so use unknown type in that case (eg error case) - if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - var type = getDeclaredTypeOfSymbol(typeSymbol); - if (type === unknownType) { - return ts.TypeReferenceSerializationKind.Unknown; - } - else if (type.flags & 1 /* Any */) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - else if (isTypeOfKind(type, 1024 /* Void */ | 6144 /* Nullable */ | 8192 /* Never */)) { - return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; - } - else if (isTypeOfKind(type, 136 /* BooleanLike */)) { - return ts.TypeReferenceSerializationKind.BooleanType; - } - else if (isTypeOfKind(type, 84 /* NumberLike */)) { - return ts.TypeReferenceSerializationKind.NumberLikeType; - } - else if (isTypeOfKind(type, 262178 /* StringLike */)) { - return ts.TypeReferenceSerializationKind.StringLikeType; - } - else if (isTupleType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else if (isTypeOfKind(type, 512 /* ESSymbol */)) { - return ts.TypeReferenceSerializationKind.ESSymbolType; - } - else if (isFunctionType(type)) { - return ts.TypeReferenceSerializationKind.TypeWithCallSignature; - } - else if (isArrayType(type)) { - return ts.TypeReferenceSerializationKind.ArrayLikeType; - } - else { - return ts.TypeReferenceSerializationKind.ObjectType; - } - } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { - // Get type of the symbol if this is the valid symbol otherwise get type at location - var symbol = getSymbolOfNode(declaration); - var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) - ? getWidenedLiteralType(getTypeOfSymbol(symbol)) - : unknownType; - if (flags & 4096 /* AddUndefined */) { - type = getNullableType(type, 2048 /* Undefined */); - } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { - var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); - } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { - var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name) { - return globals.has(name); - } - function getReferencedValueSymbol(reference, startInDeclarationContainer) { - var resolvedSymbol = getNodeLinks(reference).resolvedSymbol; - if (resolvedSymbol) { - return resolvedSymbol; - } - var location = reference; - if (startInDeclarationContainer) { - // When resolving the name of a declaration as a value, we need to start resolution - // at a point outside of the declaration. - var parent = reference.parent; - if (ts.isDeclaration(parent) && reference === parent.name) { - location = getDeclarationContainer(parent); - } - } - return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); - } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); - if (reference) { - var symbol = getReferencedValueSymbol(reference); - if (symbol) { - return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; - } - } - } - return undefined; - } - function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 1048576 /* FreshLiteral */); - } - return false; - } - function writeLiteralConstValue(node, writer) { - var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); - } - function createResolver() { - // this variable and functions that use it are deliberately moved here from the outer scope - // to avoid scope pollution - var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives(); - var fileToDirective; - if (resolvedTypeReferenceDirectives) { - // populate reverse mapping: file path -> type reference directive that was resolved to this file - fileToDirective = ts.createFileMap(); - resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { - if (!resolvedDirective) { - return; - } - var file = host.getSourceFile(resolvedDirective.resolvedFileName); - fileToDirective.set(file.path, key); - }); - } - return { - getReferencedExportContainer: getReferencedExportContainer, - getReferencedImportDeclaration: getReferencedImportDeclaration, - getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName, - isDeclarationWithCollidingName: isDeclarationWithCollidingName, - isValueAliasDeclaration: function (node) { - node = ts.getParseTreeNode(node); - // Synthesized nodes are always treated like values. - return node ? isValueAliasDeclaration(node) : true; - }, - hasGlobalName: hasGlobalName, - isReferencedAliasDeclaration: function (node, checkChildren) { - node = ts.getParseTreeNode(node); - // Synthesized nodes are always treated as referenced. - return node ? isReferencedAliasDeclaration(node, checkChildren) : true; - }, - getNodeCheckFlags: function (node) { - node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; - }, - isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, - isDeclarationVisible: isDeclarationVisible, - isImplementationOfOverload: isImplementationOfOverload, - isRequiredInitializedParameter: isRequiredInitializedParameter, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, - isSymbolAccessible: isSymbolAccessible, - isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); - return node ? getConstantValue(node) : undefined; - }, - collectLinkedAliases: collectLinkedAliases, - getReferencedValueDeclaration: getReferencedValueDeclaration, - getTypeReferenceSerializationKind: getTypeReferenceSerializationKind, - isOptionalParameter: isOptionalParameter, - moduleExportsSomeValue: moduleExportsSomeValue, - isArgumentsLocalBinding: isArgumentsLocalBinding, - getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration, - getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, - getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, - isLiteralConstDeclaration: isLiteralConstDeclaration, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function () { return _jsxFactoryEntity; } - }; - // defined here to avoid outer scope pollution - function getTypeReferenceDirectivesForEntityName(node) { - // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - // property access can only be used as values - // qualified names can only be used as types\namespaces - // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 179 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) - ? 107455 /* Value */ | 1048576 /* ExportValue */ - : 793064 /* Type */ | 1920 /* Namespace */; - var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); - return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; - } - // defined here to avoid outer scope pollution - function getTypeReferenceDirectivesForSymbol(symbol, meaning) { - // program does not have any files with type reference directives - bail out - if (!fileToDirective) { - return undefined; - } - if (!isSymbolFromTypeDeclarationFile(symbol)) { - return undefined; - } - // check what declarations in the symbol can contribute to the target meaning - var typeReferenceDirectives; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - // check meaning of the local symbol to see if declaration needs to be analyzed further - if (decl.symbol && decl.symbol.flags & meaning) { - var file = ts.getSourceFileOfNode(decl); - var typeReferenceDirective = fileToDirective.get(file.path); - if (typeReferenceDirective) { - (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective); - } - else { - // found at least one entry that does not originate from type reference directive - return undefined; - } - } - } - return typeReferenceDirectives; - } - function isSymbolFromTypeDeclarationFile(symbol) { - // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern) - if (!symbol.declarations) { - return false; - } - // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope - // external modules cannot define or contribute to type declaration files - var current = symbol; - while (true) { - var parent = getParentOfSymbol(current); - if (parent) { - current = parent; - } - else { - break; - } - } - if (current.valueDeclaration && current.valueDeclaration.kind === 265 /* SourceFile */ && current.flags & 512 /* ValueModule */) { - return false; - } - // check that at least one declaration of top level symbol originates from type declaration file - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var file = ts.getSourceFileOfNode(decl); - if (fileToDirective.contains(file.path)) { - return true; - } - } - return false; - } - } - function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); - if (!moduleSymbol) { - return undefined; - } - return ts.getDeclarationOfKind(moduleSymbol, 265 /* SourceFile */); - } - function initializeTypeChecker() { - // Bind all source files and propagate errors - for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) { - var file = _a[_i]; - ts.bindSourceFile(file, compilerOptions); - } - // Initialize global symbol table - var augmentations; - for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { - var file = _c[_b]; - if (!ts.isExternalOrCommonJsModule(file)) { - mergeSymbolTable(globals, file.locals); - } - if (file.patternAmbientModules && file.patternAmbientModules.length) { - patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules); - } - if (file.moduleAugmentations.length) { - (augmentations || (augmentations = [])).push(file.moduleAugmentations); - } - if (file.symbol && file.symbol.globalExports) { - // Merge in UMD exports with first-in-wins semantics (see #9771) - var source = file.symbol.globalExports; - source.forEach(function (sourceSymbol, id) { - if (!globals.has(id)) { - globals.set(id, sourceSymbol); - } - }); - } - } - if (augmentations) { - // merge module augmentations. - // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed - for (var _d = 0, augmentations_1 = augmentations; _d < augmentations_1.length; _d++) { - var list = augmentations_1[_d]; - for (var _e = 0, list_1 = list; _e < list_1.length; _e++) { - var augmentation = list_1[_e]; - mergeModuleAugmentation(augmentation); - } - } - } - // Setup global builtins - addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); - getSymbolLinks(undefinedSymbol).type = undefinedWideningType; - getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); - getSymbolLinks(unknownSymbol).type = unknownType; - // Initialize special types - globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); - globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); - globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true); - globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true); - globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true); - globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true); - globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true); - anyArrayType = createArrayType(anyType); - autoArrayType = createArrayType(autoType); - globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1); - anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType; - globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1); - } - function checkExternalEmitHelpers(location, helpers) { - if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { - var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !ts.isInAmbientContext(location)) { - var helpersModule = resolveHelpersModule(sourceFile, location); - if (helpersModule !== unknownSymbol) { - var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - 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 */); - if (!symbol) { - error(location, ts.Diagnostics.This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1, ts.externalHelpersModuleNameText, name); - } - } - } - } - requestedExternalEmitHelpers |= helpers; - } - } - } - function getHelperName(helper) { - switch (helper) { - case 1 /* Extends */: return "__extends"; - case 2 /* Assign */: return "__assign"; - case 4 /* Rest */: return "__rest"; - case 8 /* Decorate */: return "__decorate"; - case 16 /* Metadata */: return "__metadata"; - case 32 /* Param */: return "__param"; - case 64 /* Awaiter */: return "__awaiter"; - case 128 /* Generator */: return "__generator"; - case 256 /* Values */: return "__values"; - case 512 /* Read */: return "__read"; - case 1024 /* Spread */: return "__spread"; - 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."); - } - } - function resolveHelpersModule(node, errorNode) { - if (!externalHelpersModule) { - externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; - } - return externalHelpersModule; - } - // GRAMMAR CHECKING - function checkGrammarDecorators(node) { - if (!node.decorators) { - return false; - } - if (!ts.nodeCanBeDecorated(node)) { - if (node.kind === 151 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); - } - else { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); - } - } - else if (node.kind === 153 /* GetAccessor */ || node.kind === 154 /* SetAccessor */) { - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { - return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); - } - } - return false; - } - function checkGrammarModifiers(node) { - var quickResult = reportObviousModifierErrors(node); - if (quickResult !== undefined) { - return quickResult; - } - var lastStatic, lastPrivate, lastProtected, lastDeclare, lastAsync, lastReadonly; - var flags = 0 /* None */; - for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { - var modifier = _a[_i]; - if (modifier.kind !== 131 /* ReadonlyKeyword */) { - if (node.kind === 148 /* PropertySignature */ || node.kind === 150 /* MethodSignature */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); - } - if (node.kind === 157 /* IndexSignature */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); - } - } - switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (node.kind !== 232 /* EnumDeclaration */ && node.parent.kind === 229 /* ClassDeclaration */) { - return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); - } - break; - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: - var text = visibilityToString(ts.modifierToFlag(modifier.kind)); - if (modifier.kind === 113 /* ProtectedKeyword */) { - lastProtected = modifier; - } - else if (modifier.kind === 112 /* PrivateKeyword */) { - lastPrivate = modifier; - } - if (flags & 28 /* AccessibilityModifier */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); - } - else if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); - } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); - } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); - } - else if (flags & 128 /* Abstract */) { - if (modifier.kind === 112 /* PrivateKeyword */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); - } - else { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract"); - } - } - flags |= ts.modifierToFlag(modifier.kind); - break; - case 115 /* StaticKeyword */: - if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); - } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); - } - else if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); - } - else if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - flags |= 32 /* Static */; - lastStatic = modifier; - break; - case 131 /* ReadonlyKeyword */: - if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); - } - else if (node.kind !== 149 /* PropertyDeclaration */ && node.kind !== 148 /* PropertySignature */ && node.kind !== 157 /* IndexSignature */ && node.kind !== 146 /* Parameter */) { - // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. - return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); - } - flags |= 64 /* Readonly */; - lastReadonly = modifier; - break; - case 84 /* ExportKeyword */: - if (flags & 1 /* Export */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); - } - else if (flags & 2 /* Ambient */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); - } - else if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); - } - else if (node.parent.kind === 229 /* ClassDeclaration */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); - } - flags |= 1 /* Export */; - break; - case 124 /* DeclareKeyword */: - if (flags & 2 /* Ambient */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.parent.kind === 229 /* ClassDeclaration */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); - } - else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 234 /* ModuleBlock */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); - } - flags |= 2 /* Ambient */; - lastDeclare = modifier; - break; - case 117 /* AbstractKeyword */: - if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); - } - if (node.kind !== 229 /* ClassDeclaration */) { - if (node.kind !== 151 /* MethodDeclaration */ && - node.kind !== 149 /* PropertyDeclaration */ && - node.kind !== 153 /* GetAccessor */ && - node.kind !== 154 /* SetAccessor */) { - return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); - } - if (!(node.parent.kind === 229 /* ClassDeclaration */ && ts.getModifierFlags(node.parent) & 128 /* Abstract */)) { - return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); - } - if (flags & 32 /* Static */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); - } - if (flags & 8 /* Private */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); - } - } - flags |= 128 /* Abstract */; - break; - case 120 /* AsyncKeyword */: - if (flags & 256 /* Async */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); - } - else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); - } - else if (node.kind === 146 /* Parameter */) { - return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); - } - flags |= 256 /* Async */; - lastAsync = modifier; - break; - } - } - if (node.kind === 152 /* Constructor */) { - if (flags & 32 /* Static */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); - } - if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); - } - else if (flags & 256 /* Async */) { - return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); - } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); - } - return; - } - else if ((node.kind === 238 /* ImportDeclaration */ || node.kind === 237 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { - return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); - } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); - } - else if (node.kind === 146 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { - return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); - } - if (flags & 256 /* Async */) { - return checkGrammarAsyncModifier(node, lastAsync); - } - } - /** - * true | false: Early return this value from checkGrammarModifiers. - * undefined: Need to do full checking on the modifiers. - */ - function reportObviousModifierErrors(node) { - return !node.modifiers - ? false - : shouldReportBadModifier(node) - ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here) - : undefined; - } - function shouldReportBadModifier(node) { - switch (node.kind) { - case 153 /* GetAccessor */: - case 154 /* SetAccessor */: - case 152 /* Constructor */: - case 149 /* PropertyDeclaration */: - case 148 /* PropertySignature */: - case 151 /* MethodDeclaration */: - case 150 /* MethodSignature */: - case 157 /* IndexSignature */: - case 233 /* ModuleDeclaration */: - case 238 /* ImportDeclaration */: - case 237 /* ImportEqualsDeclaration */: - case 244 /* ExportDeclaration */: - case 243 /* ExportAssignment */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - case 146 /* Parameter */: - return false; - default: - if (node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - return false; - } - switch (node.kind) { - case 228 /* FunctionDeclaration */: - return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 229 /* ClassDeclaration */: - return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 230 /* InterfaceDeclaration */: - case 208 /* VariableStatement */: - case 231 /* TypeAliasDeclaration */: - return true; - case 232 /* EnumDeclaration */: - return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); - default: - ts.Debug.fail(); - return false; - } - } - } - function nodeHasAnyModifiersExcept(node, allowedModifier) { - return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier; - } - function checkGrammarAsyncModifier(node, asyncModifier) { - switch (node.kind) { - case 151 /* MethodDeclaration */: - case 228 /* FunctionDeclaration */: - case 186 /* FunctionExpression */: - case 187 /* ArrowFunction */: - return false; - } - return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); - } - function checkGrammarForDisallowedTrailingComma(list) { - if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - var sourceFile = ts.getSourceFileOfNode(list[0]); - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); - } - } - function checkGrammarTypeParameterList(typeParameters, file) { - if (checkGrammarForDisallowedTrailingComma(typeParameters)) { - return true; - } - if (typeParameters && typeParameters.length === 0) { - var start = typeParameters.pos - "<".length; - var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; - return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); - } - } - function checkGrammarParameterList(parameters) { - var seenOptionalParameter = false; - var parameterCount = parameters.length; - for (var i = 0; i < parameterCount; i++) { - var parameter = parameters[i]; - if (parameter.dotDotDotToken) { - if (i !== (parameterCount - 1)) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); - } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer); - } - } - else if (parameter.questionToken) { - seenOptionalParameter = true; - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer); - } - } - else if (seenOptionalParameter && !parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); - } - } - } - function checkGrammarFunctionLikeDeclaration(node) { - // Prevent cascading error by short-circuit - var file = ts.getSourceFileOfNode(node); - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); - } - function checkGrammarClassLikeDeclaration(node) { - var file = ts.getSourceFileOfNode(node); - return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file); - } - function checkGrammarArrowFunction(node, file) { - if (node.kind === 187 /* ArrowFunction */) { - var arrowFunction = node; - var startLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; - var endLine = ts.getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; - if (startLine !== endLine) { - return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow); - } - } - return false; - } - function checkGrammarIndexSignatureParameters(node) { - var parameter = node.parameters[0]; - if (node.parameters.length !== 1) { - if (parameter) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - else { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter); - } - } - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); - } - if (ts.getModifierFlags(parameter) !== 0) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); - } - if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark); - } - if (parameter.initializer) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer); - } - if (!parameter.type) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); - } - if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); - } - if (!node.type) { - return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); - } - } - function checkGrammarIndexSignature(node) { - // Prevent cascading error by short-circuit - return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarIndexSignatureParameters(node); - } - function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) { - if (typeArguments && typeArguments.length === 0) { - var sourceFile = ts.getSourceFileOfNode(node); - var start = typeArguments.pos - "<".length; - var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; - return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); - } - } - function checkGrammarTypeArguments(node, typeArguments) { - return checkGrammarForDisallowedTrailingComma(typeArguments) || - checkGrammarForAtLeastOneTypeArgument(node, typeArguments); - } - function checkGrammarForOmittedArgument(node, args) { - if (args) { - var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { - var arg = args_4[_i]; - if (arg.kind === 200 /* OmittedExpression */) { - return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); - } - } - } - } - function checkGrammarArguments(node, args) { - return checkGrammarForOmittedArgument(node, args); - } - function checkGrammarHeritageClause(node) { - var types = node.types; - if (checkGrammarForDisallowedTrailingComma(types)) { - return true; - } - if (types && types.length === 0) { - var listType = ts.tokenToString(node.token); - var sourceFile = ts.getSourceFileOfNode(node); - return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); - } - } - function checkGrammarClassDeclarationHeritageClauses(node) { - var seenExtendsClause = false; - var seenImplementsClause = false; - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause); - } - if (heritageClause.types.length > 1) { - return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); - if (seenImplementsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen); - } - seenImplementsClause = true; - } - // Grammar checking heritageClause inside class declaration - checkGrammarHeritageClause(heritageClause); - } - } - } - function checkGrammarInterfaceDeclaration(node) { - var seenExtendsClause = false; - if (node.heritageClauses) { - for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) { - var heritageClause = _a[_i]; - if (heritageClause.token === 85 /* ExtendsKeyword */) { - if (seenExtendsClause) { - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen); - } - seenExtendsClause = true; - } - else { - ts.Debug.assert(heritageClause.token === 108 /* ImplementsKeyword */); - return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause); - } - // Grammar checking heritageClause inside class declaration - checkGrammarHeritageClause(heritageClause); - } - } - return false; - } - function checkGrammarComputedPropertyName(node) { - // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 144 /* ComputedPropertyName */) { - return false; - } - var computedPropertyName = node; - if (computedPropertyName.expression.kind === 194 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { - return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); - } - } - function checkGrammarForGenerator(node) { - if (node.asteriskToken) { - ts.Debug.assert(node.kind === 228 /* FunctionDeclaration */ || - node.kind === 186 /* FunctionExpression */ || - node.kind === 151 /* MethodDeclaration */); - if (ts.isInAmbientContext(node)) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); - } - if (!node.body) { - return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); - } - } - } - function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } - } - function checkGrammarObjectLiteralExpression(node, inDestructuring) { - var seen = ts.createMap(); - var Property = 1; - var GetAccessor = 2; - var SetAccessor = 4; - var GetOrSetAccessor = GetAccessor | SetAccessor; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var prop = _a[_i]; - if (prop.kind === 263 /* SpreadAssignment */) { - continue; - } - var name = prop.name; - if (name.kind === 144 /* ComputedPropertyName */) { - // If the name is not a ComputedPropertyName, the grammar checking will skip it - checkGrammarComputedPropertyName(name); - } - if (prop.kind === 262 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { - // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern - // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); - } - // Modifiers are never allowed on properties except for 'async' on a method declaration - if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { - var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 151 /* MethodDeclaration */) { - grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); - } - } - } - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = void 0; - if (prop.kind === 261 /* PropertyAssignment */ || prop.kind === 262 /* ShorthandPropertyAssignment */) { - // Grammar checking for computedPropertyName and shorthandPropertyAssignment - checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name.kind === 8 /* NumericLiteral */) { - checkGrammarNumericLiteral(name); - } - currentKind = Property; - } - else if (prop.kind === 151 /* MethodDeclaration */) { - currentKind = Property; - } - else if (prop.kind === 153 /* GetAccessor */) { - currentKind = GetAccessor; - } - else if (prop.kind === 154 /* SetAccessor */) { - currentKind = SetAccessor; - } - else { - ts.Debug.fail("Unexpected syntax kind:" + prop.kind); - } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name); - if (effectiveName === undefined) { - continue; - } - var existingKind = seen.get(effectiveName); - if (!existingKind) { - seen.set(effectiveName, currentKind); - } - else { - if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); - } - else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { - if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { - seen.set(effectiveName, currentKind | existingKind); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); - } - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); - } - } - } - } - function checkGrammarJsxElement(node) { - var seen = ts.createMap(); - for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { - var attr = _a[_i]; - if (attr.kind === 255 /* JsxSpreadAttribute */) { - continue; - } - var jsxAttr = attr; - var name = jsxAttr.name; - if (!seen.get(name.text)) { - seen.set(name.text, true); - } - else { - return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); - } - var initializer = jsxAttr.initializer; - if (initializer && initializer.kind === 256 /* JsxExpression */ && !initializer.expression) { - return grammarErrorOnNode(jsxAttr.initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); - } - } - } - function checkGrammarForInOrForOfStatement(forInOrOfStatement) { - if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { - return true; - } - if (forInOrOfStatement.kind === 216 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { - if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { - return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); - } - } - if (forInOrOfStatement.initializer.kind === 227 /* VariableDeclarationList */) { - var variableList = forInOrOfStatement.initializer; - if (!checkGrammarVariableDeclarationList(variableList)) { - var declarations = variableList.declarations; - // declarations.length can be zero if there is an error in variable declaration in for-of or for-in - // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details - // For example: - // var let = 10; - // for (let of [1,2,3]) {} // this is invalid ES6 syntax - // for (let in [1,2,3]) {} // this is invalid ES6 syntax - // We will then want to skip on grammar checking on variableList declaration - if (!declarations.length) { - return false; - } - if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ - ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement - : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; - return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); - } - var firstDeclaration = declarations[0]; - if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ - ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer - : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; - return grammarErrorOnNode(firstDeclaration.name, diagnostic); - } - if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 215 /* ForInStatement */ - ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation - : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; - return grammarErrorOnNode(firstDeclaration, diagnostic); - } - } - } - return false; - } - function checkGrammarAccessor(accessor) { - var kind = accessor.kind; - if (languageVersion < 1 /* ES5 */) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); - } - else if (ts.isInAmbientContext(accessor)) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); - } - else if (accessor.body === undefined && !(ts.getModifierFlags(accessor) & 128 /* Abstract */)) { - return grammarErrorAtPos(ts.getSourceFileOfNode(accessor), accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - else if (accessor.body && ts.getModifierFlags(accessor) & 128 /* Abstract */) { - return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation); - } - else if (accessor.typeParameters) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); - } - else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 153 /* GetAccessor */ ? - ts.Diagnostics.A_get_accessor_cannot_have_parameters : - ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); - } - else if (kind === 154 /* SetAccessor */) { - if (accessor.type) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); - } - else { - var parameter = accessor.parameters[0]; - if (parameter.dotDotDotToken) { - return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); - } - else if (parameter.questionToken) { - return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter); - } - else if (parameter.initializer) { - return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer); - } - } - } - } - /** Does the accessor have the right number of parameters? - * A get accessor has no parameters or a single `this` parameter. - * A set accessor has one parameter or a `this` parameter and one more parameter. - */ - function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 0 : 1); - } - function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 153 /* GetAccessor */ ? 1 : 2)) { - return ts.getThisParameter(accessor); - } - } - function checkGrammarForNonSymbolComputedProperty(node, message) { - if (ts.isDynamicName(node)) { - return grammarErrorOnNode(node, message); - } - } - function checkGrammarMethod(node) { - if (checkGrammarDisallowedModifiersOnObjectLiteralExpressionMethod(node) || - checkGrammarFunctionLikeDeclaration(node) || - checkGrammarForGenerator(node)) { - return true; - } - if (node.parent.kind === 178 /* ObjectLiteralExpression */) { - if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) { - return true; - } - else if (node.body === undefined) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); - } - } - if (ts.isClassLike(node.parent)) { - // Technically, computed properties in ambient contexts is disallowed - // for property declarations and accessors too, not just methods. - // However, property declarations disallow computed names in general, - // and accessors are not allowed in ambient contexts in general, - // so this error only really matters for methods. - if (ts.isInAmbientContext(node)) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol); - } - else if (!node.body) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol); - } - } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol); - } - else if (node.parent.kind === 163 /* TypeLiteral */) { - return checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol); - } - } - function checkGrammarBreakOrContinueStatement(node) { - var current = node; - while (current) { - if (ts.isFunctionLike(current)) { - return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); - } - switch (current.kind) { - case 222 /* LabeledStatement */: - if (node.label && current.label.text === node.label.text) { - // found matching label - verify that label usage is correct - // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 217 /* ContinueStatement */ - && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); - if (isMisplacedContinueLabel) { - return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); - } - return false; - } - break; - case 221 /* SwitchStatement */: - if (node.kind === 218 /* BreakStatement */ && !node.label) { - // unlabeled break within switch statement - ok - return false; - } - break; - default: - if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) { - // unlabeled break or continue within iteration statement - ok - return false; - } - break; - } - current = current.parent; - } - if (node.label) { - var message = node.kind === 218 /* BreakStatement */ - ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement - : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - else { - var message = node.kind === 218 /* BreakStatement */ - ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement - : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; - return grammarErrorOnNode(node, message); - } - } - function checkGrammarBindingElement(node) { - if (node.dotDotDotToken) { - var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); - } - if (node.name.kind === 175 /* ArrayBindingPattern */ || node.name.kind === 174 /* ObjectBindingPattern */) { - return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } - if (node.initializer) { - // Error on equals token which immediately precedes the initializer - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - } - } - function isStringOrNumberLiteralExpression(expr) { - return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 192 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && - expr.operand.kind === 8 /* NumericLiteral */; - } - function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 215 /* ForInStatement */ && node.parent.parent.kind !== 216 /* ForOfStatement */) { - if (ts.isInAmbientContext(node)) { - if (node.initializer) { - if (ts.isConst(node) && !node.type) { - if (!isStringOrNumberLiteralExpression(node.initializer)) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); - } - } - else { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - if (node.initializer && !(ts.isConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { - // Error on equals token which immediate precedes the initializer - var equalsTokenLength = "=".length; - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - else if (!node.initializer) { - if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { - return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); - } - if (ts.isConst(node)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); - } - } - } - if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { - checkESModuleMarker(node.name); - } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); - // 1. LexicalDeclaration : LetOrConst BindingList ; - // It is a Syntax Error if the BoundNames of BindingList contains "let". - // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding - // It is a Syntax Error if the BoundNames of ForDeclaration contains "let". - // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code - // and its Identifier is eval or arguments - return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); - } - function checkESModuleMarker(name) { - if (name.kind === 71 /* Identifier */) { - if (ts.unescapeIdentifier(name.text) === "__esModule") { - return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; - if (!ts.isOmittedExpression(element)) { - return checkESModuleMarker(element.name); - } - } - } - } - function checkGrammarNameInLetOrConstDeclarations(name) { - if (name.kind === 71 /* Identifier */) { - if (name.originalKeywordKind === 110 /* LetKeyword */) { - return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations); - } - } - else { - var elements = name.elements; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var element = elements_3[_i]; - if (!ts.isOmittedExpression(element)) { - checkGrammarNameInLetOrConstDeclarations(element.name); - } - } - } - } - function checkGrammarVariableDeclarationList(declarationList) { - var declarations = declarationList.declarations; - if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { - return true; - } - if (!declarationList.declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); - } - } - function allowLetAndConstDeclarations(parent) { - switch (parent.kind) { - case 211 /* IfStatement */: - case 212 /* DoStatement */: - case 213 /* WhileStatement */: - case 220 /* WithStatement */: - case 214 /* ForStatement */: - case 215 /* ForInStatement */: - case 216 /* ForOfStatement */: - return false; - case 222 /* LabeledStatement */: - return allowLetAndConstDeclarations(parent.parent); - } - return true; - } - function checkGrammarForDisallowedLetOrConstStatement(node) { - if (!allowLetAndConstDeclarations(node.parent)) { - if (ts.isLet(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); - } - else if (ts.isConst(node.declarationList)) { - return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); - } - } - } - function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */) { - if (node.name.text !== "target") { - return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.text, ts.tokenToString(node.keywordToken), "target"); - } - } - } - function hasParseDiagnostics(sourceFile) { - return sourceFile.parseDiagnostics.length > 0; - } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorAtPos(sourceFile, start, length, message, arg0, arg1, arg2) { - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); - return true; - } - } - function grammarErrorOnNode(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); - return true; - } - } - function checkGrammarConstructorTypeParameters(node) { - if (node.typeParameters) { - return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.typeParameters.pos, node.typeParameters.end - node.typeParameters.pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarConstructorTypeAnnotation(node) { - if (node.type) { - return grammarErrorOnNode(node.type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration); - } - } - function checkGrammarProperty(node) { - if (ts.isClassLike(node.parent)) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - } - else if (node.parent.kind === 230 /* InterfaceDeclaration */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); - } - } - else if (node.parent.kind === 163 /* TypeLiteral */) { - if (checkGrammarForNonSymbolComputedProperty(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol)) { - return true; - } - if (node.initializer) { - return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); - } - } - if (ts.isInAmbientContext(node) && node.initializer) { - return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); - } - } - function checkGrammarTopLevelElementForRequiredDeclareModifier(node) { - // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace - // interfaces and imports categories: - // - // DeclarationElement: - // ExportAssignment - // export_opt InterfaceDeclaration - // export_opt TypeAliasDeclaration - // export_opt ImportDeclaration - // export_opt ExternalImportDeclaration - // export_opt AmbientDeclaration - // - // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 230 /* InterfaceDeclaration */ || - node.kind === 231 /* TypeAliasDeclaration */ || - node.kind === 238 /* ImportDeclaration */ || - node.kind === 237 /* ImportEqualsDeclaration */ || - node.kind === 244 /* ExportDeclaration */ || - node.kind === 243 /* ExportAssignment */ || - node.kind === 236 /* NamespaceExportDeclaration */ || - ts.getModifierFlags(node) & (2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { - return false; - } - return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); - } - function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { - for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { - var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 208 /* VariableStatement */) { - if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { - return true; - } - } - } - } - function checkGrammarSourceFile(node) { - return ts.isInAmbientContext(node) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); - } - function checkGrammarStatementInAmbientContext(node) { - if (ts.isInAmbientContext(node)) { - // An accessors is already reported about the ambient context - if (isAccessor(node.parent.kind)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = true; - } - // Find containing block which is either Block, ModuleBlock, SourceFile - var links = getNodeLinks(node); - if (!links.hasReportedStatementInAmbientContext && ts.isFunctionLike(node.parent)) { - return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); - } - // We are either parented by another statement, or some sort of block. - // If we're in a block, we only want to really report an error once - // to prevent noisiness. So use a bit on the block to indicate if - // this has already been reported, and don't report if it has. - // - if (node.parent.kind === 207 /* Block */ || node.parent.kind === 234 /* ModuleBlock */ || node.parent.kind === 265 /* SourceFile */) { - var links_1 = getNodeLinks(node.parent); - // Check if the containing block ever report this error - if (!links_1.hasReportedStatementInAmbientContext) { - return links_1.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); - } - } - else { - // We must be parented by a statement. If so, there's no need - // to report the error as our parent will have already done it. - // Debug.assert(isStatement(node.parent)); - } - } - } - function checkGrammarNumericLiteral(node) { - // Grammar checking - if (node.numericLiteralFlags & 4 /* Octal */) { - var diagnosticMessage = void 0; - if (languageVersion >= 1 /* ES5 */) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 173 /* LiteralType */)) { - diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; - } - else if (ts.isChildOfNodeWithKind(node, 264 /* EnumMember */)) { - diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; - } - if (diagnosticMessage) { - var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 38 /* MinusToken */; - var literal = (withMinus ? "-" : "") + "0o" + node.text; - return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); - } - } - } - function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { - var sourceFile = ts.getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { - var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); - return true; - } - } - function getAmbientModules() { - var result = []; - globals.forEach(function (global, sym) { - if (ambientModuleSymbolRegex.test(sym)) { - result.push(global); - } - }); - return result; - } - } - 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 = {})); /// /// @@ -48304,11 +49373,11 @@ var ts; 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)); + return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), 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 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)); + return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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 */: @@ -48316,9 +49385,9 @@ var ts; 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)); + return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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 @@ -48327,9 +49396,9 @@ var ts; 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)); + return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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)); + return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), 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 */: @@ -48349,7 +49418,7 @@ var ts; case 171 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); case 172 /* MappedType */: - 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)); + return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), 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)); // Binding patterns @@ -48379,9 +49448,9 @@ var ts; case 185 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 186 /* FunctionExpression */: - return ts.updateFunctionExpression(node, 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)); + return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 187 /* ArrowFunction */: - return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameter), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); + return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); case 188 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); case 189 /* TypeOfExpression */: @@ -48405,7 +49474,7 @@ var ts; case 198 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); case 199 /* ClassExpression */: - return ts.updateClassExpression(node, 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)); + return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); case 201 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 202 /* AsExpression */: @@ -48457,13 +49526,13 @@ var ts; case 227 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); case 228 /* FunctionDeclaration */: - 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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)); + 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.isTypeParameterDeclaration), 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 */: @@ -48537,9 +49606,9 @@ var ts; case 265 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -48595,7 +49664,7 @@ var ts; case 209 /* EmptyStatement */: case 200 /* OmittedExpression */: case 225 /* DebuggerStatement */: - case 295 /* NotEmittedStatement */: + case 287 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names @@ -48761,9 +49830,6 @@ var ts; result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; - case 203 /* NonNullExpression */: - result = reduceNode(node.expression, cbNode, result); - break; // Misc case 205 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); @@ -48972,10 +50038,10 @@ var ts; result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -49066,38 +50132,228 @@ var ts; } var Debug; (function (Debug) { + var isDebugInfoEnabled = false; Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } + ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } : ts.noop; Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) - ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; Debug.assertNode = Debug.shouldAssert(1 /* Normal */) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertNode); } : ts.noop; Debug.assertOptionalNode = Debug.shouldAssert(1 /* Normal */) - ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } + ? function (node, test, message) { return Debug.assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertOptionalNode); } : ts.noop; Debug.assertOptionalToken = Debug.shouldAssert(1 /* Normal */) - ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }); } + ? function (node, kind, message) { return Debug.assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was not a '" + ts.formatSyntaxKind(kind) + "' token."; }, Debug.assertOptionalToken); } : ts.noop; Debug.assertMissingNode = Debug.shouldAssert(1 /* Normal */) - ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }); } + ? function (node, message) { return Debug.assert(node === undefined, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; - function getFunctionName(func) { - if (typeof func !== "function") { - return ""; + /** + * Injects debug information into frequently used types. + */ + function enableDebugInfo() { + if (isDebugInfoEnabled) + return; + // Add additional properties in debug mode to assist with debugging. + Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatSymbolFlags(this.flags); } } + }); + Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { + "__debugFlags": { get: function () { return ts.formatTypeFlags(this.flags); } }, + "__debugObjectFlags": { get: function () { return this.flags & 32768 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + "__debugTypeToString": { value: function () { return this.checker.typeToString(this); } }, + }); + var nodeConstructors = [ + ts.objectAllocator.getNodeConstructor(), + ts.objectAllocator.getIdentifierConstructor(), + ts.objectAllocator.getTokenConstructor(), + ts.objectAllocator.getSourceFileConstructor() + ]; + for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) { + var ctor = nodeConstructors_1[_i]; + if (!ctor.prototype.hasOwnProperty("__debugKind")) { + Object.defineProperties(ctor.prototype, { + "__debugKind": { get: function () { return ts.formatSyntaxKind(this.kind); } }, + "__debugModifierFlags": { get: function () { return ts.formatModifierFlags(ts.getModifierFlagsNoCache(this)); } }, + "__debugTransformFlags": { get: function () { return ts.formatTransformFlags(this.transformFlags); } }, + "__debugEmitFlags": { get: function () { return ts.formatEmitFlags(ts.getEmitFlags(this)); } }, + "__debugGetText": { + value: function (includeTrivia) { + if (ts.nodeIsSynthesized(this)) + return ""; + var parseNode = ts.getParseTreeNode(this); + var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode); + return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : ""; + } + } + }); + } } - else if (func.hasOwnProperty("name")) { - return func.name; - } - else { - var text = Function.prototype.toString.call(func); - var match = /^function\s+([\w\$]+)\s*\(/.exec(text); - return match ? match[1] : ""; + isDebugInfoEnabled = true; + } + Debug.enableDebugInfo = enableDebugInfo; + })(Debug = ts.Debug || (ts.Debug = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function getOriginalNodeId(node) { + node = ts.getOriginalNode(node); + return node ? ts.getNodeId(node) : 0; + } + ts.getOriginalNodeId = getOriginalNodeId; + function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { + var externalImports = []; + var exportSpecifiers = ts.createMultiMap(); + var exportedBindings = []; + var uniqueExports = ts.createMap(); + var exportedNames; + var hasExportDefault = false; + var exportEquals = undefined; + var hasExportStarsToExportValues = false; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var node = _a[_i]; + switch (node.kind) { + case 238 /* ImportDeclaration */: + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); + break; + case 237 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 248 /* ExternalModuleReference */) { + // import x = require("mod") + externalImports.push(node); + } + break; + case 244 /* ExportDeclaration */: + if (node.moduleSpecifier) { + if (!node.exportClause) { + // export * from "mod" + externalImports.push(node); + hasExportStarsToExportValues = true; + } + else { + // export { x, y } from "mod" + externalImports.push(node); + } + } + else { + // export { x, y } + for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { + var specifier = _c[_b]; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(specifier.name.escapedText))) { + var name = specifier.propertyName || specifier.name; + exportSpecifiers.add(ts.unescapeLeadingUnderscores(name.escapedText), specifier); + var decl = resolver.getReferencedImportDeclaration(name) + || resolver.getReferencedValueDeclaration(name); + if (decl) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); + } + uniqueExports.set(ts.unescapeLeadingUnderscores(specifier.name.escapedText), true); + exportedNames = ts.append(exportedNames, specifier.name); + } + } + } + break; + case 243 /* ExportAssignment */: + if (node.isExportEquals && !exportEquals) { + // export = x + exportEquals = node; + } + break; + case 208 /* VariableStatement */: + if (ts.hasModifier(node, 1 /* Export */)) { + for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { + var decl = _e[_d]; + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + } + } + break; + case 228 /* FunctionDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default function() { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export function x() { } + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; + case 229 /* ClassDeclaration */: + if (ts.hasModifier(node, 1 /* Export */)) { + if (ts.hasModifier(node, 512 /* Default */)) { + // export default class { } + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node)); + hasExportDefault = true; + } + } + else { + // export class x { } + var name = node.name; + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(name.escapedText))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(ts.unescapeLeadingUnderscores(name.escapedText), true); + exportedNames = ts.append(exportedNames, name); + } + } + } + break; } } - })(Debug = ts.Debug || (ts.Debug = {})); + var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); + var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + if (externalHelpersImportDeclaration) { + externalImports.unshift(externalHelpersImportDeclaration); + } + return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; + } + ts.collectExternalModuleInfo = collectExternalModuleInfo; + function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + if (ts.isBindingPattern(decl.name)) { + for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (!ts.isOmittedExpression(element)) { + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + } + } + } + else if (!ts.isGeneratedIdentifier(decl.name)) { + if (!uniqueExports.get(ts.unescapeLeadingUnderscores(decl.name.escapedText))) { + uniqueExports.set(ts.unescapeLeadingUnderscores(decl.name.escapedText), true); + exportedNames = ts.append(exportedNames, decl.name); + } + } + return exportedNames; + } + /** Use a sparse array as a multi-map. */ + function multiMapSparseArrayAdd(map, key, value) { + var values = map[key]; + if (values) { + values.push(value); + } + else { + map[key] = values = [value]; + } + return values; + } })(ts || (ts = {})); /// /// @@ -49450,11 +50706,11 @@ var ts; } else if (ts.isStringOrNumericLiteral(propertyName)) { var argumentExpression = ts.getSynthesizedClone(propertyName); - argumentExpression.text = ts.unescapeIdentifier(argumentExpression.text); + argumentExpression.text = argumentExpression.text; return ts.createElementAccess(value, argumentExpression); } else { - var name = ts.createIdentifier(ts.unescapeIdentifier(propertyName.text)); + var name = ts.createIdentifier(ts.unescapeLeadingUnderscores(propertyName.escapedText)); return ts.createPropertyAccess(value, name); } } @@ -49557,6 +50813,22 @@ var ts; /* Enables substitutions for unqualified enum members */ TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); + var ClassFacts; + (function (ClassFacts) { + ClassFacts[ClassFacts["None"] = 0] = "None"; + ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties"; + ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators"; + ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators"; + ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace"; + ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport"; + ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport"; + ClassFacts[ClassFacts["HasExtendsClause"] = 64] = "HasExtendsClause"; + ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators"; + ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName"; + ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression"; + ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported"; + })(ClassFacts || (ClassFacts = {})); function transformTypeScript(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); @@ -49834,7 +51106,9 @@ var ts; case 231 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. case 149 /* PropertyDeclaration */: - // TypeScript property declarations are elided. + // TypeScript property declarations are elided. + case 236 /* NamespaceExportDeclaration */: + // TypeScript namespace export declarations are elided. return undefined; case 152 /* Constructor */: return visitConstructor(node); @@ -49960,6 +51234,26 @@ var ts; function shouldEmitDecorateCallForParameter(parameter) { return parameter.decorators !== undefined && parameter.decorators.length > 0; } + function getClassFacts(node, staticProperties) { + var facts = 0 /* None */; + if (ts.some(staticProperties)) + facts |= 1 /* HasStaticInitializedProperties */; + if (ts.getClassExtendsHeritageClauseElement(node)) + facts |= 64 /* HasExtendsClause */; + if (shouldEmitDecorateCallForClass(node)) + facts |= 2 /* HasConstructorDecorators */; + if (ts.childIsDecorated(node)) + facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) + facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) + facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) + facts |= 16 /* IsNamedExternalExport */; + if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */)) + facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; + return facts; + } /** * Transforms a class declaration with TypeScript syntax into compatible ES6. * @@ -49973,44 +51267,73 @@ var ts; */ function visitClassDeclaration(node) { var staticProperties = getInitializedProperties(node, /*isStatic*/ true); - var hasExtendsClause = ts.getClassExtendsHeritageClauseElement(node) !== undefined; - var isDecoratedClass = shouldEmitDecorateCallForClass(node); - // emit name if - // - node has a name - // - node has static initializers - // - node has a member that is decorated - // - var name = node.name; - if (!name && (staticProperties.length > 0 || ts.childIsDecorated(node))) { - name = ts.getGeneratedNameForNode(node); + var facts = getClassFacts(node, staticProperties); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + context.startLexicalEnvironment(); } - var classStatement = isDecoratedClass - ? createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) - : createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, staticProperties.length > 0); + var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined); + var classStatement = facts & 2 /* HasConstructorDecorators */ + ? createClassDeclarationHeadWithDecorators(node, name, facts) + : createClassDeclarationHeadWithoutDecorators(node, name, facts); var statements = [classStatement]; // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - if (staticProperties.length) { - addInitializedPropertyStatements(statements, staticProperties, ts.getLocalName(node)); + if (facts & 1 /* HasStaticInitializedProperties */) { + addInitializedPropertyStatements(statements, staticProperties, facts & 128 /* UseImmediatelyInvokedFunctionExpression */ ? ts.getInternalName(node) : ts.getLocalName(node)); } // Write any decorators of the node. addClassElementDecorationStatements(statements, node, /*isStatic*/ false); addClassElementDecorationStatements(statements, node, /*isStatic*/ true); addConstructorDecorationStatement(statements, node); + if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) { + // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the + // 'es2015' transformer can properly nest static initializers and decorators. The result + // looks something like: + // + // var C = function () { + // class C { + // } + // C.static_prop = 1; + // return C; + // }(); + // + var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 18 /* CloseBraceToken */); + var localName = ts.getInternalName(node); + // The following partially-emitted expression exists purely to align our sourcemap + // emit with the original emitter. + var outer = ts.createPartiallyEmittedExpression(localName); + outer.end = closingBraceLocation.end; + ts.setEmitFlags(outer, 1536 /* NoComments */); + var statement = ts.createReturn(outer); + statement.pos = closingBraceLocation.pos; + ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); + statements.push(statement); + ts.addRange(statements, context.endLexicalEnvironment()); + var varStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), + /*type*/ undefined, ts.createImmediatelyInvokedFunctionExpression(statements)) + ])); + ts.setOriginalNode(varStatement, node); + ts.setCommentRange(varStatement, node); + ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node)); + ts.startOnNewLine(varStatement); + statements = [varStatement]; + } // If the class is exported as part of a TypeScript namespace, emit the namespace export. // Otherwise, if the class was exported at the top level and was decorated, emit an export // declaration or export default for the class. - if (isNamespaceExport(node)) { + if (facts & 8 /* IsExportOfNamespace */) { addExportMemberAssignment(statements, node); } - else if (isDecoratedClass) { - if (isDefaultExternalModuleExport(node)) { + else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) { + if (facts & 32 /* IsDefaultExternalExport */) { statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } - else if (isNamedExternalModuleExport(node)) { + else if (facts & 16 /* IsNamedExternalExport */) { statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))); } } @@ -50026,20 +51349,23 @@ var ts; * * @param node A ClassDeclaration node. * @param name The name of the class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. - * @param hasStaticProperties A value indicating whether the class has static properties. + * @param facts Precomputed facts about the class. */ - function createClassDeclarationHeadWithoutDecorators(node, name, hasExtendsClause, hasStaticProperties) { + function createClassDeclarationHeadWithoutDecorators(node, name, facts) { // ${modifiers} class ${name} ${heritageClauses} { // ${members} // } + // we do not emit modifiers on the declaration if we are emitting an IIFE + var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */) + ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier) + : undefined; var classDeclaration = ts.createClassDeclaration( - /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause)); + /*decorators*/ undefined, modifiers, name, + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0)); // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. var emitFlags = ts.getEmitFlags(node); - if (hasStaticProperties) { + if (facts & 1 /* HasStaticInitializedProperties */) { emitFlags |= 32 /* NoTrailingSourceMap */; } ts.setTextRange(classDeclaration, node); @@ -50050,13 +51376,8 @@ var ts; /** * Transforms a decorated class declaration and appends the resulting statements. If * the class requires an alias to avoid issues with double-binding, the alias is returned. - * - * @param statements A statement list to which to add the declaration. - * @param node A ClassDeclaration node. - * @param name The name of the class. - * @param hasExtendsClause A value indicating whether the class has an extends clause. */ - function createClassDeclarationHeadWithDecorators(node, name, hasExtendsClause) { + function createClassDeclarationHeadWithDecorators(node, name, facts) { // When we emit an ES6 class that has a class decorator, we must tailor the // emit to certain specific cases. // @@ -50149,7 +51470,7 @@ var ts; // ${members} // } var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause); - var members = transformClassMembers(node, hasExtendsClause); + var members = transformClassMembers(node, (facts & 64 /* HasExtendsClause */) !== 0); var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members); ts.setOriginalNode(classExpression, node); ts.setTextRange(classExpression, location); @@ -50650,8 +51971,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { - var member = members_2[_i]; + for (var _i = 0, members_3 = members; _i < members_3.length; _i++) { + var member = members_3[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -50900,7 +52221,7 @@ var ts; var numParameters = parameters.length; for (var i = 0; i < numParameters; i++) { var parameter = parameters[i]; - if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.text === "this") { + if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") { continue; } if (parameter.dotDotDotToken) { @@ -51025,7 +52346,7 @@ var ts; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; var serializedIndividual = serializeTypeNode(typeNode); - if (ts.isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } @@ -51033,7 +52354,7 @@ var ts; // Different types if (!ts.isIdentifier(serializedUnion) || !ts.isIdentifier(serializedIndividual) || - serializedUnion.text !== serializedIndividual.text) { + serializedUnion.escapedText !== serializedIndividual.escapedText) { return ts.createIdentifier("Object"); } } @@ -51148,7 +52469,7 @@ var ts; : name.expression; } else if (ts.isIdentifier(name)) { - return ts.createLiteral(ts.unescapeIdentifier(name.text)); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.getSynthesizedClone(name); @@ -51320,7 +52641,7 @@ var ts; /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var statements = [updated]; addExportMemberAssignment(statements, node); return statements; @@ -51390,7 +52711,7 @@ var ts; * - The node is exported from a TypeScript namespace. */ function visitVariableStatement(node) { - if (isNamespaceExport(node)) { + if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); if (variables.length === 0) { // elide statement if there are no initialized variables. @@ -51599,7 +52920,7 @@ var ts; * or `exports.x`). */ function hasNamespaceQualifiedExportName(node) { - return isNamespaceExport(node) + return isExportOfNamespace(node) || (isExternalModuleExport(node) && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System); @@ -51612,10 +52933,10 @@ var ts; * on symbol names. */ function recordEmittedDeclarationInScope(node) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { if (!currentScopeFirstDeclarationsOfName) { - currentScopeFirstDeclarationsOfName = ts.createMap(); + currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap(); } if (!currentScopeFirstDeclarationsOfName.has(name)) { currentScopeFirstDeclarationsOfName.set(name, node); @@ -51628,7 +52949,7 @@ var ts; */ function isFirstEmittedDeclarationInScope(node) { if (currentScopeFirstDeclarationsOfName) { - var name = node.symbol && node.symbol.name; + var name = node.symbol && node.symbol.escapedName; if (name) { return currentScopeFirstDeclarationsOfName.get(name) === node; } @@ -51965,7 +53286,7 @@ var ts; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */); - if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { + if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ @@ -51983,7 +53304,7 @@ var ts; * * @param node The node to test. */ - function isNamespaceExport(node) { + function isExportOfNamespace(node) { return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */); } /** @@ -52020,7 +53341,7 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); - ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); var statement = ts.createStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); @@ -52057,7 +53378,7 @@ var ts; function getClassAliasIfNeeded(node) { if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { enableSubstitutionForClassAliases(); - var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeIdentifier(node.name.text) : "default"); + var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.unescapeLeadingUnderscores(node.name.escapedText) : "default"); classAliases[ts.getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; @@ -52187,10 +53508,10 @@ var ts; if (declaration) { var classAlias = classAliases[declaration.id]; if (classAlias) { - var clone_2 = ts.getSynthesizedClone(classAlias); - ts.setSourceMapRange(clone_2, node); - ts.setCommentRange(clone_2, node); - return clone_2; + var clone_1 = ts.getSynthesizedClone(classAlias); + ts.setSourceMapRange(clone_1, node); + ts.setCommentRange(clone_1, node); + return clone_1; } } } @@ -52564,7 +53885,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -52893,8 +54214,10 @@ 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 createDownlevelAwait(expression) { + return enclosingFunctionFlags & 1 /* Generator */ + ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression)) + : ts.createAwait(expression); } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); @@ -52915,9 +54238,9 @@ var ts; ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), ts.createVariableDeclaration(result) ]), node.expression), 2097152 /* NoHoisting */), - /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), + /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52928,7 +54251,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - 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 */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -53155,7 +54478,7 @@ var ts; } function substitutePropertyAccessExpression(node) { if (node.expression.kind === 97 /* SuperKeyword */) { - return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), node); + return createSuperAccessInAsyncMethod(ts.createLiteral(ts.unescapeLeadingUnderscores(node.name.escapedText)), node); } return node; } @@ -53470,8 +54793,8 @@ var ts; } else { var name = node.tagName; - if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.text)) { - return ts.createLiteral(name.text); + if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) { + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } else { return ts.createExpressionFromEntityName(name); @@ -53485,11 +54808,11 @@ var ts; */ function getAttributeName(node) { var name = node.name; - if (/^[A-Za-z_]\w*$/.test(name.text)) { + if (/^[A-Za-z_]\w*$/.test(ts.unescapeLeadingUnderscores(name.escapedText))) { return name; } else { - return ts.createLiteral(name.text); + return ts.createLiteral(ts.unescapeLeadingUnderscores(name.escapedText)); } } function visitJsxExpression(node) { @@ -54006,11 +55329,58 @@ var ts; && node.kind === 219 /* ReturnStatement */ && !node.expression; } + function isClassLikeVariableStatement(node) { + if (!ts.isVariableStatement(node)) + return false; + var variable = ts.singleOrUndefined(node.declarationList.declarations); + return variable + && variable.initializer + && ts.isIdentifier(variable.name) + && (ts.isClassLike(variable.initializer) + || (ts.isAssignmentExpression(variable.initializer) + && ts.isIdentifier(variable.initializer.left) + && ts.isClassLike(variable.initializer.right))); + } + function isTypeScriptClassWrapper(node) { + var call = ts.tryCast(node, ts.isCallExpression); + if (!call || ts.isParseTreeNode(call) || + ts.some(call.typeArguments) || + ts.some(call.arguments)) { + return false; + } + var func = ts.tryCast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + if (!func || ts.isParseTreeNode(func) || + ts.some(func.typeParameters) || + ts.some(func.parameters) || + func.type || + !func.body) { + return false; + } + var statements = func.body.statements; + if (statements.length < 2) { + return false; + } + var firstStatement = statements[0]; + if (ts.isParseTreeNode(firstStatement) || + !ts.isClassLike(firstStatement) && + !isClassLikeVariableStatement(firstStatement)) { + return false; + } + var lastStatement = ts.elementAt(statements, -1); + var returnStatement = ts.tryCast(ts.isVariableStatement(lastStatement) ? ts.elementAt(statements, -2) : lastStatement, ts.isReturnStatement); + if (!returnStatement || + !returnStatement.expression || + !ts.isIdentifier(ts.skipOuterExpressions(returnStatement.expression))) { + return false; + } + return true; + } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && ts.isStatement(node)) - || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); + || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) + || isTypeScriptClassWrapper(node); } function visitor(node) { if (shouldVisitNode(node)) { @@ -54197,7 +55567,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return node; } - if (node.text !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { return node; } return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments")); @@ -54209,7 +55579,7 @@ var ts; // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement var jump = node.kind === 218 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; - var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(node.label.text)) || + var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.unescapeLeadingUnderscores(node.label.escapedText))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; @@ -54226,12 +55596,12 @@ var ts; } else { if (node.kind === 218 /* BreakStatement */) { - labelMarker = "break-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ true, node.label.text, labelMarker); + labelMarker = "break-" + node.label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } else { - labelMarker = "continue-" + node.label.text; - setLabeledJump(convertedLoopState, /*isBreak*/ false, node.label.text, labelMarker); + labelMarker = "continue-" + node.label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -55276,9 +56646,9 @@ var ts; if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var declarations = ts.flatten(ts.map(node.declarations, node.flags & 1 /* Let */ + var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */ ? visitVariableDeclarationInLetDeclarationList - : visitVariableDeclaration)); + : visitVariableDeclaration); var declarationList = ts.createVariableDeclarationList(declarations); ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); @@ -55371,9 +56741,9 @@ var ts; return visitVariableDeclaration(node); } if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) { - var clone_3 = ts.getMutableClone(node); - clone_3.initializer = ts.createVoidZero(); - return clone_3; + var clone_2 = ts.getMutableClone(node); + clone_2.initializer = ts.createVoidZero(); + return clone_2; } return ts.visitEachChild(node, visitor, context); } @@ -55396,10 +56766,10 @@ var ts; return updated; } function recordLabel(node) { - convertedLoopState.labels.set(node.label.text, node.label.text); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), true); } function resetLabel(node) { - convertedLoopState.labels.set(node.label.text, undefined); + convertedLoopState.labels.set(ts.unescapeLeadingUnderscores(node.label.escapedText), false); } function visitLabeledStatement(node) { if (convertedLoopState && !convertedLoopState.labels) { @@ -55824,17 +57194,17 @@ var ts; loop = convert(node, outermostLabeledStatement, convertedLoopBodyStatements); } else { - var clone_4 = ts.getMutableClone(node); + var clone_3 = ts.getMutableClone(node); // clean statement part - clone_4.statement = undefined; + clone_3.statement = undefined; // visit childnodes to transform initializer/condition/incrementor parts - clone_4 = ts.visitEachChild(clone_4, visitor, context); + clone_3 = ts.visitEachChild(clone_3, visitor, context); // set loop statement - clone_4.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); + clone_3.statement = ts.createBlock(convertedLoopBodyStatements, /*multiline*/ true); // reset and re-aggregate the transform flags - clone_4.transformFlags = 0; - ts.aggregateTransformFlags(clone_4); - loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel); + clone_3.transformFlags = 0; + ts.aggregateTransformFlags(clone_3); + loop = ts.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel); } statements.push(loop); return statements; @@ -55943,7 +57313,7 @@ var ts; else { loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); if (resolver.getNodeCheckFlags(decl) & 2097152 /* NeedsLoopOutParameter */) { - var outParamName = ts.createUniqueName("out_" + ts.unescapeIdentifier(name.text)); + var outParamName = ts.createUniqueName("out_" + ts.unescapeLeadingUnderscores(name.escapedText)); loopOutParameters.push({ originalName: name, outParamName: outParamName }); } } @@ -56141,12 +57511,122 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { + if (isTypeScriptClassWrapper(node)) { + return visitTypeScriptClassWrapper(node); + } if (node.transformFlags & 64 /* ES2015 */) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } + function visitTypeScriptClassWrapper(node) { + // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer. + // The wrapper has a form similar to: + // + // (function() { + // class C { // 1 + // } + // C.x = 1; // 2 + // return C; + // }()) + // + // When we transform the class, we end up with something like this: + // + // (function () { + // var C = (function () { // 3 + // function C() { + // } + // return C; // 4 + // }()); + // C.x = 1; + // return C; + // }()) + // + // We want to simplify the two nested IIFEs to end up with something like this: + // + // (function () { + // function C() { + // } + // C.x = 1; + // return C; + // }()) + // We skip any outer expressions in a number of places to get to the innermost + // expression, but we will restore them later to preserve comments and source maps. + var body = ts.cast(ts.skipOuterExpressions(node.expression), ts.isFunctionExpression).body; + // The class statements are the statements generated by visiting the first statement of the + // body (1), while all other statements are added to remainingStatements (2) + var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); + var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); + var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + // We know there is only one variable declaration here as we verified this in an + // earlier call to isTypeScriptClassWrapper + var variable = varStatement.declarationList.declarations[0]; + var initializer = ts.skipOuterExpressions(variable.initializer); + // Under certain conditions, the 'ts' transformer may introduce a class alias, which + // we see as an assignment, for example: + // + // (function () { + // var C = C_1 = (function () { + // function C() { + // } + // C.x = function () { return C_1; } + // return C; + // }()); + // C = C_1 = __decorate([dec], C); + // return C; + // var C_1; + // }()) + // + var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); + // The underlying call (3) is another IIFE that may contain a '_super' argument. + var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression); + var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression); + var funcStatements = func.body.statements; + var classBodyStart = 0; + var classBodyEnd = -1; + var statements = []; + if (aliasAssignment) { + // If we have a class alias assignment, we need to move it to the down-level constructor + // function we generated for the class. + var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement); + if (extendsCall) { + statements.push(extendsCall); + classBodyStart++; + } + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); + classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + } + // Find the trailing 'return' statement (4) + while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { + classBodyEnd--; + } + // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4) + // as we already have one that has been introduced by the 'ts' transformer. + ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd); + if (classBodyEnd < -1) { + // If there were any hoisted declarations following the return statement, we should + // append them. + ts.addRange(statements, funcStatements, classBodyEnd + 1); + } + // Add the remaining statements of the outer wrapper. + ts.addRange(statements, remainingStatements); + // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it + // after the remaining statements from the 'ts' transformer. + ts.addRange(statements, classStatements, /*start*/ 1); + // Recreate any outer parentheses or partially-emitted expressions to preserve source map + // and comment locations. + return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, func.parameters, + /*type*/ undefined, ts.updateBlock(func.body, statements))), + /*typeArguments*/ undefined, call.arguments)))); + } function visitImmediateSuperCallInBody(node) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); } @@ -56241,7 +57721,7 @@ var ts; if (ts.isCallExpression(firstSegment) && ts.isIdentifier(firstSegment.expression) && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */) - && firstSegment.expression.text === "___spread") { + && firstSegment.expression.escapedText === "___spread") { return segments[0]; } } @@ -56250,7 +57730,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadExpression(firstElement) && firstElement.expression.kind !== 177 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 177 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -56259,7 +57739,7 @@ var ts; } } function partitionSpread(node) { - return ts.isSpreadExpression(node) + return ts.isSpreadElement(node) ? visitSpanOfSpreads : visitSpanOfNonSpreads; } @@ -56460,7 +57940,7 @@ var ts; : ts.createIdentifier("_super"); } function visitMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */ && node.name.text === "target") { + if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { if (hierarchyFacts & 8192 /* ComputedPropertyName */) { hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; } @@ -56610,9 +58090,7 @@ var ts; return false; } if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { - // we are in the class body, but we treat static fields as outside of the class body - return currentNode.kind !== 149 /* PropertyDeclaration */ - || (ts.getModifierFlags(currentNode) & 32 /* Static */) === 0; + return true; } currentNode = currentNode.parent; } @@ -56659,7 +58137,7 @@ var ts; return false; } var expression = callArgument.expression; - return ts.isIdentifier(expression) && expression.text === "arguments"; + return ts.isIdentifier(expression) && expression.escapedText === "arguments"; } } ts.transformES2015 = transformES2015; @@ -56781,7 +58259,7 @@ var ts; * @param name An Identifier */ function trySubstituteReservedName(name) { - var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(name.text) : undefined); + var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.unescapeLeadingUnderscores(name.escapedText)) : undefined); if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } @@ -57324,7 +58802,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))); + return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } /** @@ -57430,10 +58908,10 @@ var ts; // _a = a(); // .yield resumeLabel // _a + %sent% + c() - var clone_5 = ts.getMutableClone(node); - clone_5.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); - clone_5.right = ts.visitNode(node.right, visitor, ts.isExpression); - return clone_5; + var clone_4 = ts.getMutableClone(node); + clone_4.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)); + clone_4.right = ts.visitNode(node.right, visitor, ts.isExpression); + return clone_4; } return ts.visitEachChild(node, visitor, context); } @@ -57694,10 +59172,10 @@ var ts; // .yield resumeLabel // .mark resumeLabel // a = _a[%sent%] - var clone_6 = ts.getMutableClone(node); - clone_6.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); - clone_6.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); - return clone_6; + var clone_5 = ts.getMutableClone(node); + clone_5.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); + clone_5.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression); + return clone_5; } return ts.visitEachChild(node, visitor, context); } @@ -57836,7 +59314,7 @@ var ts; return undefined; } function transformInitializedVariable(node) { - return ts.createAssignment(ts.getSynthesizedClone(node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)); + return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node); } function transformAndEmitIfStatement(node) { if (containsYield(node)) { @@ -58114,13 +59592,13 @@ var ts; return node; } function transformAndEmitContinueStatement(node) { - var label = findContinueTarget(node.label ? node.label.text : undefined); + var label = findContinueTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); emitBreak(label, /*location*/ node); } function visitContinueStatement(node) { if (inStatementContainingYield) { - var label = findContinueTarget(node.label && node.label.text); + var label = findContinueTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -58128,13 +59606,13 @@ var ts; return ts.visitEachChild(node, visitor, context); } function transformAndEmitBreakStatement(node) { - var label = findBreakTarget(node.label ? node.label.text : undefined); + var label = findBreakTarget(node.label ? ts.unescapeLeadingUnderscores(node.label.escapedText) : undefined); ts.Debug.assert(label > 0, "Expected break statment to point to a valid Label."); emitBreak(label, /*location*/ node); } function visitBreakStatement(node) { if (inStatementContainingYield) { - var label = findBreakTarget(node.label && node.label.text); + var label = findBreakTarget(node.label && ts.unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -58285,7 +59763,7 @@ var ts; // /*body*/ // .endlabeled // .mark endLabel - beginLabeledBlock(node.label.text); + beginLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -58295,7 +59773,7 @@ var ts; } function visitLabeledStatement(node) { if (inStatementContainingYield) { - beginScriptLabeledBlock(node.label.text); + beginScriptLabeledBlock(ts.unescapeLeadingUnderscores(node.label.escapedText)); } node = ts.visitEachChild(node, visitor, context); if (inStatementContainingYield) { @@ -58380,17 +59858,17 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(node.text)) { + if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.unescapeLeadingUnderscores(node.escapedText))) { var original = ts.getOriginalNode(node); if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)]; if (name) { - var clone_7 = ts.getMutableClone(name); - ts.setSourceMapRange(clone_7, node); - ts.setCommentRange(clone_7, node); - return clone_7; + var clone_6 = ts.getMutableClone(name); + ts.setSourceMapRange(clone_6, node); + ts.setCommentRange(clone_6, node); + return clone_6; } } } @@ -58534,7 +60012,7 @@ var ts; hoistVariableDeclaration(variable.name); } else { - var text = variable.name.text; + var text = ts.unescapeLeadingUnderscores(variable.name.escapedText); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = ts.createMap(); @@ -58618,7 +60096,7 @@ var ts; kind: 3 /* Loop */, isScript: false, breakLabel: breakLabel, - continueLabel: continueLabel + continueLabel: continueLabel, }); return breakLabel; } @@ -58656,7 +60134,7 @@ var ts; beginBlock({ kind: 2 /* Switch */, isScript: false, - breakLabel: breakLabel + breakLabel: breakLabel, }); return breakLabel; } @@ -59468,6 +60946,7 @@ var ts; var currentSourceFile; // The current file. var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. + var needUMDDynamicImportHelper; return transformSourceFile; /** * Transforms the module aspects of a SourceFile. @@ -59475,7 +60954,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } currentSourceFile = node; @@ -59486,6 +60965,7 @@ var ts; var updated = transformModule(node); currentSourceFile = undefined; currentModuleInfo = undefined; + needUMDDynamicImportHelper = false; return ts.aggregateTransformFlags(updated); } function shouldEmitUnderscoreUnderscoreESModule() { @@ -59512,11 +60992,12 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); ts.addRange(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. ts.addEmitHelper(updated, exportStarHelper); } + ts.addEmitHelpers(updated, context.readEmitHelpers()); return updated; } /** @@ -59715,11 +61196,14 @@ var ts; // and merge any new lexical declarations. ts.addRange(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); - if (currentModuleInfo.hasExportStarsToExportValues) { + if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. ts.addEmitHelper(body, exportStarHelper); } + if (needUMDDynamicImportHelper) { + ts.addEmitHelper(body, dynamicImportUMDHelper); + } return body; } /** @@ -59770,16 +61254,92 @@ var ts; return visitFunctionDeclaration(node); case 229 /* ClassDeclaration */: return visitClassDeclaration(node); - case 298 /* MergeDeclarationMarker */: + case 290 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 291 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - // This visitor does not descend into the tree, as export/import statements - // are only transformed at the top level of a file. - return node; + return ts.visitEachChild(node, importCallExpressionVisitor, context); } } + function importCallExpressionVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import, + // as export/import statements are only transformed at the top level of a file. + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + return node; + } + if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else { + return ts.visitEachChild(node, importCallExpressionVisitor, context); + } + } + function visitImportCallExpression(node) { + switch (compilerOptions.module) { + case ts.ModuleKind.AMD: + return transformImportCallExpressionAMD(node); + case ts.ModuleKind.UMD: + return transformImportCallExpressionUMD(node); + case ts.ModuleKind.CommonJS: + default: + return transformImportCallExpressionCommonJS(node); + } + } + function transformImportCallExpressionUMD(node) { + // (function (factory) { + // ... (regular UMD) + // } + // })(function (require, exports, useSyncRequire) { + // "use strict"; + // Object.defineProperty(exports, "__esModule", { value: true }); + // var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + // var __resolved = new Promise(function (resolve) { resolve(); }); + // ..... + // __syncRequire + // ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/ + // : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + needUMDDynamicImportHelper = true; + return ts.createConditional( + /*condition*/ ts.createIdentifier("__syncRequire"), + /*whenTrue*/ transformImportCallExpressionCommonJS(node), + /*whenFalse*/ transformImportCallExpressionAMD(node)); + } + function transformImportCallExpressionAMD(node) { + // improt("./blah") + // emit as + // define(["require", "exports", "blah"], function (require, exports) { + // ... + // new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/ + // }); + var resolve = ts.createUniqueName("resolve"); + var reject = ts.createUniqueName("reject"); + return ts.createNew(ts.createIdentifier("Promise"), + /*typeArguments*/ undefined, [ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, [ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve), + ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)], + /*type*/ undefined, ts.createBlock([ts.createStatement(ts.createCall(ts.createIdentifier("require"), + /*typeArguments*/ undefined, [ts.createArrayLiteral([ts.firstOrUndefined(node.arguments) || ts.createOmittedExpression()]), resolve, reject]))]))]); + } + function transformImportCallExpressionCommonJS(node) { + // import("./blah") + // emit as + // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/ + // We have to wrap require in then callback so that require is done in asynchronously + // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately + return ts.createCall(ts.createPropertyAccess(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []), "then"), + /*typeArguments*/ undefined, [ts.createFunctionExpression( + /*modifiers*/ undefined, + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + /*parameters*/ undefined, + /*type*/ undefined, ts.createBlock([ts.createReturn(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, node.arguments))]))]); + } /** * Visits an ImportDeclaration node. * @@ -59917,12 +61477,7 @@ var ts; } else { // export * from "mod"; - return ts.setTextRange(ts.createStatement(ts.createCall(ts.createIdentifier("__export"), - /*typeArguments*/ undefined, [ - moduleKind !== ts.ModuleKind.AMD - ? createRequireCall(node) - : generatedName - ])), node); + return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } /** @@ -59956,13 +61511,13 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, node.parameters, - /*type*/ undefined, node.body), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), /*location*/ node), /*original*/ node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -59984,10 +61539,10 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, node.heritageClauses, node.members), node), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -60032,7 +61587,7 @@ var ts; } } else { - statements = ts.append(statements, node); + statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -60051,13 +61606,13 @@ var ts; */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(node, + return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), /*visitor*/ undefined, context, 0 /* All */, /*needsValue*/ false, createExportExpression); } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), node.initializer); + /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); } } /** @@ -60234,7 +61789,7 @@ var ts; */ function appendExportsOfDeclaration(statements, decl) { var name = ts.getDeclarationName(decl); - var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) { var exportSpecifier = exportSpecifiers_1[_i]; @@ -60530,7 +62085,19 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + }; + function createExportStarHelper(context, module) { + var compilerOptions = context.getCompilerOptions(); + return compilerOptions.importHelpers + ? ts.createCall(ts.getHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]) + : ts.createCall(ts.createIdentifier("__export"), /*typeArguments*/ undefined, [module]); + } + // emit helper for dynamic import + var dynamicImportUMDHelper = { + name: "typescript:dynamicimport-sync-require", + scoped: true, + text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; })(ts || (ts = {})); /// @@ -60571,7 +62138,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isExternalModule(node) || compilerOptions.isolatedModules)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 67108864 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -60789,7 +62356,7 @@ var ts; if (moduleInfo.exportedNames) { for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) { var exportedLocalName = _c[_b]; - if (exportedLocalName.text === "default") { + if (exportedLocalName.escapedText === "default") { continue; } // write name of exported declaration, i.e 'export var x...' @@ -60809,7 +62376,7 @@ var ts; for (var _f = 0, _g = exportDecl.exportClause.elements; _f < _g.length; _f++) { var element = _g[_f]; // write name of indirectly exported entry, i.e. 'export {x} from ...' - exportedNames.push(ts.createPropertyAssignment(ts.createLiteral((element.name || element.propertyName).text), ts.createTrue())); + exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), ts.createTrue())); } } var exportedNamesStorageRef = ts.createUniqueName("exportedNames"); @@ -60903,7 +62470,7 @@ var ts; var properties = []; for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) { var e = _d[_c]; - properties.push(ts.createPropertyAssignment(ts.createLiteral(e.name.text), ts.createElementAccess(parameterName, ts.createLiteral((e.propertyName || e.name).text)))); + properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.unescapeLeadingUnderscores(e.name.escapedText)), ts.createElementAccess(parameterName, ts.createLiteral(ts.unescapeLeadingUnderscores((e.propertyName || e.name).escapedText))))); } statements.push(ts.createStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); @@ -61002,7 +62569,7 @@ var ts; // Elide `export=` as it is illegal in a SystemJS module. return undefined; } - var expression = ts.visitNode(node.expression, destructuringVisitor, ts.isExpression); + var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression); var original = node.original; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -61021,11 +62588,11 @@ var ts; function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1 /* Export */)) { hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringVisitor, ts.isParameterDeclaration), - /*type*/ undefined, ts.visitNode(node.body, destructuringVisitor, ts.isBlock))); + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), + /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock))); } else { - hoistedStatements = ts.append(hoistedStatements, node); + hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -61050,7 +62617,7 @@ var ts; // Rewrite the class declaration into an assignment of a class expression. statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( /*modifiers*/ undefined, node.name, - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringVisitor, ts.isClassElement)), node))), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); @@ -61069,7 +62636,7 @@ var ts; */ function visitVariableStatement(node) { if (!shouldHoistVariableDeclarationList(node.declarationList)) { - return ts.visitNode(node, destructuringVisitor, ts.isStatement); + return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement); } var expressions; var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */); @@ -61135,9 +62702,9 @@ var ts; function transformInitializedVariable(node, isExportedDeclaration) { var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment; return ts.isBindingPattern(node.name) - ? ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, /*needsValue*/ false, createAssignment) - : createAssignment(node.name, ts.visitNode(node.initializer, destructuringVisitor, ts.isExpression)); + : createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Creates an assignment expression for an exported variable declaration. @@ -61320,7 +62887,7 @@ var ts; var excludeName = void 0; if (exportSelf) { statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl)); - excludeName = decl.name.text; + excludeName = ts.unescapeLeadingUnderscores(decl.name.escapedText); } statements = appendExportsOfDeclaration(statements, decl, excludeName); } @@ -61343,7 +62910,7 @@ var ts; if (ts.hasModifier(decl, 1 /* Export */)) { var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name; statements = appendExportStatement(statements, exportName, ts.getLocalName(decl)); - excludeName = exportName.text; + excludeName = ts.getTextOfIdentifierOrLiteral(exportName); } if (decl.name) { statements = appendExportsOfDeclaration(statements, decl, excludeName); @@ -61364,11 +62931,11 @@ var ts; return statements; } var name = ts.getDeclarationName(decl); - var exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text); + var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) { var exportSpecifier = exportSpecifiers_2[_i]; - if (exportSpecifier.name.text !== excludeName) { + if (exportSpecifier.name.escapedText !== excludeName) { statements = appendExportStatement(statements, exportSpecifier.name, name); } } @@ -61459,12 +63026,12 @@ var ts; return visitCatchClause(node); case 207 /* Block */: return visitBlock(node); - case 298 /* MergeDeclarationMarker */: + case 290 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 299 /* EndOfDeclarationMarker */: + case 291 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - return destructuringVisitor(node); + return destructuringAndImportCallVisitor(node); } } /** @@ -61475,7 +63042,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -61487,7 +63054,7 @@ var ts; function visitForInStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -61499,7 +63066,7 @@ var ts; function visitForOfStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -61540,7 +63107,7 @@ var ts; * @param node The node to visit. */ function visitDoStatement(node) { - return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression)); + return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression)); } /** * Visits the body of a WhileStatement to hoist declarations. @@ -61548,7 +63115,7 @@ var ts; * @param node The node to visit. */ function visitWhileStatement(node) { - return ts.updateWhile(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } /** * Visits the body of a LabeledStatement to hoist declarations. @@ -61564,7 +63131,7 @@ var ts; * @param node The node to visit. */ function visitWithStatement(node) { - return ts.updateWith(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); + return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock)); } /** * Visits the body of a SwitchStatement to hoist declarations. @@ -61572,7 +63139,7 @@ var ts; * @param node The node to visit. */ function visitSwitchStatement(node) { - return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); + return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock)); } /** * Visits the body of a CaseBlock to hoist declarations. @@ -61592,7 +63159,7 @@ var ts; * @param node The node to visit. */ function visitCaseClause(node) { - return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); + return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement)); } /** * Visits the body of a DefaultClause to hoist declarations. @@ -61642,18 +63209,35 @@ var ts; * * @param node The node to visit. */ - function destructuringVisitor(node) { + function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ && node.kind === 194 /* BinaryExpression */) { return visitDestructuringAssignment(node); } - else if (node.transformFlags & 2048 /* ContainsDestructuringAssignment */) { - return ts.visitEachChild(node, destructuringVisitor, context); + else if (ts.isImportCall(node)) { + return visitImportCallExpression(node); + } + else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { return node; } } + function visitImportCallExpression(node) { + // import("./blah") + // emit as + // System.register([], function (_export, _context) { + // return { + // setters: [], + // execute: () => { + // _context.import('./blah'); + // } + // }; + // }); + return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), + /*typeArguments*/ undefined, node.arguments); + } /** * Visits a DestructuringAssignment to flatten destructuring to exported symbols. * @@ -61661,10 +63245,10 @@ var ts; */ function visitDestructuringAssignment(node) { if (hasExportedReferenceInDestructuringTarget(node.left)) { - return ts.flattenDestructuringAssignment(node, destructuringVisitor, context, 0 /* All */, + return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, /*needsValue*/ true); } - return ts.visitEachChild(node, destructuringVisitor, context); + return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } /** * Determines whether the target of a destructuring assigment refers to an exported symbol. @@ -61675,7 +63259,7 @@ var ts; if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { return hasExportedReferenceInDestructuringTarget(node.left); } - else if (ts.isSpreadExpression(node)) { + else if (ts.isSpreadElement(node)) { return hasExportedReferenceInDestructuringTarget(node.expression); } else if (ts.isObjectLiteralExpression(node)) { @@ -62026,6 +63610,7 @@ var ts; ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); /// +/// /// /// /// @@ -62042,6 +63627,7 @@ var ts; (function (ts) { function getModuleTransformer(moduleKind) { switch (moduleKind) { + case ts.ModuleKind.ESNext: case ts.ModuleKind.ES2015: return ts.transformES2015Module; case ts.ModuleKind.System: @@ -62106,7 +63692,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(300 /* Count */); + var enabledSyntaxKindFeatures = new Array(292 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -62237,7 +63823,7 @@ var ts; function hoistVariableDeclaration(name) { ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization."); ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed."); - var decl = ts.createVariableDeclaration(name); + var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */); if (!lexicalEnvironmentVariableDeclarations) { lexicalEnvironmentVariableDeclarations = [decl]; } @@ -62374,7 +63960,7 @@ var ts; function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; - var currentSourceFile; + var currentSource; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be // Current source map file and its index in the sources list @@ -62397,6 +63983,12 @@ var ts; getText: getText, getSourceMappingURL: getSourceMappingURL, }; + /** + * Skips trivia such as comments and white-space that can optionally overriden by the source map source + */ + function skipSourceTrivia(pos) { + return currentSource.skipTrivia ? currentSource.skipTrivia(pos) : ts.skipTrivia(currentSourceText, pos); + } /** * Initialize the SourceMapWriter for a new output file. * @@ -62411,7 +64003,7 @@ var ts; if (sourceMapData) { reset(); } - currentSourceFile = undefined; + currentSource = undefined; currentSourceText = undefined; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; @@ -62468,7 +64060,7 @@ var ts; if (disabled) { return; } - currentSourceFile = undefined; + currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; lastRecordedSourceMapSpan = undefined; @@ -62528,7 +64120,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("beforeSourcemap"); } - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); + var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); // Convert the location to be one-based. sourceLinePos.line++; sourceLinePos.character++; @@ -62577,12 +64169,21 @@ var ts; if (node) { var emitNode = node.emitNode; var emitFlags = emitNode && emitNode.flags; - var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; - if (node.kind !== 295 /* NotEmittedStatement */ + var range = emitNode && emitNode.sourceMapRange; + var _a = range || node, pos = _a.pos, end = _a.end; + var source = range && range.source; + var oldSource = currentSource; + if (source === oldSource) + source = undefined; + if (source) + setSourceFile(source); + if (node.kind !== 287 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { - emitPos(ts.skipTrivia(currentSourceText, pos)); + emitPos(skipSourceTrivia(pos)); } + if (source) + setSourceFile(oldSource); if (emitFlags & 64 /* NoNestedSourceMaps */) { disabled = true; emitCallback(hint, node); @@ -62591,11 +64192,15 @@ var ts; else { emitCallback(hint, node); } - if (node.kind !== 295 /* NotEmittedStatement */ + if (source) + setSourceFile(source); + if (node.kind !== 287 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); } + if (source) + setSourceFile(oldSource); } } /** @@ -62613,7 +64218,7 @@ var ts; var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; - tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } @@ -62634,22 +64239,22 @@ var ts; if (disabled) { return; } - currentSourceFile = sourceFile; - currentSourceText = currentSourceFile.text; + currentSource = sourceFile; + currentSourceText = currentSource.text; // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSourceFile.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(currentSourceFile.fileName); + sourceMapData.inputSourceFileNames.push(currentSource.fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSourceFile.text); + sourceMapData.sourceMapSourcesContent.push(currentSource.text); } } } @@ -62766,9 +64371,11 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 295 /* NotEmittedStatement */; - var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0; - var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0; + var isEmittedNode = node.kind !== 287 /* NotEmittedStatement */; + // 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. + var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; + var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 10 /* JsxText */; // Emit leading comments if the position is not synthesized and the node // has not opted out from emitting leading comments. if (!skipLeadingComments) { @@ -63227,7 +64834,7 @@ var ts; var writer = ts.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; @@ -63335,10 +64942,10 @@ var ts; handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } - function reportIllegalExtends() { + function reportPrivateInBaseOfClassExpression(propertyName) { if (errorNameNode) { reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced, ts.declarationNameToString(errorNameNode))); + emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); } } function reportInaccessibleThisError() { @@ -63351,17 +64958,22 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); // use the checker's type, not the declared type, - // for non-optional initialized parameters that aren't a parameter property + // for optional parameter properties + // and also for non-optional initialized parameters that aren't a parameter property + // these types may need to add `undefined`. var shouldUseResolverType = declaration.kind === 146 /* Parameter */ && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { // Write the type emitType(type); } else { errorNameNode = declaration.name; - var format = 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */ | - (shouldUseResolverType ? 4096 /* AddUndefined */ : 0); + var format = 4 /* UseTypeOfFunction */ | + 16384 /* WriteClassExpressionAsTypeLiteral */ | + 2048 /* UseTypeAliasValue */ | + (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -63375,7 +64987,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); errorNameNode = undefined; } } @@ -63584,7 +65196,7 @@ var ts; currentIdentifiers = node.identifiers; isCurrentFileExternalModule = ts.isExternalModule(node); enclosingDeclaration = node; - ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); + ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComments*/ true); emitLines(node.statements); } // Return a temp variable name to be used in `export default`/`export class ... extends` statements. @@ -63613,7 +65225,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 2048 /* UseTypeAliasValue */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); write(";"); writeLine(); return tempVarName; @@ -64097,7 +65709,7 @@ var ts; if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? "null" : - emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name @@ -64800,6 +66412,64 @@ var ts; var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ + /** + * Iterates over the source files that are expected to have an emit output. + * + * @param host An EmitHost. + * @param action The action to execute. + * @param sourceFilesOrTargetSourceFile + * If an array, the full list of source files to emit. + * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. + */ + function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); + var options = host.getCompilerOptions(); + if (options.outFile || options.out) { + if (sourceFiles.length) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + } + } + else { + for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { + var sourceFile = sourceFiles_1[_a]; + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + } + } + } + ts.forEachEmittedFile = forEachEmittedFile; + function getSourceMapFilePath(jsFilePath, options) { + return options.sourceMap ? jsFilePath + ".map" : undefined; + } + // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. + // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. + // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + function getOutputExtension(sourceFile, options) { + if (options.jsx === 1 /* Preserve */) { + if (ts.isSourceFileJavaScript(sourceFile)) { + if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { + return ".jsx" /* Jsx */; + } + } + else if (sourceFile.languageVariant === 1 /* JSX */) { + // TypeScript source file preserving JSX syntax + return ".jsx" /* Jsx */; + } + } + return ".js" /* Js */; + } + function getOriginalSourceFileOrBundle(sourceFileOrBundle) { + if (sourceFileOrBundle.kind === 266 /* Bundle */) { + return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); + } + return ts.getOriginalSourceFile(sourceFileOrBundle); + } + /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { var compilerOptions = host.getCompilerOptions(); @@ -64834,7 +66504,7 @@ var ts; }); // Emit each output file ts.performance.mark("beforePrint"); - ts.forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); // Clean up emit nodes on parse tree transform.dispose(); @@ -64856,7 +66526,7 @@ var ts; emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -65278,6 +66948,8 @@ var ts; return emitModuleBlock(node); case 235 /* CaseBlock */: return emitCaseBlock(node); + case 236 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); case 237 /* ImportEqualsDeclaration */: return emitImportEqualsDeclaration(node); case 238 /* ImportDeclaration */: @@ -65367,6 +67039,7 @@ var ts; case 97 /* SuperKeyword */: case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: writeTokenNode(node); return; // Expressions @@ -65430,9 +67103,9 @@ var ts; case 250 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); // Transformation nodes - case 296 /* PartiallyEmittedExpression */: + case 288 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 297 /* CommaListExpression */: + case 289 /* CommaListExpression */: return emitCommaList(node); } } @@ -65531,6 +67204,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); write(";"); @@ -65550,6 +67224,7 @@ var ts; emitModifiers(node, node.modifiers); writeIfPresent(node.asteriskToken, "*"); emit(node.name); + writeIfPresent(node.questionToken, "?"); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -65612,7 +67287,7 @@ var ts; function emitConstructorType(node) { write("new "); emitTypeParameters(node, node.typeParameters); - emitParametersForArrow(node, node.parameters); + emitParameters(node, node.parameters); write(" => "); emit(node.type); } @@ -65704,7 +67379,7 @@ var ts; } else { write("{"); - emitList(node, elements, ts.getEmitFlags(node) & 1 /* SingleLine */ ? 272 /* ObjectBindingPatternElements */ : 432 /* ObjectBindingPatternElementsWithSpaceBetweenBraces */); + emitList(node, elements, 432 /* ObjectBindingPatternElements */); write("}"); } } @@ -66413,6 +68088,11 @@ var ts; } write(";"); } + function emitNamespaceExportDeclaration(node) { + write("export as namespace "); + emit(node.name); + write(";"); + } function emitNamedExports(node) { emitNamedImportsOrExports(node); } @@ -66525,6 +68205,21 @@ var ts; ts.nodeIsSynthesized(parentNode) || ts.nodeIsSynthesized(statements[0]) || 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]); @@ -66637,7 +68332,7 @@ var ts; } emit(statement); if (seenPrologueDirectives) { - seenPrologueDirectives.set(statement.expression.text, statement.expression.text); + seenPrologueDirectives.set(statement.expression.text, true); } } } @@ -66686,7 +68381,7 @@ var ts; // function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 256 /* Modifiers */); + emitList(node, modifiers, 131328 /* Modifiers */); write(" "); } } @@ -66732,11 +68427,24 @@ var ts; function emitParameters(parentNode, parameters) { emitList(parentNode, parameters, 1360 /* Parameters */); } + function canEmitSimpleArrowHead(parentNode, parameters) { + var parameter = ts.singleOrUndefined(parameters); + return parameter + && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter + && !(ts.isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && !ts.some(parentNode.decorators) // parent may not have decorators + && !ts.some(parentNode.modifiers) // parent may not have modifiers + && !ts.some(parentNode.typeParameters) // parent may not have type parameters + && !ts.some(parameter.decorators) // parameter may not have decorators + && !ts.some(parameter.modifiers) // parameter may not have modifiers + && !parameter.dotDotDotToken // parameter may not be rest + && !parameter.questionToken // parameter may not be optional + && !parameter.type // parameter may not have a type annotation + && !parameter.initializer // parameter may not have an initializer + && ts.isIdentifier(parameter.name); // parameter name must be identifier + } function emitParametersForArrow(parentNode, parameters) { - if (parameters && - parameters.length === 1 && - parameters[0].type === undefined && - parameters[0].pos === parentNode.pos) { + if (canEmitSimpleArrowHead(parentNode, parameters)) { emit(parameters[0]); } else { @@ -67080,7 +68788,7 @@ var ts; return generateName(node); } else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { - return ts.unescapeIdentifier(node.text); + return ts.unescapeLeadingUnderscores(node.escapedText); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { return getTextOfNode(node.textSourceNode, includeTrivia); @@ -67131,12 +68839,12 @@ var ts; // Auto, Loop, and Unique names are cached based on their unique // autoGenerateId. var autoGenerateId = name.autoGenerateId; - return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = ts.unescapeIdentifier(makeName(name))); + return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } function generateNameCached(node) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = ts.unescapeIdentifier(generateNameForNode(node))); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); } /** * Returns a value indicating whether a name is unique globally, within the current file, @@ -67153,9 +68861,9 @@ var ts; function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { if (node.locals) { - var local = node.locals.get(name); + var local = node.locals.get(ts.escapeLeadingUnderscores(name)); // We conservatively include alias symbols to cover cases where they're emitted as locals - if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { + if (local && local.flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) { return false; } } @@ -67204,7 +68912,7 @@ var ts; while (true) { var generatedName = baseName + i; if (isUniqueName(generatedName)) { - generatedNames.set(generatedName, generatedName); + generatedNames.set(generatedName, true); return generatedName; } i++; @@ -67223,8 +68931,8 @@ var ts; */ function generateNameForImportOrExportDeclaration(node) { var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 9 /* StringLiteral */ ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; + var baseName = ts.isStringLiteral(expr) ? + ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); } /** @@ -67282,7 +68990,7 @@ var ts; case 2 /* Loop */: return makeTempVariableName(268435456 /* _i */); case 3 /* Unique */: - return makeUniqueName(ts.unescapeIdentifier(name.text)); + return makeUniqueName(ts.unescapeLeadingUnderscores(name.escapedText)); } ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } @@ -67374,15 +69082,14 @@ var ts; ListFormat[ListFormat["NoTrailingNewLine"] = 65536] = "NoTrailingNewLine"; ListFormat[ListFormat["NoInterveningComments"] = 131072] = "NoInterveningComments"; // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 256] = "Modifiers"; + ListFormat[ListFormat["Modifiers"] = 131328] = "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["ObjectBindingPatternElements"] = 432] = "ObjectBindingPatternElements"; ListFormat[ListFormat["ArrayBindingPatternElements"] = 304] = "ArrayBindingPatternElements"; ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 978] = "ObjectLiteralExpressionProperties"; ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 4466] = "ArrayLiteralExpressionElements"; @@ -67418,7 +69125,6 @@ var ts; /// var ts; (function (ts) { - var emptyArray = []; var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { if (configName === void 0) { configName = "tsconfig.json"; } @@ -67641,9 +69347,9 @@ var ts; 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 start = diagnostic.start, length_6 = 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 _b = ts.getLineAndCharacterOfPosition(file, start + length_6), 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; @@ -67693,6 +69399,7 @@ var ts; 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); + output += ts.sys.newLine; } return output; } @@ -67739,6 +69446,19 @@ var ts; } return resolutions; } + /** + * 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. + */ function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -67772,11 +69492,12 @@ var ts; var currentDirectory = host.getCurrentDirectory(); var supportedExtensions = ts.getSupportedExtensions(options); // Map storing if there is emit blocking diagnostics for given input - var hasEmitBlockingDiagnostics = ts.createFileMap(getCanonicalFileName); + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; var moduleResolutionCache; var resolveModuleNamesWorker; if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile).map(function (resolved) { + resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile).map(function (resolved) { // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. if (!resolved || resolved.extension !== undefined) { return resolved; @@ -67789,20 +69510,20 @@ var ts; else { moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; + resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); }; } else { var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; - resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(checkAllDefined(typeReferenceDirectiveNames), containingFile, loader_2); }; } - var filesByName = ts.createFileMap(); + var filesByName = ts.createMap(); // 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; + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; var structuralIsReused = tryReuseStructureFromOldProgram(); if (structuralIsReused !== 2 /* Completely */) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); @@ -67835,6 +69556,7 @@ var ts; } } } + var missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks moduleResolutionCache = undefined; // unconditionally set oldProgram to undefined to prevent it from being captured in closure @@ -67844,6 +69566,7 @@ var ts; getSourceFile: getSourceFile, getSourceFileByPath: getSourceFileByPath, getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, getCompilerOptions: function () { return options; }, getSyntacticDiagnostics: getSyntacticDiagnostics, getOptionsDiagnostics: getOptionsDiagnostics, @@ -67870,6 +69593,9 @@ var ts; ts.performance.mark("afterProgram"); ts.performance.measure("Program", "beforeProgram", "afterProgram"); return program; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function getCommonSourceDirectory() { if (commonSourceDirectory === undefined) { var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); @@ -67893,7 +69619,7 @@ var ts; if (!classifiableNames) { // Initialize a checker so that all our files are bound. getTypeChecker(); - classifiableNames = ts.createMap(); + classifiableNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { var sourceFile = files_2[_i]; ts.copyEntries(sourceFile.classifiableNames, classifiableNames); @@ -67981,7 +69707,7 @@ var ts; } var resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, containingFile) - : emptyArray; + : ts.emptyArray; // Combine results of resolutions and predicted results if (!result) { // There were no unresolved/ambient resolutions. @@ -68086,6 +69812,10 @@ var ts; // moduleAugmentations has changed oldProgram.structureIsReused = 1 /* SafeModules */; } + if ((oldSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */) !== (newSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { // 'types' references has changed oldProgram.structureIsReused = 1 /* SafeModules */; @@ -68135,14 +69865,28 @@ var ts; if (oldProgram.structureIsReused !== 2 /* Completely */) { return oldProgram.structureIsReused; } + // If a file has ceased to be missing, then we need to discard some of the old + // structure in order to pick it up. + // Caution: if the file has created and then deleted between since it was discovered to + // be missing, then the corresponding file watcher will have been closed and no new one + // will be created until we encounter a change that prevents complete structure reuse. + // During this interval, creation of the file will go unnoticed. We expect this to be + // both rare and low-impact. + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + for (var _d = 0, _e = oldProgram.getMissingFilePaths(); _d < _e.length; _d++) { + var p = _e[_d]; + filesByName.set(p, undefined); + } // update fileName -> file mapping for (var i = 0; i < newSourceFiles.length; i++) { filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _d = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _d < modifiedSourceFiles_2.length; _d++) { - var modifiedFile = modifiedSourceFiles_2[_d]; + for (var _f = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _f < modifiedSourceFiles_2.length; _f++) { + var modifiedFile = modifiedSourceFiles_2[_f]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); @@ -68179,7 +69923,7 @@ var ts; return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); } function isEmitBlocked(emitFileName) { - return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; @@ -68220,7 +69964,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return getSourceFileByPath(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { return filesByName.get(path); @@ -68229,14 +69973,12 @@ var ts; if (sourceFile) { return getDiagnostics(sourceFile, cancellationToken); } - var allDiagnostics = []; - ts.forEach(program.getSourceFiles(), function (sourceFile) { + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); } - ts.addRange(allDiagnostics, getDiagnostics(sourceFile, cancellationToken)); - }); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return getDiagnostics(sourceFile, cancellationToken); + })); } function getSyntacticDiagnostics(sourceFile, cancellationToken) { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); @@ -68260,6 +70002,9 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + if (ts.isCheckJsEnabledForFile(sourceFile, options)) { + sourceFile.additionalSyntacticDiagnostics = ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.jsDocDiagnostics); + } } return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -68295,14 +70040,14 @@ var ts; // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a // '/// ' directive. if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { - return emptyArray; + return ts.emptyArray; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var bindDiagnostics = sourceFile.bindDiagnostics; // For JavaScript files, we don't want to report semantic errors unless explicitly requested. - var includeCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); - var checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : []; + var includeBindAndCheckDiagnostics = !ts.isSourceFileJavaScript(sourceFile) || ts.isCheckJsEnabledForFile(sourceFile, options); + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); @@ -68360,7 +70105,6 @@ var ts; case 186 /* FunctionExpression */: case 228 /* FunctionDeclaration */: case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: case 226 /* VariableDeclaration */: // type annotation if (parent.type === node) { @@ -68397,10 +70141,14 @@ var ts; case 232 /* EnumDeclaration */: diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case 184 /* TypeAssertionExpression */: - var typeAssertionExpression = node; - diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + case 203 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; + case 202 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 184 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } var prevParent = parent; parent = node; @@ -68421,7 +70169,6 @@ var ts; case 186 /* FunctionExpression */: case 228 /* FunctionDeclaration */: case 187 /* ArrowFunction */: - case 228 /* FunctionDeclaration */: // Check type parameters if (nodes === parent.typeParameters) { diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); @@ -68521,10 +70268,10 @@ var ts; if (cachedResult) { return cachedResult; } - var result = getDiagnostics(sourceFile, cancellationToken) || emptyArray; + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; if (sourceFile) { if (!cache.perFile) { - cache.perFile = ts.createFileMap(); + cache.perFile = ts.createMap(); } cache.perFile.set(sourceFile.path, result); } @@ -68537,15 +70284,10 @@ var ts; return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); - ts.addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); } function getGlobalDiagnostics() { - var allDiagnostics = []; - ts.addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); - return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); } function processRootFile(fileName, isDefaultLib) { processSourceFile(ts.normalizePath(fileName), isDefaultLib); @@ -68565,6 +70307,7 @@ var ts; } var isJavaScriptFile = ts.isSourceFileJavaScript(file); var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import var imports; var moduleAugmentations; var ambientModules; @@ -68583,13 +70326,13 @@ var ts; for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var node = _a[_i]; collectModuleReferences(node, /*inAmbientModule*/ false); - if (isJavaScriptFile) { - collectRequireCalls(node); + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(node); } } - file.imports = imports || emptyArray; - file.moduleAugmentations = moduleAugmentations || emptyArray; - file.ambientModuleNames = ambientModules || emptyArray; + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; return; function collectModuleReferences(node, inAmbientModule) { switch (node.kind) { @@ -68597,7 +70340,7 @@ var ts; case 237 /* ImportEqualsDeclaration */: case 244 /* ExportDeclaration */: var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || moduleNameExpr.kind !== 9 /* StringLiteral */) { + if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { break; } if (!moduleNameExpr.text) { @@ -68612,19 +70355,20 @@ var ts; break; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { - var moduleName = node.name; + var moduleName = node.name; // TODO: GH#17347 + var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name // immediately nested in top level ambient module declaration . - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(moduleName.text))) { + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module - (ambientModules || (ambientModules = [])).push(moduleName.text); + (ambientModules || (ambientModules = [])).push(nameText); } // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. @@ -68642,18 +70386,21 @@ var ts; } } } - function collectRequireCalls(node) { + function collectDynamicImportOrRequireCalls(node) { if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { (imports || (imports = [])).push(node.arguments[0]); } + else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { + (imports || (imports = [])).push(node.arguments[0]); + } else { - ts.forEachChild(node, collectRequireCalls); + ts.forEachChild(node, collectDynamicImportOrRequireCalls); } } } /** 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)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -68683,13 +70430,13 @@ var ts; } var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); if (fail && !sourceFileWithAddedExtension) - fail(ts.Diagnostics.File_0_not_found, fileName + ".ts"); + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); return sourceFileWithAddedExtension; } } /** 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) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd); }, function (diagnostic) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; @@ -68708,7 +70455,7 @@ var ts; } // Get source file from normalized fileName function findSourceFile(fileName, path, isDefaultLib, refFile, refPos, refEnd) { - if (filesByName.contains(path)) { + if (filesByName.has(path)) { var file_1 = filesByName.get(path); // try to check if we've already seen this file but with a different casing in path // NOTE: this only makes sense for case-insensitive file systems @@ -68748,13 +70495,14 @@ var ts; sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); file.path = path; if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(path); + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); if (existingFile) { reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); } else { - filesByNameIgnoreCase.set(path, file); + filesByNameIgnoreCase.set(pathLowerCase, file); } } skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; @@ -68880,7 +70628,7 @@ var ts; modulesWithElidedImports.set(file.path, true); } else if (shouldAddFile) { - var path = ts.toPath(resolvedFileName, currentDirectory, getCanonicalFileName); + var path = toPath(resolvedFileName); var pos = ts.skipTrivia(file.text, file.imports[i].pos); findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, file, pos, file.imports[i].end); } @@ -68924,28 +70672,28 @@ var ts; function verifyCompilerOptions() { if (options.isolatedModules) { if (options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); } if (options.noEmitOnError) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); } if (options.out) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); } if (options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); } } if (options.inlineSourceMap) { if (options.sourceMap) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); } if (options.mapRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); } } if (options.paths && options.baseUrl === undefined) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option)); + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); } if (options.paths) { for (var key in options.paths) { @@ -68953,65 +70701,66 @@ var ts; continue; } if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); } if (ts.isArray(options.paths[key])) { - if (options.paths[key].length === 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key)); + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); } - for (var _i = 0, _a = options.paths[key]; _i < _a.length; _i++) { - var subst = _a[_i]; + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst)); + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); } } } else { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key)); + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); } } } if (!options.sourceMap && !options.inlineSourceMap) { if (options.inlineSources) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); } if (options.sourceRoot) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); } } if (options.out && options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); } if (options.mapRoot && !options.sourceMap) { // Error to specify --mapRoot without --sourcemap - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); } if (options.declarationDir) { if (!options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); } if (options.out || options.outFile) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); } } if (options.lib && options.noLib) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); } if (options.noImplicitUseStrict && (options.alwaysStrict === undefined ? options.strict : options.alwaysStrict)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; 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)); + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); } var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); if (firstNonExternalModuleSourceFile) { @@ -69027,7 +70776,7 @@ var ts; // Cannot specify module gen that isn't amd or system with --out if (outFile) { if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile")); + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); } else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); @@ -69043,34 +70792,34 @@ var ts; var dir = getCommonSourceDirectory(); // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); } } if (!options.noEmit && options.allowJs && options.declaration) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); } if (options.checkJs && !options.allowJs) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } if (options.jsxFactory) { if (options.reactNamespace) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory")); + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); } if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory)); + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); } } else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace)); + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); } // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit && !options.suppressOutputPathCheck) { var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createFileMap(!host.useCaseSensitiveFileNames() ? function (key) { return key.toLocaleLowerCase(); } : undefined); + var emitFilesSeen_1 = ts.createMap(); ts.forEachEmittedFile(emitHost, function (emitFileNames) { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); @@ -69079,9 +70828,9 @@ var ts; // Verify that all the emit files are unique and don't overwrite input files function verifyEmitFilePath(emitFileName, emitFilesSeen) { if (emitFileName) { - var emitFilePath = ts.toPath(emitFileName, currentDirectory, getCanonicalFileName); + var emitFilePath = toPath(emitFileName); // Report error if the output overwrites input file - if (filesByName.contains(emitFilePath)) { + if (filesByName.has(emitFilePath)) { var chain_1; if (!options.configFilePath) { // The program is from either an inferred project or an external project @@ -69090,19 +70839,98 @@ var ts; chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; // Report error if multiple files write into same file - if (emitFilesSeen.contains(emitFilePath)) { + if (emitFilesSeen.has(emitFileKey)) { // Already seen the same emit file - report error blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); } else { - emitFilesSeen.set(emitFilePath, true); + emitFilesSeen.set(emitFileKey, true); } } } } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + if (ts.isArrayLiteralExpression(keyProps.initializer) && + keyProps.initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionPathsSyntax() { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); + } + return ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile && options.configFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); + } + return !!props.length; + } function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName), true); + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } } @@ -69116,15 +70944,15 @@ var ts; function getResolutionDiagnostic(options, _a) { var extension = _a.extension; switch (extension) { - case ts.Extension.Ts: - case ts.Extension.Dts: + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: // These are always allowed. return undefined; - case ts.Extension.Tsx: + case ".tsx" /* Tsx */: return needJsx(); - case ts.Extension.Jsx: + case ".jsx" /* Jsx */: return needJsx() || needAllowJs(); - case ts.Extension.Js: + case ".js" /* Js */: return needAllowJs(); } function needJsx() { @@ -69135,12 +70963,16 @@ var ts; } } ts.getResolutionDiagnostic = getResolutionDiagnostic; + function checkAllDefined(names) { + ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); + return names; + } })(ts || (ts = {})); /// /// /// /// -/// +/// var ts; (function (ts) { /* @internal */ @@ -69237,11 +71069,12 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES2015, "es2015": ts.ModuleKind.ES2015, + "esnext": ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, }, { name: "lib", @@ -69748,6 +71581,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, { // A list of plugins to load in the language service name: "plugins", @@ -69811,7 +71650,6 @@ var ts; return typeAcquisition; } ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; - /* @internal */ function getOptionNameMap() { if (optionNameMapCache) { return optionNameMapCache; @@ -69827,13 +71665,15 @@ var ts; optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; return optionNameMapCache; } - ts.getOptionNameMap = getOptionNameMap; /* @internal */ function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } /* @internal */ function parseCustomTypeOption(opt, value, errors) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); @@ -69864,7 +71704,6 @@ var ts; var options = {}; var fileNames = []; var errors = []; - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; parseStrings(commandLine); return { options: options, @@ -69880,13 +71719,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45 /* minus */) { - s = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); - // Try to translate short option names to their full equivalents. - var short = shortOptionNames.get(s); - if (short !== undefined) { - s = short; - } - var opt = optionNameMap.get(s); + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -69974,19 +71807,26 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } /** * Read tsconfig.json file * @param fileName The path to the config file */ function readConfigFile(fileName, readFile) { - var text = ""; - try { - text = readFile(fileName); - } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; - } - return parseConfigFileTextToJson(fileName, text); + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; } ts.readConfigFile = readConfigFile; /** @@ -69994,17 +71834,239 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } - try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; - } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; - } + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]); + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value + */ + function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.jsonObject) { + return {}; + } + return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, + /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 261 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined" && typeof value !== "undefined") { + result[keyText] = value; + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || knownOptions === knownRootOptions)) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (knownOptions === knownRootOptions) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 86 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95 /* NullKeyword */: + reportInvalidOptionValue(!!option); + return null; // tslint:disable-line:no-null-keyword + case 9 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + var text = valueExpression.text; + if (option && typeof option.type !== "string") { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text)) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 178 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 177 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return node.kind === 9 /* StringLiteral */ && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34 /* doubleQuote */; + } + } + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + typeof option.type === "string" ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = typeof option.type === "string" ? option.type : "string"; + return typeof value === expectedType; + } + } /** * Generate tsconfig configuration when running command line "--init" * @param options commandlineOptions to be generated into tsconfig.json @@ -70013,13 +72075,7 @@ var ts; /* @internal */ function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - // only set the files property if we have at least one file - configurations.files = fileNames; - } + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition) { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { @@ -70042,40 +72098,38 @@ var ts; }); } function serializeCompilerOptions(options) { - var result = {}; + var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name in options) { + var _loop_5 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - continue; + return "continue"; } var value = options[name]; var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { // There is no map associated with this compiler option then use the value as-is // This is the case if the value is expect to be string, number, boolean or list of string - result[name] = value; + result.set(name, value); } else { if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name] = convertedValue; + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { // There is a typeMap associated with this command-line option so use it to map value back to its name - result[name] = getNameOfCompilerOptionValue(value, customTypeMap); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } + }; + for (var name in options) { + _loop_5(name); } return result; } @@ -70092,7 +72146,7 @@ var ts; case "object": return {}; default: - return ts.arrayFrom(option.type.keys())[0]; + return option.type.keys().next().value; } } function makePadding(paddingLength) { @@ -70100,31 +72154,31 @@ var ts; } function writeConfigurations() { // Filter applicable options to place in the file - var categorizedOptions = ts.reduceLeft(ts.filter(ts.optionDeclarations, function (o) { return o.category !== ts.Diagnostics.Command_line_Options && o.category !== ts.Diagnostics.Advanced_Options; }), function (memo, value) { - if (value.category) { - var name = ts.getLocaleSpecificMessage(value.category); - (memo[name] || (memo[name] = [])).push(value); + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); } - return memo; - }, {}); - // Serialize all options and thier descriptions + } + // Serialize all options and their descriptions var marginLength = 0; var seenKnownKeys = 0; var nameColumn = []; var descriptionColumn = []; - var knownKeysCount = ts.getOwnKeys(configurations.compilerOptions).length; - for (var category in categorizedOptions) { + categorizedOptions.forEach(function (options, category) { if (nameColumn.length !== 0) { nameColumn.push(""); descriptionColumn.push(""); } nameColumn.push("/* " + category + " */"); descriptionColumn.push(""); - for (var _i = 0, _a = categorizedOptions[category]; _i < _a.length; _i++) { - var option = _a[_i]; + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; var optionName = void 0; - if (ts.hasProperty(configurations.compilerOptions, option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(configurations.compilerOptions[option.name]) + ((seenKnownKeys += 1) === knownKeysCount ? "" : ","); + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); } else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; @@ -70133,7 +72187,7 @@ var ts; descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); marginLength = Math.max(optionName.length, marginLength); } - } + }); // Write the output var tab = makePadding(2); var result = []; @@ -70143,13 +72197,13 @@ var ts; for (var i = 0; i < nameColumn.length; i++) { var optionName = nameColumn[i]; var description = descriptionColumn[i]; - result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description); + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); } - if (configurations.files && configurations.files.length) { + if (fileNames.length) { result.push(tab + "},"); result.push(tab + "\"files\": ["); - for (var i = 0; i < configurations.files.length; i++) { - result.push("" + tab + tab + JSON.stringify(configurations.files[i]) + (i === configurations.files.length - 1 ? "" : ",")); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); } result.push(tab + "]"); } @@ -70161,194 +72215,285 @@ var ts; } } ts.generateTSConfig = generateTSConfig; - /** - * Remove the comments from a json like text. - * Comments can be single line comments (starting with # or //) or multiline comments using / * * / - * - * This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate. - */ - function removeComments(jsonText) { - var output = ""; - var scanner = ts.createScanner(1 /* ES5 */, /* skipTrivia */ false, 0 /* Standard */, jsonText); - var token; - while ((token = scanner.scan()) !== 1 /* EndOfFileToken */) { - switch (token) { - case 2 /* SingleLineCommentTrivia */: - case 3 /* MultiLineCommentTrivia */: - // replace comments with whitespace to preserve original character positions - output += scanner.getTokenText().replace(/\S/g, " "); - break; - default: - output += scanner.getTokenText(); - break; - } - } - return output; - } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse * @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) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @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 + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @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 parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - 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); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.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); + setConfigFileInOptions(options, sourceFile); var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typeAcquisition: typeAcquisition, - raw: json, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + compileOnSave: !!raw.compileOnSave }; function getFileNames() { var fileNames; - if (ts.hasProperty(json, "files")) { - if (ts.isArray(json["files"])) { - fileNames = json["files"]; + if (ts.hasProperty(raw, "files")) { + if (ts.isArray(raw["files"])) { + fileNames = raw["files"]; if (fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); } } var includeSpecs; - if (ts.hasProperty(json, "include")) { - if (ts.isArray(json["include"])) { - includeSpecs = json["include"]; + if (ts.hasProperty(raw, "include")) { + if (ts.isArray(raw["include"])) { + includeSpecs = raw["include"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(json, "exclude")) { - if (ts.isArray(json["exclude"])) { - excludeSpecs = json["exclude"]; + if (ts.hasProperty(raw, "exclude")) { + if (ts.isArray(raw["exclude"])) { + excludeSpecs = raw["exclude"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { // If no includes were specified, exclude common package folders and the outDir - excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; + var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - excludeSpecs.push(outDir); + specs.push(outDir); } + excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); - if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } return result; } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } + } + function isSuccessfulParsedTsconfig(value) { + return !!value.options; } - 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) { + function parseConfig(json, sourceFile, 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 }; + return { raw: json || convertToObject(sourceFile, errors) }; } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { 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; + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; 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); + if (typeof json.extends !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } - return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - 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; + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } } - extended = ts.normalizeSlashes(extended); + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(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)); + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); return undefined; } - var extendedConfigPath = ts.toPath(extended, basePath, getCanonicalFileName); + 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, extended)); + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return undefined; } } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); 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 }; + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; + return undefined; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); if (typeof result === "boolean" && result) { @@ -70356,7 +72501,6 @@ var ts; } return false; } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -70369,15 +72513,23 @@ var ts; return { options: options, errors: errors }; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultCompilerOptions(configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultTypeAcquisition(configFileName) { var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return options; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; @@ -70386,7 +72538,7 @@ var ts; if (!jsonOptions) { return; } - var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); + var optionNameMap = commandLineOptionsToMap(optionDeclarations); for (var id in jsonOptions) { var opt = optionNameMap.get(id); if (opt) { @@ -70398,28 +72550,41 @@ var ts; } } function convertJsonOption(opt, value, basePath, errors) { - var optType = opt.type; - var expectedType = typeof optType === "string" ? optType : "string"; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); - } - else if (typeof value === expectedType) { - if (typeof optType !== "string") { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (typeof optType !== "string") { return convertJsonOptionOfCustomType(opt, value, errors); } - else { - if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; - } - } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType)); + else if (typeof option.type !== "string") { + return option.type.get(value); } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); @@ -70515,7 +72680,7 @@ var ts; * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the @@ -70530,10 +72695,10 @@ var ts; // via wildcard, and to handle extension priority. var wildcardFileMap = ts.createMap(); if (include) { - include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false); + include = validateSpecs(include, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); } if (exclude) { - exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true); + exclude = validateSpecs(exclude, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); } // Wildcard directories (provided as part of a wildcard path) are stored in a // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), @@ -70553,7 +72718,7 @@ var ts; } } if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, /*depth*/ undefined); _a < _b.length; _a++) { var file = _b[_a]; // If we have already included a literal or wildcard path with a // higher priority extension, we should skip this file. @@ -70582,24 +72747,40 @@ var ts; wildcardDirectories: wildcardDirectories }; } - function validateSpecs(specs, errors, allowTrailingRecursion) { + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { var validSpecs = []; for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { var spec = specs_1[_i]; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else { validSpecs.push(spec); } } return validSpecs; + function createDiagnostic(message, spec) { + if (jsonSourceFile && jsonSourceFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isArrayLiteralExpression(property.initializer)) { + for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (ts.isStringLiteral(element) && element.text === spec) { + return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); + } + } + } + } + } + return ts.createCompilerDiagnostic(message, spec); + } } /** * Gets directories in a set of include patterns that should be watched for changes. @@ -70641,7 +72822,7 @@ var ts; } } // Remove any subpaths under an existing recursively watched directory. - for (var key in wildcardDirectories) + for (var key in wildcardDirectories) { if (ts.hasProperty(wildcardDirectories, key)) { for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { var recursiveKey = recursiveKeys_1[_a]; @@ -70650,6 +72831,7 @@ var ts; } } } + } } return wildcardDirectories; } @@ -70719,6 +72901,45 @@ var ts; function caseInsensitiveKeyMapper(key) { return key.toLowerCase(); } + /** + * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object":// "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string":// Could be any arbitrary string -- use empty string instead. + return ""; + case "number":// Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -70756,10 +72977,10 @@ var ts; ts.TextChange = TextChange; var HighlightSpanKind; (function (HighlightSpanKind) { - HighlightSpanKind.none = "none"; - HighlightSpanKind.definition = "definition"; - HighlightSpanKind.reference = "reference"; - HighlightSpanKind.writtenReference = "writtenReference"; + HighlightSpanKind["none"] = "none"; + HighlightSpanKind["definition"] = "definition"; + HighlightSpanKind["reference"] = "reference"; + HighlightSpanKind["writtenReference"] = "writtenReference"; })(HighlightSpanKind = ts.HighlightSpanKind || (ts.HighlightSpanKind = {})); var IndentStyle; (function (IndentStyle) { @@ -70820,115 +73041,111 @@ var ts; TokenClass[TokenClass["StringLiteral"] = 7] = "StringLiteral"; TokenClass[TokenClass["RegExpLiteral"] = 8] = "RegExpLiteral"; })(TokenClass = ts.TokenClass || (ts.TokenClass = {})); - // TODO: move these to enums var ScriptElementKind; (function (ScriptElementKind) { - ScriptElementKind.unknown = ""; - ScriptElementKind.warning = "warning"; + ScriptElementKind["unknown"] = ""; + ScriptElementKind["warning"] = "warning"; /** predefined type (void) or keyword (class) */ - ScriptElementKind.keyword = "keyword"; + ScriptElementKind["keyword"] = "keyword"; /** top level script node */ - ScriptElementKind.scriptElement = "script"; + ScriptElementKind["scriptElement"] = "script"; /** module foo {} */ - ScriptElementKind.moduleElement = "module"; + ScriptElementKind["moduleElement"] = "module"; /** class X {} */ - ScriptElementKind.classElement = "class"; + ScriptElementKind["classElement"] = "class"; /** var x = class X {} */ - ScriptElementKind.localClassElement = "local class"; + ScriptElementKind["localClassElement"] = "local class"; /** interface Y {} */ - ScriptElementKind.interfaceElement = "interface"; + ScriptElementKind["interfaceElement"] = "interface"; /** type T = ... */ - ScriptElementKind.typeElement = "type"; + ScriptElementKind["typeElement"] = "type"; /** enum E */ - ScriptElementKind.enumElement = "enum"; - ScriptElementKind.enumMemberElement = "enum member"; + ScriptElementKind["enumElement"] = "enum"; + ScriptElementKind["enumMemberElement"] = "enum member"; /** * Inside module and script only * const v = .. */ - ScriptElementKind.variableElement = "var"; + ScriptElementKind["variableElement"] = "var"; /** Inside function */ - ScriptElementKind.localVariableElement = "local var"; + ScriptElementKind["localVariableElement"] = "local var"; /** * Inside module and script only * function f() { } */ - ScriptElementKind.functionElement = "function"; + ScriptElementKind["functionElement"] = "function"; /** Inside function */ - ScriptElementKind.localFunctionElement = "local function"; + ScriptElementKind["localFunctionElement"] = "local function"; /** class X { [public|private]* foo() {} } */ - ScriptElementKind.memberFunctionElement = "method"; + ScriptElementKind["memberFunctionElement"] = "method"; /** class X { [public|private]* [get|set] foo:number; } */ - ScriptElementKind.memberGetAccessorElement = "getter"; - ScriptElementKind.memberSetAccessorElement = "setter"; + ScriptElementKind["memberGetAccessorElement"] = "getter"; + ScriptElementKind["memberSetAccessorElement"] = "setter"; /** * class X { [public|private]* foo:number; } * interface Y { foo:number; } */ - ScriptElementKind.memberVariableElement = "property"; + ScriptElementKind["memberVariableElement"] = "property"; /** class X { constructor() { } } */ - ScriptElementKind.constructorImplementationElement = "constructor"; + ScriptElementKind["constructorImplementationElement"] = "constructor"; /** interface Y { ():number; } */ - ScriptElementKind.callSignatureElement = "call"; + ScriptElementKind["callSignatureElement"] = "call"; /** interface Y { []:number; } */ - ScriptElementKind.indexSignatureElement = "index"; + ScriptElementKind["indexSignatureElement"] = "index"; /** interface Y { new():Y; } */ - ScriptElementKind.constructSignatureElement = "construct"; + ScriptElementKind["constructSignatureElement"] = "construct"; /** function foo(*Y*: string) */ - ScriptElementKind.parameterElement = "parameter"; - ScriptElementKind.typeParameterElement = "type parameter"; - ScriptElementKind.primitiveType = "primitive type"; - ScriptElementKind.label = "label"; - ScriptElementKind.alias = "alias"; - ScriptElementKind.constElement = "const"; - ScriptElementKind.letElement = "let"; - ScriptElementKind.directory = "directory"; - ScriptElementKind.externalModuleName = "external module name"; + ScriptElementKind["parameterElement"] = "parameter"; + ScriptElementKind["typeParameterElement"] = "type parameter"; + ScriptElementKind["primitiveType"] = "primitive type"; + ScriptElementKind["label"] = "label"; + ScriptElementKind["alias"] = "alias"; + ScriptElementKind["constElement"] = "const"; + ScriptElementKind["letElement"] = "let"; + ScriptElementKind["directory"] = "directory"; + ScriptElementKind["externalModuleName"] = "external module name"; /** * */ - ScriptElementKind.jsxAttribute = "JSX attribute"; + ScriptElementKind["jsxAttribute"] = "JSX attribute"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { - ScriptElementKindModifier.none = ""; - ScriptElementKindModifier.publicMemberModifier = "public"; - ScriptElementKindModifier.privateMemberModifier = "private"; - ScriptElementKindModifier.protectedMemberModifier = "protected"; - ScriptElementKindModifier.exportedModifier = "export"; - ScriptElementKindModifier.ambientModifier = "declare"; - ScriptElementKindModifier.staticModifier = "static"; - ScriptElementKindModifier.abstractModifier = "abstract"; + ScriptElementKindModifier["none"] = ""; + ScriptElementKindModifier["publicMemberModifier"] = "public"; + ScriptElementKindModifier["privateMemberModifier"] = "private"; + ScriptElementKindModifier["protectedMemberModifier"] = "protected"; + ScriptElementKindModifier["exportedModifier"] = "export"; + ScriptElementKindModifier["ambientModifier"] = "declare"; + ScriptElementKindModifier["staticModifier"] = "static"; + ScriptElementKindModifier["abstractModifier"] = "abstract"; })(ScriptElementKindModifier = ts.ScriptElementKindModifier || (ts.ScriptElementKindModifier = {})); - var ClassificationTypeNames = (function () { - function ClassificationTypeNames() { - } - return ClassificationTypeNames; - }()); - ClassificationTypeNames.comment = "comment"; - ClassificationTypeNames.identifier = "identifier"; - ClassificationTypeNames.keyword = "keyword"; - ClassificationTypeNames.numericLiteral = "number"; - ClassificationTypeNames.operator = "operator"; - ClassificationTypeNames.stringLiteral = "string"; - ClassificationTypeNames.whiteSpace = "whitespace"; - ClassificationTypeNames.text = "text"; - ClassificationTypeNames.punctuation = "punctuation"; - ClassificationTypeNames.className = "class name"; - ClassificationTypeNames.enumName = "enum name"; - ClassificationTypeNames.interfaceName = "interface name"; - ClassificationTypeNames.moduleName = "module name"; - ClassificationTypeNames.typeParameterName = "type parameter name"; - ClassificationTypeNames.typeAliasName = "type alias name"; - ClassificationTypeNames.parameterName = "parameter name"; - ClassificationTypeNames.docCommentTagName = "doc comment tag name"; - ClassificationTypeNames.jsxOpenTagName = "jsx open tag name"; - ClassificationTypeNames.jsxCloseTagName = "jsx close tag name"; - ClassificationTypeNames.jsxSelfClosingTagName = "jsx self closing tag name"; - ClassificationTypeNames.jsxAttribute = "jsx attribute"; - ClassificationTypeNames.jsxText = "jsx text"; - ClassificationTypeNames.jsxAttributeStringLiteralValue = "jsx attribute string literal value"; - ts.ClassificationTypeNames = ClassificationTypeNames; + var ClassificationTypeNames; + (function (ClassificationTypeNames) { + ClassificationTypeNames["comment"] = "comment"; + ClassificationTypeNames["identifier"] = "identifier"; + ClassificationTypeNames["keyword"] = "keyword"; + ClassificationTypeNames["numericLiteral"] = "number"; + ClassificationTypeNames["operator"] = "operator"; + ClassificationTypeNames["stringLiteral"] = "string"; + ClassificationTypeNames["whiteSpace"] = "whitespace"; + ClassificationTypeNames["text"] = "text"; + ClassificationTypeNames["punctuation"] = "punctuation"; + ClassificationTypeNames["className"] = "class name"; + ClassificationTypeNames["enumName"] = "enum name"; + ClassificationTypeNames["interfaceName"] = "interface name"; + ClassificationTypeNames["moduleName"] = "module name"; + ClassificationTypeNames["typeParameterName"] = "type parameter name"; + ClassificationTypeNames["typeAliasName"] = "type alias name"; + ClassificationTypeNames["parameterName"] = "parameter name"; + ClassificationTypeNames["docCommentTagName"] = "doc comment tag name"; + ClassificationTypeNames["jsxOpenTagName"] = "jsx open tag name"; + ClassificationTypeNames["jsxCloseTagName"] = "jsx close tag name"; + ClassificationTypeNames["jsxSelfClosingTagName"] = "jsx self closing tag name"; + ClassificationTypeNames["jsxAttribute"] = "jsx attribute"; + ClassificationTypeNames["jsxText"] = "jsx text"; + ClassificationTypeNames["jsxAttributeStringLiteralValue"] = "jsx attribute string literal value"; + })(ClassificationTypeNames = ts.ClassificationTypeNames || (ts.ClassificationTypeNames = {})); var ClassificationType; (function (ClassificationType) { ClassificationType[ClassificationType["comment"] = 1] = "comment"; @@ -70962,7 +73179,6 @@ var ts; var ts; (function (ts) { ts.scanner = ts.createScanner(5 /* Latest */, /*skipTrivia*/ true); - ts.emptyArray = []; var SemanticMeaning; (function (SemanticMeaning) { SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; @@ -70996,11 +73212,12 @@ var ts; case 231 /* TypeAliasDeclaration */: case 163 /* TypeLiteral */: return 2 /* Type */; + case 283 /* JSDocTypedefTag */: + // If it has no name node, it shares the name with the value declaration below it. + return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; case 264 /* EnumMember */: case 229 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 232 /* EnumDeclaration */: - return 7 /* All */; case 233 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; @@ -71011,6 +73228,7 @@ var ts; else { return 4 /* Namespace */; } + case 232 /* EnumDeclaration */: case 241 /* NamedImports */: case 242 /* ImportSpecifier */: case 237 /* ImportEqualsDeclaration */: @@ -71022,7 +73240,7 @@ var ts; case 265 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { @@ -71030,9 +73248,9 @@ var ts; return 1 /* Value */; } else if (node.parent.kind === 243 /* ExportAssignment */) { - return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; + return 7 /* All */; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -71044,6 +73262,10 @@ var ts; else if (isNamespaceReference(node)) { return 4 /* Namespace */; } + else if (ts.isTypeParameterDeclaration(node.parent)) { + ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName + return 2 /* Type */; + } else { return 1 /* Value */; } @@ -71061,12 +73283,13 @@ var ts; } return 4 /* Namespace */; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -71101,10 +73324,19 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { node = node.parent; } - return node.parent.kind === 159 /* TypeReference */ || - (node.parent.kind === 201 /* ExpressionWithTypeArguments */ && !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent)) || - (node.kind === 99 /* ThisKeyword */ && !ts.isPartOfExpression(node)) || - node.kind === 169 /* ThisType */; + switch (node.kind) { + case 99 /* ThisKeyword */: + return !ts.isPartOfExpression(node); + case 169 /* ThisType */: + return true; + } + switch (node.parent.kind) { + case 159 /* TypeReference */: + return true; + case 201 /* ExpressionWithTypeArguments */: + return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); + } + return false; } function isCallExpressionTarget(node) { return isCallOrNewExpressionTarget(node, 181 /* CallExpression */); @@ -71124,7 +73356,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 222 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 222 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -71192,6 +73424,12 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { + if (node.kind === 283 /* JSDocTypedefTag */) { + // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. + // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. + // Then we get parent again in the loop. + node = node.parent.parent; + } while (true) { node = node.parent; if (!node) { @@ -71217,15 +73455,15 @@ var ts; function getNodeKind(node) { switch (node.kind) { case 265 /* SourceFile */: - return ts.isExternalModule(node) ? ts.ScriptElementKind.moduleElement : ts.ScriptElementKind.scriptElement; + return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; case 233 /* ModuleDeclaration */: - return ts.ScriptElementKind.moduleElement; + return "module" /* moduleElement */; case 229 /* ClassDeclaration */: case 199 /* ClassExpression */: - return ts.ScriptElementKind.classElement; - case 230 /* InterfaceDeclaration */: return ts.ScriptElementKind.interfaceElement; - case 231 /* TypeAliasDeclaration */: return ts.ScriptElementKind.typeElement; - case 232 /* EnumDeclaration */: return ts.ScriptElementKind.enumElement; + return "class" /* classElement */; + case 230 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 231 /* TypeAliasDeclaration */: return "type" /* typeElement */; + case 232 /* EnumDeclaration */: return "enum" /* enumElement */; case 226 /* VariableDeclaration */: return getKindOfVariableDeclaration(node); case 176 /* BindingElement */: @@ -71233,39 +73471,39 @@ var ts; case 187 /* ArrowFunction */: case 228 /* FunctionDeclaration */: case 186 /* FunctionExpression */: - return ts.ScriptElementKind.functionElement; - case 153 /* GetAccessor */: return ts.ScriptElementKind.memberGetAccessorElement; - case 154 /* SetAccessor */: return ts.ScriptElementKind.memberSetAccessorElement; + return "function" /* functionElement */; + case 153 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 154 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; case 151 /* MethodDeclaration */: case 150 /* MethodSignature */: - return ts.ScriptElementKind.memberFunctionElement; + return "method" /* memberFunctionElement */; case 149 /* PropertyDeclaration */: case 148 /* PropertySignature */: - return ts.ScriptElementKind.memberVariableElement; - case 157 /* IndexSignature */: return ts.ScriptElementKind.indexSignatureElement; - case 156 /* ConstructSignature */: return ts.ScriptElementKind.constructSignatureElement; - case 155 /* CallSignature */: return ts.ScriptElementKind.callSignatureElement; - case 152 /* Constructor */: return ts.ScriptElementKind.constructorImplementationElement; - case 145 /* TypeParameter */: return ts.ScriptElementKind.typeParameterElement; - case 264 /* EnumMember */: return ts.ScriptElementKind.enumMemberElement; - case 146 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? ts.ScriptElementKind.memberVariableElement : ts.ScriptElementKind.parameterElement; + return "property" /* memberVariableElement */; + case 157 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 156 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 155 /* CallSignature */: return "call" /* callSignatureElement */; + case 152 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 145 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 264 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 146 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; case 237 /* ImportEqualsDeclaration */: case 242 /* ImportSpecifier */: case 239 /* ImportClause */: case 246 /* ExportSpecifier */: case 240 /* NamespaceImport */: - return ts.ScriptElementKind.alias; - case 290 /* JSDocTypedefTag */: - return ts.ScriptElementKind.typeElement; + return "alias" /* alias */; + case 283 /* JSDocTypedefTag */: + return "type" /* typeElement */; default: - return ts.ScriptElementKind.unknown; + return "" /* unknown */; } function getKindOfVariableDeclaration(v) { return ts.isConst(v) - ? ts.ScriptElementKind.constElement + ? "const" /* constElement */ : ts.isLet(v) - ? ts.ScriptElementKind.letElement - : ts.ScriptElementKind.variableElement; + ? "let" /* letElement */ + : "var" /* variableElement */; } } ts.getNodeKind = getNodeKind; @@ -71482,7 +73720,7 @@ var ts; // for the position of the relevant node (or comma). var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { // find syntax list that covers the span of the node - if (c.kind === 294 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (ts.isSyntaxList(c) && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -71495,33 +73733,31 @@ var ts; * position >= start and (position < end or (position === end && token is keyword or identifier)) */ function getTouchingWord(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isWord(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); } ts.getTouchingWord = getTouchingWord; /* 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)) */ function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTouchingToken(sourceFile, position, function (n) { return isPropertyName(n.kind); }, includeJsDocComment); + return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; - /** Returns the token if position is in [start, end) or if position === end and includeItemAtEndPosition(token) === true */ - function getTouchingToken(sourceFile, position, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includeItemAtEndPosition, includeJsDocComment); + /** + * Returns the token if position is in [start, end). + * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true + */ + function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false, includeJsDocComment); } ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile, position, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includeItemAtEndPosition*/ undefined, includeJsDocComment); + function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); } ts.getTokenAtPosition = getTokenAtPosition; /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includeItemAtEndPosition, includeJsDocComment) { - if (includeJsDocComment === void 0) { includeJsDocComment = false; } + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { var current = sourceFile; outer: while (true) { if (ts.isToken(current)) { @@ -71531,21 +73767,22 @@ var ts; // find the child that contains 'position' for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; - if (ts.isJSDocNode(child) && !includeJsDocComment) { + if (!includeJsDocComment && ts.isJSDocNode(child)) { continue; } var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); if (start > position) { - continue; + // If this child begins after position, then all subsequent children will as well. + break; } var end = child.getEnd(); - if (position < end || (position === end && child.kind === 1 /* EndOfFileToken */)) { + if (position < end || (position === end && (child.kind === 1 /* EndOfFileToken */ || includeEndPosition))) { current = child; continue outer; } - else if (includeItemAtEndPosition && end === position) { + else if (includePrecedingTokenAtEndPosition && end === position) { var previousToken = findPrecedingToken(position, sourceFile, child); - if (previousToken && includeItemAtEndPosition(previousToken)) { + if (previousToken && includePrecedingTokenAtEndPosition(previousToken)) { return previousToken; } } @@ -71564,7 +73801,7 @@ var ts; function findTokenOnLeftOfPosition(file, position) { // 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. - var tokenAtPosition = getTokenAtPosition(file, position); + var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } @@ -71594,7 +73831,7 @@ var ts; } } ts.findNextToken = findNextToken; - function findPrecedingToken(position, sourceFile, startNode) { + function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { return find(startNode || sourceFile); function findRightmostToken(n) { if (ts.isToken(n)) { @@ -71620,7 +73857,7 @@ var ts; // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { - var start = child.getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { @@ -71634,7 +73871,7 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 265 /* SourceFile */); + ts.Debug.assert(startNode !== undefined || n.kind === 265 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. @@ -71656,7 +73893,7 @@ var ts; ts.findPrecedingToken = findPrecedingToken; function isInString(sourceFile, position) { var previousToken = findPrecedingToken(position, sourceFile); - if (previousToken && previousToken.kind === 9 /* StringLiteral */) { + if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); // To be "in" one of these literals, the position has to be: @@ -71677,7 +73914,7 @@ var ts; * returns true if the position is in between the open and close elements of an JSX expression. */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return false; } @@ -71706,7 +73943,7 @@ var ts; } ts.isInsideJsxElementOrAttribute = isInsideJsxElementOrAttribute; function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; @@ -71717,7 +73954,7 @@ var ts; * @param predicate Additional predicate to test on the comment range. */ function isInComment(sourceFile, position, tokenAtPosition, predicate) { - if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position); } + if (tokenAtPosition === void 0) { tokenAtPosition = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } return position <= tokenAtPosition.getStart(sourceFile) && (isInCommentRange(ts.getLeadingCommentRanges(sourceFile.text, tokenAtPosition.pos)) || isInCommentRange(ts.getTrailingCommentRanges(sourceFile.text, tokenAtPosition.pos))); @@ -71751,7 +73988,7 @@ var ts; } } function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position); + var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // First, we have to see if this position actually landed in a comment. var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); return ts.forEach(commentRanges, jsDocPrefix); @@ -71761,42 +73998,6 @@ var ts; } } ts.hasDocComment = hasDocComment; - /** - * Get the corresponding JSDocTag node if the position is in a jsDoc comment - */ - function getJsDocTagAtPosition(sourceFile, position) { - var node = ts.getTokenAtPosition(sourceFile, position); - if (ts.isToken(node)) { - switch (node.kind) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - // if the current token is var, let or const, skip the VariableDeclarationList - node = node.parent === undefined ? undefined : node.parent.parent; - break; - default: - node = node.parent; - break; - } - } - if (node) { - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (jsDoc.tags) { - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.pos <= position && position <= tag.end) { - return tag; - } - } - } - } - } - } - return undefined; - } - ts.getJsDocTagAtPosition = getJsDocTagAtPosition; function nodeHasTokens(n) { // If we have a token or node that has a non-zero width, it must have tokens. // Note, that getWidth() does not take trivia into account. @@ -71806,20 +74007,20 @@ var ts; var flags = ts.getCombinedModifierFlags(node); var result = []; if (flags & 8 /* Private */) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); + result.push("private" /* privateMemberModifier */); if (flags & 16 /* Protected */) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + result.push("protected" /* protectedMemberModifier */); if (flags & 4 /* Public */) - result.push(ts.ScriptElementKindModifier.publicMemberModifier); + result.push("public" /* publicMemberModifier */); if (flags & 32 /* Static */) - result.push(ts.ScriptElementKindModifier.staticModifier); + result.push("static" /* staticModifier */); if (flags & 128 /* Abstract */) - result.push(ts.ScriptElementKindModifier.abstractModifier); + result.push("abstract" /* abstractModifier */); if (flags & 1 /* Export */) - result.push(ts.ScriptElementKindModifier.exportedModifier); + result.push("export" /* exportedModifier */); if (ts.isInAmbientContext(node)) - result.push(ts.ScriptElementKindModifier.ambientModifier); - return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; + result.push("declare" /* ambientModifier */); + return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { @@ -71871,6 +74072,12 @@ var ts; return false; } ts.isAccessibilityModifier = isAccessibilityModifier; + function cloneCompilerOptions(options) { + var result = ts.clone(options); + ts.setConfigFileInOptions(result, options && options.configFile); + return result; + } + ts.cloneCompilerOptions = cloneCompilerOptions; function compareDataObjects(dst, src) { if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { return false; @@ -72005,7 +74212,7 @@ var ts; clear: resetWriter, trackSymbol: ts.noop, reportInaccessibleThisError: ts.noop, - reportIllegalExtends: ts.noop + reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { if (lineStart) { @@ -72077,7 +74284,7 @@ var ts; else if (flags & 524288 /* TypeAlias */) { return ts.SymbolDisplayPartKind.aliasName; } - else if (flags & 8388608 /* Alias */) { + else if (flags & 2097152 /* Alias */) { return ts.SymbolDisplayPartKind.aliasName; } return ts.SymbolDisplayPartKind.text; @@ -72085,10 +74292,7 @@ var ts; } ts.symbolPart = symbolPart; function displayPart(text, kind) { - return { - text: text, - kind: ts.SymbolDisplayPartKind[kind] - }; + return { text: text, kind: ts.SymbolDisplayPartKind[kind] }; } ts.displayPart = displayPart; function spacePart() { @@ -72131,10 +74335,13 @@ var ts; } ts.lineBreakPart = lineBreakPart; function mapToDisplayParts(writeDisplayParts) { - writeDisplayParts(displayPartWriter); - var result = displayPartWriter.displayParts(); - displayPartWriter.clear(); - return result; + try { + writeDisplayParts(displayPartWriter); + return displayPartWriter.displayParts(); + } + finally { + displayPartWriter.clear(); + } } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { @@ -72159,7 +74366,7 @@ var ts; // If this is an export or import specifier it could have been renamed using the 'as' syntax. // If so we want to search for whatever is under the cursor. if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 144 /* ComputedPropertyName */) { - return location.text; + return ts.getTextOfIdentifierOrLiteral(location); } // Try to get the local symbol if we're dealing with an 'export default' // since that symbol has the "true" name. @@ -72200,41 +74407,9 @@ var ts; function getScriptKind(fileName, host) { // First check to see if the script kind was specified by the host. Chances are the host // may override the default script kind for the file extension. - var scriptKind; - if (host && host.getScriptKind) { - scriptKind = host.getScriptKind(fileName); - } - if (!scriptKind) { - scriptKind = ts.getScriptKindFromFileName(fileName); - } - return ts.ensureScriptKind(fileName, scriptKind); + return ts.ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } ts.getScriptKind = getScriptKind; - function sanitizeConfigFile(configFileName, content) { - var options = { - fileName: "config.js", - compilerOptions: { - target: 2 /* ES2015 */, - removeComments: true - }, - reportDiagnostics: true - }; - var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; - // Becasue the content was wrapped in "()", the start position of diagnostics needs to be subtract by 1 - // 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_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; - return { - configJsonObject: config || {}, - diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics - }; - } - ts.sanitizeConfigFile = sanitizeConfigFile; function getFirstNonSpaceCharacterPosition(text, position) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -72248,7 +74423,7 @@ var ts; } ts.getOpenBrace = getOpenBrace; function getOpenBraceOfClassLike(declaration, sourceFile) { - return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1); + return ts.getTokenAtPosition(sourceFile, declaration.members.pos - 1, /*includeJsDocComment*/ false); } ts.getOpenBraceOfClassLike = getOpenBraceOfClassLike; })(ts || (ts = {})); @@ -72320,7 +74495,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_7 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -72329,8 +74504,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_7, classification: convertClassification(type) }); + lastEnd = start + length_7; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -72759,7 +74934,7 @@ var ts; // Only bother calling into the typechecker if this is an identifier that // could possibly resolve to a type name. This makes classification run // in a third of the time it would normally take. - if (classifiableNames.get(identifier.text)) { + if (classifiableNames.has(identifier.escapedText)) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { var type = classifySymbol(symbol, ts.getMeaningFromLocation(node)); @@ -72776,29 +74951,29 @@ var ts; ts.getEncodedSemanticClassifications = getEncodedSemanticClassifications; function getClassificationTypeName(type) { switch (type) { - case 1 /* comment */: return ts.ClassificationTypeNames.comment; - case 2 /* identifier */: return ts.ClassificationTypeNames.identifier; - case 3 /* keyword */: return ts.ClassificationTypeNames.keyword; - case 4 /* numericLiteral */: return ts.ClassificationTypeNames.numericLiteral; - case 5 /* operator */: return ts.ClassificationTypeNames.operator; - case 6 /* stringLiteral */: return ts.ClassificationTypeNames.stringLiteral; - case 8 /* whiteSpace */: return ts.ClassificationTypeNames.whiteSpace; - case 9 /* text */: return ts.ClassificationTypeNames.text; - case 10 /* punctuation */: return ts.ClassificationTypeNames.punctuation; - case 11 /* className */: return ts.ClassificationTypeNames.className; - case 12 /* enumName */: return ts.ClassificationTypeNames.enumName; - case 13 /* interfaceName */: return ts.ClassificationTypeNames.interfaceName; - case 14 /* moduleName */: return ts.ClassificationTypeNames.moduleName; - case 15 /* typeParameterName */: return ts.ClassificationTypeNames.typeParameterName; - case 16 /* typeAliasName */: return ts.ClassificationTypeNames.typeAliasName; - case 17 /* parameterName */: return ts.ClassificationTypeNames.parameterName; - case 18 /* docCommentTagName */: return ts.ClassificationTypeNames.docCommentTagName; - case 19 /* jsxOpenTagName */: return ts.ClassificationTypeNames.jsxOpenTagName; - case 20 /* jsxCloseTagName */: return ts.ClassificationTypeNames.jsxCloseTagName; - case 21 /* jsxSelfClosingTagName */: return ts.ClassificationTypeNames.jsxSelfClosingTagName; - case 22 /* jsxAttribute */: return ts.ClassificationTypeNames.jsxAttribute; - case 23 /* jsxText */: return ts.ClassificationTypeNames.jsxText; - case 24 /* jsxAttributeStringLiteralValue */: return ts.ClassificationTypeNames.jsxAttributeStringLiteralValue; + case 1 /* comment */: return "comment" /* comment */; + case 2 /* identifier */: return "identifier" /* identifier */; + case 3 /* keyword */: return "keyword" /* keyword */; + case 4 /* numericLiteral */: return "number" /* numericLiteral */; + case 5 /* operator */: return "operator" /* operator */; + case 6 /* stringLiteral */: return "string" /* stringLiteral */; + case 8 /* whiteSpace */: return "whitespace" /* whiteSpace */; + case 9 /* text */: return "text" /* text */; + case 10 /* punctuation */: return "punctuation" /* punctuation */; + case 11 /* className */: return "class name" /* className */; + case 12 /* enumName */: return "enum name" /* enumName */; + case 13 /* interfaceName */: return "interface name" /* interfaceName */; + case 14 /* moduleName */: return "module name" /* moduleName */; + case 15 /* typeParameterName */: return "type parameter name" /* typeParameterName */; + case 16 /* typeAliasName */: return "type alias name" /* typeAliasName */; + case 17 /* parameterName */: return "parameter name" /* parameterName */; + case 18 /* docCommentTagName */: return "doc comment tag name" /* docCommentTagName */; + case 19 /* jsxOpenTagName */: return "jsx open tag name" /* jsxOpenTagName */; + case 20 /* jsxCloseTagName */: return "jsx close tag name" /* jsxCloseTagName */; + case 21 /* jsxSelfClosingTagName */: return "jsx self closing tag name" /* jsxSelfClosingTagName */; + case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; + case 23 /* jsxText */: return "jsx text" /* jsxText */; + case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; } } function convertClassifications(classifications) { @@ -72870,9 +75045,9 @@ var ts; pushClassification(start, width, 1 /* comment */); continue; } - // for the ======== add a comment for the first line, and then lex all - // subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 61 /* equals */); + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); classifyDisabledMergeCode(text, start, end); } } @@ -72904,20 +75079,20 @@ var ts; if (tag.pos !== pos) { pushCommentRange(pos, tag.pos - pos); } - pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); - pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); + pushClassification(tag.atToken.pos, tag.atToken.end - tag.atToken.pos, 10 /* punctuation */); // "@" + pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 286 /* JSDocParameterTag */: + case 279 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 289 /* JSDocTemplateTag */: + case 282 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); break; - case 288 /* JSDocTypeTag */: + case 281 /* JSDocTypeTag */: processElement(tag.typeExpression); break; - case 287 /* JSDocReturnTag */: + case 280 /* JSDocReturnTag */: processElement(tag.typeExpression); break; } @@ -72929,20 +75104,20 @@ var ts; } return; function processJSDocParameterTag(tag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, 17 /* parameterName */); - pos = tag.preParameterName.end; + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; } if (tag.typeExpression) { pushCommentRange(pos, tag.typeExpression.pos - pos); processElement(tag.typeExpression); pos = tag.typeExpression.end; } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, 17 /* parameterName */); - pos = tag.postParameterName.end; + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, 17 /* parameterName */); + pos = tag.name.end; } } } @@ -72953,8 +75128,8 @@ var ts; } } function classifyDisabledMergeCode(text, start, end) { - // Classify the line that the ======= marker is on as a comment. Then just lex - // all further tokens and add them to the result. + // Classify the line that the ||||||| or ======= marker is on as a comment. + // Then just lex all further tokens and add them to the result. var i; for (i = start; i < end; i++) { if (ts.isLineBreak(text.charCodeAt(i))) { @@ -72981,7 +75156,7 @@ var ts; * False will mean that node is not classified and traverse routine should recurse into node contents. */ function tryClassifyNode(node) { - if (ts.isJSDocTag(node)) { + if (ts.isJSDoc(node)) { return true; } if (ts.nodeIsMissing(node)) { @@ -73179,14 +75354,9 @@ var ts; // Make all paths absolute/normalized if they are not already rootDirs = ts.map(rootDirs, function (rootDirectory) { return ts.normalizePath(ts.isRootedDiskPath(rootDirectory) ? rootDirectory : ts.combinePaths(basePath, rootDirectory)); }); // Determine the path to the directory containing the script relative to the root directory it is contained within - var relativeDirectory; - for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { - var rootDirectory = rootDirs_1[_i]; - if (ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase)) { - relativeDirectory = scriptPath.substr(rootDirectory.length); - break; - } - } + var relativeDirectory = ts.forEach(rootDirs, function (rootDirectory) { + return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; + }); // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(ts.map(rootDirs, function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); })); } @@ -73245,7 +75415,7 @@ var ts; } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createCompletionEntryForModule(foundFile, ts.ScriptElementKind.scriptElement, span)); + result.push(createCompletionEntryForModule(foundFile, "script" /* scriptElement */, span)); }); } // If possible, get folder completion as well @@ -73254,7 +75424,7 @@ var ts; for (var _a = 0, directories_2 = directories; _a < directories_2.length; _a++) { var directory = directories_2[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - result.push(createCompletionEntryForModule(directoryName, ts.ScriptElementKind.directory, span)); + result.push(createCompletionEntryForModule(directoryName, "directory" /* directory */, span)); } } } @@ -73284,7 +75454,7 @@ var ts; var pattern = _a[_i]; for (var _b = 0, _c = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _b < _c.length; _b++) { var match = _c[_b]; - result.push(createCompletionEntryForModule(match, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); } } } @@ -73292,7 +75462,7 @@ var ts; else if (ts.startsWith(path, fragment)) { var entry = paths[path] && paths[path].length === 1 && paths[path][0]; if (entry) { - result.push(createCompletionEntryForModule(path, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); } } } @@ -73305,7 +75475,7 @@ var ts; getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); for (var _d = 0, _e = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _d < _e.length; _d++) { var moduleName = _e[_d]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } @@ -73339,8 +75509,8 @@ var ts; continue; } var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); + var length_8 = normalizedMatch.length - start - normalizedSuffix.length; + result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_8))); } return result; } @@ -73354,24 +75524,21 @@ var ts; var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; // Get modules that the type checker picked up var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); - var nonRelativeModules = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.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) { var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModules = ts.map(nonRelativeModules, function (moduleName) { - if (ts.startsWith(fragment, moduleNameWithSeperator_1)) { - return moduleName.substr(moduleNameWithSeperator_1.length); - } - return moduleName; + nonRelativeModuleNames = ts.map(nonRelativeModuleNames, function (nonRelativeModuleName) { + return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); }); } if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { var visibleModule = _a[_i]; if (!isNestedModule) { - nonRelativeModules.push(visibleModule.moduleName); + nonRelativeModuleNames.push(visibleModule.moduleName); } else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); @@ -73380,16 +75547,16 @@ var ts; var f = nestedFiles_1[_b]; f = ts.normalizePath(f); var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); - nonRelativeModules.push(nestedModule); + nonRelativeModuleNames.push(nestedModule); } } } } } - return ts.deduplicate(nonRelativeModules); + return ts.deduplicate(nonRelativeModuleNames); } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position); + var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); if (!token) { return undefined; } @@ -73441,7 +75608,7 @@ var ts; if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } } else if (host.getDirectories) { @@ -73475,7 +75642,7 @@ var ts; for (var _i = 0, directories_3 = directories; _i < directories_3.length; _i++) { var typeDirectory = directories_3[_i]; typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), ts.ScriptElementKind.externalModuleName, span)); + result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); } } } @@ -73547,7 +75714,7 @@ var ts; } } function createCompletionEntryForModule(name, kind, replacementSpan) { - return { name: name, kind: kind, kindModifiers: ts.ScriptElementKindModifier.none, sortText: name, replacementSpan: replacementSpan }; + return { name: name, kind: kind, kindModifiers: "" /* none */, sortText: name, replacementSpan: replacementSpan }; } // Replace everything after the last directory seperator that appears function getDirectoryFragmentTextSpan(text, textStart) { @@ -73620,6 +75787,12 @@ var ts; (function (ts) { var Completions; (function (Completions) { + var KeywordCompletionFilters; + (function (KeywordCompletionFilters) { + KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; + KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position) { if (ts.isInReferenceComment(sourceFile, position)) { return Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); @@ -73631,80 +75804,78 @@ 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, 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() }; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters; + if (sourceFile.languageVariant === 1 /* JSX */ && + location && location.parent && location.parent.kind === 252 /* JsxClosingElement */) { + // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, + // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. + // For example: + // var x =
completion list at "1" will contain "div" with type any + var tagName = location.parent.parent.openingElement.tagName; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, + entries: [{ + name: tagName.getFullText(), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }] }; } - if (requestJsDocTag) { - // If the current position is a jsDoc tag, only tags should be provided for completion - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getJSDocTagCompletions() }; + if (request) { + var entries_2 = request.kind === "JsDocTagName" + ? ts.JsDoc.getJSDocTagNameCompletions() + : request.kind === "JsDocTag" + ? ts.JsDoc.getJSDocTagCompletions() + : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); - ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target)); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { - if (!symbols || symbols.length === 0) { - if (sourceFile.languageVariant === 1 /* JSX */ && - location.parent && location.parent.kind === 252 /* JsxClosingElement */) { - // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, - // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. - // For example: - // var x =
completion list at "1" will contain "div" with type any - var tagName = location.parent.parent.openingElement.tagName; - entries.push({ - name: tagName.text, - kind: undefined, - kindModifiers: undefined, - sortText: "0", - }); - } - else if (!hasFilteredClassMemberKeywords) { - return undefined; - } + if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log); } - if (hasFilteredClassMemberKeywords) { - ts.addRange(entries, classMemberKeywordCompletions); - } - else if (!isMemberCompletion && !requestJsDocTag && !requestJsDocTagName) { - ts.addRange(entries, keywordCompletions); + // TODO add filter for keyword based on type/value/namespace and also location + // Add all keywords if + // - this is not a member completion list (all the keywords) + // - other filters are enabled in required scenario so add those keywords + if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { + ts.addRange(entries, getKeywordCompletions(keywordFilters)); } return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target) { - var entries = []; - var nameTable = ts.getNameTable(sourceFile); - nameTable.forEach(function (pos, name) { + function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { + ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location if (pos === position) { return; } - if (!uniqueNames.get(name)) { - uniqueNames.set(name, name); - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name), target, /*performCharacterChecks*/ true); - if (displayName) { - var entry = { - name: displayName, - kind: ts.ScriptElementKind.warning, - kindModifiers: "", - sortText: "1" - }; - entries.push(entry); - } + var realName = ts.unescapeLeadingUnderscores(name); + if (uniqueNames.has(realName)) { + return; + } + uniqueNames.set(realName, true); + var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true); + if (displayName) { + entries.push({ + name: displayName, + kind: "warning" /* warning */, + kindModifiers: "", + sortText: "1" + }); } }); - return entries; } function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target) { // Try to get a valid display name for this symbol, if we could not find one, then ignore it. // We would like to only show things that can be added after a dot, so for instance numeric properties can // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location); + var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks); if (!displayName) { return undefined; } @@ -73730,10 +75901,10 @@ var ts; var symbol = symbols_5[_i]; var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target); if (entry) { - var id = ts.escapeIdentifier(entry.name); - if (!uniqueNames.get(id)) { + var id = entry.name; + if (!uniqueNames.has(id)) { entries.push(entry); - uniqueNames.set(id, id); + uniqueNames.set(id, true); } } } @@ -73818,9 +75989,9 @@ var ts; 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]; + typeChecker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; addStringLiteralCompletionsFromType(typeChecker.getParameterType(candidate, argumentInfo.argumentIndex), entries, typeChecker, uniques); } if (entries.length) { @@ -73869,8 +76040,8 @@ var ts; uniques.set(name, true); result.push({ name: name, - kindModifiers: ts.ScriptElementKindModifier.none, - kind: ts.ScriptElementKind.variableElement, + kindModifiers: "" /* none */, + kind: "var" /* variableElement */, sortText: "0" }); } @@ -73880,14 +76051,14 @@ var ts; // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); if (completionData) { - var symbols = completionData.symbols, location_1 = completionData.location; + var symbols = completionData.symbols, location = completionData.location; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_1) === entryName ? s : undefined; }); + var symbol = ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); if (symbol) { - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location_1, location_1, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; return { name: entryName, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -73899,12 +76070,12 @@ var ts; } } // Didn't find a symbol with this name. See if we can find a keyword instead. - var keywordCompletion = ts.forEach(keywordCompletions, function (c) { return c.name === entryName; }); + var keywordCompletion = ts.forEach(getKeywordCompletions(0 /* None */), function (c) { return c.name === entryName; }); if (keywordCompletion) { return { name: entryName, - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, displayParts: [ts.displayPart(entryName, ts.SymbolDisplayPartKind.keyword)], documentation: undefined, tags: undefined @@ -73916,36 +76087,31 @@ var ts; function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryName) { // Compute all the completion symbols again. var completionData = getCompletionData(typeChecker, log, sourceFile, position); - if (completionData) { - var symbols = completionData.symbols, location_2 = completionData.location; - // Find the symbol with the matching entry name. - // We don't need to perform character checks here because we're only comparing the - // name against 'entryName' (which is known to be good), not building a new - // completion entry. - return ts.forEach(symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location_2) === entryName ? s : undefined; }); - } - return undefined; + // Find the symbol with the matching entry name. + // We don't need to perform character checks here because we're only comparing the + // name against 'entryName' (which is known to be good), not building a new + // completion entry. + return completionData && ts.forEach(completionData.symbols, function (s) { return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false) === entryName ? s : undefined; }); } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; function getCompletionData(typeChecker, log, sourceFile, position) { var isJavaScriptFile = ts.isSourceFileJavaScript(sourceFile); - // JsDoc tag-name is just the name of the JSDoc tagname (exclude "@") - var requestJsDocTagName = false; - // JsDoc tag includes both "@" and tag-name - var requestJsDocTag = false; + var request; var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position); + var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) 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.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { - // The current position is next to the '@' sign, when no tag name being provided yet. - // Provide a full list of tag names if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { - requestJsDocTagName = true; + // The current position is next to the '@' sign, when no tag name being provided yet. + // Provide a full list of tag names + request = { kind: "JsDocTagName" }; } else { // When completion is requested without "@", we will have check to make sure that @@ -73965,33 +76131,37 @@ var ts; // * |c| // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); - requestJsDocTag = !(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/)); + if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { + request = { kind: "JsDocTag" }; + } } } // Completion should work inside certain JsDoc tags. For example: // /** @type {number | string} */ // Completion should work in the brackets - var insideJsDocTagExpression = false; - var tag = ts.getJsDocTagAtPosition(sourceFile, position); + var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - requestJsDocTagName = true; + request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 288 /* JSDocTypeTag */: - case 286 /* JSDocParameterTag */: - case 287 /* JSDocReturnTag */: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression) { - insideJsDocTagExpression = tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 267 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 284 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } - if (requestJsDocTagName || requestJsDocTag) { - return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, requestJsDocTagName: requestJsDocTagName, requestJsDocTag: requestJsDocTag, hasFilteredClassMemberKeywords: false }; + if (request) { + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, keywordFilters: 0 /* None */ }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -73999,7 +76169,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -74007,9 +76177,9 @@ var ts; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { - var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile); - log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); + var start_4 = ts.timestamp(); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. // Also determine whether we are trying to complete with members of that node @@ -74018,7 +76188,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position); + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -74077,7 +76247,7 @@ var ts; var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; - var hasFilteredClassMemberKeywords = false; + var keywordFilters = 0 /* None */; var symbols = []; if (isRightOfDot) { getTypeScriptMemberSymbols(); @@ -74085,7 +76255,7 @@ var ts; else if (isRightOfOpenTag) { var tagSymbols = typeChecker.getJsxIntrinsicTagNames(); if (tryGetGlobalSymbols()) { - symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 8388608 /* Alias */)); })); + symbols = tagSymbols.concat(symbols.filter(function (s) { return !!(s.flags & (107455 /* Value */ | 2097152 /* Alias */)); })); } else { symbols = tagSymbols; @@ -74111,51 +76281,75 @@ 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, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 277 /* JSDocAugmentsTag */: + case 279 /* JSDocParameterTag */: + case 284 /* JSDocPropertyTag */: + case 280 /* JSDocReturnTag */: + case 281 /* JSDocTypeTag */: + case 283 /* JSDocTypedefTag */: + return true; + } + } function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; - if (node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */ || node.kind === 179 /* PropertyAccessExpression */) { + // Since this is qualified name check its a type node location + var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); + if (ts.isEntityName(node)) { var symbol = typeChecker.getSymbolAtLocation(node); - // This is an alias, follow what it aliases - if (symbol && symbol.flags & 8388608 /* Alias */) { - symbol = typeChecker.getAliasedSymbol(symbol); - } - if (symbol && symbol.flags & 1952 /* HasExports */) { - // Extract module or enum members - var exportedSymbols = typeChecker.getExportsOfModule(symbol); - ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); + if (symbol) { + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & (1536 /* Module */ | 384 /* Enum */)) { + // Extract module or enum members + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanBeReferencedAtTypeLocation(symbol); }; + var isValidAccess = isRhsOfImportDeclaration ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; + for (var _i = 0, exportedSymbols_1 = exportedSymbols; _i < exportedSymbols_1.length; _i++) { + var symbol_2 = exportedSymbols_1[_i]; + if (isValidAccess(symbol_2)) { + symbols.push(symbol_2); + } } - }); + // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). + if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 265 /* SourceFile */ && d.kind !== 233 /* ModuleDeclaration */ && d.kind !== 232 /* EnumDeclaration */; })) { + addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); + } + return; + } } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + addTypeProperties(typeChecker.getTypeAtLocation(node)); + } } function addTypeProperties(type) { - if (type) { - // Filter private properties - for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { - var symbol = _a[_i]; - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { - symbols.push(symbol); - } + // Filter private properties + for (var _i = 0, _a = type.getApparentProperties(); _i < _a.length; _i++) { + var symbol = _a[_i]; + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + symbols.push(symbol); } - if (isJavaScriptFile && type.flags & 65536 /* Union */) { - // In javascript files, for union types, we don't just get the members that - // the individual types have in common, we also include all the members that - // each individual type has. This is because we're going to add all identifiers - // anyways. So we might as well elevate the members that were at least part - // of the individual types to a higher status since we know what they are. - var unionType = type; - for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { - var elementType = _c[_b]; - addTypeProperties(elementType); - } + } + if (isJavaScriptFile && type.flags & 65536 /* Union */) { + // In javascript files, for union types, we don't just get the members that + // the individual types have in common, we also include all the members that + // each individual type has. This is because we're going to add all identifiers + // anyways. So we might as well elevate the members that were at least part + // of the individual types to a higher status since we know what they are. + var unionType = type; + for (var _b = 0, _c = unionType.types; _b < _c.length; _b++) { + var elementType = _c[_b]; + addTypeProperties(elementType); } } } @@ -74172,6 +76366,15 @@ var ts; // try to show exported member for imported module return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } + if (tryGetConstructorLikeCompletionContainer(contextToken)) { + // no members, only keywords + isMemberCompletion = false; + // Declaring new property/method/accessor + isNewIdentifierLocation = true; + // Has keywords for constructor parameter + keywordFilters = 2 /* ConstructorParameterKeywords */; + return true; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -74232,11 +76435,72 @@ var ts; scopeNode.kind === 256 /* JsxExpression */ || ts.isStatement(scopeNode); } - /// TODO filter meaning based on the current context - var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 2097152 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + // Its a type, but you can reach it by namespace.type as well + return symbolCanBeReferencedAtTypeLocation(symbol); + } + } + // expressions are value space (which includes the value namespaces) + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 107455 /* Value */); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 /* TypeOfKeyword */ && + contextToken.parent.kind === 162 /* TypeQuery */; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56 /* ColonToken */: + return parentKind === 149 /* PropertyDeclaration */ || + parentKind === 148 /* PropertySignature */ || + parentKind === 146 /* Parameter */ || + parentKind === 226 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 58 /* EqualsToken */: + return parentKind === 231 /* TypeAliasDeclaration */; + case 118 /* AsKeyword */: + return parentKind === 202 /* AsExpression */; + } + } + } + function symbolCanBeReferencedAtTypeLocation(symbol) { + symbol = symbol.exportSymbol || symbol; + // This is an alias, follow what it aliases + symbol = ts.skipAlias(symbol, typeChecker); + if (symbol.flags & 793064 /* Type */) { + return true; + } + if (symbol.flags & 1536 /* Module */) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + // If the exported symbols contains type, + // symbol can be referenced at locations where type is allowed + return ts.forEach(exportedSymbols, symbolCanBeReferencedAtTypeLocation); + } + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -74293,7 +76557,7 @@ var ts; || containingNodeKind === 157 /* IndexSignature */ // [ | : string ] || containingNodeKind === 144 /* ComputedPropertyName */; // [ | /* this can become an index signature */ case 128 /* ModuleKeyword */: // module | - case 129 /* NamespaceKeyword */: + case 129 /* NamespaceKeyword */:// namespace | return true; case 23 /* DotToken */: return containingNodeKind === 233 /* ModuleDeclaration */; // module A.| @@ -74325,13 +76589,13 @@ var ts; if (contextToken.kind === 9 /* StringLiteral */ || contextToken.kind === 12 /* RegularExpressionLiteral */ || ts.isTemplateLiteralKind(contextToken.kind)) { - var start_3 = contextToken.getStart(); + var start_5 = contextToken.getStart(); var end = contextToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. // 2. at the end position of an unterminated token. // 3. at the end of a regular expression (due to trailing flags like '/foo/g'). - if (start_3 < position && position < end) { + if (start_5 < position && position < end) { return true; } if (position === end) { @@ -74362,41 +76626,36 @@ var ts; typeMembers = typeChecker.getAllPossiblePropertiesOfType(typeForObject); existingMembers = objectLikeContainer.properties; } - else if (objectLikeContainer.kind === 174 /* ObjectBindingPattern */) { + else { + ts.Debug.assert(objectLikeContainer.kind === 174 /* ObjectBindingPattern */); // We are *only* completing on properties from the type being destructured. isNewIdentifierLocation = false; var rootDeclaration = ts.getRootDeclaration(objectLikeContainer.parent); - if (ts.isVariableLike(rootDeclaration)) { - // We don't want to complete using the type acquired by the shape - // of the binding pattern; we are only interested in types acquired - // through type declaration or inference. - // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - - // type of parameter will flow in from the contextual type of the function - var canGetType = !!(rootDeclaration.initializer || rootDeclaration.type); - if (!canGetType && rootDeclaration.kind === 146 /* Parameter */) { - if (ts.isExpression(rootDeclaration.parent)) { - canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); - } - else if (rootDeclaration.parent.kind === 151 /* MethodDeclaration */ || rootDeclaration.parent.kind === 154 /* SetAccessor */) { - canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); - } + if (!ts.isVariableLike(rootDeclaration)) + throw ts.Debug.fail("Root declaration is not variable-like."); + // We don't want to complete using the type acquired by the shape + // of the binding pattern; we are only interested in types acquired + // through type declaration or inference. + // Also proceed if rootDeclaration is a parameter and if its containing function expression/arrow function is contextually typed - + // type of parameter will flow in from the contextual type of the function + var canGetType = rootDeclaration.initializer || rootDeclaration.type || rootDeclaration.parent.parent.kind === 216 /* ForOfStatement */; + if (!canGetType && rootDeclaration.kind === 146 /* Parameter */) { + if (ts.isExpression(rootDeclaration.parent)) { + canGetType = !!typeChecker.getContextualType(rootDeclaration.parent); } - if (canGetType) { - 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; + else if (rootDeclaration.parent.kind === 151 /* MethodDeclaration */ || rootDeclaration.parent.kind === 154 /* SetAccessor */) { + canGetType = ts.isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(rootDeclaration.parent.parent); } } - else { - ts.Debug.fail("Root declaration is not variable-like."); + if (canGetType) { + 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; } } - else { - ts.Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind); - } if (typeMembers && typeMembers.length > 0) { // Add filtered items to the completion list symbols = filterObjectMembersList(typeMembers, existingMembers); @@ -74448,7 +76707,7 @@ var ts; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements - hasFilteredClassMemberKeywords = true; + keywordFilters = 1 /* ClassElementKeywords */; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); var implementsTypeNodes = ts.getClassImplementsHeritageClauseElements(classLikeDeclaration); if (baseTypeNode || implementsTypeNodes) { @@ -74476,12 +76735,12 @@ var ts; } } var implementedInterfaceTypePropertySymbols = (classElementModifierFlags & 32 /* Static */) ? - undefined : - ts.flatMap(implementsTypeNodes, function (typeNode) { return typeChecker.getPropertiesOfType(typeChecker.getTypeAtLocation(typeNode)); }); + ts.emptyArray : + ts.flatMap(implementsTypeNodes || ts.emptyArray, 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); + ts.emptyArray, implementedInterfaceTypePropertySymbols, classLikeDeclaration.members, classElementModifierFlags); } } } @@ -74493,9 +76752,9 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // const x = { | - case 26 /* CommaToken */: + case 26 /* CommaToken */:// const x = { a: 0, | var parent = contextToken.parent; - if (parent && (parent.kind === 178 /* ObjectLiteralExpression */ || parent.kind === 174 /* ObjectBindingPattern */)) { + if (ts.isObjectLiteralExpression(parent) || ts.isObjectBindingPattern(parent)) { return parent; } break; @@ -74511,7 +76770,7 @@ var ts; if (contextToken) { switch (contextToken.kind) { case 17 /* OpenBraceToken */: // import { | - case 26 /* CommaToken */: + case 26 /* CommaToken */:// import { a as 0, | switch (contextToken.parent.kind) { case 241 /* NamedImports */: case 245 /* NamedExports */: @@ -74524,6 +76783,14 @@ var ts; function isFromClassElementDeclaration(node) { return ts.isClassElement(node.parent) && ts.isClassLike(node.parent.parent); } + function isParameterOfConstructorDeclaration(node) { + return ts.isParameter(node) && ts.isConstructorDeclaration(node.parent); + } + function isConstructorParameterCompletion(node) { + return node.parent && + isParameterOfConstructorDeclaration(node.parent) && + (isConstructorParameterCompletionKeyword(node.kind) || ts.isDeclarationName(node)); + } /** * 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. @@ -74531,13 +76798,18 @@ var ts; function tryGetClassLikeCompletionContainer(contextToken) { if (contextToken) { switch (contextToken.kind) { - case 17 /* OpenBraceToken */: + case 17 /* OpenBraceToken */:// class c { | + if (ts.isClassLike(contextToken.parent)) { + return contextToken.parent; + } + break; + // class c {getValue(): number, | } + case 26 /* CommaToken */: 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 */: @@ -74554,11 +76826,29 @@ var ts; } } // class c { method() { } | method2() { } } - if (location && location.kind === 294 /* SyntaxList */ && ts.isClassLike(location.parent)) { + if (location && location.kind === 286 /* SyntaxList */ && ts.isClassLike(location.parent)) { return location.parent; } return undefined; } + /** + * 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 tryGetConstructorLikeCompletionContainer(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 19 /* OpenParenToken */: + case 26 /* CommaToken */: + return ts.isConstructorDeclaration(contextToken.parent) && contextToken.parent; + default: + if (isConstructorParameterCompletion(contextToken)) { + return contextToken.parent.parent; + } + } + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -74616,19 +76906,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152 /* Constructor */: - case 161 /* ConstructorType */: - case 160 /* FunctionType */: - return false; - default: - return true; - } - } /** * @returns true if we are certain that the currently edited location must define a new location; false otherwise. */ @@ -74640,12 +76917,15 @@ var ts; containingNodeKind === 227 /* VariableDeclarationList */ || containingNodeKind === 208 /* VariableStatement */ || containingNodeKind === 232 /* EnumDeclaration */ || - isFunction(containingNodeKind) || - containingNodeKind === 229 /* ClassDeclaration */ || - containingNodeKind === 199 /* ClassExpression */ || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 230 /* InterfaceDeclaration */ || containingNodeKind === 175 /* ArrayBindingPattern */ || - containingNodeKind === 231 /* TypeAliasDeclaration */; // type Map, K, | + containingNodeKind === 231 /* TypeAliasDeclaration */ || + // class A= contextToken.pos); case 23 /* DotToken */: return containingNodeKind === 175 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: @@ -74654,7 +76934,7 @@ var ts; return containingNodeKind === 175 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: return containingNodeKind === 260 /* CatchClause */ || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: return containingNodeKind === 232 /* EnumDeclaration */ || containingNodeKind === 230 /* InterfaceDeclaration */ || @@ -74669,7 +76949,7 @@ var ts; containingNodeKind === 199 /* ClassExpression */ || containingNodeKind === 230 /* InterfaceDeclaration */ || containingNodeKind === 231 /* TypeAliasDeclaration */ || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: @@ -74679,7 +76959,7 @@ var ts; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 146 /* Parameter */; + return containingNodeKind === 146 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); case 118 /* AsKeyword */: return containingNodeKind === 242 /* ImportSpecifier */ || containingNodeKind === 246 /* ExportSpecifier */ || @@ -74699,7 +76979,7 @@ var ts; case 110 /* LetKeyword */: case 76 /* ConstKeyword */: case 116 /* YieldKeyword */: - case 138 /* TypeKeyword */: + case 138 /* TypeKeyword */:// type htm| return true; } // If the previous token is keyword correspoding to class member completion keyword @@ -74708,6 +76988,17 @@ var ts; isFromClassElementDeclaration(contextToken)) { return false; } + if (isConstructorParameterCompletion(contextToken)) { + // constructor parameter completion is available only if + // - its modifier of the constructor parameter or + // - its name of the parameter and not being edited + // eg. constructor(a |<- this shouldnt show completion + if (!ts.isIdentifier(contextToken) || + isConstructorParameterCompletionKeywordText(contextToken.getText()) || + isCurrentlyEditingNode(contextToken)) { + return false; + } + } // Previous token may have been a keyword that was converted to an identifier. switch (contextToken.getText()) { case "abstract": @@ -74727,7 +77018,10 @@ var ts; case "yield": return true; } - return false; + return ts.isDeclarationName(contextToken) && !ts.isJsxAttribute(contextToken.parent); + } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -74746,7 +77040,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = ts.createMap(); + var existingImportsOrExports = ts.createUnderscoreEscapedMap(); 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 @@ -74754,12 +77048,12 @@ var ts; continue; } var name = element.propertyName || element.name; - existingImportsOrExports.set(name.text, true); + existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default"; }); } - return ts.filter(exportsOfModule, function (e) { return e.name !== "default" && !existingImportsOrExports.get(e.name); }); + return ts.filter(exportsOfModule, function (e) { return e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName); }); } /** * Filters out completion suggestions for named imports or exports. @@ -74771,7 +77065,7 @@ var ts; if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; } - var existingMemberNames = ts.createMap(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members @@ -74791,18 +77085,19 @@ var ts; if (m.kind === 176 /* BindingElement */ && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { - existingName = m.propertyName.text; + existingName = m.propertyName.escapedText; } } else { - // TODO(jfreeman): Account for computed property name + // TODO: 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 = ts.getNameOfDeclaration(m).text; + var name = ts.getNameOfDeclaration(m); + existingName = ts.getEscapedTextOfIdentifierOrLiteral(name); } existingMemberNames.set(existingName, true); } - return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.name); }); + return ts.filter(contextualMemberSymbols, function (m) { return !existingMemberNames.get(m.escapedName); }); } /** * Filters out completion suggestions for class elements. @@ -74810,7 +77105,7 @@ var ts; * @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(); + var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members @@ -74840,9 +77135,20 @@ var ts; 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 */); })); + var result = []; + addPropertySymbols(baseSymbols, 8 /* Private */); + addPropertySymbols(implementingTypeSymbols, 24 /* NonPublicAccessibilityModifier */); + return result; + function addPropertySymbols(properties, inValidModifierFlags) { + for (var _i = 0, properties_11 = properties; _i < properties_11.length; _i++) { + var property = properties_11[_i]; + if (isValidProperty(property, inValidModifierFlags)) { + result.push(property); + } + } + } function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.name) && + return !existingMemberNames.get(propertySymbol.escapedName) && propertySymbol.getDeclarations() && !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); } @@ -74854,7 +77160,7 @@ var ts; * do not occur at the current position and have not otherwise been typed. */ function filterJsxAttributes(symbols, attributes) { - var seenNames = ts.createMap(); + var seenNames = ts.createUnderscoreEscapedMap(); 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 @@ -74862,10 +77168,10 @@ var ts; continue; } if (attr.kind === 253 /* JsxAttribute */) { - seenNames.set(attr.name.text, true); + seenNames.set(attr.name.escapedText, true); } } - return ts.filter(symbols, function (a) { return !seenNames.get(a.name); }); + return ts.filter(symbols, function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { return node.getStart() <= position && position <= node.getEnd(); @@ -74874,53 +77180,70 @@ var ts; /** * Get the name to be display in completion from a given symbol. * - * @return undefined if the name is of external module otherwise a name with striped of any quote + * @return undefined if the name is of external module */ - function getCompletionEntryDisplayNameForSymbol(typeChecker, symbol, target, performCharacterChecks, location) { - var displayName = ts.getDeclaredName(typeChecker, symbol, location); - if (displayName) { - var firstCharCode = displayName.charCodeAt(0); - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if ((symbol.flags & 1920 /* Namespace */) && (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */)) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks) { + var name = symbol.name; + if (!name) + return undefined; + // First check of the displayName is not external module; if it is an external module, it is not valid entry + if (symbol.flags & 1920 /* Namespace */) { + var firstCharCode = name.charCodeAt(0); + if (firstCharCode === 39 /* singleQuote */ || firstCharCode === 34 /* doubleQuote */) { // If the symbol is external module, don't show it in the completion list // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) return undefined; } } - return getCompletionEntryDisplayName(displayName, target, performCharacterChecks); + return getCompletionEntryDisplayName(name, target, performCharacterChecks); } /** * Get a displayName from a given for completion list, performing any necessary quotes stripping * and checking whether the name is valid identifier name. */ function getCompletionEntryDisplayName(name, target, performCharacterChecks) { - if (!name) { - return undefined; - } - name = ts.stripQuotes(name); - if (!name) { - return undefined; - } // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks) { - if (!ts.isIdentifierText(name, target)) { - return undefined; - } + if (performCharacterChecks && !ts.isIdentifierText(name, target)) { + return undefined; } return name; } // A cache of completion entries for keywords, these do not change between sessions - var keywordCompletions = []; - for (var i = 72 /* FirstKeyword */; i <= 142 /* LastKeyword */; i++) { - keywordCompletions.push({ - name: ts.tokenToString(i), - kind: ts.ScriptElementKind.keyword, - kindModifiers: ts.ScriptElementKindModifier.none, - sortText: "0" - }); + var _keywordCompletions = []; + function getKeywordCompletions(keywordFilter) { + var completions = _keywordCompletions[keywordFilter]; + if (completions) { + return completions; + } + return _keywordCompletions[keywordFilter] = generateKeywordCompletions(keywordFilter); + function generateKeywordCompletions(keywordFilter) { + switch (keywordFilter) { + case 0 /* None */: + return getAllKeywordCompletions(); + case 1 /* ClassElementKeywords */: + return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); + case 2 /* ConstructorParameterKeywords */: + return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + } + } + function getAllKeywordCompletions() { + var allKeywordsCompletions = []; + for (var i = 72 /* FirstKeyword */; i <= 142 /* LastKeyword */; i++) { + allKeywordsCompletions.push({ + name: ts.tokenToString(i), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: "0" + }); + } + return allKeywordsCompletions; + } + function getFilteredKeywordCompletions(filterFn) { + return ts.filter(getKeywordCompletions(0 /* None */), function (entry) { return filterFn(entry.name); }); + } } function isClassMemberCompletionKeyword(kind) { switch (kind) { @@ -74940,9 +77263,18 @@ var ts; function isClassMemberCompletionKeywordText(text) { return isClassMemberCompletionKeyword(ts.stringToToken(text)); } - var classMemberKeywordCompletions = ts.filter(keywordCompletions, function (entry) { - return isClassMemberCompletionKeywordText(entry.name); - }); + function isConstructorParameterCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + return true; + } + } + function isConstructorParameterCompletionKeywordText(text) { + return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); + } function isEqualityExpression(node) { return ts.isBinaryExpression(node) && isEqualityOperatorKind(node.operatorToken.kind); } @@ -74952,6 +77284,36 @@ var ts; kind === 34 /* EqualsEqualsEqualsToken */ || kind === 35 /* ExclamationEqualsEqualsToken */; } + /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ + function getJsDocTagAtPosition(node, position) { + var jsDoc = getJsDocHavingNode(node).jsDoc; + if (!jsDoc) + return undefined; + for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) { + var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags; + if (!tags || position < pos || position > end) + continue; + for (var i = tags.length - 1; i >= 0; i--) { + var tag = tags[i]; + if (position >= tag.pos) { + return tag; + } + } + } + } + function getJsDocHavingNode(node) { + if (!ts.isToken(node)) + return node; + switch (node.kind) { + case 104 /* VarKeyword */: + case 110 /* LetKeyword */: + case 76 /* ConstKeyword */: + // if the current token is var, let or const, skip the VariableDeclarationList + return node.parent.parent; + default: + return node.parent; + } + } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); /* @internal */ @@ -74960,17 +77322,28 @@ var ts; var DocumentHighlights; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position); - return node && (getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile)); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + // Note that getTouchingWord indicates failure by returning the sourceFile node. + if (node === sourceFile) + return undefined; + ts.Debug.assert(node.parent !== undefined); + if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + // For a JSX element, just highlight the matching tag, not all references. + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + var highlightSpans = [openingElement, closingElement].map(function (_a) { + var tagName = _a.tagName; + return getHighlightSpanForNode(tagName, sourceFile); + }); + return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; + } + return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { - var start = node.getStart(sourceFile); - var end = node.getEnd(); return { fileName: sourceFile.fileName, - textSpan: ts.createTextSpanFromBounds(start, end), - kind: ts.HighlightSpanKind.none + textSpan: ts.createTextSpanFromNode(node, sourceFile), + kind: "none" /* none */ }; } function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { @@ -75224,7 +77597,7 @@ var ts; case 265 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */) { - nodes = declaration.members.concat(declaration); + nodes = declaration.members.concat([declaration]); } else { nodes = container.statements; @@ -75247,7 +77620,7 @@ var ts; } } else if (modifierFlag & 128 /* Abstract */) { - nodes = nodes.concat(container); + nodes = nodes.concat([container]); } break; default: @@ -75451,7 +77824,7 @@ var ts; result.push({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), - kind: ts.HighlightSpanKind.reference + kind: "reference" /* reference */ }); i++; // skip the next keyword continue; @@ -75468,7 +77841,7 @@ var ts; */ function isLabeledBy(node, labelName) { for (var owner = node.parent; owner.kind === 222 /* LabeledStatement */; owner = owner.parent) { - if (owner.label.text === labelName) { + if (owner.label.escapedText === labelName) { return true; } } @@ -75490,7 +77863,7 @@ var ts; function getBucketForCompilationSettings(key, createIfMissing) { var bucket = buckets.get(key); if (!bucket && createIfMissing) { - buckets.set(key, bucket = ts.createFileMap()); + buckets.set(key, bucket = ts.createMap()); } return bucket; } @@ -75498,9 +77871,9 @@ var ts; var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { var entries = buckets.get(name); var sourceFiles = []; - entries.forEachValue(function (key, entry) { + entries.forEach(function (entry, name) { sourceFiles.push({ - name: key, + name: name, refCount: entry.languageServiceRefCount, references: entry.owners.slice(0) }); @@ -75573,7 +77946,7 @@ var ts; entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(path); + bucket.delete(path); } } return { @@ -75642,7 +78015,7 @@ var ts; } function handleDirectImports(exportingModuleSymbol) { var theseDirectImports = getDirectImports(exportingModuleSymbol); - if (theseDirectImports) + if (theseDirectImports) { for (var _i = 0, theseDirectImports_1 = theseDirectImports; _i < theseDirectImports_1.length; _i++) { var direct = theseDirectImports_1[_i]; if (!markSeenDirectImport(direct)) { @@ -75688,6 +78061,7 @@ var ts; break; } } + } } function handleNamespaceImport(importDeclaration, name, isReExport) { if (exportKind === 2 /* ExportEquals */) { @@ -75721,11 +78095,12 @@ var ts; var moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); var directImports = getDirectImports(moduleSymbol); - if (directImports) + if (directImports) { for (var _i = 0, directImports_1 = directImports; _i < directImports_1.length; _i++) { var directImport = directImports_1[_i]; addIndirectUsers(getSourceFileLikeForImportDeclaration(directImport)); } + } } function getDirectImports(moduleSymbol) { return allDirectImports.get(ts.getSymbolId(moduleSymbol).toString()); @@ -75737,17 +78112,18 @@ var ts; * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. */ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, checker, isForRename) { - var exportName = exportSymbol.name; + var exportName = exportSymbol.escapedName; var importSearches = []; var singleReferences = []; function addSearch(location, symbol) { importSearches.push([location, symbol]); } - if (directImports) + if (directImports) { for (var _i = 0, directImports_2 = directImports; _i < directImports_2.length; _i++) { var decl = directImports_2[_i]; handleImport(decl); } + } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { if (decl.kind === 237 /* ImportEqualsDeclaration */) { @@ -75785,7 +78161,7 @@ var ts; var name = importClause.name; // If a default import has the same name as the default export, allow to rename it. // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.text === symbolName(exportSymbol))) { + if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { var defaultImportAlias = checker.getSymbolAtLocation(name); addSearch(name, defaultImportAlias); } @@ -75803,16 +78179,16 @@ var ts; */ function handleNamespaceImportLike(importName) { // Don't rename an import that already has a different name than the export. - if (exportKind === 2 /* ExportEquals */ && (!isForRename || importName.text === exportName)) { + if (exportKind === 2 /* ExportEquals */ && (!isForRename || importName.escapedText === exportName)) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } function searchForNamedImport(namedBindings) { - if (namedBindings) + if (namedBindings) { for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var element = _a[_i]; var name = element.name, propertyName = element.propertyName; - if ((propertyName || name).text !== exportName) { + if ((propertyName || name).escapedText !== exportName) { continue; } if (propertyName) { @@ -75830,6 +78206,7 @@ var ts; addSearch(name, localSymbol); } } + } } } /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ @@ -75962,24 +78339,22 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; - if (symbol.flags & 7340032 /* Export */) { + if (symbol.exportSymbol) { if (parent.kind === 179 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && parent.parent.kind === 194 /* BinaryExpression */ + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) : undefined; } else { - var exportSymbol = symbol.exportSymbol; - ts.Debug.assert(!!exportSymbol); - return exportInfo(exportSymbol, getExportKindForDeclaration(parent)); + return exportInfo(symbol.exportSymbol, getExportKindForDeclaration(parent)); } } else { - var exportNode = getExportNode(parent); + var exportNode = getExportNode(parent, node); if (exportNode && ts.hasModifier(exportNode, 1 /* Export */)) { - if (exportNode.kind === 237 /* ImportEqualsDeclaration */ && exportNode.moduleReference === node) { + if (ts.isImportEqualsDeclaration(exportNode) && exportNode.moduleReference === node) { // We're at `Y` in `export import X = Y`. This is not the exported symbol, the left-hand-side is. So treat this as an import statement. if (comingFromExport) { return undefined; @@ -75991,19 +78366,25 @@ var ts; return exportInfo(symbol, getExportKindForDeclaration(exportNode)); } } - else if (parent.kind === 243 /* ExportAssignment */) { - // Get the symbol for the `export =` node; its parent is the module it's the export of. - var exportingModuleSymbol = parent.symbol.parent; - ts.Debug.assert(!!exportingModuleSymbol); - return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 /* ExportEquals */ } }; + else if (ts.isExportAssignment(parent)) { + return getExportAssignmentExport(parent); } - else if (parent.kind === 194 /* BinaryExpression */) { + else if (ts.isExportAssignment(parent.parent)) { + return getExportAssignmentExport(parent.parent); + } + else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (parent.parent.kind === 194 /* BinaryExpression */) { + else if (ts.isBinaryExpression(parent.parent)) { return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); } } + function getExportAssignmentExport(ex) { + // Get the symbol for the `export =` node; its parent is the module it's the export of. + var exportingModuleSymbol = ex.symbol.parent; + ts.Debug.assert(!!exportingModuleSymbol); + return { kind: 1 /* Export */, symbol: symbol, exportInfo: { exportingModuleSymbol: exportingModuleSymbol, exportKind: 2 /* ExportEquals */ } }; + } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; switch (ts.getSpecialPropertyAssignmentKind(node)) { @@ -76023,19 +78404,19 @@ var ts; function getImport() { var isImport = isNodeImport(node); if (!isImport) - return; + return undefined; // A symbol being imported is always an alias. So get what that aliases to find the local symbol. var importedSymbol = checker.getImmediateAliasedSymbol(symbol); - if (importedSymbol) { - // Search on the local symbol in the exporting module, not the exported symbol. - importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); - // Similarly, skip past the symbol for 'export =' - if (importedSymbol.name === "export=") { - importedSymbol = checker.getImmediateAliasedSymbol(importedSymbol); - } - if (symbolName(importedSymbol) === symbol.name) { - return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); - } + if (!importedSymbol) + return undefined; + // Search on the local symbol in the exporting module, not the exported symbol. + importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); + // Similarly, skip past the symbol for 'export =' + if (importedSymbol.escapedName === "export=") { + importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); + } + if (symbolName(importedSymbol) === symbol.escapedName) { + return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } } function exportInfo(symbol, kind) { @@ -76048,11 +78429,26 @@ var ts; } } FindAllReferences.getImportOrExportSymbol = getImportOrExportSymbol; + function getExportEqualsLocalSymbol(importedSymbol, checker) { + if (importedSymbol.flags & 2097152 /* Alias */) { + return checker.getImmediateAliasedSymbol(importedSymbol); + } + var decl = importedSymbol.valueDeclaration; + if (ts.isExportAssignment(decl)) { + return decl.expression.symbol; + } + else if (ts.isBinaryExpression(decl)) { + return decl.right.symbol; + } + ts.Debug.fail(); + } + // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. - function getExportNode(parent) { + function getExportNode(parent, node) { if (parent.kind === 226 /* VariableDeclaration */) { var p = parent; - return p.parent.kind === 260 /* CatchClause */ ? undefined : p.parent.parent.kind === 208 /* VariableStatement */ ? p.parent.parent : undefined; + return p.name !== node ? undefined : + p.parent.kind === 260 /* CatchClause */ ? undefined : p.parent.parent.kind === 208 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -76083,27 +78479,28 @@ var ts; } FindAllReferences.getExportInfo = getExportInfo; function symbolName(symbol) { - if (symbol.name !== "default") { - return symbol.name; + if (symbol.escapedName !== "default") { + return symbol.escapedName; } return ts.forEach(symbol.declarations, function (decl) { if (ts.isExportAssignment(decl)) { - return ts.isIdentifier(decl.expression) ? decl.expression.text : undefined; + return ts.isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; } var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ && name.text; + return name && name.kind === 71 /* Identifier */ && name.escapedText; }); } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. - if (symbol.declarations) + if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (ts.isExportSpecifier(declaration) && !declaration.propertyName && !declaration.parent.parent.moduleSpecifier) { return checker.getExportSpecifierLocalTargetSymbol(declaration); } } + } return symbol; } function getContainingModuleSymbol(importer, checker) { @@ -76157,13 +78554,17 @@ var ts; } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + // A node in a JSDoc comment can't have an implementation anyway. + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); 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(program, cancellationToken, sourceFiles, node) { + if (node.kind === 265 /* SourceFile */) { + return undefined; + } 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). @@ -76211,22 +78612,22 @@ var ts; } case "label": { var node_3 = def.node; - return { node: node_3, name: node_3.text, kind: ts.ScriptElementKind.label, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; + return { node: node_3, name: node_3.text, kind: "label" /* label */, displayParts: [ts.displayPart(node_3.text, ts.SymbolDisplayPartKind.text)] }; } case "keyword": { var node_4 = def.node; var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: ts.ScriptElementKind.keyword, displayParts: [{ text: name_4, kind: ts.ScriptElementKind.keyword }] }; + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; - return { node: node_5, name: "this", kind: ts.ScriptElementKind.variableElement, displayParts: displayParts_2 }; + return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { var node_6 = def.node; - return { node: node_6, name: node_6.text, kind: ts.ScriptElementKind.variableElement, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; + return { node: node_6, name: node_6.text, kind: "var" /* variableElement */, displayParts: [ts.displayPart(ts.getTextOfNode(node_6), ts.SymbolDisplayPartKind.stringLiteral)] }; } } })(); @@ -76236,7 +78637,7 @@ var ts; var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); return { - containerKind: "", + containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, @@ -76258,7 +78659,7 @@ var ts; fileName: node.getSourceFile().fileName, textSpan: getTextSpan(node), isWriteAccess: isWriteAccess(node), - isDefinition: ts.isDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), + isDefinition: ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), isInString: isInString }; } @@ -76269,7 +78670,7 @@ var ts; } else { var textSpan = entry.textSpan, fileName = entry.fileName; - return { textSpan: textSpan, fileName: fileName, kind: ts.ScriptElementKind.unknown, displayParts: [] }; + return { textSpan: textSpan, fileName: fileName, kind: "" /* unknown */, displayParts: [] }; } } function implementationKindDisplayParts(node, checker) { @@ -76279,13 +78680,13 @@ var ts; } else if (node.kind === 178 /* ObjectLiteralExpression */) { return { - kind: ts.ScriptElementKind.interfaceElement, + kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } else if (node.kind === 199 /* ClassExpression */) { return { - kind: ts.ScriptElementKind.localClassElement, + kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] }; } @@ -76296,14 +78697,14 @@ var ts; function toHighlightSpan(entry) { if (entry.type === "span") { var fileName_1 = entry.fileName, textSpan = entry.textSpan; - return { fileName: fileName_1, span: { textSpan: textSpan, kind: ts.HighlightSpanKind.reference } }; + return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } var node = entry.node, isInString = entry.isInString; var fileName = entry.node.getSourceFile().fileName; var writeAccess = isWriteAccess(node); var span = { textSpan: getTextSpan(node), - kind: writeAccess ? ts.HighlightSpanKind.writtenReference : ts.HighlightSpanKind.reference, + kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: isInString }; return { fileName: fileName, span: span }; @@ -76320,20 +78721,19 @@ var ts; } /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccess(node) { - if (node.kind === 71 /* Identifier */ && ts.isDeclarationName(node)) { + if (ts.isAnyDeclarationName(node)) { return true; } var parent = node.parent; - if (parent) { - if (parent.kind === 193 /* PostfixUnaryExpression */ || parent.kind === 192 /* PrefixUnaryExpression */) { + switch (parent && parent.kind) { + case 193 /* PostfixUnaryExpression */: + case 192 /* PrefixUnaryExpression */: return true; - } - else if (parent.kind === 194 /* BinaryExpression */ && parent.left === node) { - var operator = parent.operatorToken.kind; - return 58 /* FirstAssignment */ <= operator && operator <= 70 /* LastAssignment */; - } + case 194 /* BinaryExpression */: + return parent.left === node && ts.isAssignmentOperator(parent.operatorToken.kind); + default: + return false; } - return false; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -76384,7 +78784,7 @@ var ts; case 244 /* ExportDeclaration */: return true; case 181 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -76453,7 +78853,7 @@ var ts; // Compute the meaning from the location and the symbol it references var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; - var state = createState(sourceFiles, node, checker, cancellationToken, searchMeaning, options, result); + var state = new State(sourceFiles, /*isForConstructor*/ node.kind === 123 /* ConstructorKeyword */, checker, cancellationToken, searchMeaning, options, result); var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). @@ -76483,53 +78883,94 @@ var ts; } return symbol; } - function createState(sourceFiles, originalLocation, checker, cancellationToken, searchMeaning, options, result) { - var symbolIdToReferences = []; - var inheritsFromCache = ts.createMap(); - // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. - var sourceFileToSeenSymbols = []; - var isForConstructor = originalLocation.kind === 123 /* ConstructorKeyword */; - var importTracker; - return __assign({}, options, { sourceFiles: sourceFiles, isForConstructor: isForConstructor, checker: checker, cancellationToken: cancellationToken, searchMeaning: searchMeaning, inheritsFromCache: inheritsFromCache, getImportSearches: getImportSearches, createSearch: createSearch, referenceAdder: referenceAdder, addStringOrCommentReference: addStringOrCommentReference, - markSearchedSymbol: markSearchedSymbol, markSeenContainingTypeReference: ts.nodeSeenTracker(), markSeenReExportRHS: ts.nodeSeenTracker() }); - function getImportSearches(exportSymbol, exportInfo) { - if (!importTracker) - importTracker = FindAllReferences.createImportTracker(sourceFiles, checker, cancellationToken); - return importTracker(exportSymbol, exportInfo, options.isForRename); + /** + * Holds all state needed for the finding references. + * Unlike `Search`, there is only one `State`. + */ + var State = (function () { + function State(sourceFiles, + /** True if we're searching for constructor references. */ + isForConstructor, checker, cancellationToken, searchMeaning, options, result) { + this.sourceFiles = sourceFiles; + this.isForConstructor = isForConstructor; + this.checker = checker; + this.cancellationToken = cancellationToken; + this.searchMeaning = searchMeaning; + this.options = options; + this.result = result; + /** Cache for `explicitlyinheritsFrom`. */ + this.inheritsFromCache = ts.createMap(); + /** + * Type nodes can contain multiple references to the same type. For example: + * let x: Foo & (Foo & Bar) = ... + * Because we are returning the implementation locations and not the identifier locations, + * duplicate entries would be returned here as each of the type references is part of + * the same implementation. For that reason, check before we add a new entry. + */ + this.markSeenContainingTypeReference = ts.nodeSeenTracker(); + /** + * It's possible that we will encounter the right side of `export { foo as bar } from "x";` more than once. + * For example: + * // b.ts + * export { foo as bar } from "./a"; + * import { bar } from "./b"; + * + * Normally at `foo as bar` we directly add `foo` and do not locally search for it (since it doesn't declare a local). + * But another reference to it may appear in the same source file. + * See `tests/cases/fourslash/transitiveExportImports3.ts`. + */ + this.markSeenReExportRHS = ts.nodeSeenTracker(); + this.symbolIdToReferences = []; + // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. + this.sourceFileToSeenSymbols = []; } - function createSearch(location, symbol, comingFrom, searchOptions) { + /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ + State.prototype.getImportSearches = function (exportSymbol, exportInfo) { + if (!this.importTracker) + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + }; + /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ + State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; - var escapedText = ts.escapeIdentifier(text); - var parents = options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, checker); - return { location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, includes: includes }; - function includes(referenceSymbol) { - return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; - } - } - function referenceAdder(referenceSymbol, searchLocation) { - var symbolId = ts.getSymbolId(referenceSymbol); - var references = symbolIdToReferences[symbolId]; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.getDeclaredName(this.checker, symbol, location)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; + var escapedText = ts.escapeLeadingUnderscores(text); + var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); + return { + location: location, symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, + includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, + }; + }; + /** + * Callback to add references for a particular searched symbol. + * This initializes a reference group, so only call this if you will add at least one reference. + */ + State.prototype.referenceAdder = function (searchSymbol, searchLocation) { + var symbolId = ts.getSymbolId(searchSymbol); + var references = this.symbolIdToReferences[symbolId]; if (!references) { - references = symbolIdToReferences[symbolId] = []; - result.push({ definition: { type: "symbol", symbol: referenceSymbol, node: searchLocation }, references: references }); + references = this.symbolIdToReferences[symbolId] = []; + this.result.push({ definition: { type: "symbol", symbol: searchSymbol, node: searchLocation }, references: references }); } return function (node) { return references.push(FindAllReferences.nodeEntry(node)); }; - } - function addStringOrCommentReference(fileName, textSpan) { - result.push({ + }; + /** Add a reference with no associated definition. */ + State.prototype.addStringOrCommentReference = function (fileName, textSpan) { + this.result.push({ definition: undefined, references: [{ type: "span", fileName: fileName, textSpan: textSpan }] }); - } - function markSearchedSymbol(sourceFile, symbol) { + }; + /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ + State.prototype.markSearchedSymbol = function (sourceFile, symbol) { var sourceId = ts.getNodeId(sourceFile); var symbolId = ts.getSymbolId(symbol); - var seenSymbols = sourceFileToSeenSymbols[sourceId] || (sourceFileToSeenSymbols[sourceId] = []); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []); return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true); - } - } + }; + return State; + }()); /** Search for all imports of a given exported symbol using `State.getImportSearches`. */ function searchForImportsOfExport(exportLocation, exportSymbol, exportInfo, state) { var _a = state.getImportSearches(exportSymbol, exportInfo), importSearches = _a.importSearches, singleReferences = _a.singleReferences, indirectUsers = _a.indirectUsers; @@ -76554,7 +78995,7 @@ var ts; break; case 1 /* Default */: // Search for a property access to '.default'. This can't be renamed. - indirectSearch = state.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); + indirectSearch = state.options.isForRename ? undefined : state.createSearch(exportLocation, exportSymbol, 1 /* Export */, { text: "default" }); break; case 2 /* ExportEquals */: break; @@ -76584,15 +79025,17 @@ var ts; return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && checker.getPropertySymbolOfDestructuringAssignment(location); } - function isObjectBindingPatternElementWithoutPropertyName(symbol) { + function getObjectBindingElementWithoutPropertyName(symbol) { var bindingElement = ts.getDeclarationOfKind(symbol, 176 /* BindingElement */); - return bindingElement && + if (bindingElement && bindingElement.parent.kind === 174 /* ObjectBindingPattern */ && - !bindingElement.propertyName; + !bindingElement.propertyName) { + return bindingElement; + } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { - var bindingElement = ts.getDeclarationOfKind(symbol, 176 /* BindingElement */); + var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); + if (bindingElement) { var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } @@ -76618,14 +79061,16 @@ var ts; } // If this is private property or method, the scope is the containing class if (flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.find(declarations, function (d) { return !!(ts.getModifierFlags(d) & 8 /* Private */); }); + var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 229 /* ClassDeclaration */); } + // Else this is a public property and could be accessed from anywhere. + return undefined; } // If symbol is of object binding pattern element without property name we would want to // look for property too and that could be anywhere - if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { + if (getObjectBindingElementWithoutPropertyName(symbol)) { return undefined; } // If the symbol has a parent, it's globally visible. @@ -76634,10 +79079,6 @@ var ts; if (parent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } - // If this is a synthetic property, it's a property and must be searched for globally. - if ((flags & 134217728 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */)) { - return undefined; - } var scope; for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { var declaration = declarations_10[_i]; @@ -76661,11 +79102,8 @@ 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, container, fullStart) { + function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { 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. @@ -76676,10 +79114,10 @@ var ts; var text = sourceFile.text; var sourceLength = text.length; var symbolNameLength = symbolName.length; - var position = text.indexOf(symbolName, start); + var position = text.indexOf(symbolName, container.pos); while (position >= 0) { // If we are past the end, stop looking - if (position > end) + if (position > container.end) break; // We found a match. Make sure it's not part of a larger word (i.e. the char // before and after it have to be a non-identifier char). @@ -76700,7 +79138,7 @@ var ts; 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); + var node = ts.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 && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel))) { references.push(FindAllReferences.nodeEntry(node)); @@ -76712,7 +79150,7 @@ 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 ts.unescapeIdentifier(node.text).length === searchSymbolName.length; + return node.text.length === searchSymbolName.length; case 9 /* StringLiteral */: return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && node.text.length === searchSymbolName.length; @@ -76732,10 +79170,10 @@ var ts; return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } function addReferencesForKeywordInFile(sourceFile, kind, searchText, references) { - var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText); + var possiblePositions = getPossibleSymbolReferencePositions(sourceFile, searchText, sourceFile); for (var _i = 0, possiblePositions_2 = possiblePositions; _i < possiblePositions_2.length; _i++) { var position = possiblePositions_2[_i]; - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (referenceLocation.kind === kind) { references.push(FindAllReferences.nodeEntry(referenceLocation)); } @@ -76754,18 +79192,18 @@ var ts; if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } - for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container, /*fullStart*/ state.findInComments); _i < _a.length; _i++) { + for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; getReferencesAtLocation(sourceFile, position, search, state); } } function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); + var referenceLocation = ts.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 // match in a comment or string if that's what the caller is asking // for. - if (!state.implementations && (state.findInStrings && ts.isInString(sourceFile, position) || state.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { + if (!state.options.implementations && (state.options.findInStrings && ts.isInString(sourceFile, position) || state.options.findInComments && ts.isInNonReferenceComment(sourceFile, position))) { // In the case where we're looking inside comments/strings, we don't have // an actual definition. So just use 'undefined' here. Features like // 'Rename' won't care (as they ignore the definitions), and features like @@ -76820,7 +79258,7 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.isForRename && state.markSeenReExportRHS(name)) { + if (!state.options.isForRename && state.markSeenReExportRHS(name)) { addReference(name, referenceSymbol, name, state); } } @@ -76830,7 +79268,7 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.isForRename)) { + if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); ts.Debug.assert(!!exportInfo); @@ -76866,7 +79304,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.isForRename || importOrExport.isNamedImport) { + if (!state.options.isForRename || importOrExport.isNamedImport) { searchForImportedSymbol(symbol, state); } } @@ -76885,13 +79323,13 @@ var ts; * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the * position of property accessing, the referenceEntry of such position will be handled in the first case. */ - if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { + if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) { addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { var addRef = state.referenceAdder(relatedSymbol, searchLocation); - if (state.implementations) { + if (state.options.implementations) { addImplementationReferences(referenceLocation, addRef, state); } else { @@ -76925,7 +79363,7 @@ var ts; * Reference the constructor and all calls to `new this()`. */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor").declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); ts.Debug.assert(decl.kind === 152 /* Constructor */ && !!ctrKeyword); @@ -76948,7 +79386,7 @@ var ts; /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor"); + var ctr = symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } @@ -76992,15 +79430,16 @@ var ts; addReference(parent.initializer); } else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { - if (parent.body.kind === 207 /* Block */) { - ts.forEachReturnStatement(parent.body, function (returnStatement) { + var body = parent.body; + if (body.kind === 207 /* Block */) { + ts.forEachReturnStatement(body, function (returnStatement) { if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { addReference(returnStatement.expression); } }); } - else if (isImplementationExpression(parent.body)) { - addReference(parent.body); + else if (isImplementationExpression(body)) { + addReference(body); } } else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { @@ -77155,7 +79594,7 @@ var ts; 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); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || node.kind !== 97 /* SuperKeyword */) { continue; } @@ -77221,7 +79660,7 @@ var ts; }]; function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, result) { ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position); + var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (!node || !ts.isThis(node)) { return; } @@ -77271,7 +79710,7 @@ var ts; function getReferencesForStringLiteralInFile(sourceFile, searchText, possiblePositions, references) { for (var _i = 0, possiblePositions_4 = possiblePositions; _i < possiblePositions_4.length; _i++) { var position = possiblePositions_4[_i]; - var node_7 = ts.getTouchingWord(sourceFile, position); + var node_7 = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); if (node_7 && node_7.kind === 9 /* StringLiteral */ && node_7.text === searchText) { references.push(FindAllReferences.nodeEntry(node_7, /*isInString*/ true)); } @@ -77339,7 +79778,7 @@ var ts; } // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap(), checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); } } return result; @@ -77367,7 +79806,7 @@ var ts; // the function will add any found symbol of the property-name, then its sub-routine will call // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. - if (previousIterationSymbolsCache.has(symbol.name)) { + if (previousIterationSymbolsCache.has(symbol.escapedName)) { return; } if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -77391,7 +79830,7 @@ var ts; result.push.apply(result, checker.getRootSymbols(propertySymbol)); } // Visit the typeReference as well to see if it directly or indirectly use that property - previousIterationSymbolsCache.set(symbol.name, symbol); + previousIterationSymbolsCache.set(symbol.escapedName, symbol); getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); } } @@ -77444,7 +79883,7 @@ var ts; return undefined; } var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getName(), result, /*previousIterationSymbolsCache*/ ts.createMap(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), state.checker); return ts.find(result, search.includes); } return undefined; @@ -77459,7 +79898,7 @@ var ts; } return undefined; } - return node.name.text; + return ts.getTextOfIdentifierOrLiteral(node.name); } /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { @@ -77615,7 +80054,7 @@ var ts; if (referenceFile) { return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; } - return undefined; + // Might still be on jsdoc, so keep looking. } // Type reference directives var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); @@ -77624,15 +80063,15 @@ var ts; return referenceFile && referenceFile.resolvedFileName && [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } // Labels if (ts.isJumpStatementTarget(node)) { var labelName = node.text; - var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, ts.ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; + var label = ts.getTargetLabel(node.parent, labelName); + return label ? [createDefinitionInfoFromName(label, "label" /* label */, labelName, /*containerName*/ undefined)] : undefined; } var typeChecker = program.getTypeChecker(); var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); @@ -77649,7 +80088,7 @@ 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 */ && shouldSkipAlias(node, symbol.declarations[0])) { + if (symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { var aliased = typeChecker.getAliasedSymbol(symbol); if (aliased.declarations) { symbol = aliased; @@ -77691,7 +80130,7 @@ var ts; GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -77761,8 +80200,7 @@ var ts; for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { var declaration = _a[_i]; if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, - /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); + return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); } } ts.Debug.fail("Expected declaration to have at least one class-like declaration"); @@ -77848,7 +80286,7 @@ var ts; return { fileName: targetFileName, textSpan: ts.createTextSpanFromBounds(0, 0), - kind: ts.ScriptElementKind.scriptElement, + kind: "script" /* scriptElement */, name: name, containerName: undefined, containerKind: undefined @@ -77934,19 +80372,14 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - var comments = ts.getCommentsFromJSDoc(declaration); - if (!comments) { - return; - } - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var comment = comments_3[_i]; - if (comment) { + ts.forEach(ts.getAllJSDocs(declaration), function (doc) { + if (doc.comment) { if (documentationComment.length) { documentationComment.push(ts.lineBreakPart()); } - documentationComment.push(ts.textPart(comment)); + documentationComment.push(ts.textPart(doc.comment)); } - } + }); }); return documentationComment; } @@ -77955,20 +80388,10 @@ var ts; // Only collect doc comments from duplicate declarations once. var tags = []; forEachUnique(declarations, function (declaration) { - var jsDocs = ts.getJSDocs(declaration); - if (!jsDocs) { - return; - } - for (var _i = 0, jsDocs_1 = jsDocs; _i < jsDocs_1.length; _i++) { - var doc = jsDocs_1[_i]; - var tagsForDoc = doc.tags; - if (tagsForDoc) { - tags.push.apply(tags, tagsForDoc.filter(function (tag) { return tag.kind === 284 /* JSDocTag */; }).map(function (jsDocTag) { - return { - name: jsDocTag.tagName.text, - text: jsDocTag.comment - }; - })); + for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { + var tag = _a[_i]; + if (tag.kind === 276 /* JSDocTag */) { + tags.push({ name: tag.tagName.text, text: tag.comment }); } } }); @@ -77997,7 +80420,7 @@ var ts; return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword" /* keyword */, kindModifiers: "", sortText: "0", }; @@ -78008,13 +80431,34 @@ var ts; return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { name: "@" + tagName, - kind: ts.ScriptElementKind.keyword, + kind: "keyword" /* keyword */, kindModifiers: "", sortText: "0" }; })); } JsDoc.getJSDocTagCompletions = getJSDocTagCompletions; + function getJSDocParameterNameCompletions(tag) { + if (!ts.isIdentifier(tag.name)) { + return ts.emptyArray; + } + var nameThusFar = tag.name.text; + var jsdoc = tag.parent; + var fn = jsdoc.parent; + if (!ts.isFunctionLike(fn)) + return []; + return ts.mapDefined(fn.parameters, function (param) { + if (!ts.isIdentifier(param.name)) + return undefined; + var name = param.name.text; + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { + return undefined; + } + return { name: name, kind: "parameter" /* parameterElement */, kindModifiers: "", sortText: "0" }; + }); + } + JsDoc.getJSDocParameterNameCompletions = getJSDocParameterNameCompletions; /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. @@ -78040,7 +80484,7 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var tokenStart = tokenAtPos.getStart(); if (!tokenAtPos || tokenStart < position) { return undefined; @@ -78084,7 +80528,7 @@ var ts; for (var i = 0; i < parameters.length; i++) { var currentName = parameters[i].name; var paramName = currentName.kind === 71 /* Identifier */ ? - currentName.text : + currentName.escapedText : "param" + i; if (isJavaScriptFile) { docParams += indentationStr + " * @param {any} " + paramName + newLine; @@ -78161,10 +80605,6 @@ var ts; (function (ts) { var JsTyping; (function (JsTyping) { - // A map of loose file names to library names - // that we are confident require typings - var safeList; - var EmptySafeList = ts.createMap(); /* @internal */ JsTyping.nodeCoreModuleList = [ "buffer", "querystring", "events", "http", "cluster", @@ -78175,6 +80615,11 @@ var ts; "constants", "process", "v8", "timers", "console" ]; var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -78184,53 +80629,41 @@ var ts; * @param typeAcquisition is used to customize the typing acquisition process * @param compilerOptions are used as a source for typing inference */ - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { - // A typing name to typing file path mapping - var inferredTypings = ts.createMap(); + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 /* JS */ || kind === 2 /* JSX */; + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMapFromTemplate(result.config) : EmptySafeList; - } var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - var searchDirs = []; - var exclude = []; - mergeTypings(typeAcquisition.include); - exclude = typeAcquisition.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { var packageJsonPath = ts.combinePaths(searchDir, "package.json"); getTypingNamesFromJson(packageJsonPath, filesToWatch); var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); getTypingNamesFromJson(bowerJsonPath, filesToWatch); var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath); - } + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); getTypingNamesFromSourceFileNames(fileNames); // add typings for unresolved imports if (unresolvedImports) { - for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { - var moduleId = unresolvedImports_1[_a]; - var typingName = nodeCoreModules.has(moduleId) ? "node" : moduleId; - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } + var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + addInferredTypings(module, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach(function (typingLocation, name) { @@ -78239,9 +80672,11 @@ var ts; } }); // Remove typings that the user has added to the exclude list - for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { - var excludeTypingName = exclude_1[_b]; - inferredTypings.delete(excludeTypingName); + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); } var newTypingNames = []; var cachedTypingPaths = []; @@ -78253,44 +80688,31 @@ var ts; newTypingNames.push(typing); } }); - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - /** - * Merge a given list of typingNames to the inferredTypings map - */ - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!inferredTypings.has(typing)) { - inferredTypings.set(typing, undefined); - } + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); } } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } /** * Get the typing info from common package manager json files like package.json or bower.json */ function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (host.fileExists(jsonPath)) { - filesToWatch.push(jsonPath); - } - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } + if (!host.fileExists(jsonPath)) { + return; } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); } /** * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" @@ -78299,29 +80721,38 @@ var ts; * @param fileNames are the names for source files in the project */ function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return safeList.has(f); })); + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); if (hasJsxFile) { - mergeTypings(["react"]); + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); } } /** * Infer typing names from packages folder (ex: node_module, bower_components) * @param packagesFolderPath is the path to the packages folder */ - function getTypingNamesFromPackagesFolder(packagesFolderPath) { + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { filesToWatch.push(packagesFolderPath); // Todo: add support for ModuleResolutionHost too if (!host.directoryExists(packagesFolderPath)) { return; } - var typingNames = []; + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` var fileNames = host.readDirectory(packagesFolderPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -78329,11 +80760,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; + var result_8 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_8.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -78346,15 +80774,18 @@ var ts; if (!packageJson.name) { continue; } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); inferredTypings.set(packageJson.name, absolutePath); } else { - typingNames.push(packageJson.name); + packageNames.push(packageJson.name); } } - mergeTypings(typingNames); + addInferredTypings(packageNames, " Found package names"); } } JsTyping.discoverTypings = discoverTypings; @@ -78368,9 +80799,9 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_6 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; } ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { @@ -78405,7 +80836,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_6(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. rawItems = ts.filter(rawItems, function (item) { @@ -78413,7 +80844,7 @@ var ts; if (decl.kind === 239 /* ImportClause */ || decl.kind === 242 /* ImportSpecifier */ || decl.kind === 237 /* ImportEqualsDeclaration */) { var importer = checker.getSymbolAtLocation(decl.name); var imported = checker.getAliasedSymbol(importer); - return importer.name !== imported.name; + return importer.escapedName !== imported.escapedName; } else { return true; @@ -78436,21 +80867,11 @@ var ts; } return true; } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - node.kind === 8 /* NumericLiteral */) { - return node.text; - } - } - return undefined; - } function tryAddSingleDeclarationName(declaration, containers) { if (declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var text = getTextOfIdentifierOrLiteral(name); + var text = ts.getTextOfIdentifierOrLiteral(name); if (text !== undefined) { containers.unshift(text); } @@ -78469,7 +80890,7 @@ var ts; // // [X.Y.Z]() { } function tryAddComputedPropertyName(expression, containers, includeLastPortion) { - var text = getTextOfIdentifierOrLiteral(expression); + var text = ts.getTextOfIdentifierOrLiteral(expression); if (text !== undefined) { if (includeLastPortion) { containers.unshift(text); @@ -78540,7 +80961,7 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ }; } } @@ -78780,7 +81201,7 @@ var ts; default: ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 290 /* JSDocTypedefTag */) { + if (tag.kind === 283 /* JSDocTypedefTag */) { addLeafNode(tag); } }); @@ -78884,14 +81305,14 @@ var ts; } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.getPropertyNameForPropertyNameNode(declName); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); } switch (node.kind) { case 186 /* FunctionExpression */: case 187 /* ArrowFunction */: case 199 /* ClassExpression */: return getFunctionOrClassName(node); - case 290 /* JSDocTypedefTag */: + case 283 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return undefined; @@ -78934,7 +81355,7 @@ var ts; return "()"; case 157 /* IndexSignature */: return "[]"; - case 290 /* JSDocTypedefTag */: + case 283 /* JSDocTypedefTag */: return getJSDocTypedefTagName(node); default: return ""; @@ -78982,7 +81403,7 @@ var ts; case 233 /* ModuleDeclaration */: case 265 /* SourceFile */: case 231 /* TypeAliasDeclaration */: - case 290 /* JSDocTypedefTag */: + case 283 /* JSDocTypedefTag */: return true; case 152 /* Constructor */: case 151 /* MethodDeclaration */: @@ -79069,10 +81490,10 @@ var ts; } // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); while (moduleDeclaration.body && moduleDeclaration.body.kind === 233 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; - result.push(moduleDeclaration.name.text); + result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } return result.join("."); } @@ -79137,7 +81558,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), hintSpan: ts.createTextSpanFromNode(hintSpanNode, sourceFile), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_13); } @@ -79148,7 +81569,7 @@ var ts; textSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), hintSpan: ts.createTextSpanFromBounds(commentSpan.pos, commentSpan.end), bannerText: collapseText, - autoCollapse: autoCollapse + autoCollapse: autoCollapse, }; elements.push(span_14); } @@ -79160,8 +81581,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0, comments_4 = comments; _i < comments_4.length; _i++) { - var currentComment = comments_4[_i]; + for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { + var currentComment = comments_3[_i]; cancellationToken.throwIfCancellationRequested(); // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last @@ -79891,13 +82312,9 @@ var ts; }); } function getFileReference() { - var file = ts.scanner.getTokenValue(); + var fileName = ts.scanner.getTokenValue(); var pos = ts.scanner.getTokenPos(); - return { - fileName: file, - pos: pos, - end: pos + file.length - }; + return { fileName: fileName, pos: pos, end: pos + fileName.length }; } function recordAmbientExternalModule() { if (!ambientExternalModules) { @@ -79939,7 +82356,15 @@ var ts; var token = ts.scanner.getToken(); if (token === 91 /* ImportKeyword */) { token = nextToken(); - if (token === 9 /* StringLiteral */) { + if (token === 19 /* OpenParenToken */) { + token = nextToken(); + if (token === 9 /* StringLiteral */) { + // import("mod"); + recordModuleName(); + return true; + } + } + else if (token === 9 /* StringLiteral */) { // import "mod"; recordModuleName(); return true; @@ -80123,7 +82548,7 @@ var ts; // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); - // + // import("mod"); // export * from "mod" // export {a as b} from "mod" // export import i = require("mod") @@ -80230,7 +82655,7 @@ var ts; return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } var displayName = ts.stripQuotes(node.text); - return getRenameInfoSuccess(displayName, displayName, ts.ScriptElementKind.variableElement, ts.ScriptElementKindModifier.none, node, sourceFile); + return getRenameInfoSuccess(displayName, displayName, "var" /* variableElement */, "" /* none */, node, sourceFile); } } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { @@ -80279,7 +82704,6 @@ var ts; (function (ts) { var SignatureHelp; (function (SignatureHelp) { - var emptyArray = []; var ArgumentListKind; (function (ArgumentListKind) { ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; @@ -80296,14 +82720,13 @@ var ts; return undefined; } var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); + if (!argumentInfo) + return undefined; cancellationToken.throwIfCancellationRequested(); // Semantic filtering of signature help - if (!argumentInfo) { - return undefined; - } var call = argumentInfo.invocation; var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates); + var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); cancellationToken.throwIfCancellationRequested(); if (!candidates.length) { // We didn't have any sig help items produced by the TS compiler. If this is a JS @@ -80328,7 +82751,7 @@ var ts; : expression.kind === 179 /* PropertyAccessExpression */ ? expression.name : undefined; - if (!name || !name.text) { + if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); @@ -80359,7 +82782,9 @@ var ts; */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { if (ts.isCallOrNewExpression(node.parent)) { - var callExpression = node.parent; + var invocation = node.parent; + var list = void 0; + var argumentIndex = void 0; // There are 3 cases to handle: // 1. The token introduces a list, and should begin a signature help session // 2. The token is either not associated with a list, or ends a list, so the session should end @@ -80374,43 +82799,30 @@ var ts; // Case 3: // foo(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - if (node.kind === 27 /* LessThanToken */ || - node.kind === 19 /* OpenParenToken */) { + if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - var list = getChildListThatStartsWithOpenerToken(callExpression, node, sourceFile); - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; + list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); ts.Debug.assert(list !== undefined); - return { - kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: 0, - argumentCount: getArgumentCount(list) - }; + argumentIndex = 0; } - // findListItemInfo can return undefined if we are not in parent's argument list - // or type argument list. This includes cases where the cursor is: - // - To the right of the closing parenthesis, non-substitution template, or template tail. - // - Between the type arguments and the arguments (greater than token) - // - On the target of the call (parent.func) - // - On the 'new' keyword in a 'new' expression - var listItemInfo = ts.findListItemInfo(node); - if (listItemInfo) { - var list = listItemInfo.list; - var isTypeArgList = callExpression.typeArguments && callExpression.typeArguments.pos === list.pos; - var argumentIndex = getArgumentIndex(list, node); - var argumentCount = getArgumentCount(list); - ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - kind: isTypeArgList ? 0 /* TypeArguments */ : 1 /* CallArguments */, - invocation: callExpression, - argumentsSpan: getApplicableSpanForArguments(list, sourceFile), - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + else { + // findListItemInfo can return undefined if we are not in parent's argument list + // or type argument list. This includes cases where the cursor is: + // - To the right of the closing parenthesis, non-substitution template, or template tail. + // - Between the type arguments and the arguments (greater than token) + // - On the target of the call (parent.func) + // - On the 'new' keyword in a 'new' expression + list = ts.findContainingList(node); + if (!list) + return undefined; + argumentIndex = getArgumentIndex(list, node); } - return undefined; + var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; + var argumentCount = getArgumentCount(list); + ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); + var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); + return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 183 /* TaggedTemplateExpression */) { // Check if we're actually inside the template; @@ -80598,33 +83010,9 @@ var ts; ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } - /** - * The selectedItemIndex could be negative for several reasons. - * 1. There are too many arguments for all of the overloads - * 2. None of the overloads were type compatible - * The solution here is to try to pick the best overload by picking - * either the first one that has an appropriate number of parameters, - * or the one with the most parameters. - */ - function selectBestInvalidOverloadIndex(candidates, argumentCount) { - var maxParamsSignatureIndex = -1; - var maxParams = -1; - for (var i = 0; i < candidates.length; i++) { - var candidate = candidates[i]; - if (candidate.hasRestParameter || candidate.parameters.length >= argumentCount) { - return i; - } - if (candidate.parameters.length > maxParams) { - maxParams = candidate.parameters.length; - maxParamsSignatureIndex = i; - } - } - return maxParamsSignatureIndex; - } - function createSignatureHelpItems(candidates, bestSignature, argumentListInfo, typeChecker) { - var applicableSpan = argumentListInfo.argumentsSpan; + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var invocation = argumentListInfo.invocation; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); @@ -80639,8 +83027,9 @@ var ts; if (isTypeParameterList) { isVariadic = false; // type parameter lists are not variadic prefixDisplayParts.push(ts.punctuationPart(27 /* LessThanToken */)); - var typeParameters = candidateSignature.typeParameters; - signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray; + // Use `.mapper` to ensure we get the generic type arguments even if this is an instantiated version of the signature. + var typeParameters = candidateSignature.mapper ? candidateSignature.mapper.mappedTypes : candidateSignature.typeParameters; + signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); @@ -80654,8 +83043,7 @@ var ts; }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); - var parameters = candidateSignature.parameters; - signatureHelpParameters = parameters.length > 0 ? ts.map(parameters, createSignatureHelpParameterForParameter) : emptyArray; + signatureHelpParameters = ts.map(candidateSignature.parameters, createSignatureHelpParameterForParameter); suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { @@ -80672,21 +83060,10 @@ var ts; tags: candidateSignature.getJsDocTags() }; }); - var argumentIndex = argumentListInfo.argumentIndex; - // argumentCount is the *apparent* number of arguments. - var argumentCount = argumentListInfo.argumentCount; - var selectedItemIndex = candidates.indexOf(bestSignature); - if (selectedItemIndex < 0) { - selectedItemIndex = selectBestInvalidOverloadIndex(candidates, argumentCount); - } ts.Debug.assert(argumentIndex === 0 || argumentIndex < argumentCount, "argumentCount < argumentIndex, " + argumentCount + " < " + argumentIndex); - return { - items: items, - applicableSpan: applicableSpan, - selectedItemIndex: selectedItemIndex, - argumentIndex: argumentIndex, - argumentCount: argumentCount - }; + var selectedItemIndex = candidates.indexOf(resolvedSignature); + ts.Debug.assert(selectedItemIndex !== -1); // If candidates is non-empty it should always include bestSignature. We check for an empty candidates before calling this function. + return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); @@ -80704,7 +83081,7 @@ var ts; }); return { name: typeParameter.symbol.name, - documentation: emptyArray, + documentation: ts.emptyArray, displayParts: displayParts, isOptional: false }; @@ -80719,72 +83096,73 @@ var ts; (function (SymbolDisplay) { // TODO(drosen): use contextual SemanticMeaning. function getSymbolKind(typeChecker, symbol, location) { - var flags = symbol.flags; - if (flags & 32 /* Class */) + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + if (flags & 32 /* Class */) { return ts.getDeclarationOfKind(symbol, 199 /* ClassExpression */) ? - ts.ScriptElementKind.localClassElement : ts.ScriptElementKind.classElement; + "local class" /* localClassElement */ : "class" /* classElement */; + } if (flags & 384 /* Enum */) - return ts.ScriptElementKind.enumElement; + return "enum" /* enumElement */; if (flags & 524288 /* TypeAlias */) - return ts.ScriptElementKind.typeElement; + return "type" /* typeElement */; if (flags & 64 /* Interface */) - return ts.ScriptElementKind.interfaceElement; + return "interface" /* interfaceElement */; if (flags & 262144 /* TypeParameter */) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter" /* typeParameterElement */; var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - if (result === ts.ScriptElementKind.unknown) { + if (result === "" /* unknown */) { if (flags & 262144 /* TypeParameter */) - return ts.ScriptElementKind.typeParameterElement; + return "type parameter" /* typeParameterElement */; if (flags & 8 /* EnumMember */) - return ts.ScriptElementKind.enumMemberElement; - if (flags & 8388608 /* Alias */) - return ts.ScriptElementKind.alias; + return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) + return "alias" /* alias */; if (flags & 1536 /* Module */) - return ts.ScriptElementKind.moduleElement; + return "module" /* moduleElement */; } return result; } SymbolDisplay.getSymbolKind = getSymbolKind; function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { if (typeChecker.isUndefinedSymbol(symbol)) { - return ts.ScriptElementKind.variableElement; + return "var" /* variableElement */; } if (typeChecker.isArgumentsSymbol(symbol)) { - return ts.ScriptElementKind.localVariableElement; + return "local var" /* localVariableElement */; } if (location.kind === 99 /* ThisKeyword */ && ts.isExpression(location)) { - return ts.ScriptElementKind.parameterElement; + return "parameter" /* parameterElement */; } - var flags = symbol.flags; + var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 3 /* Variable */) { if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { - return ts.ScriptElementKind.parameterElement; + return "parameter" /* parameterElement */; } else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { - return ts.ScriptElementKind.constElement; + return "const" /* constElement */; } else if (ts.forEach(symbol.declarations, ts.isLet)) { - return ts.ScriptElementKind.letElement; + return "let" /* letElement */; } - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localVariableElement : ts.ScriptElementKind.variableElement; + return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; } if (flags & 16 /* Function */) - return isLocalVariableOrFunction(symbol) ? ts.ScriptElementKind.localFunctionElement : ts.ScriptElementKind.functionElement; + return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; if (flags & 32768 /* GetAccessor */) - return ts.ScriptElementKind.memberGetAccessorElement; + return "getter" /* memberGetAccessorElement */; if (flags & 65536 /* SetAccessor */) - return ts.ScriptElementKind.memberSetAccessorElement; + return "setter" /* memberSetAccessorElement */; if (flags & 8192 /* Method */) - return ts.ScriptElementKind.memberFunctionElement; + return "method" /* memberFunctionElement */; if (flags & 16384 /* Constructor */) - return ts.ScriptElementKind.constructorImplementationElement; + return "constructor" /* constructorImplementationElement */; if (flags & 4 /* Property */) { - if (flags & 134217728 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { + if (flags & 33554432 /* Transient */ && symbol.checkFlags & 6 /* Synthetic */) { // If union property is result of union of non method (property/accessors/variables), it is labeled as property var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (98308 /* PropertyOrAccessor */ | 3 /* Variable */)) { - return ts.ScriptElementKind.memberVariableElement; + return "property" /* memberVariableElement */; } ts.Debug.assert(!!(rootSymbolFlags & 8192 /* Method */)); }); @@ -80793,23 +83171,23 @@ var ts; // make sure it has call signatures before we can label it as method var typeOfUnionProperty = typeChecker.getTypeOfSymbolAtLocation(symbol, location); if (typeOfUnionProperty.getCallSignatures().length) { - return ts.ScriptElementKind.memberFunctionElement; + return "method" /* memberFunctionElement */; } - return ts.ScriptElementKind.memberVariableElement; + return "property" /* memberVariableElement */; } return unionPropertyKind; } if (location.parent && ts.isJsxAttribute(location.parent)) { - return ts.ScriptElementKind.jsxAttribute; + return "JSX attribute" /* jsxAttribute */; } - return ts.ScriptElementKind.memberVariableElement; + return "property" /* memberVariableElement */; } - return ts.ScriptElementKind.unknown; + return "" /* unknown */; } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) - : ts.ScriptElementKindModifier.none; + : "" /* none */; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location @@ -80818,19 +83196,19 @@ var ts; var displayParts = []; var documentation; var tags; - var symbolFlags = symbol.flags; + var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; // Class at constructor site need to be shown as constructor apart from property,method, vars - if (symbolKind !== ts.ScriptElementKind.unknown || symbolFlags & 32 /* Class */ || symbolFlags & 8388608 /* Alias */) { + if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor - if (symbolKind === ts.ScriptElementKind.memberGetAccessorElement || symbolKind === ts.ScriptElementKind.memberSetAccessorElement) { - symbolKind = ts.ScriptElementKind.memberVariableElement; + if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { + symbolKind = "property" /* memberVariableElement */; } var signature = void 0; - type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); + type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); if (type) { if (location.parent && location.parent.kind === 179 /* PropertyAccessExpression */) { var right = location.parent.name; @@ -80867,11 +83245,11 @@ var ts; if (signature) { if (useConstructSignatures && (symbolFlags & 32 /* Class */)) { // Constructor - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } - else if (symbolFlags & 8388608 /* Alias */) { - symbolKind = ts.ScriptElementKind.alias; + else if (symbolFlags & 2097152 /* Alias */) { + symbolKind = "alias" /* alias */; pushTypePart(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { @@ -80884,13 +83262,13 @@ var ts; addPrefixForAnyFunctionOrVar(symbol, symbolKind); } switch (symbolKind) { - case ts.ScriptElementKind.jsxAttribute: - case ts.ScriptElementKind.memberVariableElement: - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.parameterElement: - case ts.ScriptElementKind.localVariableElement: + case "JSX attribute" /* jsxAttribute */: + case "property" /* memberVariableElement */: + case "var" /* variableElement */: + case "const" /* constElement */: + case "let" /* letElement */: + case "parameter" /* parameterElement */: + case "local var" /* localVariableElement */: // If it is call or construct signature of lambda's write type name displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); @@ -80901,7 +83279,7 @@ var ts; if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); } - addSignatureDisplayParts(signature, allSignatures, 8 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -80910,7 +83288,7 @@ var ts; hasAddedSymbolInfo = true; } } - else if ((ts.isNameOfFunctionDeclaration(location) && !(symbol.flags & 98304 /* Accessor */)) || + else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 152 /* Constructor */)) { // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; @@ -80928,7 +83306,7 @@ var ts; } if (functionDeclaration_1.kind === 152 /* Constructor */) { // show (constructor) Type(...) signature - symbolKind = ts.ScriptElementKind.constructorImplementationElement; + symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { @@ -80947,7 +83325,7 @@ var ts; // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class - pushTypePart(ts.ScriptElementKind.localClassElement); + pushTypePart("local class" /* localClassElement */); } else { // Class declaration has name which is not local. @@ -80973,7 +83351,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 512 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); @@ -81022,7 +83400,7 @@ var ts; else if (declaration.kind !== 155 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 231 /* TypeAliasDeclaration */) { // Type alias type parameter @@ -81038,7 +83416,7 @@ var ts; } } if (symbolFlags & 8 /* EnumMember */) { - symbolKind = ts.ScriptElementKind.enumMemberElement; + symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; if (declaration.kind === 264 /* EnumMember */) { @@ -81051,7 +83429,7 @@ var ts; } } } - if (symbolFlags & 8388608 /* Alias */) { + if (symbolFlags & 2097152 /* Alias */) { addNewLineIfDisplayPartsExist(); if (symbol.declarations[0].kind === 236 /* NamespaceExportDeclaration */) { displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -81089,7 +83467,7 @@ var ts; }); } if (!hasAddedSymbolInfo) { - if (symbolKind !== ts.ScriptElementKind.unknown) { + if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { addNewLineIfDisplayPartsExist(); @@ -81099,10 +83477,10 @@ var ts; addPrefixForAnyFunctionOrVar(symbol, symbolKind); } // For properties, variables and local vars: show the type - if (symbolKind === ts.ScriptElementKind.memberVariableElement || - symbolKind === ts.ScriptElementKind.jsxAttribute || + if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || - symbolKind === ts.ScriptElementKind.localVariableElement || + symbolKind === "local var" /* localVariableElement */ || isThisExpression) { displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); @@ -81122,7 +83500,7 @@ var ts; symbolFlags & 16384 /* Constructor */ || symbolFlags & 131072 /* Signature */ || symbolFlags & 98304 /* Accessor */ || - symbolKind === ts.ScriptElementKind.memberFunctionElement) { + symbolKind === "method" /* memberFunctionElement */) { var allSignatures = type.getNonNullableType().getCallSignatures(); addSignatureDisplayParts(allSignatures[0], allSignatures); } @@ -81135,7 +83513,7 @@ var ts; if (!documentation) { documentation = symbol.getDocumentationComment(); tags = symbol.getJsDocTags(); - if (documentation.length === 0 && symbol.flags & 4 /* Property */) { + if (documentation.length === 0 && symbolFlags & 4 /* Property */) { // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. @@ -81183,11 +83561,11 @@ var ts; } function pushTypePart(symbolKind) { switch (symbolKind) { - case ts.ScriptElementKind.variableElement: - case ts.ScriptElementKind.functionElement: - case ts.ScriptElementKind.letElement: - case ts.ScriptElementKind.constElement: - case ts.ScriptElementKind.constructorImplementationElement: + case "var" /* variableElement */: + case "function" /* functionElement */: + case "let" /* letElement */: + case "const" /* constElement */: + case "constructor" /* constructorImplementationElement */: displayParts.push(ts.textOrKeywordPart(symbolKind)); return; default: @@ -81198,7 +83576,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -81345,8 +83723,8 @@ var ts; commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || ts.filter(ts.optionDeclarations, function (o) { return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); - options = ts.clone(options); - var _loop_5 = function (opt) { + options = ts.cloneCompilerOptions(options); + var _loop_7 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -81365,7 +83743,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_7(opt); } return options; } @@ -81589,11 +83967,7 @@ var ts; break; } } - lastTokenInfo = { - leadingTrivia: leadingTrivia, - trailingTrivia: trailingTrivia, - token: token - }; + lastTokenInfo = { leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, token: token }; return fixTokenKind(lastTokenInfo, n); } function isOnToken() { @@ -81719,7 +84093,8 @@ var ts; FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; - FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnOpeningCurlyBrace"] = 4] = "FormatOnOpeningCurlyBrace"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 5] = "FormatOnClosingCurlyBrace"; })(FormattingRequestKind = formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81861,9 +84236,9 @@ var ts; } return true; }; + RuleOperationContext.Any = new RuleOperationContext(); return RuleOperationContext; }()); - RuleOperationContext.Any = new RuleOperationContext(); formatting.RuleOperationContext = RuleOperationContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -81903,13 +84278,13 @@ var ts; this.NoSpaceAfterCloseBracket = new formatting.Rule(formatting.RuleDescriptor.create3(22 /* CloseBracketToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsNonJsxSameLineTokenContext, Rules.IsNotBeforeBlockInFunctionDeclarationContext), 8 /* Delete */)); // Place a space before open brace in a function declaration this.FunctionOpenBraceLeftTokenRange = formatting.Shared.TokenRange.AnyIncludingMultilineComments; - this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInFunction = new formatting.Rule(formatting.RuleDescriptor.create2(this.FunctionOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsFunctionDeclContext, Rules.IsBeforeBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a TypeScript declaration that has braces as children (class, module, enum, etc) this.TypeScriptOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([71 /* Identifier */, 3 /* MultiLineCommentTrivia */, 75 /* ClassKeyword */, 84 /* ExportKeyword */, 91 /* ImportKeyword */]); - this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInTypeScriptDeclWithBlock = new formatting.Rule(formatting.RuleDescriptor.create2(this.TypeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForFunctions"), Rules.IsTypeScriptDeclWithBlockContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Place a space before open brace in a control flow construct this.ControlOpenBraceLeftTokenRange = formatting.Shared.TokenRange.FromTokens([20 /* CloseParenToken */, 3 /* MultiLineCommentTrivia */, 81 /* DoKeyword */, 102 /* TryKeyword */, 87 /* FinallyKeyword */, 82 /* ElseKeyword */]); - this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeMultilineBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); + this.SpaceBeforeOpenBraceInControl = new formatting.Rule(formatting.RuleDescriptor.create2(this.ControlOpenBraceLeftTokenRange, 17 /* OpenBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine("placeOpenBraceOnNewLineForControlBlocks"), Rules.IsControlDeclContext, Rules.IsNotFormatOnEnter, Rules.IsSameLineTokenOrBeforeBlockContext), 2 /* Space */), 1 /* CanDeleteNewLines */); // Insert a space after { and before } in single-line contexts, but remove space from empty object literals {}. this.SpaceAfterOpenBrace = new formatting.Rule(formatting.RuleDescriptor.create3(17 /* OpenBraceToken */, formatting.Shared.TokenRange.Any), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); this.SpaceBeforeCloseBrace = new formatting.Rule(formatting.RuleDescriptor.create2(formatting.Shared.TokenRange.Any, 18 /* CloseBraceToken */), formatting.RuleOperation.create2(new formatting.RuleOperationContext(Rules.IsOptionEnabledOrUndefined("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces"), Rules.IsBraceWrappedContext), 2 /* Space */)); @@ -82155,6 +84530,9 @@ var ts; Rules.IsOptionDisabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName]; }; }; + Rules.isOptionDisabledOrUndefinedOrTokensOnSameLine = function (optionName) { + return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !context.options[optionName] || context.TokensAreOnSameLine(); }; + }; Rules.IsOptionEnabledOrUndefined = function (optionName) { return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; }; @@ -82206,24 +84584,8 @@ var ts; Rules.IsConditionalOperatorContext = function (context) { return context.contextNode.kind === 195 /* ConditionalExpression */; }; - Rules.IsSameLineTokenOrBeforeMultilineBlockContext = function (context) { - //// This check is mainly used inside SpaceBeforeOpenBraceInControl and SpaceBeforeOpenBraceInFunction. - //// - //// Ex: - //// if (1) { .... - //// * ) and { are on the same line so apply the rule. Here we don't care whether it's same or multi block context - //// - //// Ex: - //// if (1) - //// { ... } - //// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we don't format. - //// - //// Ex: - //// if (1) - //// { ... - //// } - //// * ) and { are on different lines. We only need to format if the block is multiline context. So in this case we format. - return context.TokensAreOnSameLine() || Rules.IsBeforeMultilineBlockContext(context); + Rules.IsSameLineTokenOrBeforeBlockContext = function (context) { + return context.TokensAreOnSameLine() || Rules.IsBeforeBlockContext(context); }; Rules.IsBraceWrappedContext = function (context) { return context.contextNode.kind === 174 /* ObjectBindingPattern */ || Rules.IsSingleLineBlockContext(context); @@ -82275,7 +84637,7 @@ var ts; // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 230 /* InterfaceDeclaration */: + case 230 /* InterfaceDeclaration */:// This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; @@ -82828,11 +85190,39 @@ var ts; } formatting.formatOnEnter = formatOnEnter; function formatOnSemicolon(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 25 /* SemicolonToken */, sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); + var semicolon = findImmediatelyPrecedingTokenOfKind(position, 25 /* SemicolonToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, options, rulesProvider, 3 /* FormatOnSemicolon */); } formatting.formatOnSemicolon = formatOnSemicolon; + function formatOnOpeningCurly(position, sourceFile, rulesProvider, options) { + var openingCurly = findImmediatelyPrecedingTokenOfKind(position, 17 /* OpenBraceToken */, sourceFile); + if (!openingCurly) { + return []; + } + var curlyBraceRange = openingCurly.parent; + var outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange); + /** + * We limit the span to end at the opening curly to handle the case where + * the brace matched to that just typed will be incorrect after further edits. + * For example, we could type the opening curly for the following method + * body without brace-matching activated: + * ``` + * class C { + * foo() + * } + * ``` + * and we wouldn't want to move the closing brace. + */ + var textRange = { + pos: ts.getLineStartPositionForPosition(outermostNode.getStart(sourceFile), sourceFile), + end: position + }; + return formatSpan(textRange, sourceFile, options, rulesProvider, 4 /* FormatOnOpeningCurlyBrace */); + } + formatting.formatOnOpeningCurly = formatOnOpeningCurly; function formatOnClosingCurly(position, sourceFile, rulesProvider, options) { - return formatOutermostParent(position, 18 /* CloseBraceToken */, sourceFile, options, rulesProvider, 4 /* FormatOnClosingCurlyBrace */); + var precedingToken = findImmediatelyPrecedingTokenOfKind(position, 18 /* CloseBraceToken */, sourceFile); + return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, options, rulesProvider, 5 /* FormatOnClosingCurlyBrace */); } formatting.formatOnClosingCurly = formatOnClosingCurly; function formatDocument(sourceFile, rulesProvider, options) { @@ -82847,46 +85237,39 @@ var ts; // format from the beginning of the line var span = { pos: ts.getLineStartPositionForPosition(start, sourceFile), - end: end + end: end, }; return formatSpan(span, sourceFile, options, rulesProvider, 1 /* FormatSelection */); } formatting.formatSelection = formatSelection; - function formatOutermostParent(position, expectedLastToken, sourceFile, options, rulesProvider, requestKind) { - var parent = findOutermostParent(position, expectedLastToken, sourceFile); - if (!parent) { - return []; - } - var span = { - pos: ts.getLineStartPositionForPosition(parent.getStart(sourceFile), sourceFile), - end: parent.end - }; - return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + /** + * Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment). + * @param expectedTokenKind The kind of the last token constituting the desired parent node. + */ + function findImmediatelyPrecedingTokenOfKind(end, expectedTokenKind, sourceFile) { + var precedingToken = ts.findPrecedingToken(end, sourceFile); + return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ? + precedingToken : + undefined; } - function findOutermostParent(position, expectedTokenKind, sourceFile) { - var precedingToken = ts.findPrecedingToken(position, sourceFile); - // when it is claimed that trigger character was typed at given position - // we verify that there is a token with a matching kind whose end is equal to position (because the character was just typed). - // If this condition is not hold - then trigger character was typed in some other context, - // i.e.in comment and thus should not trigger autoformatting - if (!precedingToken || - precedingToken.kind !== expectedTokenKind || - position !== precedingToken.getEnd()) { - return undefined; - } - // walk up and search for the parent node that ends at the same position with precedingToken. - // for cases like this - // - // let x = 1; - // while (true) { - // } - // after typing close curly in while statement we want to reformat just the while statement. - // However if we just walk upwards searching for the parent that has the same end value - - // we'll end up with the whole source file. isListElement allows to stop on the list element level - var current = precedingToken; + /** + * Finds the highest node enclosing `node` at the same list level as `node` + * and whose end does not exceed `node.end`. + * + * Consider typing the following + * ``` + * let x = 1; + * while (true) { + * } + * ``` + * Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding + * variable declaration. + */ + function findOutermostNodeWithinListLevel(node) { + var current = node; while (current && current.parent && - current.parent.end === precedingToken.end && + current.parent.end === node.end && !isListElement(current.parent, current)) { current = current.parent; } @@ -83020,12 +85403,22 @@ var ts; return 0; } /* @internal */ - function formatNode(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { + function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, rulesProvider) { var range = { pos: 0, end: sourceFileLike.text.length }; return formatSpanWorker(range, node, initialIndentation, delta, formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end), rulesProvider.getFormatOptions(), rulesProvider, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors sourceFileLike); } - formatting.formatNode = formatNode; + formatting.formatNodeGivenIndentation = formatNodeGivenIndentation; + function formatNodeLines(node, sourceFile, options, rulesProvider, requestKind) { + if (!node) { + return []; + } + var span = { + pos: ts.getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile), + end: node.end + }; + return formatSpan(span, sourceFile, options, rulesProvider, requestKind); + } function formatSpan(originalRange, sourceFile, options, rulesProvider, requestKind) { // find the smallest node that fully wraps the range and compute the initial indentation for the node var enclosingNode = findEnclosingNode(originalRange, sourceFile); @@ -83626,7 +86019,7 @@ var ts; if (rule.Flag !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { return; } - // edit should not be applied only if we have one line feed between elements + // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); @@ -84342,7 +86735,7 @@ var ts; return this; } if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end); + var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(node, nextToken)) { // find first non-whitespace position in the leading trivia of the node var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -84354,7 +86747,7 @@ var ts; } } else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end); + var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); if (previousToken && isSeparator(node, previousToken)) { this.deleteNodeRange(sourceFile, previousToken, node); } @@ -84431,7 +86824,7 @@ var ts; if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - var nextToken = ts.getTokenAtPosition(sourceFile, after.end); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -84550,7 +86943,7 @@ var ts; }; ChangeTracker.prototype.getChanges = function () { var _this = this; - var changesPerFile = ts.createFileMap(); + var changesPerFile = ts.createMap(); // group changes per file for (var _i = 0, _a = this.changes; _i < _a.length; _i++) { var c = _a[_i]; @@ -84562,8 +86955,7 @@ var ts; } // convert changes var fileChangesList = []; - changesPerFile.forEachValue(function (path) { - var changesInFile = changesPerFile.get(path); + changesPerFile.forEach(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; var fileTextChanges = { fileName: sourceFile.fileName, textChanges: [] }; for (var _i = 0, _a = ChangeTracker.normalize(changesInFile); _i < _a.length; _i++) { @@ -84636,7 +87028,7 @@ var ts; lineMap: lineMap, getLineAndCharacterOfPosition: function (pos) { return ts.computeLineAndCharacterOfPosition(lineMap, pos); } }; - var changes = ts.formatting.formatNode(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); + var changes = ts.formatting.formatNodeGivenIndentation(nonFormattedText.node, file, sourceFile.languageVariant, initialIndentation, delta, rulesProvider); return applyChanges(nonFormattedText.text, changes); } textChanges.applyFormatting = applyFormatting; @@ -84817,40 +87209,48 @@ var ts; } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { - var results; - var refactorList = []; - refactors.forEach(function (refactor) { - refactorList.push(refactor); + return ts.flatMapIter(refactors.values(), function (refactor) { + return context.cancellationToken && context.cancellationToken.isCancellationRequested() ? [] : refactor.getAvailableActions(context); }); - 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; + function getEditsForRefactor(context, refactorName, actionName) { var refactor = refactors.get(refactorName); - if (!refactor) { - return undefined; - } - var codeActions = refactor.getCodeActions(context); - if (codeActions) { - ts.addRange((result || (result = [])), codeActions); - } - return result; + return refactor && refactor.getEditsForAction(context, actionName); } - refactor_1.getRefactorCodeActions = getRefactorCodeActions; + refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var qualifiedName = ts.getAncestor(token, 143 /* QualifiedName */); + ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + if (!ts.isIdentifier(qualifiedName.left)) { + return undefined; + } + var leftText = qualifiedName.left.getText(sourceFile); + var rightText = qualifiedName.right.getText(sourceFile); + var replacement = ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), ts.createLiteralTypeNode(ts.createLiteral(rightText))); + var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + return [{ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [leftText + "[\"" + rightText + "\"]"]), + changes: changeTracker.getChanges() + }]; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -84861,7 +87261,7 @@ var ts; function getActionForClassLikeIncorrectImplementsInterface(context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); var classDeclaration = ts.getContainingClass(token); if (!classDeclaration) { @@ -84902,11 +87302,7 @@ var ts; newNodes.push(newIndexSignatureDeclaration); } function pushAction(result, newNodes, description) { - var newAction = { - description: description, - changes: codefix.newNodesToChanges(newNodes, openBrace, context) - }; - result.push(newAction); + result.push({ description: description, changes: codefix.newNodesToChanges(newNodes, openBrace, context) }); } } })(codefix = ts.codefix || (ts.codefix = {})); @@ -84922,85 +87318,118 @@ var ts; getCodeActions: getActionsForAddMissingMember }); function getActionsForAddMissingMember(context) { - var sourceFile = context.sourceFile; + var tokenSourceFile = context.sourceFile; var start = context.span.start; - // This is the identifier of the missing property. eg: + // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(tokenSourceFile, start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } - if (!ts.isPropertyAccessExpression(token.parent) || token.parent.expression.kind !== 99 /* ThisKeyword */) { + if (!ts.isPropertyAccessExpression(token.parent)) { return undefined; } - var classMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); - if (!ts.isClassElement(classMemberDeclaration)) { - return undefined; + var tokenName = token.getText(tokenSourceFile); + var makeStatic = false; + var classDeclaration; + if (token.parent.expression.kind === 99 /* ThisKeyword */) { + var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); + if (!ts.isClassElement(containingClassMemberDeclaration)) { + return undefined; + } + classDeclaration = containingClassMemberDeclaration.parent; + // Property accesses on `this` in a static method are accesses of a static member. + makeStatic = classDeclaration && ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */); + } + else { + var checker = context.program.getTypeChecker(); + var leftExpression = token.parent.expression; + var leftExpressionType = checker.getTypeAtLocation(leftExpression); + if (leftExpressionType.flags & 32768 /* Object */) { + var symbol = leftExpressionType.symbol; + if (symbol.flags & 32 /* Class */) { + classDeclaration = symbol.declarations && symbol.declarations[0]; + if (leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol)) { + // The expression is a class symbol but the type is not the instance-side. + makeStatic = true; + } + } + } } - var classDeclaration = classMemberDeclaration.parent; if (!classDeclaration || !ts.isClassLike(classDeclaration)) { return undefined; } - var isStatic = ts.hasModifier(classMemberDeclaration, 32 /* Static */); - return ts.isInJavaScriptFile(sourceFile) ? getActionsForAddMissingMemberInJavaScriptFile() : getActionsForAddMissingMemberInTypeScriptFile(); - function getActionsForAddMissingMemberInJavaScriptFile() { - var memberName = token.getText(); - if (isStatic) { + var classDeclarationSourceFile = ts.getSourceFileOfNode(classDeclaration); + var classOpenBrace = ts.getOpenBraceOfClassLike(classDeclaration, classDeclarationSourceFile); + return ts.isInJavaScriptFile(classDeclarationSourceFile) ? + getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) : + getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic); + function getActionsForAddMissingMemberInJavaScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ false); + if (methodCodeAction) { + actions = [methodCodeAction]; + } + if (makeStatic) { if (classDeclaration.kind === 199 /* ClassExpression */) { - return undefined; + return actions; } var className = classDeclaration.name.getText(); - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classDeclaration.getEnd(), length: 0 }, - newText: "" + context.newLineCharacter + className + "." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var staticInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier(className), tokenName), ts.createIdentifier("undefined"))); + var staticInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + staticInitializationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classDeclaration, staticInitialization, { suffix: context.newLineCharacter }); + var initializeStaticAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_static_property_0), [tokenName]), + changes: staticInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeStaticAction); + return actions; } else { var classConstructor = ts.getFirstConstructorWithBody(classDeclaration); if (!classConstructor) { - return undefined; + return actions; } - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [memberName]), - changes: [{ - fileName: sourceFile.fileName, - textChanges: [{ - span: { start: classConstructor.body.getEnd() - 1, length: 0 }, - newText: "this." + memberName + " = undefined;" + context.newLineCharacter - }] - }] - }]; + var propertyInitialization = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), tokenName), ts.createIdentifier("undefined"))); + var propertyInitializationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + propertyInitializationChangeTracker.insertNodeAt(classDeclarationSourceFile, classConstructor.body.getEnd() - 1, propertyInitialization, { prefix: context.newLineCharacter, suffix: context.newLineCharacter }); + var initializeAction = { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]), + changes: propertyInitializationChangeTracker.getChanges() + }; + (actions || (actions = [])).push(initializeAction); + return actions; } } - function getActionsForAddMissingMemberInTypeScriptFile() { + function getActionsForAddMissingMemberInTypeScriptFile(classDeclaration, makeStatic) { + var actions; + var methodCodeAction = getActionForMethodDeclaration(/*includeTypeScriptSyntax*/ true); + if (methodCodeAction) { + actions = [methodCodeAction]; + } var typeNode; if (token.parent.parent.kind === 194 /* BinaryExpression */) { var binaryExpression = token.parent.parent; + var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var checker = context.program.getTypeChecker(); - var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(binaryExpression.right))); + var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); typeNode = checker.typeToTypeNode(widenedType, classDeclaration); } typeNode = typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); - var openBrace = ts.getOpenBraceOfClassLike(classDeclaration, sourceFile); var property = ts.createProperty( /*decorators*/ undefined, - /*modifiers*/ isStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, token.getText(sourceFile), + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); var propertyChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - propertyChangeTracker.insertNodeAfter(sourceFile, openBrace, property, { suffix: context.newLineCharacter }); - var actions = [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_declaration_for_missing_property_0), [token.getText()]), - changes: propertyChangeTracker.getChanges() - }]; - if (!isStatic) { + propertyChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, property, { suffix: context.newLineCharacter }); + (actions || (actions = [])).push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Declare_property_0), [tokenName]), + changes: propertyChangeTracker.getChanges() + }); + if (!makeStatic) { + // Index signatures cannot have the static modifier. var stringTypeNode = ts.createKeywordTypeNode(136 /* StringKeyword */); var indexingParameter = ts.createParameter( /*decorators*/ undefined, @@ -85012,14 +87441,28 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, [indexingParameter], typeNode); var indexSignatureChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); - indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter }); + indexSignatureChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, indexSignature, { suffix: context.newLineCharacter }); actions.push({ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_missing_property_0), [token.getText()]), + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: indexSignatureChangeTracker.getChanges() }); } return actions; } + function getActionForMethodDeclaration(includeTypeScriptSyntax) { + if (token.parent.parent.kind === 181 /* CallExpression */) { + var callExpression = token.parent.parent; + var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, tokenName, includeTypeScriptSyntax, makeStatic); + var methodDeclarationChangeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); + methodDeclarationChangeTracker.insertNodeAfter(classDeclarationSourceFile, classOpenBrace, methodDeclaration, { suffix: context.newLineCharacter }); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? + ts.Diagnostics.Declare_method_0 : + ts.Diagnostics.Declare_static_method_0), [tokenName]), + changes: methodDeclarationChangeTracker.getChanges() + }; + } + } } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -85038,10 +87481,11 @@ var ts; // This is the identifier of the misspelled word. eg: // this.speling = 1; // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, context.span.start); + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 var checker = context.program.getTypeChecker(); var suggestion; - if (node.kind === 71 /* Identifier */ && ts.isPropertyAccessExpression(node.parent)) { + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71 /* Identifier */); var containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); } @@ -85095,7 +87539,7 @@ var ts; var 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. - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var checker = context.program.getTypeChecker(); if (ts.isClassLike(token.parent)) { var classDeclaration = token.parent; @@ -85133,7 +87577,7 @@ var ts; errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 99 /* ThisKeyword */) { return undefined; } @@ -85145,9 +87589,9 @@ var ts; // figure out if the `this` access is actually inside the supercall // i.e. super(this.a), since in that case we won't suggest a fix if (superCall.expression && superCall.expression.kind === 181 /* CallExpression */) { - var arguments_1 = superCall.expression.arguments; - for (var i = 0; i < arguments_1.length; i++) { - if (arguments_1[i].expression === token) { + var expressionArguments = superCall.expression.arguments; + for (var i = 0; i < expressionArguments.length; i++) { + if (expressionArguments[i].expression === token) { return undefined; } } @@ -85181,7 +87625,7 @@ var ts; errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 123 /* ConstructorKeyword */) { return undefined; } @@ -85206,7 +87650,7 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var classDeclNode = ts.getContainingClass(token); if (!(token.kind === 71 /* Identifier */ && ts.isClassLike(classDeclNode))) { return undefined; @@ -85246,7 +87690,7 @@ var ts; errorCodes: [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); if (token.kind !== 71 /* Identifier */) { return undefined; } @@ -85273,140 +87717,147 @@ var ts; getCodeActions: function (context) { var sourceFile = context.sourceFile; var start = context.span.start; - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); // this handles var ["computed"] = 12; if (token.kind === 21 /* OpenBracketToken */) { - token = ts.getTokenAtPosition(sourceFile, start + 1); + token = ts.getTokenAtPosition(sourceFile, start + 1, /*includeJsDocComment*/ false); } switch (token.kind) { case 71 /* Identifier */: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: return deleteDefault(); } function deleteDefault() { if (ts.isDeclarationName(token)) { - return deleteNode(token.parent); + return [deleteNode(token.parent)]; } else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - return deleteNode(token.parent.parent); + return [deleteNode(token.parent.parent)]; } else { return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226 /* VariableDeclaration */: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = 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); + var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; // handle case where 'import a = A;' case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237 /* ImportEqualsDeclaration */); + return [deleteNode(importEquals)]; case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; + var namedImports = 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); + return deleteNamedImportBinding(namedImports); } else { // delete import specifier - return deleteNodeInList(token.parent); + return [deleteNodeInList(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; + case 239 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); + 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); + var start_6 = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); 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) }); + return [deleteRange({ pos: start_6, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; } else { - return deleteNode(importClause.name); + 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); - } + return deleteNamedImportBinding(parent); default: return deleteDefault(); } } + function deleteNamedImportBinding(namedBindings) { + if (namedBindings.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); + if (previousToken && previousToken.kind === 26 /* CommaToken */) { + return [deleteRange({ pos: previousToken.getStart(), end: namedBindings.end })]; + } + return undefined; + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(namedBindings, 238 /* ImportDeclaration */); + return [deleteNode(importDecl)]; + } + } // token.parent is a variableDeclaration - function deleteVariableDeclaration(varDecl) { + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, 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); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : 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()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215 /* ForInStatement */: // There is no valid fix in the case of: // for .. in - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -85426,10 +87877,10 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); @@ -85437,6 +87888,48 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code], + getCodeActions: getActionsForJSDocTypes + }); + function getActionsForJSDocTypes(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + var decl = ts.findAncestor(node, function (n) { return n.kind === 226 /* VariableDeclaration */; }); + if (!decl) + return; + var checker = context.program.getTypeChecker(); + var jsdocType = decl.type; + var original = ts.getTextOfNode(jsdocType); + var type = checker.getTypeFromTypeNode(jsdocType); + var actions = [createAction(jsdocType, sourceFile.fileName, original, checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */))]; + if (jsdocType.kind === 270 /* JSDocNullableType */) { + // for nullable types, suggest the flow-compatible `T | null | undefined` + // in addition to the jsdoc/closure-compatible `T | null` + var replacementWithUndefined = checker.typeToString(checker.getNullableType(type, 2048 /* Undefined */), /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); + actions.push(createAction(jsdocType, sourceFile.fileName, original, replacementWithUndefined)); + } + return actions; + } + function createAction(declaration, fileName, original, replacement) { + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, replacement]), + changes: [{ + fileName: fileName, + textChanges: [{ + span: { start: declaration.getStart(), length: declaration.getWidth() }, + newText: replacement + }] + }], + }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -85551,7 +88044,7 @@ var ts; 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 token = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); var name = token.getText(); var symbolIdActionMap = new ImportCodeActionMap(); // this is a module id -> module import declaration map @@ -85559,8 +88052,22 @@ var ts; 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 umdSymbol = checker.getSymbolAtLocation(token); + var symbol = void 0; + var symbolName = void 0; + if (umdSymbol.flags & 2097152 /* Alias */) { + symbol = checker.getAliasedSymbol(umdSymbol); + symbolName = name; + } + else if (ts.isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), 107455 /* Value */)); + symbolName = symbol.name; + } + else { + ts.Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); + } + return getCodeActionForImport(symbol, symbolName, /*isDefault*/ false, /*isNamespaceImport*/ true); } var candidateModules = checker.getAmbientModules(); for (var _i = 0, allSourceFiles_1 = allSourceFiles; _i < allSourceFiles_1.length; _i++) { @@ -85576,17 +88083,19 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { // check if this symbol is already used var symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, /*isDefault*/ true)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isDefault*/ true)); } } + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(name !== "default"); // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { var symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); } } return symbolIdActionMap.getAllActions(); @@ -85621,16 +88130,13 @@ var ts; } } function getUniqueSymbolId(symbol) { - if (symbol.flags & 8388608 /* Alias */) { - return ts.getSymbolId(checker.getAliasedSymbol(symbol)); - } - return ts.getSymbolId(symbol); + return ts.getSymbolId(ts.skipAlias(symbol, checker)); } 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) { + function getCodeActionForImport(moduleSymbol, symbolName, 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. @@ -85763,10 +88269,10 @@ var ts; var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier || getModuleSpecifierForNewImport()); var changeTracker = createChangeTracker(); var importClause = isDefault - ? ts.createImportClause(ts.createIdentifier(name), /*namedBindings*/ undefined) + ? ts.createImportClause(ts.createIdentifier(symbolName), /*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))])); + ? ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(symbolName))) + : ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName))])); 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 }); @@ -85777,7 +88283,7 @@ var ts; // 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); + return createCodeAction(ts.Diagnostics.Import_0_from_1, [symbolName, "\"" + moduleSpecifierWithoutQuotes + "\""], changeTracker.getChanges(), "NewImport", moduleSpecifierWithoutQuotes); function getModuleSpecifierForNewImport() { var fileName = sourceFile.fileName; var moduleFileName = moduleSymbol.valueDeclaration.getSourceFile().fileName; @@ -85790,8 +88296,9 @@ var ts; tryGetModuleNameFromRootDirs() || ts.removeFileExtension(getRelativePath(moduleFileName, sourceDirectory)); function tryGetModuleNameFromAmbientModule() { - if (moduleSymbol.valueDeclaration.kind !== 265 /* SourceFile */) { - return moduleSymbol.name; + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; } } function tryGetModuleNameFromBaseUrl() { @@ -85859,44 +88366,101 @@ var ts; // nothing to do here return undefined; } - var indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { 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"))); + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (context.host.fileExists(packageJsonPath)) { + var packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); 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 mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } } - catch (e) { } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + function getNodeResolvablePath(path) { + var basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory); + } } - return relativeFileName; } } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[otherpackage/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["PackageContent"] = 2] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + packageRootIndex = partEnd; + state = 2 /* PackageContent */; + break; + case 2 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 2 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } function getPathRelativeToRootDirs(path, rootDirs) { - for (var _i = 0, rootDirs_2 = rootDirs; _i < rootDirs_2.length; _i++) { - var rootDir = rootDirs_2[_i]; + for (var _i = 0, rootDirs_1 = rootDirs; _i < rootDirs_1.length; _i++) { + var rootDir = rootDirs_1[_i]; var relativeName = getRelativePathIfInDirectory(path, rootDir); if (relativeName !== undefined) { return relativeName; @@ -85917,7 +88481,7 @@ var ts; } function getRelativePath(path, directoryPath) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath; + return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; } } } @@ -85959,7 +88523,7 @@ var ts; // 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 (!ts.isInComment(sourceFile, startPosition) && !ts.isInString(sourceFile, startPosition) && !ts.isInTemplateString(sourceFile, startPosition)) { - var token = ts.getTouchingToken(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); var tokenLeadingCommnets = ts.getLeadingCommentRangesOfNode(token, sourceFile); if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { return { @@ -85968,7 +88532,7 @@ var ts; }; } } - // If all fails, add an extra new line immediatlly before the error span. + // If all fails, add an extra new line immediately before the error span. return { span: { start: position, length: 0 }, newText: (position === startPosition ? "" : newLineCharacter) + "// @ts-ignore" + newLineCharacter @@ -86037,7 +88601,7 @@ var ts; */ function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker) { var classMembers = classDeclaration.symbol.members; - var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.getName()); }); + var missingMembers = possiblyMissingSymbols.filter(function (symbol) { return !classMembers.has(symbol.escapedName); }); var newNodes = []; for (var _i = 0, missingMembers_1 = missingMembers; _i < missingMembers_1.length; _i++) { var symbol = missingMembers_1[_i]; @@ -86068,7 +88632,7 @@ var ts; var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); - var optional = !!(symbol.flags & 67108864 /* Optional */); + var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { case 153 /* GetAccessor */: case 154 /* SetAccessor */: @@ -86133,6 +88697,41 @@ var ts; return signatureDeclaration; } } + function createMethodFromCallExpression(callExpression, methodName, includeTypeScriptSyntax, makeStatic) { + var parameters = createDummyParameters(callExpression.arguments.length, /*names*/ undefined, /*minArgumentCount*/ undefined, includeTypeScriptSyntax); + var typeParameters; + if (includeTypeScriptSyntax) { + var typeArgCount = ts.length(callExpression.typeArguments); + for (var i = 0; i < typeArgCount; i++) { + var name = typeArgCount < 8 ? String.fromCharCode(84 /* T */ + i) : "T" + i; + var typeParameter = ts.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined); + (typeParameters ? typeParameters : typeParameters = []).push(typeParameter); + } + } + var newMethod = ts.createMethod( + /*decorators*/ undefined, + /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, + /*asteriskToken*/ undefined, methodName, + /*questionToken*/ undefined, typeParameters, parameters, + /*type*/ includeTypeScriptSyntax ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, createStubbedMethodBody()); + return newMethod; + } + codefix.createMethodFromCallExpression = createMethodFromCallExpression; + function createDummyParameters(argCount, names, minArgumentCount, addAnyType) { + var parameters = []; + for (var i = 0; i < argCount; i++) { + var newParameter = ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + /*name*/ names && names[i] || "arg" + i, + /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, + /*type*/ addAnyType ? ts.createKeywordTypeNode(119 /* AnyKeyword */) : undefined, + /*initializer*/ undefined); + parameters.push(newParameter); + } + return parameters; + } function createMethodImplementingSignatures(signatures, name, optional, modifiers) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, @@ -86152,18 +88751,8 @@ var ts; } } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); - var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.getName(); }); - var parameters = []; - for (var i = 0; i < maxNonRestArgs; i++) { - var anyType = ts.createKeywordTypeNode(119 /* AnyKeyword */); - var newParameter = ts.createParameter( - /*decorators*/ undefined, - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, maxArgsParameterSymbolNames[i], - /*questionToken*/ i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, anyType, - /*initializer*/ undefined); - parameters.push(newParameter); - } + var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -86199,6 +88788,7 @@ var ts; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/// /// /// /// @@ -86207,7 +88797,8 @@ var ts; /// /// /// -/// +/// +/// /// /// /// @@ -86216,34 +88807,55 @@ var ts; (function (ts) { var refactor; (function (refactor) { + var actionName = "convert"; var convertFunctionToES6Class = { name: "Convert to ES2015 class", description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getCodeActions: getCodeActions, - isApplicable: isApplicable + getEditsForAction: getEditsForAction, + getAvailableActions: getAvailableActions }; refactor.registerRefactor(convertFunctionToES6Class); - function isApplicable(context) { + function getAvailableActions(context) { + if (!ts.isInJavaScriptFile(context.file)) { + return undefined; + } var start = context.startPosition; - var node = ts.getTokenAtPosition(context.file, start); + var node = ts.getTokenAtPosition(context.file, start, /*includeJsDocComment*/ false); 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; + if (symbol && (symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { + return [ + { + name: convertFunctionToES6Class.name, + description: convertFunctionToES6Class.description, + actions: [ + { + description: convertFunctionToES6Class.description, + name: actionName + } + ] + } + ]; + } } - function getCodeActions(context) { + function getEditsForAction(context, action) { + // Somehow wrong action got invoked? + if (actionName !== action) { + return undefined; + } var start = context.startPosition; var sourceFile = context.file; var checker = context.program.getTypeChecker(); - var token = ts.getTokenAtPosition(sourceFile, start); + var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); var ctorSymbol = checker.getSymbolAtLocation(token); var newLine = context.rulesProvider.getFormatOptions().newLineCharacter; var deletedNodes = []; var deletes = []; if (!(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { - return []; + return undefined; } var ctorDeclaration = ctorSymbol.valueDeclaration; var changeTracker = ts.textChanges.ChangeTracker.fromCodeFixContext(context); @@ -86267,7 +88879,7 @@ var ts; break; } if (!newClassDeclaration) { - return []; + return undefined; } // Because the preceding node could be touched, we need to insert nodes before delete nodes. changeTracker.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration, { suffix: newLine }); @@ -86275,10 +88887,9 @@ var ts; var deleteCallback = deletes_1[_i]; deleteCallback(); } - return [{ - description: ts.formatStringFromArgs(ts.Diagnostics.Convert_function_0_to_class.message, [ctorSymbol.name]), - changes: changeTracker.getChanges() - }]; + return { + edits: changeTracker.getChanges() + }; function deleteNode(node, inList) { if (inList === void 0) { inList = false; } if (deletedNodes.some(function (n) { return ts.isNodeDescendantOf(node, n); })) { @@ -86338,11 +88949,14 @@ var ts; /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 186 /* FunctionExpression */: + case 186 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; - return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - case 187 /* ArrowFunction */: + copyComments(assignmentBinaryExpression, method); + return method; + } + case 187 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; @@ -86354,18 +88968,39 @@ var ts; var expression = arrowFunctionBody; bodyBlock = ts.createBlock([ts.createReturn(expression)]); } - return ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, + var method = ts.createMethod(/*decorators*/ undefined, modifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - default: + copyComments(assignmentBinaryExpression, method); + return method; + } + 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, + var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentBinaryExpression.right); + copyComments(assignmentBinaryExpression.parent, prop); + return prop; + } } } } + function copyComments(sourceNode, targetNode) { + ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, function (pos, end, kind, htnl) { + if (kind === 3 /* MultiLineCommentTrivia */) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + ts.addSyntheticLeadingComment(targetNode, kind, sourceFile.text.slice(pos, end), htnl); + }); + } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; if (!initializer || initializer.kind !== 186 /* FunctionExpression */) { @@ -86378,16 +89013,20 @@ var ts; if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } - return ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; } 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, + var cls = ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, /*heritageClauses*/ undefined, memberElements); + // Don't call copyComments here because we'll already leave them in place + return cls; } } })(refactor = ts.refactor || (ts.refactor = {})); @@ -86429,7 +89068,7 @@ var ts; /* @internal */ var ruleProvider; function createNode(kind, pos, end, parent) { - var node = kind >= 143 /* FirstNode */ ? new NodeObject(kind, pos, end) : + var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; @@ -86474,10 +89113,11 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end, useJSDocScanner) { + NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { ts.scanner.setTextPos(pos); while (pos < end) { - var token = useJSDocScanner ? ts.scanner.scanJSDocToken() : ts.scanner.scan(); + var token = ts.scanner.scan(); + ts.Debug.assert(token !== 1 /* EndOfFileToken */); // Else it would infinitely loop var textPos = ts.scanner.getTextPos(); if (textPos <= end) { nodes.push(createNode(token, pos, textPos, this)); @@ -86487,7 +89127,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(294 /* SyntaxList */, nodes.pos, nodes.end, this); + var list = createNode(286 /* SyntaxList */, nodes.pos, nodes.end, this); list._children = []; var pos = nodes.pos; for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { @@ -86505,47 +89145,49 @@ var ts; }; NodeObject.prototype.createChildren = function (sourceFile) { var _this = this; - var children; - if (this.kind >= 143 /* FirstNode */) { - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - children = []; - var pos_3 = this.pos; - var useJSDocScanner_1 = this.kind >= 283 /* FirstJSDocTagNode */ && this.kind <= 293 /* LastJSDocTagNode */; - var processNode = function (node) { - var isJSDocTagNode = ts.isJSDocTag(node); - if (!isJSDocTagNode && pos_3 < node.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, node.pos, useJSDocScanner_1); - } - children.push(node); - if (!isJSDocTagNode) { - pos_3 = node.end; - } - }; - var processNodes = function (nodes) { - if (pos_3 < nodes.pos) { - pos_3 = _this.addSyntheticNodes(children, pos_3, nodes.pos, useJSDocScanner_1); - } - children.push(_this.createSyntaxList(nodes)); - pos_3 = nodes.end; - }; - // jsDocComments need to be the first children - if (this.jsDoc) { - for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - processNode(jsDocComment); - } - } - // For syntactic classifications, all trivia are classcified together, including jsdoc comments. - // For that to work, the jsdoc comments should still be the leading trivia of the first child. - // Restoring the scanner position ensures that. - pos_3 = this.pos; - ts.forEachChild(this, processNode, processNodes); - if (pos_3 < this.end) { - this.addSyntheticNodes(children, pos_3, this.end); - } - ts.scanner.setText(undefined); + if (!ts.isNodeKind(this.kind)) { + this._children = ts.emptyArray; + return; } - this._children = children || ts.emptyArray; + if (ts.isJSDocCommentContainingNode(this)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + var children_3 = []; + this.forEachChild(function (child) { children_3.push(child); }); + this._children = children_3; + return; + } + var children = []; + ts.scanner.setText((sourceFile || this.getSourceFile()).text); + var pos = this.pos; + var processNode = function (node) { + pos = _this.addSyntheticNodes(children, pos, node.pos); + children.push(node); + pos = node.end; + }; + var processNodes = function (nodes) { + if (pos < nodes.pos) { + pos = _this.addSyntheticNodes(children, pos, nodes.pos); + } + children.push(_this.createSyntaxList(nodes)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + if (this.jsDoc) { + for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + processNode(jsDocComment); + } + } + // For syntactic classifications, all trivia are classcified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = this.pos; + ts.forEachChild(this, processNode, processNodes); + if (pos < this.end) { + this.addSyntheticNodes(children, pos, this.end); + } + ts.scanner.setText(undefined); + this._children = children; }; NodeObject.prototype.getChildCount = function (sourceFile) { if (!this._children) @@ -86567,7 +89209,7 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 267 /* FirstJSDocNode */ || kid.kind > 293 /* LastJSDocNode */; }); + var child = ts.find(children, function (kid) { return kid.kind < 267 /* FirstJSDocNode */ || kid.kind > 285 /* LastJSDocNode */; }); return child.kind < 143 /* FirstNode */ ? child : child.getFirstToken(sourceFile); @@ -86643,11 +89285,21 @@ var ts; var SymbolObject = (function () { function SymbolObject(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; } SymbolObject.prototype.getFlags = function () { return this.flags; }; + Object.defineProperty(SymbolObject.prototype, "name", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedName); + }, + enumerable: true, + configurable: true + }); + SymbolObject.prototype.getEscapedName = function () { + return this.escapedName; + }; SymbolObject.prototype.getName = function () { return this.name; }; @@ -86682,6 +89334,13 @@ var ts; function IdentifierObject(_kind, pos, end) { return _super.call(this, pos, end) || this; } + Object.defineProperty(IdentifierObject.prototype, "text", { + get: function () { + return ts.unescapeLeadingUnderscores(this.escapedText); + }, + enumerable: true, + configurable: true + }); return IdentifierObject; }(TokenOrIdentifierObject)); IdentifierObject.prototype.kind = 71 /* Identifier */; @@ -86814,26 +89473,16 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_8 = getTextOfIdentifierOrLiteral(name); - if (result_8 !== undefined) { - return result_8; + var result_9 = ts.getTextOfIdentifierOrLiteral(name); + if (result_9 !== undefined) { + return result_9; } if (name.kind === 144 /* ComputedPropertyName */) { var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } - return getTextOfIdentifierOrLiteral(expr); - } - } - return undefined; - } - function getTextOfIdentifierOrLiteral(node) { - if (node) { - if (node.kind === 71 /* Identifier */ || - node.kind === 9 /* StringLiteral */ || - node.kind === 8 /* NumericLiteral */) { - return node.text; + return ts.getTextOfIdentifierOrLiteral(expr); } } return undefined; @@ -86872,7 +89521,6 @@ var ts; case 237 /* ImportEqualsDeclaration */: case 246 /* ExportSpecifier */: case 242 /* ImportSpecifier */: - case 237 /* ImportEqualsDeclaration */: case 239 /* ImportClause */: case 240 /* NamespaceImport */: case 153 /* GetAccessor */: @@ -86894,8 +89542,9 @@ var ts; ts.forEachChild(decl.name, visit); break; } - if (decl.initializer) + if (decl.initializer) { visit(decl.initializer); + } } // falls through case 264 /* EnumMember */: @@ -86938,6 +89587,17 @@ var ts; }; return SourceFileObject; }(NodeObject)); + var SourceMapSourceObject = (function () { + function SourceMapSourceObject(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia; + } + SourceMapSourceObject.prototype.getLineAndCharacterOfPosition = function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }; + return SourceMapSourceObject; + }()); function getServicesObjectAllocator() { return { getNodeConstructor: function () { return NodeObject; }, @@ -86947,6 +89607,7 @@ var ts; getSymbolConstructor: function () { return SymbolObject; }, getTypeConstructor: function () { return TypeObject; }, getSignatureConstructor: function () { return SignatureObject; }, + getSourceMapSourceConstructor: function () { return SourceMapSourceObject; }, }; } function toEditorSettings(optionsAsMap) { @@ -86998,10 +89659,9 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index this.currentDirectory = host.getCurrentDirectory(); - this.fileNameToEntry = ts.createFileMap(); + this.fileNameToEntry = ts.createMap(); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { @@ -87028,24 +89688,20 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { - return this.fileNameToEntry.contains(path); - }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); + HostCache.prototype.containsEntryByPath = function (path) { + return this.fileNameToEntry.has(path); }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (_path, value) { + this.fileNameToEntry.forEach(function (value) { if (value) { fileNames.push(value.hostFileName); } @@ -87053,11 +89709,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -87285,12 +89941,19 @@ var ts; getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { // stub missing host functionality - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -87407,8 +90070,18 @@ var ts; return false; } } + var currentOptions = program.getCompilerOptions(); + var newOptions = hostCache.compilationSettings(); // If the compilation settings do no match, then the program is not up-to-date - return ts.compareDataObjects(program.getCompilerOptions(), hostCache.compilationSettings()); + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; } } function getProgram() { @@ -87423,7 +90096,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } /// Diagnostics function getSyntacticDiagnostics(fileName) { @@ -87466,7 +90141,7 @@ var ts; function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position); + var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } @@ -87488,8 +90163,8 @@ var ts; var type = typeChecker.getTypeAtLocation(node); if (type) { return { - kind: ts.ScriptElementKind.unknown, - kindModifiers: ts.ScriptElementKindModifier.none, + kind: "" /* unknown */, + kindModifiers: "" /* none */, textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined, @@ -87554,7 +90229,7 @@ var ts; result.push({ fileName: entry.fileName, textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === ts.HighlightSpanKind.writtenReference, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, isDefinition: false, isInString: highlightSpan.isInString, }); @@ -87587,12 +90262,8 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; - function writeFile(fileName, data, writeByteOrderMark) { - outputFiles.push({ - name: fileName, - writeByteOrderMark: writeByteOrderMark, - text: data - }); + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); } var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); @@ -87620,7 +90291,7 @@ var ts; function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - var node = ts.getTouchingPropertyName(sourceFile, startPos); + var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); if (node === sourceFile) { return; } @@ -87714,7 +90385,7 @@ var ts; function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var result = []; - var token = ts.getTouchingToken(sourceFile, position); + var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); if (token.getStart(sourceFile) === position) { var matchKind = getMatchingTokenKind(token); // Ensure that there is a corresponding token to match ours. @@ -87776,7 +90447,10 @@ var ts; function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); var settings = toEditorSettings(options); - if (key === "}") { + if (key === "{") { + return ts.formatting.formatOnOpeningCurly(position, sourceFile, getRuleProvider(settings), settings); + } + else if (key === "}") { return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { @@ -87790,27 +90464,13 @@ var ts; function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var span = { start: start, length: end - start }; - var newLineChar = ts.getNewLineOrDefaultFromHost(host); - var allFixes = []; - ts.forEach(ts.deduplicate(errorCodes), function (error) { + var span = ts.createTextSpanFromBounds(start, end); + var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); + var rulesProvider = getRuleProvider(formatOptions); + return ts.flatMap(ts.deduplicate(errorCodes), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - var context = { - errorCode: error, - sourceFile: sourceFile, - span: span, - program: program, - newLineCharacter: newLineChar, - host: host, - cancellationToken: cancellationToken, - rulesProvider: getRuleProvider(formatOptions) - }; - var fixes = ts.codefix.getFixes(context); - if (fixes) { - allFixes = allFixes.concat(fixes); - } + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, rulesProvider: rulesProvider }); }); - return allFixes; } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); @@ -87836,6 +90496,12 @@ var ts; if (ts.isInTemplateString(sourceFile, position)) { return false; } + switch (openingBrace) { + case 39 /* singleQuote */: + case 34 /* doubleQuote */: + case 96 /* backtick */: + return !ts.isInComment(sourceFile, position); + } return true; } function getTodoComments(fileName, descriptors) { @@ -87850,7 +90516,8 @@ var ts; cancellationToken.throwIfCancellationRequested(); var fileContents = sourceFile.text; var result = []; - if (descriptors.length > 0) { + // Exclude node_modules files as we don't want to show the todos of external libraries. + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { var regExp = getTodoCommentsRegExp(); var matchArray = void 0; while (matchArray = regExp.exec(fileContents)) { @@ -87894,11 +90561,7 @@ var ts; continue; } var message = matchArray[2]; - result.push({ - descriptor: descriptor, - message: message, - position: matchPosition - }); + result.push({ descriptor: descriptor, message: message, position: matchPosition }); } } return result; @@ -87960,6 +90623,10 @@ var ts; (char >= 65 /* A */ && char <= 90 /* Z */) || (char >= 48 /* _0 */ && char <= 57 /* _9 */); } + function isNodeModulesFile(path) { + var node_modulesFolderName = "/node_modules/"; + return path.indexOf(node_modulesFolderName) !== -1; + } } function getRenameInfo(fileName, position) { synchronizeHostData(); @@ -87983,18 +90650,16 @@ var ts; var file = getValidSourceFile(fileName); return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); } - function getRefactorCodeActions(fileName, formatOptions, positionOrRange, refactorName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getRefactorCodeActions(getRefactorContext(file, positionOrRange, formatOptions), refactorName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); } return { dispose: dispose, cleanupSemanticCache: cleanupSemanticCache, getSyntacticDiagnostics: getSyntacticDiagnostics, getSemanticDiagnostics: getSemanticDiagnostics, - getApplicableRefactors: getApplicableRefactors, - getRefactorCodeActions: getRefactorCodeActions, getCompilerOptionsDiagnostics: getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications, getSemanticClassifications: getSemanticClassifications, @@ -88032,7 +90697,9 @@ var ts; getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, - getProgram: getProgram + getProgram: getProgram, + getApplicableRefactors: getApplicableRefactors, + getEditsForRefactor: getEditsForRefactor, }; } ts.createLanguageService = createLanguageService; @@ -88046,40 +90713,32 @@ var ts; } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { - var nameTable = ts.createMap(); - walk(sourceFile); - sourceFile.nameTable = nameTable; - function walk(node) { - switch (node.kind) { - case 71 /* Identifier */: - setNameTable(node.text, node); - break; - case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - // We want to store any numbers/strings if they were a name that could be - // related to a declaration. So, if we have 'import x = require("something")' - // then we want 'something' to be in the name table. Similarly, if we have - // "a['propname']" then we want to store "propname" in the name table. - if (ts.isDeclarationName(node) || - node.parent.kind === 248 /* ExternalModuleReference */ || - isArgumentOfElementAccessExpression(node) || - ts.isLiteralComputedPropertyDeclarationName(node)) { - setNameTable(node.text, node); - } - break; - default: - ts.forEachChild(node, walk); - if (node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - ts.forEachChild(jsDoc, walk); - } - } + var nameTable = sourceFile.nameTable = ts.createUnderscoreEscapedMap(); + sourceFile.forEachChild(function walk(node) { + if (ts.isIdentifier(node) && node.escapedText || ts.isStringOrNumericLiteral(node) && literalIsName(node)) { + var text = ts.getEscapedTextOfIdentifierOrLiteral(node); + nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } - } - function setNameTable(text, node) { - nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); - } + ts.forEachChild(node, walk); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + ts.forEachChild(jsDoc, walk); + } + } + }); + } + /** + * We want to store any numbers/strings if they were a name that could be + * related to a declaration. So, if we have 'import x = require("something")' + * then we want 'something' to be in the name table. Similarly, if we have + * "a['propname']" then we want to store "propname" in the name table. + */ + function literalIsName(node) { + return ts.isDeclarationName(node) || + node.parent.kind === 248 /* ExternalModuleReference */ || + isArgumentOfElementAccessExpression(node) || + ts.isLiteralComputedPropertyDeclarationName(node); } function isObjectLiteralElement(node) { switch (node.kind) { @@ -88118,22 +90777,22 @@ var ts; function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name = ts.getTextOfPropertyName(node.name); + var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(node.name)); if (name && contextualType) { - var result_9 = []; + var result_10 = []; var symbol = contextualType.getProperty(name); if (contextualType.flags & 65536 /* Union */) { ts.forEach(contextualType.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_9.push(symbol); + result_10.push(symbol); } }); - return result_9; + return result_10; } if (symbol) { - result_9.push(symbol); - return result_9; + result_10.push(symbol); + return result_10; } } return undefined; @@ -88176,7 +90835,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); var 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 @@ -88977,25 +91636,8 @@ var ts; } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - // Wrap the API changes for 2.0 release. This try/catch - // should be removed once TypeScript 2.0 has shipped. - try { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); - return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); - } - catch (e) { - var results = []; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - for (var _a = 0, _b = this.readDirectoryFallback(rootDir, extension, exclude); _a < _b.length; _a++) { - var file = _b[_a]; - if (!ts.contains(results, file)) { - results.push(file); - } - } - } - return results; - } + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { return this.shimHost.fileExists(fileName); @@ -89003,9 +91645,6 @@ var ts; CoreServicesShimHostAdapter.prototype.readFile = function (fileName) { return this.shimHost.readFile(fileName); }; - CoreServicesShimHostAdapter.prototype.readDirectoryFallback = function (rootDir, extension, exclude) { - return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); - }; CoreServicesShimHostAdapter.prototype.getDirectories = function (path) { return JSON.parse(this.shimHost.getDirectories(path)); }; @@ -89391,7 +92030,7 @@ 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) { + if (result.resolvedModule && result.resolvedModule.extension !== ".ts" /* Ts */ && result.resolvedModule.extension !== ".tsx" /* Tsx */ && result.resolvedModule.extension !== ".d.ts" /* Dts */) { resolvedFileName = undefined; } return { @@ -89452,24 +92091,15 @@ var ts; var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseConfigFileTextToJson(fileName, text); - if (result.error) { - return { - options: {}, - typeAcquisition: {}, - files: [], - raw: {}, - errors: [realizeDiagnostic(result.error, "\r\n")] - }; - } + var result = ts.parseJsonText(fileName, text); var normalizedFileName = ts.normalizeSlashes(fileName); - var configFile = ts.parseJsonConfigFileContent(result.config, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); + var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, typeAcquisition: configFile.typeAcquisition, files: configFile.fileNames, raw: configFile.raw, - errors: realizeDiagnostics(configFile.errors, "\r\n") + errors: realizeDiagnostics(result.parseDiagnostics.concat(configFile.errors), "\r\n") }; }); }; @@ -89481,7 +92111,10 @@ var ts; var getCanonicalFileName = ts.createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); return this.forwardJSONCall("discoverTypings()", function () { var info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings(_this.host, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); + if (_this.safeList === undefined) { + _this.safeList = ts.JsTyping.loadSafeList(_this.host, ts.toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return ts.JsTyping.discoverTypings(_this.host, function (msg) { return _this.logger.log(msg); }, info.fileNames, ts.toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), _this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); }); }; return CoreServicesShimObject; @@ -89531,7 +92164,7 @@ var ts; }; TypeScriptServicesFactory.prototype.close = function () { // Forget all the registered shims - this._shims = []; + ts.clear(this._shims); this.documentRegistry = undefined; }; TypeScriptServicesFactory.prototype.registerShim = function (shim) { @@ -89567,6 +92200,4 @@ var TypeScript; // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ -var toolsVersion = "2.4"; - -//# sourceMappingURL=typescriptServices.js.map +var toolsVersion = "2.5"; diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 554dc3bcaca..0aea3ef2359 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -13,6 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || @@ -25,449 +26,12 @@ 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"; @@ -492,45 +56,6 @@ var ts; 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"; @@ -545,196 +70,6 @@ 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"; @@ -754,309 +89,8 @@ var ts; ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; ModuleKind[ModuleKind["System"] = 4] = "System"; ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ESNext"] = 6] = "ESNext"; })(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"; - Extension[Extension["Tsx"] = 1] = "Tsx"; - Extension[Extension["Dts"] = 2] = "Dts"; - Extension[Extension["Js"] = 3] = "Js"; - 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) { @@ -1119,15 +153,10 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.0"; + ts.versionMajorMinor = "2.5"; + ts.version = ts.versionMajorMinor + ".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() { @@ -1140,12 +169,28 @@ var ts; return new MapCtr(); } ts.createMap = createMap; + function createUnderscoreEscapedMap() { + return new MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function createSymbolTable(symbols) { + var result = createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; function createMapFromTemplate(template) { var map = new MapCtr(); - for (var key in template) + for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); } + } return map; } ts.createMapFromTemplate = createMapFromTemplate; @@ -1215,45 +260,6 @@ var ts; return class_1; }()); } - function createFileMap(keyMapper) { - var files = createMap(); - return { - get: get, - set: set, - contains: contains, - remove: remove, - forEachValue: forEachValueInMap, - getKeys: getKeys, - clear: clear, - }; - function forEachValueInMap(f) { - files.forEach(function (file, key) { - f(key, file); - }); - } - function getKeys() { - return arrayFrom(files.keys()); - } - function get(path) { - return files.get(toKey(path)); - } - function set(path, value) { - files.set(toKey(path), value); - } - function contains(path) { - return files.has(toKey(path)); - } - function remove(path) { - files.delete(toKey(path)); - } - function clear() { - files.clear(); - } - function toKey(path) { - return keyMapper ? keyMapper(path) : path; - } - } - ts.createFileMap = createFileMap; function toPath(fileName, basePath, getCanonicalFileName) { var nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) @@ -1261,12 +267,6 @@ 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; } @@ -1448,6 +448,10 @@ var ts; array.length = outIndex; } ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; function map(array, f) { var result; if (array) { @@ -1517,6 +521,19 @@ var ts; return result; } ts.flatMap = flatMap; + function flatMapIter(iter, mapfn) { + var result = []; + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) + break; + var res = mapfn(value); + if (res) + result.push.apply(result, res); + } + return result; + } + ts.flatMapIter = flatMapIter; function sameFlatMap(array, mapfn) { var result; if (array) { @@ -1539,6 +556,18 @@ var ts; return result || array; } ts.sameFlatMap = sameFlatMap; + function mapDefined(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapFn(item, i); + if (mapped !== undefined) { + result.push(mapped); + } + } + return result; + } + ts.mapDefined = mapDefined; function span(array, f) { if (array) { for (var i = 0; i < array.length; i++) { @@ -1732,12 +761,21 @@ var ts; return to; } ts.append = append; - function addRange(to, from) { + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { if (from === undefined) return to; - for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { - var v = from_1[_i]; - to = append(to, v); + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + var v = from[i]; + if (v !== undefined) { + to.push(from[i]); + } } return to; } @@ -1760,16 +798,22 @@ var ts; return true; } ts.rangeEquals = rangeEquals; + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; function firstOrUndefined(array) { - return array && array.length > 0 - ? array[0] - : undefined; + return elementAt(array, 0); } ts.firstOrUndefined = firstOrUndefined; function lastOrUndefined(array) { - return array && array.length > 0 - ? array[array.length - 1] - : undefined; + return elementAt(array, -1); } ts.lastOrUndefined = lastOrUndefined; function singleOrUndefined(array) { @@ -1874,10 +918,11 @@ var ts; ts.getProperty = getProperty; function getOwnKeys(map) { var keys = []; - for (var key in map) + for (var key in map) { if (hasOwnProperty.call(map, key)) { keys.push(key); } + } return keys; } ts.getOwnKeys = getOwnKeys; @@ -1890,15 +935,6 @@ var ts; var _b; } ts.arrayFrom = arrayFrom; - function convertToArray(iterator, f) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(f(value)); - } - return result; - var _b; - } - ts.convertToArray = convertToArray; function forEachEntry(map, callback) { var iterator = map.entries(); for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { @@ -1937,10 +973,11 @@ var ts; } for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { var arg = args_1[_a]; - for (var p in arg) + for (var p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; } + } } return t; } @@ -1950,18 +987,20 @@ var ts; return true; if (!left || !right) return false; - for (var key in left) + for (var key in left) { if (hasOwnProperty.call(left, key)) { if (!hasOwnProperty.call(right, key) === undefined) return false; if (equalityComparer ? !equalityComparer(left[key], right[key]) : left[key] !== right[key]) return false; } - for (var key in right) + } + for (var key in right) { if (hasOwnProperty.call(right, key)) { if (!hasOwnProperty.call(left, key)) return false; } + } return true; } ts.equalOwnProperties = equalOwnProperties; @@ -1974,6 +1013,10 @@ var ts; return result; } ts.arrayToMap = arrayToMap; + function arrayToSet(array, makeKey) { + return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; function cloneMap(map) { var clone = createMap(); copyEntries(map, clone); @@ -1992,14 +1035,16 @@ var ts; ts.clone = clone; function extend(first, second) { var result = {}; - for (var id in second) + for (var id in second) { if (hasOwnProperty.call(second, id)) { result[id] = second[id]; } - for (var id in first) + } + for (var id in first) { if (hasOwnProperty.call(first, id)) { result[id] = first[id]; } + } return result; } ts.extend = extend; @@ -2033,6 +1078,16 @@ var ts; return Array.isArray ? Array.isArray(value) : value instanceof Array; } ts.isArray = isArray; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; function noop() { } ts.noop = noop; function notImplemented() { @@ -2350,10 +1405,18 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); + return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function moduleHasNonRelativeName(moduleName) { + return !isExternalModuleNameRelative(moduleName); + } + ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function getEmitScriptTarget(compilerOptions) { return compilerOptions.target || 0; } @@ -2456,7 +1519,7 @@ var ts; var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - directoryComponents.length--; + directoryComponents.pop(); } var joinStartIndex; for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { @@ -2580,7 +1643,7 @@ var ts; return path.length > extension.length && endsWith(path, extension); } ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsAny(path, extensions) { + function fileExtensionIsOneOf(path, extensions) { for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { var extension = extensions_1[_i]; if (fileExtensionIs(path, extension)) { @@ -2589,7 +1652,7 @@ var ts; } return false; } - ts.fileExtensionIsAny = fileExtensionIsAny; + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; var reservedCharacterPattern = /[^\w\s\/]/g; var wildcardCharCodes = [42, 63]; var singleAsteriskRegexFragmentFiles = "([^./]|(\\.(?!min\\.js$))?)*"; @@ -2692,7 +1755,7 @@ var ts; }; } ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, getFileSystemEntries) { + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { path = normalizePath(path); currentDirectory = normalizePath(currentDirectory); var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); @@ -2704,17 +1767,16 @@ var ts; var comparer = useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive; for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath)); + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); } return flatten(results); - function visitDirectory(path, absolutePath) { + function visitDirectory(path, absolutePath, depth) { var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; files = files.slice().sort(comparer); - directories = directories.slice().sort(comparer); var _loop_1 = function (current) { var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsAny(name, extensions)) + if (extensions && !fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) return "continue"; @@ -2732,13 +1794,20 @@ var ts; var current = files_1[_i]; _loop_1(current); } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + directories = directories.slice().sort(comparer); for (var _b = 0, directories_1 = directories; _b < directories_1.length; _b++) { var current = directories_1[_b]; var name = combinePaths(path, current); var absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName); + visitDirectory(name, absoluteName, depth); } } } @@ -2776,7 +1845,7 @@ var ts; return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } function ensureScriptKind(fileName, scriptKind) { - return (scriptKind || getScriptKindFromFileName(fileName)) || 3; + return scriptKind || getScriptKindFromFileName(fileName) || 3; } ts.ensureScriptKind = ensureScriptKind; function getScriptKindFromFileName(fileName) { @@ -2790,6 +1859,8 @@ var ts; return 3; case ".tsx": return 4; + case ".json": + return 6; default: return 0; } @@ -2835,13 +1906,6 @@ 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])) { @@ -2898,11 +1962,14 @@ var ts; ts.changeExtension = changeExtension; function Symbol(flags, name) { this.flags = flags; - this.name = name; + this.escapedName = name; this.declarations = undefined; } - function Type(_checker, flags) { + function Type(checker, flags) { this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } } function Signature() { } @@ -2917,6 +1984,11 @@ var ts; this.parent = undefined; this.original = undefined; } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, getTokenConstructor: function () { return Node; }, @@ -2924,37 +1996,49 @@ var ts; getSourceFileConstructor: function () { return Node; }, getSymbolConstructor: function () { return Symbol; }, getTypeConstructor: function () { return Type; }, - getSignatureConstructor: function () { return Signature; } + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; - 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; + Debug.isDebugging = false; function shouldAssert(level) { return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo) { + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { if (!expression) { - var verboseDebugString = ""; if (verboseDebugInfo) { - verboseDebugString = "\r\nVerbose Debug Information: " + verboseDebugInfo(); + message += "\r\nVerbose Debug Information: " + verboseDebugInfo(); } - debugger; - throw new Error("Debug Failure. False expression: " + (message || "") + verboseDebugString); + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); } } Debug.assert = assert; - function fail(message) { - Debug.assert(false, message); + function fail(message, stackCrawlMark) { + debugger; + var e = new Error(message ? "Debug Failure. " + message : "Debug Failure."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; } Debug.fail = fail; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; })(Debug = ts.Debug || (ts.Debug = {})); function orderedRemoveItem(array, item) { for (var i = 0; i < array.length; i++) { @@ -3055,7 +2139,7 @@ var ts; } ts.positionIsSynthesized = positionIsSynthesized; function extensionIsTypeScript(ext) { - return ext <= ts.Extension.LastTypeScriptExtension; + return ext === ".ts" || ext === ".tsx" || ext === ".d.ts"; } ts.extensionIsTypeScript = extensionIsTypeScript; function extensionFromPath(path) { @@ -3067,21 +2151,7 @@ var ts; } ts.extensionFromPath = extensionFromPath; function tryGetExtensionFromPath(path) { - if (fileExtensionIs(path, ".d.ts")) { - return ts.Extension.Dts; - } - if (fileExtensionIs(path, ".ts")) { - return ts.Extension.Ts; - } - if (fileExtensionIs(path, ".tsx")) { - return ts.Extension.Tsx; - } - if (fileExtensionIs(path, ".js")) { - return ts.Extension.Js; - } - if (fileExtensionIs(path, ".jsx")) { - return ts.Extension.Jsx; - } + return find(ts.supportedTypescriptExtensionsForExtractExtension, function (e) { return fileExtensionIs(path, e); }) || find(ts.supportedJavascriptExtensions, function (e) { return fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { @@ -3091,6 +2161,12 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var FileWatcherEventKind; + (function (FileWatcherEventKind) { + FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created"; + FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed"; + FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted"; + })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {})); function getNodeMajorVersion() { if (typeof process === "undefined") { return undefined; @@ -3163,7 +2239,7 @@ var ts; if (callbacks) { for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { var fileCallback = callbacks_1[_i]; - fileCallback(fileName); + fileCallback(fileName, FileWatcherEventKind.Changed); } } } @@ -3176,7 +2252,13 @@ var ts; if (platform === "win32" || platform === "win64") { return false; } - return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + return !fileExists(swapCase(__filename)); + } + function swapCase(s) { + return s.replace(/\w/g, function (ch) { + var up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); } var platform = _os.platform(); var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); @@ -3249,14 +2331,9 @@ var ts; return { files: [], directories: [] }; } } - function readDirectory(path, extensions, excludes, includes) { - return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), getAccessibleFileSystemEntries); + function readDirectory(path, extensions, excludes, includes, depth) { + return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, 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); @@ -3302,10 +2379,19 @@ var ts; }; } function fileChanged(curr, prev) { - if (+curr.mtime <= +prev.mtime) { + var isCurrZero = +curr.mtime === 0; + var isPrevZero = +prev.mtime === 0; + var created = !isCurrZero && isPrevZero; + var deleted = isCurrZero && !isPrevZero; + var eventKind = created + ? FileWatcherEventKind.Created + : deleted + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + if (eventKind === FileWatcherEventKind.Changed && +curr.mtime <= +prev.mtime) { return; } - callback(fileName); + callback(fileName, eventKind); } }, watchDirectory: function (directoryName, callback, recursive) { @@ -3325,9 +2411,7 @@ var ts; } }); }, - resolvePath: function (path) { - return _path.resolve(path); - }, + resolvePath: function (path) { return _path.resolve(path); }, fileExists: fileExists, directoryExists: directoryExists, createDirectory: function (directoryName) { @@ -3381,6 +2465,7 @@ var ts; realpath: function (path) { return _fs.realpathSync(path); }, + debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { try { require("source-map-support").install(); @@ -3417,7 +2502,7 @@ var ts; getCurrentDirectory: function () { return ChakraHost.currentDirectory; }, getDirectories: ChakraHost.getDirectories, getEnvironmentVariable: ChakraHost.getEnvironmentVariable || (function () { return ""; }), - readDirectory: function (path, extensions, excludes, includes) { + readDirectory: function (path, extensions, excludes, includes, _depth) { var pattern = ts.getFileMatcherPatterns(path, excludes, includes, !!ChakraHost.useCaseSensitiveFileNames, ChakraHost.currentDirectory); return ChakraHost.readDirectory(path, extensions, pattern.basePaths, pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern); }, @@ -3459,913 +2544,5405 @@ var ts; ? 1 : 0; } + if (ts.sys && ts.sys.debugMode) { + ts.Debug.isDebugging = true; + } })(ts || (ts = {})); var ts; (function (ts) { + function diag(code, category, key, message) { + return { code: code, category: category, key: key, message: message }; + } ts.Diagnostics = { - Unterminated_string_literal: { code: 1002, category: ts.DiagnosticCategory.Error, key: "Unterminated_string_literal_1002", message: "Unterminated string literal." }, - Identifier_expected: { code: 1003, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_1003", message: "Identifier expected." }, - _0_expected: { code: 1005, category: ts.DiagnosticCategory.Error, key: "_0_expected_1005", message: "'{0}' expected." }, - A_file_cannot_have_a_reference_to_itself: { code: 1006, category: ts.DiagnosticCategory.Error, key: "A_file_cannot_have_a_reference_to_itself_1006", message: "A file cannot have a reference to itself." }, - Trailing_comma_not_allowed: { code: 1009, category: ts.DiagnosticCategory.Error, key: "Trailing_comma_not_allowed_1009", message: "Trailing comma not allowed." }, - Asterisk_Slash_expected: { code: 1010, category: ts.DiagnosticCategory.Error, key: "Asterisk_Slash_expected_1010", message: "'*/' expected." }, - Unexpected_token: { code: 1012, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_1012", message: "Unexpected token." }, - A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_last_in_a_parameter_list_1014", message: "A rest parameter must be last in a parameter list." }, - Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: ts.DiagnosticCategory.Error, key: "Parameter_cannot_have_question_mark_and_initializer_1015", message: "Parameter cannot have question mark and initializer." }, - A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: ts.DiagnosticCategory.Error, key: "A_required_parameter_cannot_follow_an_optional_parameter_1016", message: "A required parameter cannot follow an optional parameter." }, - An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: ts.DiagnosticCategory.Error, key: "An_index_signature_cannot_have_a_rest_parameter_1017", message: "An index signature cannot have a rest parameter." }, - An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", message: "An index signature parameter cannot have an accessibility modifier." }, - An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_a_question_mark_1019", message: "An index signature parameter cannot have a question mark." }, - An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_cannot_have_an_initializer_1020", message: "An index signature parameter cannot have an initializer." }, - An_index_signature_must_have_a_type_annotation: { code: 1021, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_a_type_annotation_1021", message: "An index signature must have a type annotation." }, - An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_must_have_a_type_annotation_1022", message: "An index signature parameter must have a type annotation." }, - An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: ts.DiagnosticCategory.Error, key: "An_index_signature_parameter_type_must_be_string_or_number_1023", message: "An index signature parameter type must be 'string' or 'number'." }, - readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: { code: 1024, category: ts.DiagnosticCategory.Error, key: "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", message: "'readonly' modifier can only appear on a property declaration or index signature." }, - Accessibility_modifier_already_seen: { code: 1028, category: ts.DiagnosticCategory.Error, key: "Accessibility_modifier_already_seen_1028", message: "Accessibility modifier already seen." }, - _0_modifier_must_precede_1_modifier: { code: 1029, category: ts.DiagnosticCategory.Error, key: "_0_modifier_must_precede_1_modifier_1029", message: "'{0}' modifier must precede '{1}' modifier." }, - _0_modifier_already_seen: { code: 1030, category: ts.DiagnosticCategory.Error, key: "_0_modifier_already_seen_1030", message: "'{0}' modifier already seen." }, - _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_class_element_1031", message: "'{0}' modifier cannot appear on a class element." }, - super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: ts.DiagnosticCategory.Error, key: "super_must_be_followed_by_an_argument_list_or_member_access_1034", message: "'super' must be followed by an argument list or member access." }, - Only_ambient_modules_can_use_quoted_names: { code: 1035, category: ts.DiagnosticCategory.Error, key: "Only_ambient_modules_can_use_quoted_names_1035", message: "Only ambient modules can use quoted names." }, - Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: ts.DiagnosticCategory.Error, key: "Statements_are_not_allowed_in_ambient_contexts_1036", message: "Statements are not allowed in ambient contexts." }, - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", message: "A 'declare' modifier cannot be used in an already ambient context." }, - Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: ts.DiagnosticCategory.Error, key: "Initializers_are_not_allowed_in_ambient_contexts_1039", message: "Initializers are not allowed in ambient contexts." }, - _0_modifier_cannot_be_used_in_an_ambient_context: { code: 1040, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_in_an_ambient_context_1040", message: "'{0}' modifier cannot be used in an ambient context." }, - _0_modifier_cannot_be_used_with_a_class_declaration: { code: 1041, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_a_class_declaration_1041", message: "'{0}' modifier cannot be used with a class declaration." }, - _0_modifier_cannot_be_used_here: { code: 1042, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_here_1042", message: "'{0}' modifier cannot be used here." }, - _0_modifier_cannot_appear_on_a_data_property: { code: 1043, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_data_property_1043", message: "'{0}' modifier cannot appear on a data property." }, - _0_modifier_cannot_appear_on_a_module_or_namespace_element: { code: 1044, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", message: "'{0}' modifier cannot appear on a module or namespace element." }, - A_0_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", message: "A '{0}' modifier cannot be used with an interface declaration." }, - A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: ts.DiagnosticCategory.Error, key: "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", message: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, - A_rest_parameter_cannot_be_optional: { code: 1047, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_be_optional_1047", message: "A rest parameter cannot be optional." }, - A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_cannot_have_an_initializer_1048", message: "A rest parameter cannot have an initializer." }, - A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_must_have_exactly_one_parameter_1049", message: "A 'set' accessor must have exactly one parameter." }, - A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_an_optional_parameter_1051", message: "A 'set' accessor cannot have an optional parameter." }, - A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_parameter_cannot_have_an_initializer_1052", message: "A 'set' accessor parameter cannot have an initializer." }, - A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_rest_parameter_1053", message: "A 'set' accessor cannot have rest parameter." }, - A_get_accessor_cannot_have_parameters: { code: 1054, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_cannot_have_parameters_1054", message: "A 'get' accessor cannot have parameters." }, - Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: { code: 1055, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", message: "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value." }, - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: ts.DiagnosticCategory.Error, key: "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", message: "Accessors are only available when targeting ECMAScript 5 and higher." }, - An_async_function_or_method_must_have_a_valid_awaitable_return_type: { code: 1057, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", message: "An async function or method must have a valid awaitable return type." }, - The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1058, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", message: "The return type of an async function must either be a valid promise or must not contain a callable 'then' member." }, - A_promise_must_have_a_then_method: { code: 1059, category: ts.DiagnosticCategory.Error, key: "A_promise_must_have_a_then_method_1059", message: "A promise must have a 'then' method." }, - The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: { code: 1060, category: ts.DiagnosticCategory.Error, key: "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", message: "The first parameter of the 'then' method of a promise must be a callback." }, - Enum_member_must_have_initializer: { code: 1061, category: ts.DiagnosticCategory.Error, key: "Enum_member_must_have_initializer_1061", message: "Enum member must have initializer." }, - Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: { code: 1062, category: ts.DiagnosticCategory.Error, key: "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", message: "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method." }, - An_export_assignment_cannot_be_used_in_a_namespace: { code: 1063, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_namespace_1063", message: "An export assignment cannot be used in a namespace." }, - The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: { code: 1064, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", message: "The return type of an async function or method must be the global Promise type." }, - In_ambient_enum_declarations_member_initializer_must_be_constant_expression: { code: 1066, category: ts.DiagnosticCategory.Error, key: "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", message: "In ambient enum declarations member initializer must be constant expression." }, - Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", message: "Unexpected token. A constructor, method, accessor, or property was expected." }, - _0_modifier_cannot_appear_on_a_type_member: { code: 1070, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_type_member_1070", message: "'{0}' modifier cannot appear on a type member." }, - _0_modifier_cannot_appear_on_an_index_signature: { code: 1071, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_an_index_signature_1071", message: "'{0}' modifier cannot appear on an index signature." }, - A_0_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: ts.DiagnosticCategory.Error, key: "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", message: "A '{0}' modifier cannot be used with an import declaration." }, - Invalid_reference_directive_syntax: { code: 1084, category: ts.DiagnosticCategory.Error, key: "Invalid_reference_directive_syntax_1084", message: "Invalid 'reference' directive syntax." }, - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: { code: 1085, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", message: "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'." }, - An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_be_declared_in_an_ambient_context_1086", message: "An accessor cannot be declared in an ambient context." }, - _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", message: "'{0}' modifier cannot appear on a constructor declaration." }, - _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_appear_on_a_parameter_1090", message: "'{0}' modifier cannot appear on a parameter." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", message: "Only a single variable declaration is allowed in a 'for...in' statement." }, - Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: ts.DiagnosticCategory.Error, key: "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", message: "Type parameters cannot appear on a constructor declaration." }, - Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: ts.DiagnosticCategory.Error, key: "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", message: "Type annotation cannot appear on a constructor declaration." }, - An_accessor_cannot_have_type_parameters: { code: 1094, category: ts.DiagnosticCategory.Error, key: "An_accessor_cannot_have_type_parameters_1094", message: "An accessor cannot have type parameters." }, - A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: ts.DiagnosticCategory.Error, key: "A_set_accessor_cannot_have_a_return_type_annotation_1095", message: "A 'set' accessor cannot have a return type annotation." }, - An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: ts.DiagnosticCategory.Error, key: "An_index_signature_must_have_exactly_one_parameter_1096", message: "An index signature must have exactly one parameter." }, - _0_list_cannot_be_empty: { code: 1097, category: ts.DiagnosticCategory.Error, key: "_0_list_cannot_be_empty_1097", message: "'{0}' list cannot be empty." }, - Type_parameter_list_cannot_be_empty: { code: 1098, category: ts.DiagnosticCategory.Error, key: "Type_parameter_list_cannot_be_empty_1098", message: "Type parameter list cannot be empty." }, - Type_argument_list_cannot_be_empty: { code: 1099, category: ts.DiagnosticCategory.Error, key: "Type_argument_list_cannot_be_empty_1099", message: "Type argument list cannot be empty." }, - Invalid_use_of_0_in_strict_mode: { code: 1100, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_in_strict_mode_1100", message: "Invalid use of '{0}' in strict mode." }, - with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_strict_mode_1101", message: "'with' statements are not allowed in strict mode." }, - delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: ts.DiagnosticCategory.Error, key: "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", message: "'delete' cannot be called on an identifier in strict mode." }, - A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: { code: 1103, category: ts.DiagnosticCategory.Error, key: "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", message: "A 'for-await-of' statement is only allowed within an async function or async generator." }, - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", message: "A 'continue' statement can only be used within an enclosing iteration statement." }, - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", message: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, - Jump_target_cannot_cross_function_boundary: { code: 1107, category: ts.DiagnosticCategory.Error, key: "Jump_target_cannot_cross_function_boundary_1107", message: "Jump target cannot cross function boundary." }, - A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: ts.DiagnosticCategory.Error, key: "A_return_statement_can_only_be_used_within_a_function_body_1108", message: "A 'return' statement can only be used within a function body." }, - Expression_expected: { code: 1109, category: ts.DiagnosticCategory.Error, key: "Expression_expected_1109", message: "Expression expected." }, - Type_expected: { code: 1110, category: ts.DiagnosticCategory.Error, key: "Type_expected_1110", message: "Type expected." }, - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: ts.DiagnosticCategory.Error, key: "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", message: "A 'default' clause cannot appear more than once in a 'switch' statement." }, - Duplicate_label_0: { code: 1114, category: ts.DiagnosticCategory.Error, key: "Duplicate_label_0_1114", message: "Duplicate label '{0}'." }, - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: ts.DiagnosticCategory.Error, key: "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", message: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: ts.DiagnosticCategory.Error, key: "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", message: "A 'break' statement can only jump to a label of an enclosing statement." }, - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", message: "An object literal cannot have multiple properties with the same name in strict mode." }, - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", message: "An object literal cannot have multiple get/set accessors with the same name." }, - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: ts.DiagnosticCategory.Error, key: "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", message: "An object literal cannot have property and accessor with the same name." }, - An_export_assignment_cannot_have_modifiers: { code: 1120, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_have_modifiers_1120", message: "An export assignment cannot have modifiers." }, - Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: ts.DiagnosticCategory.Error, key: "Octal_literals_are_not_allowed_in_strict_mode_1121", message: "Octal literals are not allowed in strict mode." }, - A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: ts.DiagnosticCategory.Error, key: "A_tuple_type_element_list_cannot_be_empty_1122", message: "A tuple type element list cannot be empty." }, - Variable_declaration_list_cannot_be_empty: { code: 1123, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_list_cannot_be_empty_1123", message: "Variable declaration list cannot be empty." }, - Digit_expected: { code: 1124, category: ts.DiagnosticCategory.Error, key: "Digit_expected_1124", message: "Digit expected." }, - Hexadecimal_digit_expected: { code: 1125, category: ts.DiagnosticCategory.Error, key: "Hexadecimal_digit_expected_1125", message: "Hexadecimal digit expected." }, - Unexpected_end_of_text: { code: 1126, category: ts.DiagnosticCategory.Error, key: "Unexpected_end_of_text_1126", message: "Unexpected end of text." }, - Invalid_character: { code: 1127, category: ts.DiagnosticCategory.Error, key: "Invalid_character_1127", message: "Invalid character." }, - Declaration_or_statement_expected: { code: 1128, category: ts.DiagnosticCategory.Error, key: "Declaration_or_statement_expected_1128", message: "Declaration or statement expected." }, - Statement_expected: { code: 1129, category: ts.DiagnosticCategory.Error, key: "Statement_expected_1129", message: "Statement expected." }, - case_or_default_expected: { code: 1130, category: ts.DiagnosticCategory.Error, key: "case_or_default_expected_1130", message: "'case' or 'default' expected." }, - Property_or_signature_expected: { code: 1131, category: ts.DiagnosticCategory.Error, key: "Property_or_signature_expected_1131", message: "Property or signature expected." }, - Enum_member_expected: { code: 1132, category: ts.DiagnosticCategory.Error, key: "Enum_member_expected_1132", message: "Enum member expected." }, - Variable_declaration_expected: { code: 1134, category: ts.DiagnosticCategory.Error, key: "Variable_declaration_expected_1134", message: "Variable declaration expected." }, - Argument_expression_expected: { code: 1135, category: ts.DiagnosticCategory.Error, key: "Argument_expression_expected_1135", message: "Argument expression expected." }, - Property_assignment_expected: { code: 1136, category: ts.DiagnosticCategory.Error, key: "Property_assignment_expected_1136", message: "Property assignment expected." }, - Expression_or_comma_expected: { code: 1137, category: ts.DiagnosticCategory.Error, key: "Expression_or_comma_expected_1137", message: "Expression or comma expected." }, - Parameter_declaration_expected: { code: 1138, category: ts.DiagnosticCategory.Error, key: "Parameter_declaration_expected_1138", message: "Parameter declaration expected." }, - Type_parameter_declaration_expected: { code: 1139, category: ts.DiagnosticCategory.Error, key: "Type_parameter_declaration_expected_1139", message: "Type parameter declaration expected." }, - Type_argument_expected: { code: 1140, category: ts.DiagnosticCategory.Error, key: "Type_argument_expected_1140", message: "Type argument expected." }, - String_literal_expected: { code: 1141, category: ts.DiagnosticCategory.Error, key: "String_literal_expected_1141", message: "String literal expected." }, - Line_break_not_permitted_here: { code: 1142, category: ts.DiagnosticCategory.Error, key: "Line_break_not_permitted_here_1142", message: "Line break not permitted here." }, - or_expected: { code: 1144, category: ts.DiagnosticCategory.Error, key: "or_expected_1144", message: "'{' or ';' expected." }, - Declaration_expected: { code: 1146, category: ts.DiagnosticCategory.Error, key: "Declaration_expected_1146", message: "Declaration expected." }, - Import_declarations_in_a_namespace_cannot_reference_a_module: { code: 1147, category: ts.DiagnosticCategory.Error, key: "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", message: "Import declarations in a namespace cannot reference a module." }, - Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: { code: 1148, category: ts.DiagnosticCategory.Error, key: "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", message: "Cannot use imports, exports, or module augmentations when '--module' is 'none'." }, - File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: ts.DiagnosticCategory.Error, key: "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", message: "File name '{0}' differs from already included file name '{1}' only in casing." }, - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: ts.DiagnosticCategory.Error, key: "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", message: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, - const_declarations_must_be_initialized: { code: 1155, category: ts.DiagnosticCategory.Error, key: "const_declarations_must_be_initialized_1155", message: "'const' declarations must be initialized." }, - const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: ts.DiagnosticCategory.Error, key: "const_declarations_can_only_be_declared_inside_a_block_1156", message: "'const' declarations can only be declared inside a block." }, - let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: ts.DiagnosticCategory.Error, key: "let_declarations_can_only_be_declared_inside_a_block_1157", message: "'let' declarations can only be declared inside a block." }, - Unterminated_template_literal: { code: 1160, category: ts.DiagnosticCategory.Error, key: "Unterminated_template_literal_1160", message: "Unterminated template literal." }, - Unterminated_regular_expression_literal: { code: 1161, category: ts.DiagnosticCategory.Error, key: "Unterminated_regular_expression_literal_1161", message: "Unterminated regular expression literal." }, - An_object_member_cannot_be_declared_optional: { code: 1162, category: ts.DiagnosticCategory.Error, key: "An_object_member_cannot_be_declared_optional_1162", message: "An object member cannot be declared optional." }, - A_yield_expression_is_only_allowed_in_a_generator_body: { code: 1163, category: ts.DiagnosticCategory.Error, key: "A_yield_expression_is_only_allowed_in_a_generator_body_1163", message: "A 'yield' expression is only allowed in a generator body." }, - Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: ts.DiagnosticCategory.Error, key: "Computed_property_names_are_not_allowed_in_enums_1164", message: "Computed property names are not allowed in enums." }, - A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", message: "A computed property name in an ambient context must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", message: "A computed property name in a class property declaration must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", message: "A computed property name in a method overload must directly refer to a built-in symbol." }, - A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", message: "A computed property name in an interface must directly refer to a built-in symbol." }, - A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", message: "A computed property name in a type literal must directly refer to a built-in symbol." }, - A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: ts.DiagnosticCategory.Error, key: "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", message: "A comma expression is not allowed in a computed property name." }, - extends_clause_already_seen: { code: 1172, category: ts.DiagnosticCategory.Error, key: "extends_clause_already_seen_1172", message: "'extends' clause already seen." }, - extends_clause_must_precede_implements_clause: { code: 1173, category: ts.DiagnosticCategory.Error, key: "extends_clause_must_precede_implements_clause_1173", message: "'extends' clause must precede 'implements' clause." }, - Classes_can_only_extend_a_single_class: { code: 1174, category: ts.DiagnosticCategory.Error, key: "Classes_can_only_extend_a_single_class_1174", message: "Classes can only extend a single class." }, - implements_clause_already_seen: { code: 1175, category: ts.DiagnosticCategory.Error, key: "implements_clause_already_seen_1175", message: "'implements' clause already seen." }, - Interface_declaration_cannot_have_implements_clause: { code: 1176, category: ts.DiagnosticCategory.Error, key: "Interface_declaration_cannot_have_implements_clause_1176", message: "Interface declaration cannot have 'implements' clause." }, - Binary_digit_expected: { code: 1177, category: ts.DiagnosticCategory.Error, key: "Binary_digit_expected_1177", message: "Binary digit expected." }, - Octal_digit_expected: { code: 1178, category: ts.DiagnosticCategory.Error, key: "Octal_digit_expected_1178", message: "Octal digit expected." }, - Unexpected_token_expected: { code: 1179, category: ts.DiagnosticCategory.Error, key: "Unexpected_token_expected_1179", message: "Unexpected token. '{' expected." }, - Property_destructuring_pattern_expected: { code: 1180, category: ts.DiagnosticCategory.Error, key: "Property_destructuring_pattern_expected_1180", message: "Property destructuring pattern expected." }, - Array_element_destructuring_pattern_expected: { code: 1181, category: ts.DiagnosticCategory.Error, key: "Array_element_destructuring_pattern_expected_1181", message: "Array element destructuring pattern expected." }, - A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: ts.DiagnosticCategory.Error, key: "A_destructuring_declaration_must_have_an_initializer_1182", message: "A destructuring declaration must have an initializer." }, - An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1183, category: ts.DiagnosticCategory.Error, key: "An_implementation_cannot_be_declared_in_ambient_contexts_1183", message: "An implementation cannot be declared in ambient contexts." }, - Modifiers_cannot_appear_here: { code: 1184, category: ts.DiagnosticCategory.Error, key: "Modifiers_cannot_appear_here_1184", message: "Modifiers cannot appear here." }, - Merge_conflict_marker_encountered: { code: 1185, category: ts.DiagnosticCategory.Error, key: "Merge_conflict_marker_encountered_1185", message: "Merge conflict marker encountered." }, - A_rest_element_cannot_have_an_initializer: { code: 1186, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_have_an_initializer_1186", message: "A rest element cannot have an initializer." }, - A_parameter_property_may_not_be_declared_using_a_binding_pattern: { code: 1187, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", message: "A parameter property may not be declared using a binding pattern." }, - Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: { code: 1188, category: ts.DiagnosticCategory.Error, key: "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", message: "Only a single variable declaration is allowed in a 'for...of' statement." }, - The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: { code: 1189, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", message: "The variable declaration of a 'for...in' statement cannot have an initializer." }, - The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: { code: 1190, category: ts.DiagnosticCategory.Error, key: "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", message: "The variable declaration of a 'for...of' statement cannot have an initializer." }, - An_import_declaration_cannot_have_modifiers: { code: 1191, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_cannot_have_modifiers_1191", message: "An import declaration cannot have modifiers." }, - Module_0_has_no_default_export: { code: 1192, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_default_export_1192", message: "Module '{0}' has no default export." }, - An_export_declaration_cannot_have_modifiers: { code: 1193, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_cannot_have_modifiers_1193", message: "An export declaration cannot have modifiers." }, - Export_declarations_are_not_permitted_in_a_namespace: { code: 1194, category: ts.DiagnosticCategory.Error, key: "Export_declarations_are_not_permitted_in_a_namespace_1194", message: "Export declarations are not permitted in a namespace." }, - Catch_clause_variable_cannot_have_a_type_annotation: { code: 1196, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_a_type_annotation_1196", message: "Catch clause variable cannot have a type annotation." }, - Catch_clause_variable_cannot_have_an_initializer: { code: 1197, category: ts.DiagnosticCategory.Error, key: "Catch_clause_variable_cannot_have_an_initializer_1197", message: "Catch clause variable cannot have an initializer." }, - An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: { code: 1198, category: ts.DiagnosticCategory.Error, key: "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", message: "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive." }, - Unterminated_Unicode_escape_sequence: { code: 1199, category: ts.DiagnosticCategory.Error, key: "Unterminated_Unicode_escape_sequence_1199", message: "Unterminated Unicode escape sequence." }, - 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." }, - Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: { code: 1209, category: ts.DiagnosticCategory.Error, key: "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", message: "Ambient const enums are not allowed when the '--isolatedModules' flag is provided." }, - Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: { code: 1210, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", message: "Invalid use of '{0}'. Class definitions are automatically in strict mode." }, - A_class_declaration_without_the_default_modifier_must_have_a_name: { code: 1211, category: ts.DiagnosticCategory.Error, key: "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", message: "A class declaration without the 'default' modifier must have a name." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode: { code: 1212, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", message: "Identifier expected. '{0}' is a reserved word in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, - Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, - Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, - Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, - Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, - Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, - Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, - Generators_are_not_allowed_in_an_ambient_context: { code: 1221, category: ts.DiagnosticCategory.Error, key: "Generators_are_not_allowed_in_an_ambient_context_1221", message: "Generators are not allowed in an ambient context." }, - An_overload_signature_cannot_be_declared_as_a_generator: { code: 1222, category: ts.DiagnosticCategory.Error, key: "An_overload_signature_cannot_be_declared_as_a_generator_1222", message: "An overload signature cannot be declared as a generator." }, - _0_tag_already_specified: { code: 1223, category: ts.DiagnosticCategory.Error, key: "_0_tag_already_specified_1223", message: "'{0}' tag already specified." }, - Signature_0_must_have_a_type_predicate: { code: 1224, category: ts.DiagnosticCategory.Error, key: "Signature_0_must_have_a_type_predicate_1224", message: "Signature '{0}' must have a type predicate." }, - Cannot_find_parameter_0: { code: 1225, category: ts.DiagnosticCategory.Error, key: "Cannot_find_parameter_0_1225", message: "Cannot find parameter '{0}'." }, - Type_predicate_0_is_not_assignable_to_1: { code: 1226, category: ts.DiagnosticCategory.Error, key: "Type_predicate_0_is_not_assignable_to_1_1226", message: "Type predicate '{0}' is not assignable to '{1}'." }, - Parameter_0_is_not_in_the_same_position_as_parameter_1: { code: 1227, category: ts.DiagnosticCategory.Error, key: "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", message: "Parameter '{0}' is not in the same position as parameter '{1}'." }, - A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: { code: 1228, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", message: "A type predicate is only allowed in return type position for functions and methods." }, - A_type_predicate_cannot_reference_a_rest_parameter: { code: 1229, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_a_rest_parameter_1229", message: "A type predicate cannot reference a rest parameter." }, - A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: { code: 1230, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", message: "A type predicate cannot reference element '{0}' in a binding pattern." }, - An_export_assignment_can_only_be_used_in_a_module: { code: 1231, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_can_only_be_used_in_a_module_1231", message: "An export assignment can only be used in a module." }, - An_import_declaration_can_only_be_used_in_a_namespace_or_module: { code: 1232, category: ts.DiagnosticCategory.Error, key: "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", message: "An import declaration can only be used in a namespace or module." }, - An_export_declaration_can_only_be_used_in_a_module: { code: 1233, category: ts.DiagnosticCategory.Error, key: "An_export_declaration_can_only_be_used_in_a_module_1233", message: "An export declaration can only be used in a module." }, - An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: { code: 1234, category: ts.DiagnosticCategory.Error, key: "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", message: "An ambient module declaration is only allowed at the top level in a file." }, - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: { code: 1235, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", message: "A namespace declaration is only allowed in a namespace or module." }, - The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", message: "The return type of a property decorator function must be either 'void' or 'any'." }, - The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", message: "The return type of a parameter decorator function must be either 'void' or 'any'." }, - Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", message: "Unable to resolve signature of class decorator when called as an expression." }, - Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", message: "Unable to resolve signature of parameter decorator when called as an expression." }, - Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", message: "Unable to resolve signature of property decorator when called as an expression." }, - Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: ts.DiagnosticCategory.Error, key: "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", message: "Unable to resolve signature of method decorator when called as an expression." }, - abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: { code: 1242, category: ts.DiagnosticCategory.Error, key: "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", message: "'abstract' modifier can only appear on a class, method, or property declaration." }, - _0_modifier_cannot_be_used_with_1_modifier: { code: 1243, category: ts.DiagnosticCategory.Error, key: "_0_modifier_cannot_be_used_with_1_modifier_1243", message: "'{0}' modifier cannot be used with '{1}' modifier." }, - Abstract_methods_can_only_appear_within_an_abstract_class: { code: 1244, category: ts.DiagnosticCategory.Error, key: "Abstract_methods_can_only_appear_within_an_abstract_class_1244", message: "Abstract methods can only appear within an abstract class." }, - Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: { code: 1245, category: ts.DiagnosticCategory.Error, key: "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", message: "Method '{0}' cannot have an implementation because it is marked abstract." }, - An_interface_property_cannot_have_an_initializer: { code: 1246, category: ts.DiagnosticCategory.Error, key: "An_interface_property_cannot_have_an_initializer_1246", message: "An interface property cannot have an initializer." }, - A_type_literal_property_cannot_have_an_initializer: { code: 1247, category: ts.DiagnosticCategory.Error, key: "A_type_literal_property_cannot_have_an_initializer_1247", message: "A type literal property cannot have an initializer." }, - A_class_member_cannot_have_the_0_keyword: { code: 1248, category: ts.DiagnosticCategory.Error, key: "A_class_member_cannot_have_the_0_keyword_1248", message: "A class member cannot have the '{0}' keyword." }, - A_decorator_can_only_decorate_a_method_implementation_not_an_overload: { code: 1249, category: ts.DiagnosticCategory.Error, key: "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", message: "A decorator can only decorate a method implementation, not an overload." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: { code: 1250, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: { code: 1251, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode." }, - Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: { code: 1252, category: ts.DiagnosticCategory.Error, key: "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", message: "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode." }, - _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: { code: 1253, category: ts.DiagnosticCategory.Error, key: "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", message: "'{0}' tag cannot be used independently as a top level JSDoc tag." }, - A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: { code: 1254, category: ts.DiagnosticCategory.Error, key: "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", message: "A 'const' initializer in an ambient context must be a string or numeric literal." }, - with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: ts.DiagnosticCategory.Error, key: "with_statements_are_not_allowed_in_an_async_function_block_1300", message: "'with' statements are not allowed in an async function block." }, - await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, - can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, - The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, - Global_module_exports_may_only_appear_in_module_files: { code: 1314, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_module_files_1314", message: "Global module exports may only appear in module files." }, - Global_module_exports_may_only_appear_in_declaration_files: { code: 1315, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_in_declaration_files_1315", message: "Global module exports may only appear in declaration files." }, - Global_module_exports_may_only_appear_at_top_level: { code: 1316, category: ts.DiagnosticCategory.Error, key: "Global_module_exports_may_only_appear_at_top_level_1316", message: "Global module exports may only appear at top level." }, - A_parameter_property_cannot_be_declared_using_a_rest_parameter: { code: 1317, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", message: "A parameter property cannot be declared using a rest parameter." }, - An_abstract_accessor_cannot_have_an_implementation: { code: 1318, category: ts.DiagnosticCategory.Error, key: "An_abstract_accessor_cannot_have_an_implementation_1318", message: "An abstract accessor cannot have an implementation." }, - A_default_export_can_only_be_used_in_an_ECMAScript_style_module: { code: 1319, category: ts.DiagnosticCategory.Error, key: "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", message: "A default export can only be used in an ECMAScript-style module." }, - Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1320, category: ts.DiagnosticCategory.Error, key: "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", message: "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1321, category: ts.DiagnosticCategory.Error, key: "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", message: "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member." }, - Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: { code: 1322, category: ts.DiagnosticCategory.Error, key: "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", message: "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member." }, - Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, - Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, - Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, - Circular_definition_of_import_alias_0: { code: 2303, category: ts.DiagnosticCategory.Error, key: "Circular_definition_of_import_alias_0_2303", message: "Circular definition of import alias '{0}'." }, - Cannot_find_name_0: { code: 2304, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_2304", message: "Cannot find name '{0}'." }, - Module_0_has_no_exported_member_1: { code: 2305, category: ts.DiagnosticCategory.Error, key: "Module_0_has_no_exported_member_1_2305", message: "Module '{0}' has no exported member '{1}'." }, - File_0_is_not_a_module: { code: 2306, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_a_module_2306", message: "File '{0}' is not a module." }, - Cannot_find_module_0: { code: 2307, category: ts.DiagnosticCategory.Error, key: "Cannot_find_module_0_2307", message: "Cannot find module '{0}'." }, - Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: { code: 2308, category: ts.DiagnosticCategory.Error, key: "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", message: "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity." }, - An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: ts.DiagnosticCategory.Error, key: "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", message: "An export assignment cannot be used in a module with other exported elements." }, - Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: ts.DiagnosticCategory.Error, key: "Type_0_recursively_references_itself_as_a_base_type_2310", message: "Type '{0}' recursively references itself as a base type." }, - A_class_may_only_extend_another_class: { code: 2311, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_extend_another_class_2311", message: "A class may only extend another class." }, - An_interface_may_only_extend_a_class_or_another_interface: { code: 2312, category: ts.DiagnosticCategory.Error, key: "An_interface_may_only_extend_a_class_or_another_interface_2312", message: "An interface may only extend a class or another interface." }, - Type_parameter_0_has_a_circular_constraint: { code: 2313, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_has_a_circular_constraint_2313", message: "Type parameter '{0}' has a circular constraint." }, - Generic_type_0_requires_1_type_argument_s: { code: 2314, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_1_type_argument_s_2314", message: "Generic type '{0}' requires {1} type argument(s)." }, - Type_0_is_not_generic: { code: 2315, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_generic_2315", message: "Type '{0}' is not generic." }, - Global_type_0_must_be_a_class_or_interface_type: { code: 2316, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_be_a_class_or_interface_type_2316", message: "Global type '{0}' must be a class or interface type." }, - Global_type_0_must_have_1_type_parameter_s: { code: 2317, category: ts.DiagnosticCategory.Error, key: "Global_type_0_must_have_1_type_parameter_s_2317", message: "Global type '{0}' must have {1} type parameter(s)." }, - Cannot_find_global_type_0: { code: 2318, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_type_0_2318", message: "Cannot find global type '{0}'." }, - Named_property_0_of_types_1_and_2_are_not_identical: { code: 2319, category: ts.DiagnosticCategory.Error, key: "Named_property_0_of_types_1_and_2_are_not_identical_2319", message: "Named property '{0}' of types '{1}' and '{2}' are not identical." }, - Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: ts.DiagnosticCategory.Error, key: "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", message: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." }, - Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: ts.DiagnosticCategory.Error, key: "Excessive_stack_depth_comparing_types_0_and_1_2321", message: "Excessive stack depth comparing types '{0}' and '{1}'." }, - Type_0_is_not_assignable_to_type_1: { code: 2322, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_2322", message: "Type '{0}' is not assignable to type '{1}'." }, - Cannot_redeclare_exported_variable_0: { code: 2323, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_exported_variable_0_2323", message: "Cannot redeclare exported variable '{0}'." }, - Property_0_is_missing_in_type_1: { code: 2324, category: ts.DiagnosticCategory.Error, key: "Property_0_is_missing_in_type_1_2324", message: "Property '{0}' is missing in type '{1}'." }, - Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_in_type_1_but_not_in_type_2_2325", message: "Property '{0}' is private in type '{1}' but not in type '{2}'." }, - Types_of_property_0_are_incompatible: { code: 2326, category: ts.DiagnosticCategory.Error, key: "Types_of_property_0_are_incompatible_2326", message: "Types of property '{0}' are incompatible." }, - Property_0_is_optional_in_type_1_but_required_in_type_2: { code: 2327, category: ts.DiagnosticCategory.Error, key: "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", message: "Property '{0}' is optional in type '{1}' but required in type '{2}'." }, - Types_of_parameters_0_and_1_are_incompatible: { code: 2328, category: ts.DiagnosticCategory.Error, key: "Types_of_parameters_0_and_1_are_incompatible_2328", message: "Types of parameters '{0}' and '{1}' are incompatible." }, - Index_signature_is_missing_in_type_0: { code: 2329, category: ts.DiagnosticCategory.Error, key: "Index_signature_is_missing_in_type_0_2329", message: "Index signature is missing in type '{0}'." }, - Index_signatures_are_incompatible: { code: 2330, category: ts.DiagnosticCategory.Error, key: "Index_signatures_are_incompatible_2330", message: "Index signatures are incompatible." }, - this_cannot_be_referenced_in_a_module_or_namespace_body: { code: 2331, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", message: "'this' cannot be referenced in a module or namespace body." }, - this_cannot_be_referenced_in_current_location: { code: 2332, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_current_location_2332", message: "'this' cannot be referenced in current location." }, - this_cannot_be_referenced_in_constructor_arguments: { code: 2333, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_constructor_arguments_2333", message: "'this' cannot be referenced in constructor arguments." }, - this_cannot_be_referenced_in_a_static_property_initializer: { code: 2334, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_static_property_initializer_2334", message: "'this' cannot be referenced in a static property initializer." }, - super_can_only_be_referenced_in_a_derived_class: { code: 2335, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_a_derived_class_2335", message: "'super' can only be referenced in a derived class." }, - super_cannot_be_referenced_in_constructor_arguments: { code: 2336, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_constructor_arguments_2336", message: "'super' cannot be referenced in constructor arguments." }, - Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: { code: 2337, category: ts.DiagnosticCategory.Error, key: "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", message: "Super calls are not permitted outside constructors or in nested functions inside constructors." }, - super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: { code: 2338, category: ts.DiagnosticCategory.Error, key: "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", message: "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class." }, - Property_0_does_not_exist_on_type_1: { code: 2339, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_type_1_2339", message: "Property '{0}' does not exist on type '{1}'." }, - Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: { code: 2340, category: ts.DiagnosticCategory.Error, key: "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", message: "Only public and protected methods of the base class are accessible via the 'super' keyword." }, - Property_0_is_private_and_only_accessible_within_class_1: { code: 2341, category: ts.DiagnosticCategory.Error, key: "Property_0_is_private_and_only_accessible_within_class_1_2341", message: "Property '{0}' is private and only accessible within class '{1}'." }, - An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: { code: 2342, category: ts.DiagnosticCategory.Error, key: "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", message: "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'." }, - 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}'." }, - 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." }, - Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: ts.DiagnosticCategory.Error, key: "Only_a_void_function_can_be_called_with_the_new_keyword_2350", message: "Only a void function can be called with the 'new' keyword." }, - Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: ts.DiagnosticCategory.Error, key: "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", message: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, - Type_0_cannot_be_converted_to_type_1: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_converted_to_type_1_2352", message: "Type '{0}' cannot be converted to type '{1}'." }, - Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, - This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: { code: 2354, category: ts.DiagnosticCategory.Error, key: "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", message: "This syntax requires an imported helper but module '{0}' cannot be found." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, - An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, - The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", message: "The operand of an increment or decrement operator must be a variable or a property access." }, - The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, - The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: { code: 2359, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", message: "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type." }, - The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: { code: 2360, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", message: "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'." }, - The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2361, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", message: "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter." }, - The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2362, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", message: "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: { code: 2363, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", message: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." }, - The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: { code: 2364, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", message: "The left-hand side of an assignment expression must be a variable or a property access." }, - Operator_0_cannot_be_applied_to_types_1_and_2: { code: 2365, category: ts.DiagnosticCategory.Error, key: "Operator_0_cannot_be_applied_to_types_1_and_2_2365", message: "Operator '{0}' cannot be applied to types '{1}' and '{2}'." }, - Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: { code: 2366, category: ts.DiagnosticCategory.Error, key: "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", message: "Function lacks ending return statement and return type does not include 'undefined'." }, - Type_parameter_name_cannot_be_0: { code: 2368, category: ts.DiagnosticCategory.Error, key: "Type_parameter_name_cannot_be_0_2368", message: "Type parameter name cannot be '{0}'." }, - A_parameter_property_is_only_allowed_in_a_constructor_implementation: { code: 2369, category: ts.DiagnosticCategory.Error, key: "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", message: "A parameter property is only allowed in a constructor implementation." }, - A_rest_parameter_must_be_of_an_array_type: { code: 2370, category: ts.DiagnosticCategory.Error, key: "A_rest_parameter_must_be_of_an_array_type_2370", message: "A rest parameter must be of an array type." }, - A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: { code: 2371, category: ts.DiagnosticCategory.Error, key: "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", message: "A parameter initializer is only allowed in a function or constructor implementation." }, - Parameter_0_cannot_be_referenced_in_its_initializer: { code: 2372, category: ts.DiagnosticCategory.Error, key: "Parameter_0_cannot_be_referenced_in_its_initializer_2372", message: "Parameter '{0}' cannot be referenced in its initializer." }, - Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: { code: 2373, category: ts.DiagnosticCategory.Error, key: "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", message: "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it." }, - Duplicate_string_index_signature: { code: 2374, category: ts.DiagnosticCategory.Error, key: "Duplicate_string_index_signature_2374", message: "Duplicate string index signature." }, - Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, - Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, - Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, - get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, - A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, - Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: { code: 2382, category: ts.DiagnosticCategory.Error, key: "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", message: "Specialized overload signature is not assignable to any non-specialized signature." }, - Overload_signatures_must_all_be_exported_or_non_exported: { code: 2383, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_exported_or_non_exported_2383", message: "Overload signatures must all be exported or non-exported." }, - Overload_signatures_must_all_be_ambient_or_non_ambient: { code: 2384, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", message: "Overload signatures must all be ambient or non-ambient." }, - Overload_signatures_must_all_be_public_private_or_protected: { code: 2385, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_public_private_or_protected_2385", message: "Overload signatures must all be public, private or protected." }, - Overload_signatures_must_all_be_optional_or_required: { code: 2386, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_optional_or_required_2386", message: "Overload signatures must all be optional or required." }, - Function_overload_must_be_static: { code: 2387, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_be_static_2387", message: "Function overload must be static." }, - Function_overload_must_not_be_static: { code: 2388, category: ts.DiagnosticCategory.Error, key: "Function_overload_must_not_be_static_2388", message: "Function overload must not be static." }, - Function_implementation_name_must_be_0: { code: 2389, category: ts.DiagnosticCategory.Error, key: "Function_implementation_name_must_be_0_2389", message: "Function implementation name must be '{0}'." }, - Constructor_implementation_is_missing: { code: 2390, category: ts.DiagnosticCategory.Error, key: "Constructor_implementation_is_missing_2390", message: "Constructor implementation is missing." }, - Function_implementation_is_missing_or_not_immediately_following_the_declaration: { code: 2391, category: ts.DiagnosticCategory.Error, key: "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", message: "Function implementation is missing or not immediately following the declaration." }, - Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: ts.DiagnosticCategory.Error, key: "Multiple_constructor_implementations_are_not_allowed_2392", message: "Multiple constructor implementations are not allowed." }, - Duplicate_function_implementation: { code: 2393, category: ts.DiagnosticCategory.Error, key: "Duplicate_function_implementation_2393", message: "Duplicate function implementation." }, - Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: ts.DiagnosticCategory.Error, key: "Overload_signature_is_not_compatible_with_function_implementation_2394", message: "Overload signature is not compatible with function implementation." }, - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: ts.DiagnosticCategory.Error, key: "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", message: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, - Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", message: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, - Declaration_name_conflicts_with_built_in_global_identifier_0: { code: 2397, category: ts.DiagnosticCategory.Error, key: "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", message: "Declaration name conflicts with built-in global identifier '{0}'." }, - Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", message: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, - Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", message: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, - Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: { code: 2401, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", message: "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference." }, - Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: { code: 2402, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", message: "Expression resolves to '_super' that compiler uses to capture base class reference." }, - Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: { code: 2403, category: ts.DiagnosticCategory.Error, key: "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", message: "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'." }, - The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: { code: 2404, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", message: "The left-hand side of a 'for...in' statement cannot use a type annotation." }, - The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: { code: 2405, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", message: "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'." }, - The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: { code: 2406, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", message: "The left-hand side of a 'for...in' statement must be a variable or a property access." }, - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, - Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, - Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class." }, - The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, - Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, - Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, - Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, - Class_name_cannot_be_0: { code: 2414, category: ts.DiagnosticCategory.Error, key: "Class_name_cannot_be_0_2414", message: "Class name cannot be '{0}'." }, - Class_0_incorrectly_extends_base_class_1: { code: 2415, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_extends_base_class_1_2415", message: "Class '{0}' incorrectly extends base class '{1}'." }, - Class_static_side_0_incorrectly_extends_base_class_static_side_1: { code: 2417, category: ts.DiagnosticCategory.Error, key: "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", message: "Class static side '{0}' incorrectly extends base class static side '{1}'." }, - Class_0_incorrectly_implements_interface_1: { code: 2420, category: ts.DiagnosticCategory.Error, key: "Class_0_incorrectly_implements_interface_1_2420", message: "Class '{0}' incorrectly implements interface '{1}'." }, - A_class_may_only_implement_another_class_or_interface: { code: 2422, category: ts.DiagnosticCategory.Error, key: "A_class_may_only_implement_another_class_or_interface_2422", message: "A class may only implement another class or interface." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: { code: 2423, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor." }, - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: { code: 2424, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", message: "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property." }, - Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2425, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", message: "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function." }, - Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: { code: 2426, category: ts.DiagnosticCategory.Error, key: "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", message: "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function." }, - Interface_name_cannot_be_0: { code: 2427, category: ts.DiagnosticCategory.Error, key: "Interface_name_cannot_be_0_2427", message: "Interface name cannot be '{0}'." }, - All_declarations_of_0_must_have_identical_type_parameters: { code: 2428, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_type_parameters_2428", message: "All declarations of '{0}' must have identical type parameters." }, - Interface_0_incorrectly_extends_interface_1: { code: 2430, category: ts.DiagnosticCategory.Error, key: "Interface_0_incorrectly_extends_interface_1_2430", message: "Interface '{0}' incorrectly extends interface '{1}'." }, - Enum_name_cannot_be_0: { code: 2431, category: ts.DiagnosticCategory.Error, key: "Enum_name_cannot_be_0_2431", message: "Enum name cannot be '{0}'." }, - In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: { code: 2432, category: ts.DiagnosticCategory.Error, key: "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", message: "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element." }, - A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: { code: 2433, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", message: "A namespace declaration cannot be in a different file from a class or function with which it is merged." }, - A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: { code: 2434, category: ts.DiagnosticCategory.Error, key: "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", message: "A namespace declaration cannot be located prior to a class or function with which it is merged." }, - Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: { code: 2435, category: ts.DiagnosticCategory.Error, key: "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", message: "Ambient modules cannot be nested in other modules or namespaces." }, - Ambient_module_declaration_cannot_specify_relative_module_name: { code: 2436, category: ts.DiagnosticCategory.Error, key: "Ambient_module_declaration_cannot_specify_relative_module_name_2436", message: "Ambient module declaration cannot specify relative module name." }, - Module_0_is_hidden_by_a_local_declaration_with_the_same_name: { code: 2437, category: ts.DiagnosticCategory.Error, key: "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", message: "Module '{0}' is hidden by a local declaration with the same name." }, - Import_name_cannot_be_0: { code: 2438, category: ts.DiagnosticCategory.Error, key: "Import_name_cannot_be_0_2438", message: "Import name cannot be '{0}'." }, - Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: { code: 2439, category: ts.DiagnosticCategory.Error, key: "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", message: "Import or export declaration in an ambient module declaration cannot reference module through relative module name." }, - Import_declaration_conflicts_with_local_declaration_of_0: { code: 2440, category: ts.DiagnosticCategory.Error, key: "Import_declaration_conflicts_with_local_declaration_of_0_2440", message: "Import declaration conflicts with local declaration of '{0}'." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: { code: 2441, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module." }, - Types_have_separate_declarations_of_a_private_property_0: { code: 2442, category: ts.DiagnosticCategory.Error, key: "Types_have_separate_declarations_of_a_private_property_0_2442", message: "Types have separate declarations of a private property '{0}'." }, - Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: { code: 2443, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", message: "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'." }, - Property_0_is_protected_in_type_1_but_public_in_type_2: { code: 2444, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", message: "Property '{0}' is protected in type '{1}' but public in type '{2}'." }, - Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", message: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, - Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: ts.DiagnosticCategory.Error, key: "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", message: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, - The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: ts.DiagnosticCategory.Error, key: "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", message: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, - Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: ts.DiagnosticCategory.Error, key: "Block_scoped_variable_0_used_before_its_declaration_2448", message: "Block-scoped variable '{0}' used before its declaration." }, - Class_0_used_before_its_declaration: { code: 2449, category: ts.DiagnosticCategory.Error, key: "Class_0_used_before_its_declaration_2449", message: "Class '{0}' used before its declaration." }, - Enum_0_used_before_its_declaration: { code: 2450, category: ts.DiagnosticCategory.Error, key: "Enum_0_used_before_its_declaration_2450", message: "Enum '{0}' used before its declaration." }, - Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_block_scoped_variable_0_2451", message: "Cannot redeclare block-scoped variable '{0}'." }, - An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: ts.DiagnosticCategory.Error, key: "An_enum_member_cannot_have_a_numeric_name_2452", message: "An enum member cannot have a numeric name." }, - The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: ts.DiagnosticCategory.Error, key: "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", message: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, - Variable_0_is_used_before_being_assigned: { code: 2454, category: ts.DiagnosticCategory.Error, key: "Variable_0_is_used_before_being_assigned_2454", message: "Variable '{0}' is used before being assigned." }, - Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: ts.DiagnosticCategory.Error, key: "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", message: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, - Type_alias_0_circularly_references_itself: { code: 2456, category: ts.DiagnosticCategory.Error, key: "Type_alias_0_circularly_references_itself_2456", message: "Type alias '{0}' circularly references itself." }, - Type_alias_name_cannot_be_0: { code: 2457, category: ts.DiagnosticCategory.Error, key: "Type_alias_name_cannot_be_0_2457", message: "Type alias name cannot be '{0}'." }, - An_AMD_module_cannot_have_multiple_name_assignments: { code: 2458, category: ts.DiagnosticCategory.Error, key: "An_AMD_module_cannot_have_multiple_name_assignments_2458", message: "An AMD module cannot have multiple name assignments." }, - Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_and_no_string_index_signature_2459", message: "Type '{0}' has no property '{1}' and no string index signature." }, - Type_0_has_no_property_1: { code: 2460, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_property_1_2460", message: "Type '{0}' has no property '{1}'." }, - Type_0_is_not_an_array_type: { code: 2461, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_2461", message: "Type '{0}' is not an array type." }, - A_rest_element_must_be_last_in_a_destructuring_pattern: { code: 2462, category: ts.DiagnosticCategory.Error, key: "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", message: "A rest element must be last in a destructuring pattern." }, - A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: ts.DiagnosticCategory.Error, key: "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", message: "A binding pattern parameter cannot be optional in an implementation signature." }, - A_computed_property_name_must_be_of_type_string_number_symbol_or_any: { code: 2464, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", message: "A computed property name must be of type 'string', 'number', 'symbol', or 'any'." }, - this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: ts.DiagnosticCategory.Error, key: "this_cannot_be_referenced_in_a_computed_property_name_2465", message: "'this' cannot be referenced in a computed property name." }, - super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: ts.DiagnosticCategory.Error, key: "super_cannot_be_referenced_in_a_computed_property_name_2466", message: "'super' cannot be referenced in a computed property name." }, - A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2467, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", message: "A computed property name cannot reference a type parameter from its containing type." }, - Cannot_find_global_value_0: { code: 2468, category: ts.DiagnosticCategory.Error, key: "Cannot_find_global_value_0_2468", message: "Cannot find global value '{0}'." }, - The_0_operator_cannot_be_applied_to_type_symbol: { code: 2469, category: ts.DiagnosticCategory.Error, key: "The_0_operator_cannot_be_applied_to_type_symbol_2469", message: "The '{0}' operator cannot be applied to type 'symbol'." }, - Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: { code: 2470, category: ts.DiagnosticCategory.Error, key: "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", message: "'Symbol' reference does not refer to the global Symbol constructor object." }, - A_computed_property_name_of_the_form_0_must_be_of_type_symbol: { code: 2471, category: ts.DiagnosticCategory.Error, key: "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", message: "A computed property name of the form '{0}' must be of type 'symbol'." }, - Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: { code: 2472, category: ts.DiagnosticCategory.Error, key: "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", message: "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher." }, - Enum_declarations_must_all_be_const_or_non_const: { code: 2473, category: ts.DiagnosticCategory.Error, key: "Enum_declarations_must_all_be_const_or_non_const_2473", message: "Enum declarations must all be const or non-const." }, - In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 2474, category: ts.DiagnosticCategory.Error, key: "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", message: "In 'const' enum declarations member initializer must be constant expression." }, - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 2475, category: ts.DiagnosticCategory.Error, key: "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", message: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." }, - A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 2476, category: ts.DiagnosticCategory.Error, key: "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", message: "A const enum member can only be accessed using a string literal." }, - const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 2477, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", message: "'const' enum member initializer was evaluated to a non-finite value." }, - const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 2478, category: ts.DiagnosticCategory.Error, key: "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", message: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, - Property_0_does_not_exist_on_const_enum_1: { code: 2479, category: ts.DiagnosticCategory.Error, key: "Property_0_does_not_exist_on_const_enum_1_2479", message: "Property '{0}' does not exist on 'const' enum '{1}'." }, - let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: { code: 2480, category: ts.DiagnosticCategory.Error, key: "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", message: "'let' is not allowed to be used as a name in 'let' or 'const' declarations." }, - Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: { code: 2481, category: ts.DiagnosticCategory.Error, key: "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", message: "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'." }, - The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: { code: 2483, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", message: "The left-hand side of a 'for...of' statement cannot use a type annotation." }, - Export_declaration_conflicts_with_exported_declaration_of_0: { code: 2484, category: ts.DiagnosticCategory.Error, key: "Export_declaration_conflicts_with_exported_declaration_of_0_2484", message: "Export declaration conflicts with exported declaration of '{0}'." }, - The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: { code: 2487, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", message: "The left-hand side of a 'for...of' statement must be a variable or a property access." }, - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: { code: 2488, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", message: "Type must have a '[Symbol.iterator]()' method that returns an iterator." }, - An_iterator_must_have_a_next_method: { code: 2489, category: ts.DiagnosticCategory.Error, key: "An_iterator_must_have_a_next_method_2489", message: "An iterator must have a 'next()' method." }, - The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: { code: 2490, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", message: "The type returned by the 'next()' method of an iterator must have a 'value' property." }, - The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: { code: 2491, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", message: "The left-hand side of a 'for...in' statement cannot be a destructuring pattern." }, - Cannot_redeclare_identifier_0_in_catch_clause: { code: 2492, category: ts.DiagnosticCategory.Error, key: "Cannot_redeclare_identifier_0_in_catch_clause_2492", message: "Cannot redeclare identifier '{0}' in catch clause." }, - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: { code: 2493, category: ts.DiagnosticCategory.Error, key: "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", message: "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'." }, - Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: { code: 2494, category: ts.DiagnosticCategory.Error, key: "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", message: "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher." }, - Type_0_is_not_an_array_type_or_a_string_type: { code: 2495, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_an_array_type_or_a_string_type_2495", message: "Type '{0}' is not an array type or a string type." }, - The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: { code: 2496, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", message: "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression." }, - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: { code: 2497, category: ts.DiagnosticCategory.Error, key: "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", message: "Module '{0}' resolves to a non-module entity and cannot be imported using this construct." }, - Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: { code: 2498, category: ts.DiagnosticCategory.Error, key: "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", message: "Module '{0}' uses 'export =' and cannot be used with 'export *'." }, - An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", message: "An interface can only extend an identifier/qualified-name with optional type arguments." }, - A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", message: "A class can only implement an identifier/qualified-name with optional type arguments." }, - A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A_rest_element_cannot_contain_a_binding_pattern_2501", message: "A rest element cannot contain a binding pattern." }, - _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", message: "'{0}' is referenced directly or indirectly in its own type annotation." }, - Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot_find_namespace_0_2503", message: "Cannot find namespace '{0}'." }, - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: { code: 2504, category: ts.DiagnosticCategory.Error, key: "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", message: "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator." }, - A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: ts.DiagnosticCategory.Error, key: "A_generator_cannot_have_a_void_type_annotation_2505", message: "A generator cannot have a 'void' type annotation." }, - _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: ts.DiagnosticCategory.Error, key: "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", message: "'{0}' is referenced directly or indirectly in its own base expression." }, - Type_0_is_not_a_constructor_function_type: { code: 2507, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_a_constructor_function_type_2507", message: "Type '{0}' is not a constructor function type." }, - No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: ts.DiagnosticCategory.Error, key: "No_base_constructor_has_the_specified_number_of_type_arguments_2508", message: "No base constructor has the specified number of type arguments." }, - Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: ts.DiagnosticCategory.Error, key: "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", message: "Base constructor return type '{0}' is not a class or interface type." }, - Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: ts.DiagnosticCategory.Error, key: "Base_constructors_must_all_have_the_same_return_type_2510", message: "Base constructors must all have the same return type." }, - Cannot_create_an_instance_of_the_abstract_class_0: { code: 2511, category: ts.DiagnosticCategory.Error, key: "Cannot_create_an_instance_of_the_abstract_class_0_2511", message: "Cannot create an instance of the abstract class '{0}'." }, - Overload_signatures_must_all_be_abstract_or_non_abstract: { code: 2512, category: ts.DiagnosticCategory.Error, key: "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", message: "Overload signatures must all be abstract or non-abstract." }, - Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: { code: 2513, category: ts.DiagnosticCategory.Error, key: "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", message: "Abstract method '{0}' in class '{1}' cannot be accessed via super expression." }, - Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes_containing_abstract_methods_must_be_marked_abstract_2514", message: "Classes containing abstract methods must be marked abstract." }, - Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", message: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, - All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_an_abstract_method_must_be_consecutive_2516", message: "All declarations of an abstract method must be consecutive." }, - Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", message: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, - A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: { code: 2518, category: ts.DiagnosticCategory.Error, key: "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", message: "A 'this'-based type guard is not compatible with a parameter-based type guard." }, - An_async_iterator_must_have_a_next_method: { code: 2519, category: ts.DiagnosticCategory.Error, key: "An_async_iterator_must_have_a_next_method_2519", message: "An async iterator must have a 'next()' method." }, - Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", message: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, - Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", message: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, - The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: { code: 2522, category: ts.DiagnosticCategory.Error, key: "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", message: "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method." }, - yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: ts.DiagnosticCategory.Error, key: "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", message: "'yield' expressions cannot be used in a parameter initializer." }, - await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: ts.DiagnosticCategory.Error, key: "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", message: "'await' expressions cannot be used in a parameter initializer." }, - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: ts.DiagnosticCategory.Error, key: "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", message: "Initializer provides no value for this binding element and the binding element has no default value." }, - A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: { code: 2526, category: ts.DiagnosticCategory.Error, key: "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", message: "A 'this' type is available only in a non-static member of a class or interface." }, - The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: { code: 2527, category: ts.DiagnosticCategory.Error, key: "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", message: "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary." }, - A_module_cannot_have_multiple_default_exports: { code: 2528, category: ts.DiagnosticCategory.Error, key: "A_module_cannot_have_multiple_default_exports_2528", message: "A module cannot have multiple default exports." }, - Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: { code: 2529, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", message: "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions." }, - Property_0_is_incompatible_with_index_signature: { code: 2530, category: ts.DiagnosticCategory.Error, key: "Property_0_is_incompatible_with_index_signature_2530", message: "Property '{0}' is incompatible with index signature." }, - Object_is_possibly_null: { code: 2531, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_2531", message: "Object is possibly 'null'." }, - Object_is_possibly_undefined: { code: 2532, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_undefined_2532", message: "Object is possibly 'undefined'." }, - Object_is_possibly_null_or_undefined: { code: 2533, category: ts.DiagnosticCategory.Error, key: "Object_is_possibly_null_or_undefined_2533", message: "Object is possibly 'null' or 'undefined'." }, - A_function_returning_never_cannot_have_a_reachable_end_point: { code: 2534, category: ts.DiagnosticCategory.Error, key: "A_function_returning_never_cannot_have_a_reachable_end_point_2534", message: "A function returning 'never' cannot have a reachable end point." }, - Enum_type_0_has_members_with_initializers_that_are_not_literals: { code: 2535, category: ts.DiagnosticCategory.Error, key: "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", message: "Enum type '{0}' has members with initializers that are not literals." }, - Type_0_cannot_be_used_to_index_type_1: { code: 2536, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_to_index_type_1_2536", message: "Type '{0}' cannot be used to index type '{1}'." }, - Type_0_has_no_matching_index_signature_for_type_1: { code: 2537, category: ts.DiagnosticCategory.Error, key: "Type_0_has_no_matching_index_signature_for_type_1_2537", message: "Type '{0}' has no matching index signature for type '{1}'." }, - Type_0_cannot_be_used_as_an_index_type: { code: 2538, category: ts.DiagnosticCategory.Error, key: "Type_0_cannot_be_used_as_an_index_type_2538", message: "Type '{0}' cannot be used as an index type." }, - Cannot_assign_to_0_because_it_is_not_a_variable: { code: 2539, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_not_a_variable_2539", message: "Cannot assign to '{0}' because it is not a variable." }, - Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: { code: 2540, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", message: "Cannot assign to '{0}' because it is a constant or a read-only property." }, - The_target_of_an_assignment_must_be_a_variable_or_a_property_access: { code: 2541, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", message: "The target of an assignment must be a variable or a property access." }, - Index_signature_in_type_0_only_permits_reading: { code: 2542, category: ts.DiagnosticCategory.Error, key: "Index_signature_in_type_0_only_permits_reading_2542", message: "Index signature in type '{0}' only permits reading." }, - Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, - Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, - A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, - Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, - The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: { code: 2547, category: ts.DiagnosticCategory.Error, key: "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", message: "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property." }, - Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: { 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." }, - Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: ts.DiagnosticCategory.Error, key: "Property_0_in_type_1_is_not_assignable_to_type_2_2603", message: "Property '{0}' in type '{1}' is not assignable to type '{2}'." }, - JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", message: "JSX element type '{0}' does not have any construct or call signatures." }, - JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: ts.DiagnosticCategory.Error, key: "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", message: "JSX element type '{0}' is not a constructor function for JSX elements." }, - Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: ts.DiagnosticCategory.Error, key: "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", message: "Property '{0}' of JSX spread attribute is not assignable to target property." }, - JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: ts.DiagnosticCategory.Error, key: "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", message: "JSX element class does not support attributes because it does not have a '{0}' property." }, - The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: ts.DiagnosticCategory.Error, key: "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", message: "The global type 'JSX.{0}' may not have more than one property." }, - JSX_spread_child_must_be_an_array_type: { code: 2609, category: ts.DiagnosticCategory.Error, key: "JSX_spread_child_must_be_an_array_type_2609", message: "JSX spread child must be an array type." }, - Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: { code: 2649, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", message: "Cannot augment module '{0}' with value exports because it resolves to a non-module entity." }, - Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: ts.DiagnosticCategory.Error, key: "Cannot_emit_namespaced_JSX_elements_in_React_2650", message: "Cannot emit namespaced JSX elements in React." }, - A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: ts.DiagnosticCategory.Error, key: "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", message: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." }, - Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: ts.DiagnosticCategory.Error, key: "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", message: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, - Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: ts.DiagnosticCategory.Error, key: "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", message: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." }, - Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", message: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." }, - Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: { code: 2656, category: ts.DiagnosticCategory.Error, key: "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", message: "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition." }, - JSX_expressions_must_have_one_parent_element: { code: 2657, category: ts.DiagnosticCategory.Error, key: "JSX_expressions_must_have_one_parent_element_2657", message: "JSX expressions must have one parent element." }, - Type_0_provides_no_match_for_the_signature_1: { code: 2658, category: ts.DiagnosticCategory.Error, key: "Type_0_provides_no_match_for_the_signature_1_2658", message: "Type '{0}' provides no match for the signature '{1}'." }, - super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: { code: 2659, category: ts.DiagnosticCategory.Error, key: "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", message: "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher." }, - super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: { code: 2660, category: ts.DiagnosticCategory.Error, key: "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", message: "'super' can only be referenced in members of derived classes or object literal expressions." }, - Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: { code: 2661, category: ts.DiagnosticCategory.Error, key: "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", message: "Cannot export '{0}'. Only local declarations can be exported from a module." }, - Cannot_find_name_0_Did_you_mean_the_static_member_1_0: { code: 2662, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", message: "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?" }, - Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: { code: 2663, category: ts.DiagnosticCategory.Error, key: "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", message: "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?" }, - Invalid_module_name_in_augmentation_module_0_cannot_be_found: { code: 2664, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", message: "Invalid module name in augmentation, module '{0}' cannot be found." }, - Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: { code: 2665, category: ts.DiagnosticCategory.Error, key: "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", message: "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented." }, - Exports_and_export_assignments_are_not_permitted_in_module_augmentations: { code: 2666, category: ts.DiagnosticCategory.Error, key: "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", message: "Exports and export assignments are not permitted in module augmentations." }, - Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: { code: 2667, category: ts.DiagnosticCategory.Error, key: "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", message: "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module." }, - export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: { code: 2668, category: ts.DiagnosticCategory.Error, key: "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", message: "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible." }, - Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: { code: 2669, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", message: "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." }, - Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: { code: 2670, category: ts.DiagnosticCategory.Error, key: "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", message: "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context." }, - Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: { code: 2671, category: ts.DiagnosticCategory.Error, key: "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", message: "Cannot augment module '{0}' because it resolves to a non-module entity." }, - Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: { code: 2672, category: ts.DiagnosticCategory.Error, key: "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", message: "Cannot assign a '{0}' constructor type to a '{1}' constructor type." }, - Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: { code: 2673, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", message: "Constructor of class '{0}' is private and only accessible within the class declaration." }, - Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: { code: 2674, category: ts.DiagnosticCategory.Error, key: "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", message: "Constructor of class '{0}' is protected and only accessible within the class declaration." }, - Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: { code: 2675, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", message: "Cannot extend a class '{0}'. Class constructor is marked as private." }, - Accessors_must_both_be_abstract_or_non_abstract: { code: 2676, category: ts.DiagnosticCategory.Error, key: "Accessors_must_both_be_abstract_or_non_abstract_2676", message: "Accessors must both be abstract or non-abstract." }, - A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: { code: 2677, category: ts.DiagnosticCategory.Error, key: "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", message: "A type predicate's type must be assignable to its parameter's type." }, - Type_0_is_not_comparable_to_type_1: { code: 2678, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_comparable_to_type_1_2678", message: "Type '{0}' is not comparable to type '{1}'." }, - A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: { code: 2679, category: ts.DiagnosticCategory.Error, key: "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", message: "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'." }, - A_this_parameter_must_be_the_first_parameter: { code: 2680, category: ts.DiagnosticCategory.Error, key: "A_this_parameter_must_be_the_first_parameter_2680", message: "A 'this' parameter must be the first parameter." }, - A_constructor_cannot_have_a_this_parameter: { code: 2681, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_have_a_this_parameter_2681", message: "A constructor cannot have a 'this' parameter." }, - get_and_set_accessor_must_have_the_same_this_type: { code: 2682, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_this_type_2682", message: "'get' and 'set' accessor must have the same 'this' type." }, - this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, - The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, - The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, - All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, - Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, - Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, - An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: { code: 2691, category: ts.DiagnosticCategory.Error, key: "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", message: "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead." }, - _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: { code: 2692, category: ts.DiagnosticCategory.Error, key: "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", message: "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: { code: 2693, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", message: "'{0}' only refers to a type, but is being used as a value here." }, - Namespace_0_has_no_exported_member_1: { code: 2694, category: ts.DiagnosticCategory.Error, key: "Namespace_0_has_no_exported_member_1_2694", message: "Namespace '{0}' has no exported member '{1}'." }, - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: { code: 2695, category: ts.DiagnosticCategory.Error, key: "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", message: "Left side of comma operator is unused and has no side effects." }, - The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: { code: 2696, category: ts.DiagnosticCategory.Error, key: "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", message: "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?" }, - An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: { code: 2697, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", message: "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option." }, - Spread_types_may_only_be_created_from_object_types: { code: 2698, category: ts.DiagnosticCategory.Error, key: "Spread_types_may_only_be_created_from_object_types_2698", message: "Spread types may only be created from object types." }, - Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: { code: 2699, category: ts.DiagnosticCategory.Error, key: "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", message: "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'." }, - Rest_types_may_only_be_created_from_object_types: { code: 2700, category: ts.DiagnosticCategory.Error, key: "Rest_types_may_only_be_created_from_object_types_2700", message: "Rest types may only be created from object types." }, - The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: { code: 2701, category: ts.DiagnosticCategory.Error, key: "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", message: "The target of an object rest assignment must be a variable or a property access." }, - _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: { code: 2702, category: ts.DiagnosticCategory.Error, key: "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", message: "'{0}' only refers to a type, but is being used as a namespace here." }, - The_operand_of_a_delete_operator_must_be_a_property_reference: { code: 2703, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", message: "The operand of a delete operator must be a property reference." }, - The_operand_of_a_delete_operator_cannot_be_a_read_only_property: { code: 2704, category: ts.DiagnosticCategory.Error, key: "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", message: "The operand of a delete operator cannot be a read-only property." }, - An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: { code: 2705, category: ts.DiagnosticCategory.Error, key: "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", message: "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option." }, - Required_type_parameters_may_not_follow_optional_type_parameters: { code: 2706, category: ts.DiagnosticCategory.Error, key: "Required_type_parameters_may_not_follow_optional_type_parameters_2706", message: "Required type parameters may not follow optional type parameters." }, - Generic_type_0_requires_between_1_and_2_type_arguments: { code: 2707, category: ts.DiagnosticCategory.Error, key: "Generic_type_0_requires_between_1_and_2_type_arguments_2707", message: "Generic type '{0}' requires between {1} and {2} type arguments." }, - Cannot_use_namespace_0_as_a_value: { code: 2708, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_value_2708", message: "Cannot use namespace '{0}' as a value." }, - Cannot_use_namespace_0_as_a_type: { code: 2709, category: ts.DiagnosticCategory.Error, key: "Cannot_use_namespace_0_as_a_type_2709", message: "Cannot use namespace '{0}' as a type." }, - _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: { code: 2710, category: ts.DiagnosticCategory.Error, key: "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", message: "'{0}' are specified twice. The attribute named '{0}' will be overwritten." }, - Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import_declaration_0_is_using_private_name_1_4000", message: "Import declaration '{0}' is using private name '{1}'." }, - Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", message: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, - Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", message: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4006, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", message: "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4008, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", message: "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4010, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", message: "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4012, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", message: "Type parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4014, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", message: "Type parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4016, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", message: "Type parameter '{0}' of exported function has or is using private name '{1}'." }, - Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4019, category: ts.DiagnosticCategory.Error, key: "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", message: "Implements clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_has_or_is_using_private_name_1: { code: 4020, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", message: "'extends' clause of exported class '{0}' has or is using private name '{1}'." }, - extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: { code: 4022, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", message: "'extends' clause of exported interface '{0}' has or is using private name '{1}'." }, - Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4023, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", message: "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named." }, - Exported_variable_0_has_or_is_using_name_1_from_private_module_2: { code: 4024, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", message: "Exported variable '{0}' has or is using name '{1}' from private module '{2}'." }, - Exported_variable_0_has_or_is_using_private_name_1: { code: 4025, category: ts.DiagnosticCategory.Error, key: "Exported_variable_0_has_or_is_using_private_name_1_4025", message: "Exported variable '{0}' has or is using private name '{1}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4026, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", message: "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4027, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", message: "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4028, category: ts.DiagnosticCategory.Error, key: "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", message: "Public static property '{0}' of exported class has or is using private name '{1}'." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4029, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", message: "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4030, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", message: "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'." }, - Public_property_0_of_exported_class_has_or_is_using_private_name_1: { code: 4031, category: ts.DiagnosticCategory.Error, key: "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", message: "Public property '{0}' of exported class has or is using private name '{1}'." }, - Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4032, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", message: "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'." }, - Property_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4033, category: ts.DiagnosticCategory.Error, key: "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", message: "Property '{0}' of exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4034, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", message: "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4035, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", message: "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4036, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", message: "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: { code: 4037, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", message: "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4038, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", message: "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4039, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", message: "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4040, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", message: "Return type of public static property getter from exported class has or is using private name '{0}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4041, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", message: "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4042, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", message: "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: { code: 4043, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", message: "Return type of public property getter from exported class has or is using private name '{0}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4044, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", message: "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4045, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", message: "Return type of constructor signature from exported interface has or is using private name '{0}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4046, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", message: "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4047, category: ts.DiagnosticCategory.Error, key: "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", message: "Return type of call signature from exported interface has or is using private name '{0}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4048, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", message: "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: { code: 4049, category: ts.DiagnosticCategory.Error, key: "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", message: "Return type of index signature from exported interface has or is using private name '{0}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4050, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", message: "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4051, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", message: "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: { code: 4052, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", message: "Return type of public static method from exported class has or is using private name '{0}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4053, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", message: "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: { code: 4054, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", message: "Return type of public method from exported class has or is using name '{0}' from private module '{1}'." }, - Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: { code: 4055, category: ts.DiagnosticCategory.Error, key: "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", message: "Return type of public method from exported class has or is using private name '{0}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: { code: 4056, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", message: "Return type of method from exported interface has or is using name '{0}' from private module '{1}'." }, - Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: { code: 4057, category: ts.DiagnosticCategory.Error, key: "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", message: "Return type of method from exported interface has or is using private name '{0}'." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: { code: 4058, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", message: "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named." }, - Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: { code: 4059, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", message: "Return type of exported function has or is using name '{0}' from private module '{1}'." }, - Return_type_of_exported_function_has_or_is_using_private_name_0: { code: 4060, category: ts.DiagnosticCategory.Error, key: "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", message: "Return type of exported function has or is using private name '{0}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4061, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4062, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", message: "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: { code: 4063, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", message: "Parameter '{0}' of constructor from exported class has or is using private name '{1}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4064, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", message: "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4065, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", message: "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4066, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", message: "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4067, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", message: "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4068, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4069, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", message: "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: { code: 4070, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", message: "Parameter '{0}' of public static method from exported class has or is using private name '{1}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4071, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: { code: 4072, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", message: "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: { code: 4073, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", message: "Parameter '{0}' of public method from exported class has or is using private name '{1}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4074, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", message: "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: { code: 4075, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", message: "Parameter '{0}' of method from exported interface has or is using private name '{1}'." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4076, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", message: "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named." }, - Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: { code: 4077, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", message: "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", message: "Parameter '{0}' of exported function has or is using private name '{1}'." }, - Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: ts.DiagnosticCategory.Error, key: "Exported_type_alias_0_has_or_is_using_private_name_1_4081", message: "Exported type alias '{0}' has or is using private name '{1}'." }, - Default_export_of_the_module_has_or_is_using_private_name_0: { code: 4082, category: ts.DiagnosticCategory.Error, key: "Default_export_of_the_module_has_or_is_using_private_name_0_4082", message: "Default export of the module has or is using private name '{0}'." }, - Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: { code: 4083, category: ts.DiagnosticCategory.Error, key: "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", message: "Type parameter '{0}' of exported type alias has or is using private name '{1}'." }, - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: { code: 4090, category: ts.DiagnosticCategory.Message, key: "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", message: "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: { code: 4091, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", message: "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'." }, - Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: { code: 4092, category: ts.DiagnosticCategory.Error, key: "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", message: "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'." }, - extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced: { code: 4093, category: ts.DiagnosticCategory.Error, key: "extends_clause_of_exported_class_0_refers_to_a_type_whose_name_cannot_be_referenced_4093", message: "'extends' clause of exported class '{0}' refers to a type whose name cannot be referenced." }, - The_current_host_does_not_support_the_0_option: { code: 5001, category: ts.DiagnosticCategory.Error, key: "The_current_host_does_not_support_the_0_option_5001", message: "The current host does not support the '{0}' option." }, - Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: ts.DiagnosticCategory.Error, key: "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", message: "Cannot find the common subdirectory path for the input files." }, - File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5010, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", message: "File specification cannot end in a recursive directory wildcard ('**'): '{0}'." }, - File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: { code: 5011, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", message: "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'." }, - Cannot_read_file_0_Colon_1: { code: 5012, category: ts.DiagnosticCategory.Error, key: "Cannot_read_file_0_Colon_1_5012", message: "Cannot read file '{0}': {1}." }, - Failed_to_parse_file_0_Colon_1: { code: 5014, category: ts.DiagnosticCategory.Error, key: "Failed_to_parse_file_0_Colon_1_5014", message: "Failed to parse file '{0}': {1}." }, - Unknown_compiler_option_0: { code: 5023, category: ts.DiagnosticCategory.Error, key: "Unknown_compiler_option_0_5023", message: "Unknown compiler option '{0}'." }, - Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_requires_a_value_of_type_1_5024", message: "Compiler option '{0}' requires a value of type {1}." }, - Could_not_write_file_0_Colon_1: { code: 5033, category: ts.DiagnosticCategory.Error, key: "Could_not_write_file_0_Colon_1_5033", message: "Could not write file '{0}': {1}." }, - Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: ts.DiagnosticCategory.Error, key: "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", message: "Option 'project' cannot be mixed with source files on a command line." }, - Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: { code: 5047, category: ts.DiagnosticCategory.Error, key: "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", message: "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher." }, - Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: { code: 5051, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", message: "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided." }, - Option_0_cannot_be_specified_without_specifying_option_1: { code: 5052, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_without_specifying_option_1_5052", message: "Option '{0}' cannot be specified without specifying option '{1}'." }, - Option_0_cannot_be_specified_with_option_1: { code: 5053, category: ts.DiagnosticCategory.Error, key: "Option_0_cannot_be_specified_with_option_1_5053", message: "Option '{0}' cannot be specified with option '{1}'." }, - A_tsconfig_json_file_is_already_defined_at_Colon_0: { code: 5054, category: ts.DiagnosticCategory.Error, key: "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", message: "A 'tsconfig.json' file is already defined at: '{0}'." }, - Cannot_write_file_0_because_it_would_overwrite_input_file: { code: 5055, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", message: "Cannot write file '{0}' because it would overwrite input file." }, - Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: { code: 5056, category: ts.DiagnosticCategory.Error, key: "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", message: "Cannot write file '{0}' because it would be overwritten by multiple input files." }, - Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: { code: 5057, category: ts.DiagnosticCategory.Error, key: "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", message: "Cannot find a tsconfig.json file at the specified directory: '{0}'." }, - The_specified_path_does_not_exist_Colon_0: { code: 5058, category: ts.DiagnosticCategory.Error, key: "The_specified_path_does_not_exist_Colon_0_5058", message: "The specified path does not exist: '{0}'." }, - Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: { code: 5059, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", message: "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier." }, - Option_paths_cannot_be_used_without_specifying_baseUrl_option: { code: 5060, category: ts.DiagnosticCategory.Error, key: "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", message: "Option 'paths' cannot be used without specifying '--baseUrl' option." }, - Pattern_0_can_have_at_most_one_Asterisk_character: { code: 5061, category: ts.DiagnosticCategory.Error, key: "Pattern_0_can_have_at_most_one_Asterisk_character_5061", message: "Pattern '{0}' can have at most one '*' character." }, - Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: { code: 5062, category: ts.DiagnosticCategory.Error, key: "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", message: "Substitution '{0}' in pattern '{1}' in can have at most one '*' character." }, - Substitutions_for_pattern_0_should_be_an_array: { code: 5063, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_should_be_an_array_5063", message: "Substitutions for pattern '{0}' should be an array." }, - Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: { code: 5064, category: ts.DiagnosticCategory.Error, key: "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", message: "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'." }, - File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: { code: 5065, category: ts.DiagnosticCategory.Error, key: "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", message: "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'." }, - Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: { code: 5066, category: ts.DiagnosticCategory.Error, key: "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", message: "Substitutions for pattern '{0}' shouldn't be an empty array." }, - Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: { code: 5067, category: ts.DiagnosticCategory.Error, key: "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", message: "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name." }, - Concatenate_and_emit_output_to_single_file: { code: 6001, category: ts.DiagnosticCategory.Message, key: "Concatenate_and_emit_output_to_single_file_6001", message: "Concatenate and emit output to single file." }, - Generates_corresponding_d_ts_file: { code: 6002, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_d_ts_file_6002", message: "Generates corresponding '.d.ts' file." }, - Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", message: "Specify the location where debugger should locate map files instead of generated locations." }, - Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: ts.DiagnosticCategory.Message, key: "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", message: "Specify the location where debugger should locate TypeScript files instead of source locations." }, - Watch_input_files: { code: 6005, category: ts.DiagnosticCategory.Message, key: "Watch_input_files_6005", message: "Watch input files." }, - Redirect_output_structure_to_the_directory: { code: 6006, category: ts.DiagnosticCategory.Message, key: "Redirect_output_structure_to_the_directory_6006", message: "Redirect output structure to the directory." }, - Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: ts.DiagnosticCategory.Message, key: "Do_not_erase_const_enum_declarations_in_generated_code_6007", message: "Do not erase const enum declarations in generated code." }, - Do_not_emit_outputs_if_any_errors_were_reported: { code: 6008, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_if_any_errors_were_reported_6008", message: "Do not emit outputs if any errors were reported." }, - Do_not_emit_comments_to_output: { code: 6009, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_comments_to_output_6009", message: "Do not emit comments to output." }, - Do_not_emit_outputs: { code: 6010, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_outputs_6010", message: "Do not emit outputs." }, - Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: { code: 6011, category: ts.DiagnosticCategory.Message, key: "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", message: "Allow default imports from modules with no default export. This does not affect code emit, just typechecking." }, - Skip_type_checking_of_declaration_files: { code: 6012, category: ts.DiagnosticCategory.Message, key: "Skip_type_checking_of_declaration_files_6012", message: "Skip type checking of declaration files." }, - Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: { code: 6015, category: ts.DiagnosticCategory.Message, key: "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", message: "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'." }, - Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015: { code: 6016, category: ts.DiagnosticCategory.Message, key: "Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015_6016", message: "Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'." }, - Print_this_message: { code: 6017, category: ts.DiagnosticCategory.Message, key: "Print_this_message_6017", message: "Print this message." }, - Print_the_compiler_s_version: { code: 6019, category: ts.DiagnosticCategory.Message, key: "Print_the_compiler_s_version_6019", message: "Print the compiler's version." }, - Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: { code: 6020, category: ts.DiagnosticCategory.Message, key: "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", message: "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'." }, - Syntax_Colon_0: { code: 6023, category: ts.DiagnosticCategory.Message, key: "Syntax_Colon_0_6023", message: "Syntax: {0}" }, - options: { code: 6024, category: ts.DiagnosticCategory.Message, key: "options_6024", message: "options" }, - file: { code: 6025, category: ts.DiagnosticCategory.Message, key: "file_6025", message: "file" }, - Examples_Colon_0: { code: 6026, category: ts.DiagnosticCategory.Message, key: "Examples_Colon_0_6026", message: "Examples: {0}" }, - Options_Colon: { code: 6027, category: ts.DiagnosticCategory.Message, key: "Options_Colon_6027", message: "Options:" }, - Version_0: { code: 6029, category: ts.DiagnosticCategory.Message, key: "Version_0_6029", message: "Version {0}" }, - Insert_command_line_options_and_files_from_a_file: { code: 6030, category: ts.DiagnosticCategory.Message, key: "Insert_command_line_options_and_files_from_a_file_6030", message: "Insert command line options and files from a file." }, - File_change_detected_Starting_incremental_compilation: { code: 6032, category: ts.DiagnosticCategory.Message, key: "File_change_detected_Starting_incremental_compilation_6032", message: "File change detected. Starting incremental compilation..." }, - KIND: { code: 6034, category: ts.DiagnosticCategory.Message, key: "KIND_6034", message: "KIND" }, - FILE: { code: 6035, category: ts.DiagnosticCategory.Message, key: "FILE_6035", message: "FILE" }, - VERSION: { code: 6036, category: ts.DiagnosticCategory.Message, key: "VERSION_6036", message: "VERSION" }, - LOCATION: { code: 6037, category: ts.DiagnosticCategory.Message, key: "LOCATION_6037", message: "LOCATION" }, - DIRECTORY: { code: 6038, category: ts.DiagnosticCategory.Message, key: "DIRECTORY_6038", message: "DIRECTORY" }, - STRATEGY: { code: 6039, category: ts.DiagnosticCategory.Message, key: "STRATEGY_6039", message: "STRATEGY" }, - FILE_OR_DIRECTORY: { code: 6040, category: ts.DiagnosticCategory.Message, key: "FILE_OR_DIRECTORY_6040", message: "FILE OR DIRECTORY" }, - Compilation_complete_Watching_for_file_changes: { code: 6042, category: ts.DiagnosticCategory.Message, key: "Compilation_complete_Watching_for_file_changes_6042", message: "Compilation complete. Watching for file changes." }, - Generates_corresponding_map_file: { code: 6043, category: ts.DiagnosticCategory.Message, key: "Generates_corresponding_map_file_6043", message: "Generates corresponding '.map' file." }, - Compiler_option_0_expects_an_argument: { code: 6044, category: ts.DiagnosticCategory.Error, key: "Compiler_option_0_expects_an_argument_6044", message: "Compiler option '{0}' expects an argument." }, - Unterminated_quoted_string_in_response_file_0: { code: 6045, category: ts.DiagnosticCategory.Error, key: "Unterminated_quoted_string_in_response_file_0_6045", message: "Unterminated quoted string in response file '{0}'." }, - Argument_for_0_option_must_be_Colon_1: { code: 6046, category: ts.DiagnosticCategory.Error, key: "Argument_for_0_option_must_be_Colon_1_6046", message: "Argument for '{0}' option must be: {1}." }, - Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: { code: 6048, category: ts.DiagnosticCategory.Error, key: "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", message: "Locale must be of the form or -. For example '{0}' or '{1}'." }, - Unsupported_locale_0: { code: 6049, category: ts.DiagnosticCategory.Error, key: "Unsupported_locale_0_6049", message: "Unsupported locale '{0}'." }, - Unable_to_open_file_0: { code: 6050, category: ts.DiagnosticCategory.Error, key: "Unable_to_open_file_0_6050", message: "Unable to open file '{0}'." }, - Corrupted_locale_file_0: { code: 6051, category: ts.DiagnosticCategory.Error, key: "Corrupted_locale_file_0_6051", message: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", message: "Raise error on expressions and declarations with an implied 'any' type." }, - File_0_not_found: { code: 6053, category: ts.DiagnosticCategory.Error, key: "File_0_not_found_6053", message: "File '{0}' not found." }, - File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: ts.DiagnosticCategory.Error, key: "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", message: "File '{0}' has unsupported extension. The only supported extensions are {1}." }, - Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: ts.DiagnosticCategory.Message, key: "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", message: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, - Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", message: "Do not emit declarations for code that has an '@internal' annotation." }, - Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: ts.DiagnosticCategory.Message, key: "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", message: "Specify the root directory of input files. Use to control the output directory structure with --outDir." }, - File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: ts.DiagnosticCategory.Error, key: "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", message: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." }, - Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: ts.DiagnosticCategory.Message, key: "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", message: "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, - NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, - Option_0_can_only_be_specified_in_tsconfig_json_file: { code: 6064, category: ts.DiagnosticCategory.Error, key: "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", message: "Option '{0}' can only be specified in 'tsconfig.json' file." }, - Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, - Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, - Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, - Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: { code: 6069, category: ts.DiagnosticCategory.Message, key: "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", message: "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)." }, - Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, - Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, - Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context (experimental)." }, - Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, - Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, - Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, - Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, - Specify_library_files_to_be_included_in_the_compilation_Colon: { code: 6079, category: ts.DiagnosticCategory.Message, key: "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", message: "Specify library files to be included in the compilation: " }, - Specify_JSX_code_generation_Colon_preserve_react_native_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", message: "Specify JSX code generation: 'preserve', 'react-native', or 'react'." }, - File_0_has_an_unsupported_extension_so_skipping_it: { code: 6081, category: ts.DiagnosticCategory.Message, key: "File_0_has_an_unsupported_extension_so_skipping_it_6081", message: "File '{0}' has an unsupported extension, so skipping it." }, - Only_amd_and_system_modules_are_supported_alongside_0: { code: 6082, category: ts.DiagnosticCategory.Error, key: "Only_amd_and_system_modules_are_supported_alongside_0_6082", message: "Only 'amd' and 'system' modules are supported alongside --{0}." }, - Base_directory_to_resolve_non_absolute_module_names: { code: 6083, category: ts.DiagnosticCategory.Message, key: "Base_directory_to_resolve_non_absolute_module_names_6083", message: "Base directory to resolve non-absolute module names." }, - Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: { code: 6084, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", message: "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit" }, - Enable_tracing_of_the_name_resolution_process: { code: 6085, category: ts.DiagnosticCategory.Message, key: "Enable_tracing_of_the_name_resolution_process_6085", message: "Enable tracing of the name resolution process." }, - Resolving_module_0_from_1: { code: 6086, category: ts.DiagnosticCategory.Message, key: "Resolving_module_0_from_1_6086", message: "======== Resolving module '{0}' from '{1}'. ========" }, - Explicitly_specified_module_resolution_kind_Colon_0: { code: 6087, category: ts.DiagnosticCategory.Message, key: "Explicitly_specified_module_resolution_kind_Colon_0_6087", message: "Explicitly specified module resolution kind: '{0}'." }, - Module_resolution_kind_is_not_specified_using_0: { code: 6088, category: ts.DiagnosticCategory.Message, key: "Module_resolution_kind_is_not_specified_using_0_6088", message: "Module resolution kind is not specified, using '{0}'." }, - Module_name_0_was_successfully_resolved_to_1: { code: 6089, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_successfully_resolved_to_1_6089", message: "======== Module name '{0}' was successfully resolved to '{1}'. ========" }, - Module_name_0_was_not_resolved: { code: 6090, category: ts.DiagnosticCategory.Message, key: "Module_name_0_was_not_resolved_6090", message: "======== Module name '{0}' was not resolved. ========" }, - paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: { code: 6091, category: ts.DiagnosticCategory.Message, key: "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", message: "'paths' option is specified, looking for a pattern to match module name '{0}'." }, - Module_name_0_matched_pattern_1: { code: 6092, category: ts.DiagnosticCategory.Message, key: "Module_name_0_matched_pattern_1_6092", message: "Module name '{0}', matched pattern '{1}'." }, - Trying_substitution_0_candidate_module_location_Colon_1: { code: 6093, category: ts.DiagnosticCategory.Message, key: "Trying_substitution_0_candidate_module_location_Colon_1_6093", message: "Trying substitution '{0}', candidate module location: '{1}'." }, - Resolving_module_name_0_relative_to_base_url_1_2: { code: 6094, category: ts.DiagnosticCategory.Message, key: "Resolving_module_name_0_relative_to_base_url_1_2_6094", message: "Resolving module name '{0}' relative to base url '{1}' - '{2}'." }, - Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: { code: 6095, category: ts.DiagnosticCategory.Message, key: "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", message: "Loading module as file / folder, candidate module location '{0}', target file type '{1}'." }, - File_0_does_not_exist: { code: 6096, category: ts.DiagnosticCategory.Message, key: "File_0_does_not_exist_6096", message: "File '{0}' does not exist." }, - File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, - Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, - Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, - package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, - Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, - Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, - Checking_if_0_is_the_longest_matching_prefix_for_1_2: { code: 6104, category: ts.DiagnosticCategory.Message, key: "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", message: "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'." }, - Expected_type_of_0_field_in_package_json_to_be_string_got_1: { code: 6105, category: ts.DiagnosticCategory.Message, key: "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", message: "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'." }, - baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: { code: 6106, category: ts.DiagnosticCategory.Message, key: "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", message: "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'." }, - rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: { code: 6107, category: ts.DiagnosticCategory.Message, key: "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", message: "'rootDirs' option is set, using it to resolve relative module name '{0}'." }, - Longest_matching_prefix_for_0_is_1: { code: 6108, category: ts.DiagnosticCategory.Message, key: "Longest_matching_prefix_for_0_is_1_6108", message: "Longest matching prefix for '{0}' is '{1}'." }, - Loading_0_from_the_root_dir_1_candidate_location_2: { code: 6109, category: ts.DiagnosticCategory.Message, key: "Loading_0_from_the_root_dir_1_candidate_location_2_6109", message: "Loading '{0}' from the root dir '{1}', candidate location '{2}'." }, - Trying_other_entries_in_rootDirs: { code: 6110, category: ts.DiagnosticCategory.Message, key: "Trying_other_entries_in_rootDirs_6110", message: "Trying other entries in 'rootDirs'." }, - Module_resolution_using_rootDirs_has_failed: { code: 6111, category: ts.DiagnosticCategory.Message, key: "Module_resolution_using_rootDirs_has_failed_6111", message: "Module resolution using 'rootDirs' has failed." }, - Do_not_emit_use_strict_directives_in_module_output: { code: 6112, category: ts.DiagnosticCategory.Message, key: "Do_not_emit_use_strict_directives_in_module_output_6112", message: "Do not emit 'use strict' directives in module output." }, - Enable_strict_null_checks: { code: 6113, category: ts.DiagnosticCategory.Message, key: "Enable_strict_null_checks_6113", message: "Enable strict null checks." }, - Unknown_option_excludes_Did_you_mean_exclude: { code: 6114, category: ts.DiagnosticCategory.Error, key: "Unknown_option_excludes_Did_you_mean_exclude_6114", message: "Unknown option 'excludes'. Did you mean 'exclude'?" }, - Raise_error_on_this_expressions_with_an_implied_any_type: { code: 6115, category: ts.DiagnosticCategory.Message, key: "Raise_error_on_this_expressions_with_an_implied_any_type_6115", message: "Raise error on 'this' expressions with an implied 'any' type." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_2: { code: 6116, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========" }, - Resolving_using_primary_search_paths: { code: 6117, category: ts.DiagnosticCategory.Message, key: "Resolving_using_primary_search_paths_6117", message: "Resolving using primary search paths..." }, - Resolving_from_node_modules_folder: { code: 6118, category: ts.DiagnosticCategory.Message, key: "Resolving_from_node_modules_folder_6118", message: "Resolving from node_modules folder..." }, - Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: { code: 6119, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", message: "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========" }, - Type_reference_directive_0_was_not_resolved: { code: 6120, category: ts.DiagnosticCategory.Message, key: "Type_reference_directive_0_was_not_resolved_6120", message: "======== Type reference directive '{0}' was not resolved. ========" }, - Resolving_with_primary_search_path_0: { code: 6121, category: ts.DiagnosticCategory.Message, key: "Resolving_with_primary_search_path_0_6121", message: "Resolving with primary search path '{0}'." }, - Root_directory_cannot_be_determined_skipping_primary_search_paths: { code: 6122, category: ts.DiagnosticCategory.Message, key: "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", message: "Root directory cannot be determined, skipping primary search paths." }, - Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: { code: 6123, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", message: "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========" }, - Type_declaration_files_to_be_included_in_compilation: { code: 6124, category: ts.DiagnosticCategory.Message, key: "Type_declaration_files_to_be_included_in_compilation_6124", message: "Type declaration files to be included in compilation." }, - Looking_up_in_node_modules_folder_initial_location_0: { code: 6125, category: ts.DiagnosticCategory.Message, key: "Looking_up_in_node_modules_folder_initial_location_0_6125", message: "Looking up in 'node_modules' folder, initial location '{0}'." }, - Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: { code: 6126, category: ts.DiagnosticCategory.Message, key: "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", message: "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder." }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: { code: 6127, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", message: "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========" }, - Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: { code: 6128, category: ts.DiagnosticCategory.Message, key: "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", message: "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========" }, - The_config_file_0_found_doesn_t_contain_any_source_files: { code: 6129, category: ts.DiagnosticCategory.Error, key: "The_config_file_0_found_doesn_t_contain_any_source_files_6129", message: "The config file '{0}' found doesn't contain any source files." }, - Resolving_real_path_for_0_result_1: { code: 6130, category: ts.DiagnosticCategory.Message, key: "Resolving_real_path_for_0_result_1_6130", message: "Resolving real path for '{0}', result '{1}'." }, - Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: { code: 6131, category: ts.DiagnosticCategory.Error, key: "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", message: "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'." }, - File_name_0_has_a_1_extension_stripping_it: { code: 6132, category: ts.DiagnosticCategory.Message, key: "File_name_0_has_a_1_extension_stripping_it_6132", message: "File name '{0}' has a '{1}' extension - stripping it." }, - _0_is_declared_but_never_used: { code: 6133, category: ts.DiagnosticCategory.Error, key: "_0_is_declared_but_never_used_6133", message: "'{0}' is declared but never used." }, - 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}'." }, - Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file." }, - Module_0_was_resolved_to_1_but_jsx_is_not_set: { code: 6142, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", message: "Module '{0}' was resolved to '{1}', but '--jsx' is not set." }, - Module_0_was_resolved_to_1_but_allowJs_is_not_set: { code: 6143, category: ts.DiagnosticCategory.Error, key: "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", message: "Module '{0}' was resolved to '{1}', but '--allowJs' is not set." }, - Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: { code: 6144, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", message: "Module '{0}' was resolved as locally declared ambient module in file '{1}'." }, - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: { code: 6145, category: ts.DiagnosticCategory.Message, key: "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", message: "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified." }, - Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: { code: 6146, category: ts.DiagnosticCategory.Message, key: "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", message: "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'." }, - Resolution_for_module_0_was_found_in_cache: { code: 6147, category: ts.DiagnosticCategory.Message, key: "Resolution_for_module_0_was_found_in_cache_6147", message: "Resolution for module '{0}' was found in cache." }, - Directory_0_does_not_exist_skipping_all_lookups_in_it: { code: 6148, category: ts.DiagnosticCategory.Message, key: "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", message: "Directory '{0}' does not exist, skipping all lookups in it." }, - Show_diagnostic_information: { code: 6149, category: ts.DiagnosticCategory.Message, key: "Show_diagnostic_information_6149", message: "Show diagnostic information." }, - Show_verbose_diagnostic_information: { code: 6150, category: ts.DiagnosticCategory.Message, key: "Show_verbose_diagnostic_information_6150", message: "Show verbose diagnostic information." }, - Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: { code: 6151, category: ts.DiagnosticCategory.Message, key: "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", message: "Emit a single file with source maps instead of having a separate file." }, - Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: { code: 6152, category: ts.DiagnosticCategory.Message, key: "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", message: "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set." }, - Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: { code: 6153, category: ts.DiagnosticCategory.Message, key: "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", message: "Transpile each file as a separate module (similar to 'ts.transpileModule')." }, - Print_names_of_generated_files_part_of_the_compilation: { code: 6154, category: ts.DiagnosticCategory.Message, key: "Print_names_of_generated_files_part_of_the_compilation_6154", message: "Print names of generated files part of the compilation." }, - Print_names_of_files_part_of_the_compilation: { code: 6155, category: ts.DiagnosticCategory.Message, key: "Print_names_of_files_part_of_the_compilation_6155", message: "Print names of files part of the compilation." }, - The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: { code: 6156, category: ts.DiagnosticCategory.Message, key: "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", message: "The locale used when displaying messages to the user (e.g. 'en-us')" }, - Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: { code: 6157, category: ts.DiagnosticCategory.Message, key: "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", message: "Do not generate custom helper functions like '__extends' in compiled output." }, - Do_not_include_the_default_library_file_lib_d_ts: { code: 6158, category: ts.DiagnosticCategory.Message, key: "Do_not_include_the_default_library_file_lib_d_ts_6158", message: "Do not include the default library file (lib.d.ts)." }, - Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: { code: 6159, category: ts.DiagnosticCategory.Message, key: "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", message: "Do not add triple-slash references or imported modules to the list of compiled files." }, - Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: { code: 6160, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", message: "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files." }, - List_of_folders_to_include_type_definitions_from: { code: 6161, category: ts.DiagnosticCategory.Message, key: "List_of_folders_to_include_type_definitions_from_6161", message: "List of folders to include type definitions from." }, - Disable_size_limitations_on_JavaScript_projects: { code: 6162, category: ts.DiagnosticCategory.Message, key: "Disable_size_limitations_on_JavaScript_projects_6162", message: "Disable size limitations on JavaScript projects." }, - The_character_set_of_the_input_files: { code: 6163, category: ts.DiagnosticCategory.Message, key: "The_character_set_of_the_input_files_6163", message: "The character set of the input files." }, - Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: { code: 6164, category: ts.DiagnosticCategory.Message, key: "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", message: "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files." }, - Do_not_truncate_error_messages: { code: 6165, category: ts.DiagnosticCategory.Message, key: "Do_not_truncate_error_messages_6165", message: "Do not truncate error messages." }, - Output_directory_for_generated_declaration_files: { code: 6166, category: ts.DiagnosticCategory.Message, key: "Output_directory_for_generated_declaration_files_6166", message: "Output directory for generated declaration files." }, - A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: { code: 6167, category: ts.DiagnosticCategory.Message, key: "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", message: "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'." }, - List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: { code: 6168, category: ts.DiagnosticCategory.Message, key: "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", message: "List of root folders whose combined content represents the structure of the project at runtime." }, - Show_all_compiler_options: { code: 6169, category: ts.DiagnosticCategory.Message, key: "Show_all_compiler_options_6169", message: "Show all compiler options." }, - Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: { code: 6170, category: ts.DiagnosticCategory.Message, key: "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", message: "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file" }, - Command_line_Options: { code: 6171, category: ts.DiagnosticCategory.Message, key: "Command_line_Options_6171", message: "Command-line Options" }, - Basic_Options: { code: 6172, category: ts.DiagnosticCategory.Message, key: "Basic_Options_6172", message: "Basic Options" }, - Strict_Type_Checking_Options: { code: 6173, category: ts.DiagnosticCategory.Message, key: "Strict_Type_Checking_Options_6173", message: "Strict Type-Checking Options" }, - Module_Resolution_Options: { code: 6174, category: ts.DiagnosticCategory.Message, key: "Module_Resolution_Options_6174", message: "Module Resolution Options" }, - Source_Map_Options: { code: 6175, category: ts.DiagnosticCategory.Message, key: "Source_Map_Options_6175", message: "Source Map Options" }, - Additional_Checks: { code: 6176, category: ts.DiagnosticCategory.Message, key: "Additional_Checks_6176", message: "Additional Checks" }, - Experimental_Options: { code: 6177, category: ts.DiagnosticCategory.Message, key: "Experimental_Options_6177", message: "Experimental Options" }, - Advanced_Options: { code: 6178, category: ts.DiagnosticCategory.Message, key: "Advanced_Options_6178", message: "Advanced Options" }, - Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: { code: 6179, category: ts.DiagnosticCategory.Message, key: "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", message: "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'." }, - 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." }, - new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: { code: 7009, category: ts.DiagnosticCategory.Error, key: "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", message: "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type." }, - _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: { code: 7010, category: ts.DiagnosticCategory.Error, key: "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", message: "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type." }, - Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: { code: 7011, category: ts.DiagnosticCategory.Error, key: "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", message: "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type." }, - Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7013, category: ts.DiagnosticCategory.Error, key: "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", message: "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: { code: 7015, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", message: "Element implicitly has an 'any' type because index expression is not of type 'number'." }, - Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: { code: 7016, category: ts.DiagnosticCategory.Error, key: "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", message: "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type." }, - Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: { code: 7017, category: ts.DiagnosticCategory.Error, key: "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", message: "Element implicitly has an 'any' type because type '{0}' has no index signature." }, - Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object_literal_s_property_0_implicitly_has_an_1_type_7018", message: "Object literal's property '{0}' implicitly has an '{1}' type." }, - Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest_parameter_0_implicitly_has_an_any_type_7019", message: "Rest parameter '{0}' implicitly has an 'any[]' type." }, - Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", message: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", message: "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer." }, - _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: { code: 7023, category: ts.DiagnosticCategory.Error, key: "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", message: "'{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." }, - 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: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "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." }, - Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, - JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists." }, - Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, - Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, - Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, - Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, - Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, - Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, - Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, - Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined." }, - Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: { code: 7035, category: ts.DiagnosticCategory.Error, key: "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", message: "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`" }, - You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, - You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, - import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, - export_can_only_be_used_in_a_ts_file: { code: 8003, category: ts.DiagnosticCategory.Error, key: "export_can_only_be_used_in_a_ts_file_8003", message: "'export=' can only be used in a .ts file." }, - type_parameter_declarations_can_only_be_used_in_a_ts_file: { code: 8004, category: ts.DiagnosticCategory.Error, key: "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", message: "'type parameter declarations' can only be used in a .ts file." }, - implements_clauses_can_only_be_used_in_a_ts_file: { code: 8005, category: ts.DiagnosticCategory.Error, key: "implements_clauses_can_only_be_used_in_a_ts_file_8005", message: "'implements clauses' can only be used in a .ts file." }, - interface_declarations_can_only_be_used_in_a_ts_file: { code: 8006, category: ts.DiagnosticCategory.Error, key: "interface_declarations_can_only_be_used_in_a_ts_file_8006", message: "'interface declarations' can only be used in a .ts file." }, - module_declarations_can_only_be_used_in_a_ts_file: { code: 8007, category: ts.DiagnosticCategory.Error, key: "module_declarations_can_only_be_used_in_a_ts_file_8007", message: "'module declarations' can only be used in a .ts file." }, - type_aliases_can_only_be_used_in_a_ts_file: { code: 8008, category: ts.DiagnosticCategory.Error, key: "type_aliases_can_only_be_used_in_a_ts_file_8008", message: "'type aliases' can only be used in a .ts file." }, - _0_can_only_be_used_in_a_ts_file: { code: 8009, category: ts.DiagnosticCategory.Error, key: "_0_can_only_be_used_in_a_ts_file_8009", message: "'{0}' can only be used in a .ts file." }, - types_can_only_be_used_in_a_ts_file: { code: 8010, category: ts.DiagnosticCategory.Error, key: "types_can_only_be_used_in_a_ts_file_8010", message: "'types' can only be used in a .ts file." }, - type_arguments_can_only_be_used_in_a_ts_file: { code: 8011, category: ts.DiagnosticCategory.Error, key: "type_arguments_can_only_be_used_in_a_ts_file_8011", message: "'type arguments' can only be used in a .ts file." }, - parameter_modifiers_can_only_be_used_in_a_ts_file: { code: 8012, category: ts.DiagnosticCategory.Error, key: "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", message: "'parameter modifiers' can only be used in a .ts file." }, - enum_declarations_can_only_be_used_in_a_ts_file: { code: 8015, category: ts.DiagnosticCategory.Error, key: "enum_declarations_can_only_be_used_in_a_ts_file_8015", message: "'enum declarations' can only be used in a .ts file." }, - type_assertion_expressions_can_only_be_used_in_a_ts_file: { code: 8016, category: ts.DiagnosticCategory.Error, key: "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", message: "'type assertion expressions' can only be used in a .ts file." }, - Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: { code: 9002, category: ts.DiagnosticCategory.Error, key: "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", message: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause." }, - class_expressions_are_not_currently_supported: { code: 9003, category: ts.DiagnosticCategory.Error, key: "class_expressions_are_not_currently_supported_9003", message: "'class' expressions are not currently supported." }, - Language_service_is_disabled: { code: 9004, category: ts.DiagnosticCategory.Error, key: "Language_service_is_disabled_9004", message: "Language service is disabled." }, - JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: ts.DiagnosticCategory.Error, key: "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", message: "JSX attributes must only be assigned a non-empty 'expression'." }, - JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: ts.DiagnosticCategory.Error, key: "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", message: "JSX elements cannot have multiple attributes with the same name." }, - Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: ts.DiagnosticCategory.Error, key: "Expected_corresponding_JSX_closing_tag_for_0_17002", message: "Expected corresponding JSX closing tag for '{0}'." }, - JSX_attribute_expected: { code: 17003, category: ts.DiagnosticCategory.Error, key: "JSX_attribute_expected_17003", message: "JSX attribute expected." }, - Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: ts.DiagnosticCategory.Error, key: "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", message: "Cannot use JSX unless the '--jsx' flag is provided." }, - A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: ts.DiagnosticCategory.Error, key: "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", message: "A constructor cannot contain a 'super' call when its class extends 'null'." }, - An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17006, category: ts.DiagnosticCategory.Error, key: "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", message: "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: { code: 17007, category: ts.DiagnosticCategory.Error, key: "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", message: "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses." }, - JSX_element_0_has_no_corresponding_closing_tag: { code: 17008, category: ts.DiagnosticCategory.Error, key: "JSX_element_0_has_no_corresponding_closing_tag_17008", message: "JSX element '{0}' has no corresponding closing tag." }, - super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, - Unknown_type_acquisition_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_type_acquisition_option_0_17010", message: "Unknown type acquisition option '{0}'." }, - super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: { code: 17011, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", message: "'super' must be called before accessing a property of 'super' in the constructor of a derived class." }, - _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: { code: 17012, category: ts.DiagnosticCategory.Error, key: "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", message: "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?" }, - Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: { code: 17013, category: ts.DiagnosticCategory.Error, key: "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", message: "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor." }, - Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: { code: 18001, category: ts.DiagnosticCategory.Error, key: "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", message: "A path in an 'extends' option must be relative or rooted, but '{0}' is not." }, - The_files_list_in_config_file_0_is_empty: { code: 18002, category: ts.DiagnosticCategory.Error, key: "The_files_list_in_config_file_0_is_empty_18002", message: "The 'files' list in config file '{0}' is empty." }, - No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: { code: 18003, category: ts.DiagnosticCategory.Error, key: "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", message: "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'." }, - Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, - Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, - Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'." }, - Remove_declaration_for_Colon_0: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_declaration_for_Colon_0_90004", message: "Remove declaration for: '{0}'." }, - Implement_interface_0: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_0_90006", message: "Implement interface '{0}'." }, - Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class." }, - Add_this_to_unresolved_variable: { code: 90008, category: ts.DiagnosticCategory.Message, key: "Add_this_to_unresolved_variable_90008", message: "Add 'this.' to unresolved variable." }, - Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: { code: 90009, category: ts.DiagnosticCategory.Error, key: "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", message: "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig." }, - Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: { code: 90010, category: ts.DiagnosticCategory.Error, key: "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", message: "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated." }, - Import_0_from_1: { code: 90013, category: ts.DiagnosticCategory.Message, key: "Import_0_from_1_90013", message: "Import {0} from {1}." }, - Change_0_to_1: { code: 90014, category: ts.DiagnosticCategory.Message, key: "Change_0_to_1_90014", message: "Change {0} to {1}." }, - Add_0_to_existing_import_declaration_from_1: { code: 90015, category: ts.DiagnosticCategory.Message, key: "Add_0_to_existing_import_declaration_from_1_90015", message: "Add {0} to existing import declaration from {1}." }, - Add_declaration_for_missing_property_0: { code: 90016, category: ts.DiagnosticCategory.Message, key: "Add_declaration_for_missing_property_0_90016", message: "Add declaration for missing property '{0}'." }, - Add_index_signature_for_missing_property_0: { code: 90017, category: ts.DiagnosticCategory.Message, key: "Add_index_signature_for_missing_property_0_90017", message: "Add index signature for missing property '{0}'." }, - Disable_checking_for_this_file: { code: 90018, category: ts.DiagnosticCategory.Message, key: "Disable_checking_for_this_file_90018", message: "Disable checking for this file." }, - 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." }, + Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."), + Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."), + _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."), + A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), + Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), + Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), + Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), + A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), + An_index_signature_cannot_have_a_rest_parameter: diag(1017, ts.DiagnosticCategory.Error, "An_index_signature_cannot_have_a_rest_parameter_1017", "An index signature cannot have a rest parameter."), + An_index_signature_parameter_cannot_have_an_accessibility_modifier: diag(1018, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018", "An index signature parameter cannot have an accessibility modifier."), + An_index_signature_parameter_cannot_have_a_question_mark: diag(1019, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_a_question_mark_1019", "An index signature parameter cannot have a question mark."), + An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), + An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), + An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), + An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), + Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), + _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), + _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."), + _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."), + super_must_be_followed_by_an_argument_list_or_member_access: diag(1034, ts.DiagnosticCategory.Error, "super_must_be_followed_by_an_argument_list_or_member_access_1034", "'super' must be followed by an argument list or member access."), + Only_ambient_modules_can_use_quoted_names: diag(1035, ts.DiagnosticCategory.Error, "Only_ambient_modules_can_use_quoted_names_1035", "Only ambient modules can use quoted names."), + Statements_are_not_allowed_in_ambient_contexts: diag(1036, ts.DiagnosticCategory.Error, "Statements_are_not_allowed_in_ambient_contexts_1036", "Statements are not allowed in ambient contexts."), + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: diag(1038, ts.DiagnosticCategory.Error, "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038", "A 'declare' modifier cannot be used in an already ambient context."), + Initializers_are_not_allowed_in_ambient_contexts: diag(1039, ts.DiagnosticCategory.Error, "Initializers_are_not_allowed_in_ambient_contexts_1039", "Initializers are not allowed in ambient contexts."), + _0_modifier_cannot_be_used_in_an_ambient_context: diag(1040, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_in_an_ambient_context_1040", "'{0}' modifier cannot be used in an ambient context."), + _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."), + _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."), + _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."), + _0_modifier_cannot_appear_on_a_module_or_namespace_element: diag(1044, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044", "'{0}' modifier cannot appear on a module or namespace element."), + A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."), + A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: diag(1046, ts.DiagnosticCategory.Error, "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046", "A 'declare' modifier is required for a top level declaration in a .d.ts file."), + A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."), + A_rest_parameter_cannot_have_an_initializer: diag(1048, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_have_an_initializer_1048", "A rest parameter cannot have an initializer."), + A_set_accessor_must_have_exactly_one_parameter: diag(1049, ts.DiagnosticCategory.Error, "A_set_accessor_must_have_exactly_one_parameter_1049", "A 'set' accessor must have exactly one parameter."), + A_set_accessor_cannot_have_an_optional_parameter: diag(1051, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_an_optional_parameter_1051", "A 'set' accessor cannot have an optional parameter."), + A_set_accessor_parameter_cannot_have_an_initializer: diag(1052, ts.DiagnosticCategory.Error, "A_set_accessor_parameter_cannot_have_an_initializer_1052", "A 'set' accessor parameter cannot have an initializer."), + A_set_accessor_cannot_have_rest_parameter: diag(1053, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_rest_parameter_1053", "A 'set' accessor cannot have rest parameter."), + A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."), + Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value: diag(1055, ts.DiagnosticCategory.Error, "Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Prom_1055", "Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value."), + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: diag(1056, ts.DiagnosticCategory.Error, "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056", "Accessors are only available when targeting ECMAScript 5 and higher."), + An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."), + The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1058, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_t_1058", "The return type of an async function must either be a valid promise or must not contain a callable 'then' member."), + A_promise_must_have_a_then_method: diag(1059, ts.DiagnosticCategory.Error, "A_promise_must_have_a_then_method_1059", "A promise must have a 'then' method."), + The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback: diag(1060, ts.DiagnosticCategory.Error, "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060", "The first parameter of the 'then' method of a promise must be a callback."), + Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."), + Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method: diag(1062, ts.DiagnosticCategory.Error, "Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method_1062", "Type is referenced directly or indirectly in the fulfillment callback of its own 'then' method."), + An_export_assignment_cannot_be_used_in_a_namespace: diag(1063, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_namespace_1063", "An export assignment cannot be used in a namespace."), + The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), + In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), + Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), + _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), + A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), + Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."), + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0: diag(1085, ts.DiagnosticCategory.Error, "Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0_1085", "Octal literals are not available when targeting ECMAScript 5 and higher. Use the syntax '{0}'."), + An_accessor_cannot_be_declared_in_an_ambient_context: diag(1086, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_declared_in_an_ambient_context_1086", "An accessor cannot be declared in an ambient context."), + _0_modifier_cannot_appear_on_a_constructor_declaration: diag(1089, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_constructor_declaration_1089", "'{0}' modifier cannot appear on a constructor declaration."), + _0_modifier_cannot_appear_on_a_parameter: diag(1090, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_parameter_1090", "'{0}' modifier cannot appear on a parameter."), + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: diag(1091, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement_1091", "Only a single variable declaration is allowed in a 'for...in' statement."), + Type_parameters_cannot_appear_on_a_constructor_declaration: diag(1092, ts.DiagnosticCategory.Error, "Type_parameters_cannot_appear_on_a_constructor_declaration_1092", "Type parameters cannot appear on a constructor declaration."), + Type_annotation_cannot_appear_on_a_constructor_declaration: diag(1093, ts.DiagnosticCategory.Error, "Type_annotation_cannot_appear_on_a_constructor_declaration_1093", "Type annotation cannot appear on a constructor declaration."), + An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."), + A_set_accessor_cannot_have_a_return_type_annotation: diag(1095, ts.DiagnosticCategory.Error, "A_set_accessor_cannot_have_a_return_type_annotation_1095", "A 'set' accessor cannot have a return type annotation."), + An_index_signature_must_have_exactly_one_parameter: diag(1096, ts.DiagnosticCategory.Error, "An_index_signature_must_have_exactly_one_parameter_1096", "An index signature must have exactly one parameter."), + _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."), + Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."), + Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."), + Invalid_use_of_0_in_strict_mode: diag(1100, ts.DiagnosticCategory.Error, "Invalid_use_of_0_in_strict_mode_1100", "Invalid use of '{0}' in strict mode."), + with_statements_are_not_allowed_in_strict_mode: diag(1101, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_strict_mode_1101", "'with' statements are not allowed in strict mode."), + delete_cannot_be_called_on_an_identifier_in_strict_mode: diag(1102, ts.DiagnosticCategory.Error, "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102", "'delete' cannot be called on an identifier in strict mode."), + A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."), + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: diag(1104, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104", "A 'continue' statement can only be used within an enclosing iteration statement."), + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: diag(1105, ts.DiagnosticCategory.Error, "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105", "A 'break' statement can only be used within an enclosing iteration or switch statement."), + Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."), + A_return_statement_can_only_be_used_within_a_function_body: diag(1108, ts.DiagnosticCategory.Error, "A_return_statement_can_only_be_used_within_a_function_body_1108", "A 'return' statement can only be used within a function body."), + Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."), + Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."), + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: diag(1113, ts.DiagnosticCategory.Error, "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113", "A 'default' clause cannot appear more than once in a 'switch' statement."), + Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), + An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), + Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), + A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), + Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), + Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), + Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), + Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."), + Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."), + Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."), + Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."), + case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."), + Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."), + Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."), + Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."), + Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."), + Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."), + Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."), + Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."), + Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."), + Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."), + String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."), + Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."), + or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."), + Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."), + Import_declarations_in_a_namespace_cannot_reference_a_module: diag(1147, ts.DiagnosticCategory.Error, "Import_declarations_in_a_namespace_cannot_reference_a_module_1147", "Import declarations in a namespace cannot reference a module."), + Cannot_use_imports_exports_or_module_augmentations_when_module_is_none: diag(1148, ts.DiagnosticCategory.Error, "Cannot_use_imports_exports_or_module_augmentations_when_module_is_none_1148", "Cannot use imports, exports, or module augmentations when '--module' is 'none'."), + File_name_0_differs_from_already_included_file_name_1_only_in_casing: diag(1149, ts.DiagnosticCategory.Error, "File_name_0_differs_from_already_included_file_name_1_only_in_casing_1149", "File name '{0}' differs from already included file name '{1}' only in casing."), + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: diag(1150, ts.DiagnosticCategory.Error, "new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead_1150", "'new T[]' cannot be used to create an array. Use 'new Array()' instead."), + const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."), + const_declarations_can_only_be_declared_inside_a_block: diag(1156, ts.DiagnosticCategory.Error, "const_declarations_can_only_be_declared_inside_a_block_1156", "'const' declarations can only be declared inside a block."), + let_declarations_can_only_be_declared_inside_a_block: diag(1157, ts.DiagnosticCategory.Error, "let_declarations_can_only_be_declared_inside_a_block_1157", "'let' declarations can only be declared inside a block."), + Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."), + Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."), + An_object_member_cannot_be_declared_optional: diag(1162, ts.DiagnosticCategory.Error, "An_object_member_cannot_be_declared_optional_1162", "An object member cannot be declared optional."), + A_yield_expression_is_only_allowed_in_a_generator_body: diag(1163, ts.DiagnosticCategory.Error, "A_yield_expression_is_only_allowed_in_a_generator_body_1163", "A 'yield' expression is only allowed in a generator body."), + Computed_property_names_are_not_allowed_in_enums: diag(1164, ts.DiagnosticCategory.Error, "Computed_property_names_are_not_allowed_in_enums_1164", "Computed property names are not allowed in enums."), + A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: diag(1165, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol_1165", "A computed property name in an ambient context must directly refer to a built-in symbol."), + A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol_1166", "A computed property name in a class property declaration must directly refer to a built-in symbol."), + A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: diag(1168, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol_1168", "A computed property name in a method overload must directly refer to a built-in symbol."), + A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: diag(1169, ts.DiagnosticCategory.Error, "A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol_1169", "A computed property name in an interface must directly refer to a built-in symbol."), + A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: diag(1170, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol_1170", "A computed property name in a type literal must directly refer to a built-in symbol."), + A_comma_expression_is_not_allowed_in_a_computed_property_name: diag(1171, ts.DiagnosticCategory.Error, "A_comma_expression_is_not_allowed_in_a_computed_property_name_1171", "A comma expression is not allowed in a computed property name."), + extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."), + extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."), + Classes_can_only_extend_a_single_class: diag(1174, ts.DiagnosticCategory.Error, "Classes_can_only_extend_a_single_class_1174", "Classes can only extend a single class."), + implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."), + Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."), + Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."), + Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."), + Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."), + Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."), + Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."), + A_destructuring_declaration_must_have_an_initializer: diag(1182, ts.DiagnosticCategory.Error, "A_destructuring_declaration_must_have_an_initializer_1182", "A destructuring declaration must have an initializer."), + An_implementation_cannot_be_declared_in_ambient_contexts: diag(1183, ts.DiagnosticCategory.Error, "An_implementation_cannot_be_declared_in_ambient_contexts_1183", "An implementation cannot be declared in ambient contexts."), + Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."), + Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."), + A_rest_element_cannot_have_an_initializer: diag(1186, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_an_initializer_1186", "A rest element cannot have an initializer."), + A_parameter_property_may_not_be_declared_using_a_binding_pattern: diag(1187, ts.DiagnosticCategory.Error, "A_parameter_property_may_not_be_declared_using_a_binding_pattern_1187", "A parameter property may not be declared using a binding pattern."), + Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement: diag(1188, ts.DiagnosticCategory.Error, "Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement_1188", "Only a single variable declaration is allowed in a 'for...of' statement."), + The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer: diag(1189, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer_1189", "The variable declaration of a 'for...in' statement cannot have an initializer."), + The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer: diag(1190, ts.DiagnosticCategory.Error, "The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer_1190", "The variable declaration of a 'for...of' statement cannot have an initializer."), + An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."), + Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."), + An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."), + Export_declarations_are_not_permitted_in_a_namespace: diag(1194, ts.DiagnosticCategory.Error, "Export_declarations_are_not_permitted_in_a_namespace_1194", "Export declarations are not permitted in a namespace."), + Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."), + Catch_clause_variable_cannot_have_an_initializer: diag(1197, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_an_initializer_1197", "Catch clause variable cannot have an initializer."), + An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive: diag(1198, ts.DiagnosticCategory.Error, "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198", "An extended Unicode escape value must be between 0x0 and 0x10FFFF inclusive."), + Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."), + Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "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: diag(1202, ts.DiagnosticCategory.Error, "Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asteri_1202", "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: diag(1203, ts.DiagnosticCategory.Error, "Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_defaul_1203", "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: diag(1205, ts.DiagnosticCategory.Error, "Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided_1205", "Cannot re-export a type when the '--isolatedModules' flag is provided."), + Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."), + Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name: diag(1207, ts.DiagnosticCategory.Error, "Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name_1207", "Decorators cannot be applied to multiple get/set accessors of the same name."), + Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided_1208", "Cannot compile namespaces when the '--isolatedModules' flag is provided."), + Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided: diag(1209, ts.DiagnosticCategory.Error, "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209", "Ambient const enums are not allowed when the '--isolatedModules' flag is provided."), + Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."), + A_class_declaration_without_the_default_modifier_must_have_a_name: diag(1211, ts.DiagnosticCategory.Error, "A_class_declaration_without_the_default_modifier_must_have_a_name_1211", "A class declaration without the 'default' modifier must have a name."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode: diag(1212, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_1212", "Identifier expected. '{0}' is a reserved word in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: diag(1213, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode."), + Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: diag(1214, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode."), + Invalid_use_of_0_Modules_are_automatically_in_strict_mode: diag(1215, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", "Invalid use of '{0}'. Modules are automatically in strict mode."), + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: diag(1216, ts.DiagnosticCategory.Error, "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules."), + Export_assignment_is_not_supported_when_module_flag_is_system: diag(1218, ts.DiagnosticCategory.Error, "Export_assignment_is_not_supported_when_module_flag_is_system_1218", "Export assignment is not supported when '--module' flag is 'system'."), + Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: diag(1219, ts.DiagnosticCategory.Error, "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning."), + Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."), + Generators_are_not_allowed_in_an_ambient_context: diag(1221, ts.DiagnosticCategory.Error, "Generators_are_not_allowed_in_an_ambient_context_1221", "Generators are not allowed in an ambient context."), + An_overload_signature_cannot_be_declared_as_a_generator: diag(1222, ts.DiagnosticCategory.Error, "An_overload_signature_cannot_be_declared_as_a_generator_1222", "An overload signature cannot be declared as a generator."), + _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."), + Signature_0_must_be_a_type_predicate: diag(1224, ts.DiagnosticCategory.Error, "Signature_0_must_be_a_type_predicate_1224", "Signature '{0}' must be a type predicate."), + Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."), + Type_predicate_0_is_not_assignable_to_1: diag(1226, ts.DiagnosticCategory.Error, "Type_predicate_0_is_not_assignable_to_1_1226", "Type predicate '{0}' is not assignable to '{1}'."), + Parameter_0_is_not_in_the_same_position_as_parameter_1: diag(1227, ts.DiagnosticCategory.Error, "Parameter_0_is_not_in_the_same_position_as_parameter_1_1227", "Parameter '{0}' is not in the same position as parameter '{1}'."), + A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods: diag(1228, ts.DiagnosticCategory.Error, "A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods_1228", "A type predicate is only allowed in return type position for functions and methods."), + A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), + A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), + An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."), + An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), + An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), + A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), + The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), + Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), + Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: diag(1239, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression_1239", "Unable to resolve signature of parameter decorator when called as an expression."), + Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: diag(1240, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression_1240", "Unable to resolve signature of property decorator when called as an expression."), + Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: diag(1241, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression_1241", "Unable to resolve signature of method decorator when called as an expression."), + abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration: diag(1242, ts.DiagnosticCategory.Error, "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242", "'abstract' modifier can only appear on a class, method, or property declaration."), + _0_modifier_cannot_be_used_with_1_modifier: diag(1243, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_1_modifier_1243", "'{0}' modifier cannot be used with '{1}' modifier."), + Abstract_methods_can_only_appear_within_an_abstract_class: diag(1244, ts.DiagnosticCategory.Error, "Abstract_methods_can_only_appear_within_an_abstract_class_1244", "Abstract methods can only appear within an abstract class."), + Method_0_cannot_have_an_implementation_because_it_is_marked_abstract: diag(1245, ts.DiagnosticCategory.Error, "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245", "Method '{0}' cannot have an implementation because it is marked abstract."), + An_interface_property_cannot_have_an_initializer: diag(1246, ts.DiagnosticCategory.Error, "An_interface_property_cannot_have_an_initializer_1246", "An interface property cannot have an initializer."), + A_type_literal_property_cannot_have_an_initializer: diag(1247, ts.DiagnosticCategory.Error, "A_type_literal_property_cannot_have_an_initializer_1247", "A type literal property cannot have an initializer."), + A_class_member_cannot_have_the_0_keyword: diag(1248, ts.DiagnosticCategory.Error, "A_class_member_cannot_have_the_0_keyword_1248", "A class member cannot have the '{0}' keyword."), + A_decorator_can_only_decorate_a_method_implementation_not_an_overload: diag(1249, ts.DiagnosticCategory.Error, "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249", "A decorator can only decorate a method implementation, not an overload."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5: diag(1250, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_1250", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode: diag(1251, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_d_1251", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode."), + Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode: diag(1252, ts.DiagnosticCategory.Error, "Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_1252", "Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode."), + _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), + A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), + with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), + await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), + The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), + Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), + Global_module_exports_may_only_appear_in_declaration_files: diag(1315, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_declaration_files_1315", "Global module exports may only appear in declaration files."), + Global_module_exports_may_only_appear_at_top_level: diag(1316, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_at_top_level_1316", "Global module exports may only appear at top level."), + A_parameter_property_cannot_be_declared_using_a_rest_parameter: diag(1317, ts.DiagnosticCategory.Error, "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317", "A parameter property cannot be declared using a rest parameter."), + An_abstract_accessor_cannot_have_an_implementation: diag(1318, ts.DiagnosticCategory.Error, "An_abstract_accessor_cannot_have_an_implementation_1318", "An abstract accessor cannot have an implementation."), + A_default_export_can_only_be_used_in_an_ECMAScript_style_module: diag(1319, ts.DiagnosticCategory.Error, "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319", "A default export can only be used in an ECMAScript-style module."), + Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), + Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), + Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), + Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), + Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), + Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), + String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), + Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal: diag(1328, ts.DiagnosticCategory.Error, "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328", "Property value can only be string literal, numeric literal, 'true', 'false', 'null', object literal or array literal."), + Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), + Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), + Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), + Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."), + Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."), + Module_0_has_no_exported_member_1: diag(2305, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_2305", "Module '{0}' has no exported member '{1}'."), + File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."), + Cannot_find_module_0: diag(2307, ts.DiagnosticCategory.Error, "Cannot_find_module_0_2307", "Cannot find module '{0}'."), + Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), + An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), + Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."), + An_interface_may_only_extend_a_class_or_another_interface: diag(2312, ts.DiagnosticCategory.Error, "An_interface_may_only_extend_a_class_or_another_interface_2312", "An interface may only extend a class or another interface."), + Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), + Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), + Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."), + Global_type_0_must_be_a_class_or_interface_type: diag(2316, ts.DiagnosticCategory.Error, "Global_type_0_must_be_a_class_or_interface_type_2316", "Global type '{0}' must be a class or interface type."), + Global_type_0_must_have_1_type_parameter_s: diag(2317, ts.DiagnosticCategory.Error, "Global_type_0_must_have_1_type_parameter_s_2317", "Global type '{0}' must have {1} type parameter(s)."), + Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."), + Named_property_0_of_types_1_and_2_are_not_identical: diag(2319, ts.DiagnosticCategory.Error, "Named_property_0_of_types_1_and_2_are_not_identical_2319", "Named property '{0}' of types '{1}' and '{2}' are not identical."), + Interface_0_cannot_simultaneously_extend_types_1_and_2: diag(2320, ts.DiagnosticCategory.Error, "Interface_0_cannot_simultaneously_extend_types_1_and_2_2320", "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'."), + Excessive_stack_depth_comparing_types_0_and_1: diag(2321, ts.DiagnosticCategory.Error, "Excessive_stack_depth_comparing_types_0_and_1_2321", "Excessive stack depth comparing types '{0}' and '{1}'."), + Type_0_is_not_assignable_to_type_1: diag(2322, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_2322", "Type '{0}' is not assignable to type '{1}'."), + Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."), + Property_0_is_missing_in_type_1: diag(2324, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_2324", "Property '{0}' is missing in type '{1}'."), + Property_0_is_private_in_type_1_but_not_in_type_2: diag(2325, ts.DiagnosticCategory.Error, "Property_0_is_private_in_type_1_but_not_in_type_2_2325", "Property '{0}' is private in type '{1}' but not in type '{2}'."), + Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."), + Property_0_is_optional_in_type_1_but_required_in_type_2: diag(2327, ts.DiagnosticCategory.Error, "Property_0_is_optional_in_type_1_but_required_in_type_2_2327", "Property '{0}' is optional in type '{1}' but required in type '{2}'."), + Types_of_parameters_0_and_1_are_incompatible: diag(2328, ts.DiagnosticCategory.Error, "Types_of_parameters_0_and_1_are_incompatible_2328", "Types of parameters '{0}' and '{1}' are incompatible."), + Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."), + Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."), + this_cannot_be_referenced_in_a_module_or_namespace_body: diag(2331, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_module_or_namespace_body_2331", "'this' cannot be referenced in a module or namespace body."), + this_cannot_be_referenced_in_current_location: diag(2332, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_current_location_2332", "'this' cannot be referenced in current location."), + this_cannot_be_referenced_in_constructor_arguments: diag(2333, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_constructor_arguments_2333", "'this' cannot be referenced in constructor arguments."), + this_cannot_be_referenced_in_a_static_property_initializer: diag(2334, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_static_property_initializer_2334", "'this' cannot be referenced in a static property initializer."), + super_can_only_be_referenced_in_a_derived_class: diag(2335, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_a_derived_class_2335", "'super' can only be referenced in a derived class."), + super_cannot_be_referenced_in_constructor_arguments: diag(2336, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_constructor_arguments_2336", "'super' cannot be referenced in constructor arguments."), + Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors: diag(2337, ts.DiagnosticCategory.Error, "Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors_2337", "Super calls are not permitted outside constructors or in nested functions inside constructors."), + super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class: diag(2338, ts.DiagnosticCategory.Error, "super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_der_2338", "'super' property access is permitted only in a constructor, member function, or member accessor of a derived class."), + Property_0_does_not_exist_on_type_1: diag(2339, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_2339", "Property '{0}' does not exist on type '{1}'."), + Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword: diag(2340, ts.DiagnosticCategory.Error, "Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword_2340", "Only public and protected methods of the base class are accessible via the 'super' keyword."), + Property_0_is_private_and_only_accessible_within_class_1: diag(2341, ts.DiagnosticCategory.Error, "Property_0_is_private_and_only_accessible_within_class_1_2341", "Property '{0}' is private and only accessible within class '{1}'."), + An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."), + This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1: diag(2343, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_but_module_0_has_no_exported_member_1_2343", "This syntax requires an imported helper named '{1}', but module '{0}' has no exported member '{1}'."), + Type_0_does_not_satisfy_the_constraint_1: diag(2344, ts.DiagnosticCategory.Error, "Type_0_does_not_satisfy_the_constraint_1_2344", "Type '{0}' does not satisfy the constraint '{1}'."), + Argument_of_type_0_is_not_assignable_to_parameter_of_type_1: diag(2345, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_2345", "Argument of type '{0}' is not assignable to parameter of type '{1}'."), + Call_target_does_not_contain_any_signatures: diag(2346, ts.DiagnosticCategory.Error, "Call_target_does_not_contain_any_signatures_2346", "Call target does not contain any signatures."), + Untyped_function_calls_may_not_accept_type_arguments: diag(2347, ts.DiagnosticCategory.Error, "Untyped_function_calls_may_not_accept_type_arguments_2347", "Untyped function calls may not accept type arguments."), + Value_of_type_0_is_not_callable_Did_you_mean_to_include_new: diag(2348, ts.DiagnosticCategory.Error, "Value_of_type_0_is_not_callable_Did_you_mean_to_include_new_2348", "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: diag(2349, ts.DiagnosticCategory.Error, "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349", "Cannot invoke an expression whose type lacks a call signature. Type '{0}' has no compatible call signatures."), + Only_a_void_function_can_be_called_with_the_new_keyword: diag(2350, ts.DiagnosticCategory.Error, "Only_a_void_function_can_be_called_with_the_new_keyword_2350", "Only a void function can be called with the 'new' keyword."), + Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: diag(2351, ts.DiagnosticCategory.Error, "Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature_2351", "Cannot use 'new' with an expression whose type lacks a call or construct signature."), + Type_0_cannot_be_converted_to_type_1: diag(2352, ts.DiagnosticCategory.Error, "Type_0_cannot_be_converted_to_type_1_2352", "Type '{0}' cannot be converted to type '{1}'."), + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: diag(2353, ts.DiagnosticCategory.Error, "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'."), + This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found: diag(2354, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found_2354", "This syntax requires an imported helper but module '{0}' cannot be found."), + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: diag(2355, ts.DiagnosticCategory.Error, "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", "A function whose declared type is neither 'void' nor 'any' must return a value."), + An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: diag(2356, ts.DiagnosticCategory.Error, "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", "An arithmetic operand must be of type 'any', 'number' or an enum type."), + The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access: diag(2357, ts.DiagnosticCategory.Error, "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access_2357", "The operand of an increment or decrement operator must be a variable or a property access."), + The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2358, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_Function_interface_type: diag(2359, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359", "The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type."), + The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."), + The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."), + The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2362, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2362", "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type: diag(2363, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type_2363", "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."), + The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), + Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), + Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), + A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), + A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), + A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation: diag(2371, ts.DiagnosticCategory.Error, "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371", "A parameter initializer is only allowed in a function or constructor implementation."), + Parameter_0_cannot_be_referenced_in_its_initializer: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_be_referenced_in_its_initializer_2372", "Parameter '{0}' cannot be referenced in its initializer."), + Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Initializer of parameter '{0}' cannot reference identifier '{1}' declared after it."), + Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."), + Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."), + A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties."), + Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), + A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), + Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."), + get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."), + A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."), + Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."), + Overload_signatures_must_all_be_exported_or_non_exported: diag(2383, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_exported_or_non_exported_2383", "Overload signatures must all be exported or non-exported."), + Overload_signatures_must_all_be_ambient_or_non_ambient: diag(2384, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_ambient_or_non_ambient_2384", "Overload signatures must all be ambient or non-ambient."), + Overload_signatures_must_all_be_public_private_or_protected: diag(2385, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_public_private_or_protected_2385", "Overload signatures must all be public, private or protected."), + Overload_signatures_must_all_be_optional_or_required: diag(2386, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_optional_or_required_2386", "Overload signatures must all be optional or required."), + Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."), + Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."), + Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."), + Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."), + Function_implementation_is_missing_or_not_immediately_following_the_declaration: diag(2391, ts.DiagnosticCategory.Error, "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391", "Function implementation is missing or not immediately following the declaration."), + Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."), + Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."), + Overload_signature_is_not_compatible_with_function_implementation: diag(2394, ts.DiagnosticCategory.Error, "Overload_signature_is_not_compatible_with_function_implementation_2394", "Overload signature is not compatible with function implementation."), + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: diag(2395, ts.DiagnosticCategory.Error, "Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local_2395", "Individual declarations in merged declaration '{0}' must be all exported or all local."), + Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: diag(2396, ts.DiagnosticCategory.Error, "Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters_2396", "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters."), + Declaration_name_conflicts_with_built_in_global_identifier_0: diag(2397, ts.DiagnosticCategory.Error, "Declaration_name_conflicts_with_built_in_global_identifier_0_2397", "Declaration name conflicts with built-in global identifier '{0}'."), + Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), + Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."), + Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), + Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), + The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), + The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), + The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), + Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), + Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."), + Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."), + Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), + Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), + Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), + A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), + Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), + Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), + Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), + Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), + All_declarations_of_0_must_have_identical_type_parameters: diag(2428, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_type_parameters_2428", "All declarations of '{0}' must have identical type parameters."), + Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."), + Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."), + In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element: diag(2432, ts.DiagnosticCategory.Error, "In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enu_2432", "In an enum with multiple declarations, only one declaration can omit an initializer for its first enum element."), + A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged: diag(2433, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433", "A namespace declaration cannot be in a different file from a class or function with which it is merged."), + A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged: diag(2434, ts.DiagnosticCategory.Error, "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434", "A namespace declaration cannot be located prior to a class or function with which it is merged."), + Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces: diag(2435, ts.DiagnosticCategory.Error, "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435", "Ambient modules cannot be nested in other modules or namespaces."), + Ambient_module_declaration_cannot_specify_relative_module_name: diag(2436, ts.DiagnosticCategory.Error, "Ambient_module_declaration_cannot_specify_relative_module_name_2436", "Ambient module declaration cannot specify relative module name."), + Module_0_is_hidden_by_a_local_declaration_with_the_same_name: diag(2437, ts.DiagnosticCategory.Error, "Module_0_is_hidden_by_a_local_declaration_with_the_same_name_2437", "Module '{0}' is hidden by a local declaration with the same name."), + Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."), + Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name: diag(2439, ts.DiagnosticCategory.Error, "Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relati_2439", "Import or export declaration in an ambient module declaration cannot reference module through relative module name."), + Import_declaration_conflicts_with_local_declaration_of_0: diag(2440, ts.DiagnosticCategory.Error, "Import_declaration_conflicts_with_local_declaration_of_0_2440", "Import declaration conflicts with local declaration of '{0}'."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module: diag(2441, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_2441", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module."), + Types_have_separate_declarations_of_a_private_property_0: diag(2442, ts.DiagnosticCategory.Error, "Types_have_separate_declarations_of_a_private_property_0_2442", "Types have separate declarations of a private property '{0}'."), + Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2: diag(2443, ts.DiagnosticCategory.Error, "Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2_2443", "Property '{0}' is protected but type '{1}' is not a class derived from '{2}'."), + Property_0_is_protected_in_type_1_but_public_in_type_2: diag(2444, ts.DiagnosticCategory.Error, "Property_0_is_protected_in_type_1_but_public_in_type_2_2444", "Property '{0}' is protected in type '{1}' but public in type '{2}'."), + Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: diag(2445, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses_2445", "Property '{0}' is protected and only accessible within class '{1}' and its subclasses."), + Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."), + The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: diag(2447, ts.DiagnosticCategory.Error, "The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead_2447", "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead."), + Block_scoped_variable_0_used_before_its_declaration: diag(2448, ts.DiagnosticCategory.Error, "Block_scoped_variable_0_used_before_its_declaration_2448", "Block-scoped variable '{0}' used before its declaration."), + Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."), + Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."), + Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."), + An_enum_member_cannot_have_a_numeric_name: diag(2452, ts.DiagnosticCategory.Error, "An_enum_member_cannot_have_a_numeric_name_2452", "An enum member cannot have a numeric name."), + The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."), + Variable_0_is_used_before_being_assigned: diag(2454, ts.DiagnosticCategory.Error, "Variable_0_is_used_before_being_assigned_2454", "Variable '{0}' is used before being assigned."), + Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."), + Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), + Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), + An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), + Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), + Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), + Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), + A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), + A_computed_property_name_must_be_of_type_string_number_symbol_or_any: diag(2464, ts.DiagnosticCategory.Error, "A_computed_property_name_must_be_of_type_string_number_symbol_or_any_2464", "A computed property name must be of type 'string', 'number', 'symbol', or 'any'."), + this_cannot_be_referenced_in_a_computed_property_name: diag(2465, ts.DiagnosticCategory.Error, "this_cannot_be_referenced_in_a_computed_property_name_2465", "'this' cannot be referenced in a computed property name."), + super_cannot_be_referenced_in_a_computed_property_name: diag(2466, ts.DiagnosticCategory.Error, "super_cannot_be_referenced_in_a_computed_property_name_2466", "'super' cannot be referenced in a computed property name."), + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: diag(2467, ts.DiagnosticCategory.Error, "A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type_2467", "A computed property name cannot reference a type parameter from its containing type."), + Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."), + The_0_operator_cannot_be_applied_to_type_symbol: diag(2469, ts.DiagnosticCategory.Error, "The_0_operator_cannot_be_applied_to_type_symbol_2469", "The '{0}' operator cannot be applied to type 'symbol'."), + Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."), + A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), + Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), + Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), + In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), + const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), + const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), + Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."), + let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations: diag(2480, ts.DiagnosticCategory.Error, "let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations_2480", "'let' is not allowed to be used as a name in 'let' or 'const' declarations."), + Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1: diag(2481, ts.DiagnosticCategory.Error, "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481", "Cannot initialize outer scoped variable '{0}' in the same scope as block scoped declaration '{1}'."), + The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), + Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), + The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), + Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), + The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), + The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), + Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), + Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), + Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), + The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), + Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), + An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), + A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), + A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), + Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), + Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), + _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), + Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), + No_base_constructor_has_the_specified_number_of_type_arguments: diag(2508, ts.DiagnosticCategory.Error, "No_base_constructor_has_the_specified_number_of_type_arguments_2508", "No base constructor has the specified number of type arguments."), + Base_constructor_return_type_0_is_not_a_class_or_interface_type: diag(2509, ts.DiagnosticCategory.Error, "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509", "Base constructor return type '{0}' is not a class or interface type."), + Base_constructors_must_all_have_the_same_return_type: diag(2510, ts.DiagnosticCategory.Error, "Base_constructors_must_all_have_the_same_return_type_2510", "Base constructors must all have the same return type."), + Cannot_create_an_instance_of_the_abstract_class_0: diag(2511, ts.DiagnosticCategory.Error, "Cannot_create_an_instance_of_the_abstract_class_0_2511", "Cannot create an instance of the abstract class '{0}'."), + Overload_signatures_must_all_be_abstract_or_non_abstract: diag(2512, ts.DiagnosticCategory.Error, "Overload_signatures_must_all_be_abstract_or_non_abstract_2512", "Overload signatures must all be abstract or non-abstract."), + Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression: diag(2513, ts.DiagnosticCategory.Error, "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513", "Abstract method '{0}' in class '{1}' cannot be accessed via super expression."), + Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."), + Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: diag(2515, ts.DiagnosticCategory.Error, "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515", "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'."), + All_declarations_of_an_abstract_method_must_be_consecutive: diag(2516, ts.DiagnosticCategory.Error, "All_declarations_of_an_abstract_method_must_be_consecutive_2516", "All declarations of an abstract method must be consecutive."), + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: diag(2517, ts.DiagnosticCategory.Error, "Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type_2517", "Cannot assign an abstract constructor type to a non-abstract constructor type."), + A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard: diag(2518, ts.DiagnosticCategory.Error, "A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard_2518", "A 'this'-based type guard is not compatible with a parameter-based type guard."), + An_async_iterator_must_have_a_next_method: diag(2519, ts.DiagnosticCategory.Error, "An_async_iterator_must_have_a_next_method_2519", "An async iterator must have a 'next()' method."), + Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: diag(2520, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions_2520", "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions."), + Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."), + The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_using_a_standard_function_or_method: diag(2522, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522", "The 'arguments' object cannot be referenced in an async function or method in ES3 and ES5. Consider using a standard function or method."), + yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, ts.DiagnosticCategory.Error, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), + await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, ts.DiagnosticCategory.Error, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), + Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, ts.DiagnosticCategory.Error, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), + A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, ts.DiagnosticCategory.Error, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), + The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary: diag(2527, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_references_an_inaccessible_this_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible 'this' type. A type annotation is necessary."), + A_module_cannot_have_multiple_default_exports: diag(2528, ts.DiagnosticCategory.Error, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), + Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions: diag(2529, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_func_2529", "Duplicate identifier '{0}'. Compiler reserves name '{1}' in top level scope of a module containing async functions."), + Property_0_is_incompatible_with_index_signature: diag(2530, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_index_signature_2530", "Property '{0}' is incompatible with index signature."), + Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."), + Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."), + Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."), + A_function_returning_never_cannot_have_a_reachable_end_point: diag(2534, ts.DiagnosticCategory.Error, "A_function_returning_never_cannot_have_a_reachable_end_point_2534", "A function returning 'never' cannot have a reachable end point."), + Enum_type_0_has_members_with_initializers_that_are_not_literals: diag(2535, ts.DiagnosticCategory.Error, "Enum_type_0_has_members_with_initializers_that_are_not_literals_2535", "Enum type '{0}' has members with initializers that are not literals."), + Type_0_cannot_be_used_to_index_type_1: diag(2536, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_to_index_type_1_2536", "Type '{0}' cannot be used to index type '{1}'."), + Type_0_has_no_matching_index_signature_for_type_1: diag(2537, ts.DiagnosticCategory.Error, "Type_0_has_no_matching_index_signature_for_type_1_2537", "Type '{0}' has no matching index signature for type '{1}'."), + Type_0_cannot_be_used_as_an_index_type: diag(2538, ts.DiagnosticCategory.Error, "Type_0_cannot_be_used_as_an_index_type_2538", "Type '{0}' cannot be used as an index type."), + Cannot_assign_to_0_because_it_is_not_a_variable: diag(2539, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_not_a_variable_2539", "Cannot assign to '{0}' because it is not a variable."), + Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property: diag(2540, ts.DiagnosticCategory.Error, "Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property_2540", "Cannot assign to '{0}' because it is a constant or a read-only property."), + The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."), + Index_signature_in_type_0_only_permits_reading: diag(2542, ts.DiagnosticCategory.Error, "Index_signature_in_type_0_only_permits_reading_2542", "Index signature in type '{0}' only permits reading."), + Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: diag(2543, ts.DiagnosticCategory.Error, "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference."), + Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: diag(2544, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference."), + A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: diag(2545, ts.DiagnosticCategory.Error, "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", "A mixin class must have a constructor with a single rest parameter of type 'any[]'."), + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: diag(2546, ts.DiagnosticCategory.Error, "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'."), + The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property: diag(2547, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value__2547", "The type returned by the 'next()' method of an async iterator must be a promise for a type with a 'value' property."), + Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2548, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator_2548", "Type '{0}' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2549, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns__2549", "Type '{0}' is not an array type or a string type or does not have a '[Symbol.iterator]()' method that returns an iterator."), + Generic_type_instantiation_is_excessively_deep_and_possibly_infinite: diag(2550, ts.DiagnosticCategory.Error, "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550", "Generic type instantiation is excessively deep and possibly infinite."), + Property_0_does_not_exist_on_type_1_Did_you_mean_2: diag(2551, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_mean_2_2551", "Property '{0}' does not exist on type '{1}'. Did you mean '{2}'?"), + Cannot_find_name_0_Did_you_mean_1: diag(2552, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_1_2552", "Cannot find name '{0}'. Did you mean '{1}'?"), + Computed_values_are_not_permitted_in_an_enum_with_string_valued_members: diag(2553, ts.DiagnosticCategory.Error, "Computed_values_are_not_permitted_in_an_enum_with_string_valued_members_2553", "Computed values are not permitted in an enum with string valued members."), + Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."), + Expected_at_least_0_arguments_but_got_1: diag(2555, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_2555", "Expected at least {0} arguments, but got {1}."), + Expected_0_arguments_but_got_a_minimum_of_1: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_a_minimum_of_1_2556", "Expected {0} arguments, but got a minimum of {1}."), + Expected_at_least_0_arguments_but_got_a_minimum_of_1: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_a_minimum_of_1_2557", "Expected at least {0} arguments, but got a minimum of {1}."), + Expected_0_type_arguments_but_got_1: diag(2558, ts.DiagnosticCategory.Error, "Expected_0_type_arguments_but_got_1_2558", "Expected {0} type arguments, but got {1}."), + Type_0_has_no_properties_in_common_with_type_1: diag(2559, ts.DiagnosticCategory.Error, "Type_0_has_no_properties_in_common_with_type_1_2559", "Type '{0}' has no properties in common with type '{1}'."), + JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), + The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), + JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), + Property_0_in_type_1_is_not_assignable_to_type_2: diag(2603, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_type_2_2603", "Property '{0}' in type '{1}' is not assignable to type '{2}'."), + JSX_element_type_0_does_not_have_any_construct_or_call_signatures: diag(2604, ts.DiagnosticCategory.Error, "JSX_element_type_0_does_not_have_any_construct_or_call_signatures_2604", "JSX element type '{0}' does not have any construct or call signatures."), + JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."), + Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: diag(2606, ts.DiagnosticCategory.Error, "Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property_2606", "Property '{0}' of JSX spread attribute is not assignable to target property."), + JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: diag(2607, ts.DiagnosticCategory.Error, "JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property_2607", "JSX element class does not support attributes because it does not have a '{0}' property."), + The_global_type_JSX_0_may_not_have_more_than_one_property: diag(2608, ts.DiagnosticCategory.Error, "The_global_type_JSX_0_may_not_have_more_than_one_property_2608", "The global type 'JSX.{0}' may not have more than one property."), + JSX_spread_child_must_be_an_array_type: diag(2609, ts.DiagnosticCategory.Error, "JSX_spread_child_must_be_an_array_type_2609", "JSX spread child must be an array type."), + Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), + A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), + Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: diag(2653, ts.DiagnosticCategory.Error, "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653", "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'."), + Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."), + Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."), + JSX_expressions_must_have_one_parent_element: diag(2657, ts.DiagnosticCategory.Error, "JSX_expressions_must_have_one_parent_element_2657", "JSX expressions must have one parent element."), + Type_0_provides_no_match_for_the_signature_1: diag(2658, ts.DiagnosticCategory.Error, "Type_0_provides_no_match_for_the_signature_1_2658", "Type '{0}' provides no match for the signature '{1}'."), + super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher: diag(2659, ts.DiagnosticCategory.Error, "super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_highe_2659", "'super' is only allowed in members of object literal expressions when option 'target' is 'ES2015' or higher."), + super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions: diag(2660, ts.DiagnosticCategory.Error, "super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions_2660", "'super' can only be referenced in members of derived classes or object literal expressions."), + Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module: diag(2661, ts.DiagnosticCategory.Error, "Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module_2661", "Cannot export '{0}'. Only local declarations can be exported from a module."), + Cannot_find_name_0_Did_you_mean_the_static_member_1_0: diag(2662, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662", "Cannot find name '{0}'. Did you mean the static member '{1}.{0}'?"), + Cannot_find_name_0_Did_you_mean_the_instance_member_this_0: diag(2663, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_the_instance_member_this_0_2663", "Cannot find name '{0}'. Did you mean the instance member 'this.{0}'?"), + Invalid_module_name_in_augmentation_module_0_cannot_be_found: diag(2664, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_module_0_cannot_be_found_2664", "Invalid module name in augmentation, module '{0}' cannot be found."), + Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented: diag(2665, ts.DiagnosticCategory.Error, "Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augm_2665", "Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented."), + Exports_and_export_assignments_are_not_permitted_in_module_augmentations: diag(2666, ts.DiagnosticCategory.Error, "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666", "Exports and export assignments are not permitted in module augmentations."), + Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module: diag(2667, ts.DiagnosticCategory.Error, "Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_mod_2667", "Imports are not permitted in module augmentations. Consider moving them to the enclosing external module."), + export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible: diag(2668, ts.DiagnosticCategory.Error, "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668", "'export' modifier cannot be applied to ambient modules and module augmentations since they are always visible."), + Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations: diag(2669, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669", "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."), + Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context: diag(2670, ts.DiagnosticCategory.Error, "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670", "Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context."), + Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity: diag(2671, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity_2671", "Cannot augment module '{0}' because it resolves to a non-module entity."), + Cannot_assign_a_0_constructor_type_to_a_1_constructor_type: diag(2672, ts.DiagnosticCategory.Error, "Cannot_assign_a_0_constructor_type_to_a_1_constructor_type_2672", "Cannot assign a '{0}' constructor type to a '{1}' constructor type."), + Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration: diag(2673, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration_2673", "Constructor of class '{0}' is private and only accessible within the class declaration."), + Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration: diag(2674, ts.DiagnosticCategory.Error, "Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration_2674", "Constructor of class '{0}' is protected and only accessible within the class declaration."), + Cannot_extend_a_class_0_Class_constructor_is_marked_as_private: diag(2675, ts.DiagnosticCategory.Error, "Cannot_extend_a_class_0_Class_constructor_is_marked_as_private_2675", "Cannot extend a class '{0}'. Class constructor is marked as private."), + Accessors_must_both_be_abstract_or_non_abstract: diag(2676, ts.DiagnosticCategory.Error, "Accessors_must_both_be_abstract_or_non_abstract_2676", "Accessors must both be abstract or non-abstract."), + A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type: diag(2677, ts.DiagnosticCategory.Error, "A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type_2677", "A type predicate's type must be assignable to its parameter's type."), + Type_0_is_not_comparable_to_type_1: diag(2678, ts.DiagnosticCategory.Error, "Type_0_is_not_comparable_to_type_1_2678", "Type '{0}' is not comparable to type '{1}'."), + A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void: diag(2679, ts.DiagnosticCategory.Error, "A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void_2679", "A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'."), + A_0_parameter_must_be_the_first_parameter: diag(2680, ts.DiagnosticCategory.Error, "A_0_parameter_must_be_the_first_parameter_2680", "A '{0}' parameter must be the first parameter."), + A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot have a 'this' parameter."), + get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."), + this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: diag(2683, ts.DiagnosticCategory.Error, "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", "'this' implicitly has type 'any' because it does not have a type annotation."), + The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: diag(2684, ts.DiagnosticCategory.Error, "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'."), + The_this_types_of_each_signature_are_incompatible: diag(2685, ts.DiagnosticCategory.Error, "The_this_types_of_each_signature_are_incompatible_2685", "The 'this' types of each signature are incompatible."), + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: diag(2686, ts.DiagnosticCategory.Error, "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead."), + All_declarations_of_0_must_have_identical_modifiers: diag(2687, ts.DiagnosticCategory.Error, "All_declarations_of_0_must_have_identical_modifiers_2687", "All declarations of '{0}' must have identical modifiers."), + Cannot_find_type_definition_file_for_0: diag(2688, ts.DiagnosticCategory.Error, "Cannot_find_type_definition_file_for_0_2688", "Cannot find type definition file for '{0}'."), + Cannot_extend_an_interface_0_Did_you_mean_implements: diag(2689, ts.DiagnosticCategory.Error, "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", "Cannot extend an interface '{0}'. Did you mean 'implements'?"), + An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead: diag(2691, ts.DiagnosticCategory.Error, "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691", "An import path cannot end with a '{0}' extension. Consider importing '{1}' instead."), + _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), + _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), + Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), + An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), + Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1: diag(2699, ts.DiagnosticCategory.Error, "Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1_2699", "Static property '{0}' conflicts with built-in property 'Function.{0}' of constructor function '{1}'."), + Rest_types_may_only_be_created_from_object_types: diag(2700, ts.DiagnosticCategory.Error, "Rest_types_may_only_be_created_from_object_types_2700", "Rest types may only be created from object types."), + The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access: diag(2701, ts.DiagnosticCategory.Error, "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701", "The target of an object rest assignment must be a variable or a property access."), + _0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here: diag(2702, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702", "'{0}' only refers to a type, but is being used as a namespace here."), + The_operand_of_a_delete_operator_must_be_a_property_reference: diag(2703, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_a_property_reference_2703", "The operand of a delete operator must be a property reference."), + The_operand_of_a_delete_operator_cannot_be_a_read_only_property: diag(2704, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_read_only_property_2704", "The operand of a delete operator cannot be a read-only property."), + An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2705, ts.DiagnosticCategory.Error, "An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_de_2705", "An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Required_type_parameters_may_not_follow_optional_type_parameters: diag(2706, ts.DiagnosticCategory.Error, "Required_type_parameters_may_not_follow_optional_type_parameters_2706", "Required type parameters may not follow optional type parameters."), + Generic_type_0_requires_between_1_and_2_type_arguments: diag(2707, ts.DiagnosticCategory.Error, "Generic_type_0_requires_between_1_and_2_type_arguments_2707", "Generic type '{0}' requires between {1} and {2} type arguments."), + Cannot_use_namespace_0_as_a_value: diag(2708, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_value_2708", "Cannot use namespace '{0}' as a value."), + Cannot_use_namespace_0_as_a_type: diag(2709, ts.DiagnosticCategory.Error, "Cannot_use_namespace_0_as_a_type_2709", "Cannot use namespace '{0}' as a type."), + _0_are_specified_twice_The_attribute_named_0_will_be_overwritten: diag(2710, ts.DiagnosticCategory.Error, "_0_are_specified_twice_The_attribute_named_0_will_be_overwritten_2710", "'{0}' are specified twice. The attribute named '{0}' will be overwritten."), + A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2711, ts.DiagnosticCategory.Error, "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711", "A dynamic import call returns a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), + A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option: diag(2712, ts.DiagnosticCategory.Error, "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712", "A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option."), + Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1: diag(2713, ts.DiagnosticCategory.Error, "Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_p_2713", "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?"), + Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), + Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), + Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), + Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4006, ts.DiagnosticCategory.Error, "Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4006", "Type parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4008, ts.DiagnosticCategory.Error, "Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4008", "Type parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4010, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4010", "Type parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4012, ts.DiagnosticCategory.Error, "Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4012", "Type parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4014, ts.DiagnosticCategory.Error, "Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4014", "Type parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Type_parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4016, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_function_has_or_is_using_private_name_1_4016", "Type parameter '{0}' of exported function has or is using private name '{1}'."), + Implements_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4019, ts.DiagnosticCategory.Error, "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019", "Implements clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_class_0_has_or_is_using_private_name_1: diag(4020, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020", "'extends' clause of exported class '{0}' has or is using private name '{1}'."), + extends_clause_of_exported_interface_0_has_or_is_using_private_name_1: diag(4022, ts.DiagnosticCategory.Error, "extends_clause_of_exported_interface_0_has_or_is_using_private_name_1_4022", "'extends' clause of exported interface '{0}' has or is using private name '{1}'."), + Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4023, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023", "Exported variable '{0}' has or is using name '{1}' from external module {2} but cannot be named."), + Exported_variable_0_has_or_is_using_name_1_from_private_module_2: diag(4024, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024", "Exported variable '{0}' has or is using name '{1}' from private module '{2}'."), + Exported_variable_0_has_or_is_using_private_name_1: diag(4025, ts.DiagnosticCategory.Error, "Exported_variable_0_has_or_is_using_private_name_1_4025", "Exported variable '{0}' has or is using private name '{1}'."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4026, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot__4026", "Public static property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4027, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4027", "Public static property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_static_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4028, ts.DiagnosticCategory.Error, "Public_static_property_0_of_exported_class_has_or_is_using_private_name_1_4028", "Public static property '{0}' of exported class has or is using private name '{1}'."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4029, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_name_4029", "Public property '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), + Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4030, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4030", "Public property '{0}' of exported class has or is using name '{1}' from private module '{2}'."), + Public_property_0_of_exported_class_has_or_is_using_private_name_1: diag(4031, ts.DiagnosticCategory.Error, "Public_property_0_of_exported_class_has_or_is_using_private_name_1_4031", "Public property '{0}' of exported class has or is using private name '{1}'."), + Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4032, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4032", "Property '{0}' of exported interface has or is using name '{1}' from private module '{2}'."), + Property_0_of_exported_interface_has_or_is_using_private_name_1: diag(4033, ts.DiagnosticCategory.Error, "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033", "Property '{0}' of exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4034, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_4034", "Parameter '{0}' of public static property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4035, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1_4035", "Parameter '{0}' of public static property setter from exported class has or is using private name '{1}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4036, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_4036", "Parameter '{0}' of public property setter from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1: diag(4037, ts.DiagnosticCategory.Error, "Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1_4037", "Parameter '{0}' of public property setter from exported class has or is using private name '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4038, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_externa_4038", "Return type of public static property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4039, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_4039", "Return type of public static property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4040, ts.DiagnosticCategory.Error, "Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0_4040", "Return type of public static property getter from exported class has or is using private name '{0}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4041, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_modul_4041", "Return type of public property getter from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4042, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_4042", "Return type of public property getter from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0: diag(4043, ts.DiagnosticCategory.Error, "Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0_4043", "Return type of public property getter from exported class has or is using private name '{0}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4044, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_mod_4044", "Return type of constructor signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4045, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0_4045", "Return type of constructor signature from exported interface has or is using private name '{0}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4046, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4046", "Return type of call signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4047, ts.DiagnosticCategory.Error, "Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0_4047", "Return type of call signature from exported interface has or is using private name '{0}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4048, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4048", "Return type of index signature from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0: diag(4049, ts.DiagnosticCategory.Error, "Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0_4049", "Return type of index signature from exported interface has or is using private name '{0}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4050, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module__4050", "Return type of public static method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4051, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4051", "Return type of public static method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0: diag(4052, ts.DiagnosticCategory.Error, "Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0_4052", "Return type of public static method from exported class has or is using private name '{0}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4053, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_c_4053", "Return type of public method from exported class has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1: diag(4054, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1_4054", "Return type of public method from exported class has or is using name '{0}' from private module '{1}'."), + Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0: diag(4055, ts.DiagnosticCategory.Error, "Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0_4055", "Return type of public method from exported class has or is using private name '{0}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1: diag(4056, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1_4056", "Return type of method from exported interface has or is using name '{0}' from private module '{1}'."), + Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0: diag(4057, ts.DiagnosticCategory.Error, "Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0_4057", "Return type of method from exported interface has or is using private name '{0}'."), + Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named: diag(4058, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named_4058", "Return type of exported function has or is using name '{0}' from external module {1} but cannot be named."), + Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1: diag(4059, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1_4059", "Return type of exported function has or is using name '{0}' from private module '{1}'."), + Return_type_of_exported_function_has_or_is_using_private_name_0: diag(4060, ts.DiagnosticCategory.Error, "Return_type_of_exported_function_has_or_is_using_private_name_0_4060", "Return type of exported function has or is using private name '{0}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4061, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_can_4061", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4062, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2_4062", "Parameter '{0}' of constructor from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1: diag(4063, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1_4063", "Parameter '{0}' of constructor from exported class has or is using private name '{1}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4064, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_mod_4064", "Parameter '{0}' of constructor signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4065, ts.DiagnosticCategory.Error, "Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1_4065", "Parameter '{0}' of constructor signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4066, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4066", "Parameter '{0}' of call signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4067, ts.DiagnosticCategory.Error, "Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1_4067", "Parameter '{0}' of call signature from exported interface has or is using private name '{1}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4068, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module__4068", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4069, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4069", "Parameter '{0}' of public static method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1: diag(4070, ts.DiagnosticCategory.Error, "Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1_4070", "Parameter '{0}' of public static method from exported class has or is using private name '{1}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4071, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_c_4071", "Parameter '{0}' of public method from exported class has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4072, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2_4072", "Parameter '{0}' of public method from exported class has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1: diag(4073, ts.DiagnosticCategory.Error, "Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1_4073", "Parameter '{0}' of public method from exported class has or is using private name '{1}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4074, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4074", "Parameter '{0}' of method from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1: diag(4075, ts.DiagnosticCategory.Error, "Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1_4075", "Parameter '{0}' of method from exported interface has or is using private name '{1}'."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4076, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4076", "Parameter '{0}' of exported function has or is using name '{1}' from external module {2} but cannot be named."), + Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2: diag(4077, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2_4077", "Parameter '{0}' of exported function has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_exported_function_has_or_is_using_private_name_1: diag(4078, ts.DiagnosticCategory.Error, "Parameter_0_of_exported_function_has_or_is_using_private_name_1_4078", "Parameter '{0}' of exported function has or is using private name '{1}'."), + Exported_type_alias_0_has_or_is_using_private_name_1: diag(4081, ts.DiagnosticCategory.Error, "Exported_type_alias_0_has_or_is_using_private_name_1_4081", "Exported type alias '{0}' has or is using private name '{1}'."), + Default_export_of_the_module_has_or_is_using_private_name_0: diag(4082, ts.DiagnosticCategory.Error, "Default_export_of_the_module_has_or_is_using_private_name_0_4082", "Default export of the module has or is using private name '{0}'."), + Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), + Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, ts.DiagnosticCategory.Message, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), + Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, ts.DiagnosticCategory.Error, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), + Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, ts.DiagnosticCategory.Error, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + The_current_host_does_not_support_the_0_option: diag(5001, ts.DiagnosticCategory.Error, "The_current_host_does_not_support_the_0_option_5001", "The current host does not support the '{0}' option."), + Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, ts.DiagnosticCategory.Error, "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009", "Cannot find the common subdirectory path for the input files."), + File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5010, ts.DiagnosticCategory.Error, "File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0_5010", "File specification cannot end in a recursive directory wildcard ('**'): '{0}'."), + File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0: diag(5011, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0_5011", "File specification cannot contain multiple recursive directory wildcards ('**'): '{0}'."), + Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), + Failed_to_parse_file_0_Colon_1: diag(5014, ts.DiagnosticCategory.Error, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), + Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), + Compiler_option_0_requires_a_value_of_type_1: diag(5024, ts.DiagnosticCategory.Error, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), + Could_not_write_file_0_Colon_1: diag(5033, ts.DiagnosticCategory.Error, "Could_not_write_file_0_Colon_1_5033", "Could not write file '{0}': {1}."), + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: diag(5042, ts.DiagnosticCategory.Error, "Option_project_cannot_be_mixed_with_source_files_on_a_command_line_5042", "Option 'project' cannot be mixed with source files on a command line."), + Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher: diag(5047, ts.DiagnosticCategory.Error, "Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES_5047", "Option 'isolatedModules' can only be used when either option '--module' is provided or option 'target' is 'ES2015' or higher."), + Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided: diag(5051, ts.DiagnosticCategory.Error, "Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided_5051", "Option '{0} can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided."), + Option_0_cannot_be_specified_without_specifying_option_1: diag(5052, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_5052", "Option '{0}' cannot be specified without specifying option '{1}'."), + Option_0_cannot_be_specified_with_option_1: diag(5053, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_with_option_1_5053", "Option '{0}' cannot be specified with option '{1}'."), + A_tsconfig_json_file_is_already_defined_at_Colon_0: diag(5054, ts.DiagnosticCategory.Error, "A_tsconfig_json_file_is_already_defined_at_Colon_0_5054", "A 'tsconfig.json' file is already defined at: '{0}'."), + Cannot_write_file_0_because_it_would_overwrite_input_file: diag(5055, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_overwrite_input_file_5055", "Cannot write file '{0}' because it would overwrite input file."), + Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files: diag(5056, ts.DiagnosticCategory.Error, "Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files_5056", "Cannot write file '{0}' because it would be overwritten by multiple input files."), + Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0: diag(5057, ts.DiagnosticCategory.Error, "Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0_5057", "Cannot find a tsconfig.json file at the specified directory: '{0}'."), + The_specified_path_does_not_exist_Colon_0: diag(5058, ts.DiagnosticCategory.Error, "The_specified_path_does_not_exist_Colon_0_5058", "The specified path does not exist: '{0}'."), + Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier: diag(5059, ts.DiagnosticCategory.Error, "Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier_5059", "Invalid value for '--reactNamespace'. '{0}' is not a valid identifier."), + Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."), + Pattern_0_can_have_at_most_one_Asterisk_character: diag(5061, ts.DiagnosticCategory.Error, "Pattern_0_can_have_at_most_one_Asterisk_character_5061", "Pattern '{0}' can have at most one '*' character."), + Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character: diag(5062, ts.DiagnosticCategory.Error, "Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character_5062", "Substitution '{0}' in pattern '{1}' in can have at most one '*' character."), + Substitutions_for_pattern_0_should_be_an_array: diag(5063, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_should_be_an_array_5063", "Substitutions for pattern '{0}' should be an array."), + Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2: diag(5064, ts.DiagnosticCategory.Error, "Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2_5064", "Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'."), + File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0: diag(5065, ts.DiagnosticCategory.Error, "File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildca_5065", "File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '{0}'."), + Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), + Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), + Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), + Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), + Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), + Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: diag(6004, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004", "Specify the location where debugger should locate TypeScript files instead of source locations."), + Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."), + Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."), + Do_not_erase_const_enum_declarations_in_generated_code: diag(6007, ts.DiagnosticCategory.Message, "Do_not_erase_const_enum_declarations_in_generated_code_6007", "Do not erase const enum declarations in generated code."), + Do_not_emit_outputs_if_any_errors_were_reported: diag(6008, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_if_any_errors_were_reported_6008", "Do not emit outputs if any errors were reported."), + Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."), + Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."), + Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking: diag(6011, ts.DiagnosticCategory.Message, "Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typech_6011", "Allow default imports from modules with no default export. This does not affect code emit, just typechecking."), + Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."), + Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_or_ESNEXT_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'."), + Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext_6016", "Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'."), + Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."), + Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."), + Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json: diag(6020, ts.DiagnosticCategory.Message, "Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json_6020", "Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'."), + Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"), + options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"), + file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"), + Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"), + Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"), + Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"), + Insert_command_line_options_and_files_from_a_file: diag(6030, ts.DiagnosticCategory.Message, "Insert_command_line_options_and_files_from_a_file_6030", "Insert command line options and files from a file."), + File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."), + KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"), + FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"), + VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"), + LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"), + DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), + STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), + FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), + Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), + Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), + Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), + Argument_for_0_option_must_be_Colon_1: diag(6046, ts.DiagnosticCategory.Error, "Argument_for_0_option_must_be_Colon_1_6046", "Argument for '{0}' option must be: {1}."), + Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1: diag(6048, ts.DiagnosticCategory.Error, "Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1_6048", "Locale must be of the form or -. For example '{0}' or '{1}'."), + Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."), + Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."), + Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."), + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: diag(6052, ts.DiagnosticCategory.Message, "Raise_error_on_expressions_and_declarations_with_an_implied_any_type_6052", "Raise error on expressions and declarations with an implied 'any' type."), + File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."), + File_0_has_unsupported_extension_The_only_supported_extensions_are_1: diag(6054, ts.DiagnosticCategory.Error, "File_0_has_unsupported_extension_The_only_supported_extensions_are_1_6054", "File '{0}' has unsupported extension. The only supported extensions are {1}."), + Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: diag(6055, ts.DiagnosticCategory.Message, "Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures_6055", "Suppress noImplicitAny errors for indexing objects lacking index signatures."), + Do_not_emit_declarations_for_code_that_has_an_internal_annotation: diag(6056, ts.DiagnosticCategory.Message, "Do_not_emit_declarations_for_code_that_has_an_internal_annotation_6056", "Do not emit declarations for code that has an '@internal' annotation."), + Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: diag(6058, ts.DiagnosticCategory.Message, "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058", "Specify the root directory of input files. Use to control the output directory structure with --outDir."), + File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: diag(6059, ts.DiagnosticCategory.Error, "File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files_6059", "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files."), + Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: diag(6060, ts.DiagnosticCategory.Message, "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060", "Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)."), + NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"), + Option_0_can_only_be_specified_in_tsconfig_json_file: diag(6064, ts.DiagnosticCategory.Error, "Option_0_can_only_be_specified_in_tsconfig_json_file_6064", "Option '{0}' can only be specified in 'tsconfig.json' file."), + Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."), + Enables_experimental_support_for_emitting_type_metadata_for_decorators: diag(6066, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", "Enables experimental support for emitting type metadata for decorators."), + Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."), + Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6: diag(6069, ts.DiagnosticCategory.Message, "Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6_6069", "Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)."), + Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: diag(6070, ts.DiagnosticCategory.Message, "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", "Initializes a TypeScript project and creates a tsconfig.json file."), + Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."), + Suppress_excess_property_checks_for_object_literals: diag(6072, ts.DiagnosticCategory.Message, "Suppress_excess_property_checks_for_object_literals_6072", "Suppress excess property checks for object literals."), + Stylize_errors_and_messages_using_color_and_context_experimental: diag(6073, ts.DiagnosticCategory.Message, "Stylize_errors_and_messages_using_color_and_context_experimental_6073", "Stylize errors and messages using color and context (experimental)."), + Do_not_report_errors_on_unused_labels: diag(6074, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unused_labels_6074", "Do not report errors on unused labels."), + Report_error_when_not_all_code_paths_in_function_return_a_value: diag(6075, ts.DiagnosticCategory.Message, "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", "Report error when not all code paths in function return a value."), + Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), + Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), + Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), + Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), + File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), + Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), + Base_directory_to_resolve_non_absolute_module_names: diag(6083, ts.DiagnosticCategory.Message, "Base_directory_to_resolve_non_absolute_module_names_6083", "Base directory to resolve non-absolute module names."), + Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit: diag(6084, ts.DiagnosticCategory.Message, "Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react__6084", "[Deprecated] Use '--jsxFactory' instead. Specify the object invoked for createElement when targeting 'react' JSX emit"), + Enable_tracing_of_the_name_resolution_process: diag(6085, ts.DiagnosticCategory.Message, "Enable_tracing_of_the_name_resolution_process_6085", "Enable tracing of the name resolution process."), + Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"), + Explicitly_specified_module_resolution_kind_Colon_0: diag(6087, ts.DiagnosticCategory.Message, "Explicitly_specified_module_resolution_kind_Colon_0_6087", "Explicitly specified module resolution kind: '{0}'."), + Module_resolution_kind_is_not_specified_using_0: diag(6088, ts.DiagnosticCategory.Message, "Module_resolution_kind_is_not_specified_using_0_6088", "Module resolution kind is not specified, using '{0}'."), + Module_name_0_was_successfully_resolved_to_1: diag(6089, ts.DiagnosticCategory.Message, "Module_name_0_was_successfully_resolved_to_1_6089", "======== Module name '{0}' was successfully resolved to '{1}'. ========"), + Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"), + paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0: diag(6091, ts.DiagnosticCategory.Message, "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091", "'paths' option is specified, looking for a pattern to match module name '{0}'."), + Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."), + Trying_substitution_0_candidate_module_location_Colon_1: diag(6093, ts.DiagnosticCategory.Message, "Trying_substitution_0_candidate_module_location_Colon_1_6093", "Trying substitution '{0}', candidate module location: '{1}'."), + Resolving_module_name_0_relative_to_base_url_1_2: diag(6094, ts.DiagnosticCategory.Message, "Resolving_module_name_0_relative_to_base_url_1_2_6094", "Resolving module name '{0}' relative to base url '{1}' - '{2}'."), + Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1: diag(6095, ts.DiagnosticCategory.Message, "Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1_6095", "Loading module as file / folder, candidate module location '{0}', target file type '{1}'."), + File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."), + File_0_exist_use_it_as_a_name_resolution_result: diag(6097, ts.DiagnosticCategory.Message, "File_0_exist_use_it_as_a_name_resolution_result_6097", "File '{0}' exist - use it as a name resolution result."), + Loading_module_0_from_node_modules_folder_target_file_type_1: diag(6098, ts.DiagnosticCategory.Message, "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", "Loading module '{0}' from 'node_modules' folder, target file type '{1}'."), + Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."), + package_json_does_not_have_a_0_field: diag(6100, ts.DiagnosticCategory.Message, "package_json_does_not_have_a_0_field_6100", "'package.json' does not have a '{0}' field."), + package_json_has_0_field_1_that_references_2: diag(6101, ts.DiagnosticCategory.Message, "package_json_has_0_field_1_that_references_2_6101", "'package.json' has '{0}' field '{1}' that references '{2}'."), + Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."), + Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."), + Checking_if_0_is_the_longest_matching_prefix_for_1_2: diag(6104, ts.DiagnosticCategory.Message, "Checking_if_0_is_the_longest_matching_prefix_for_1_2_6104", "Checking if '{0}' is the longest matching prefix for '{1}' - '{2}'."), + Expected_type_of_0_field_in_package_json_to_be_string_got_1: diag(6105, ts.DiagnosticCategory.Message, "Expected_type_of_0_field_in_package_json_to_be_string_got_1_6105", "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'."), + baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1: diag(6106, ts.DiagnosticCategory.Message, "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106", "'baseUrl' option is set to '{0}', using this value to resolve non-relative module name '{1}'."), + rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0: diag(6107, ts.DiagnosticCategory.Message, "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107", "'rootDirs' option is set, using it to resolve relative module name '{0}'."), + Longest_matching_prefix_for_0_is_1: diag(6108, ts.DiagnosticCategory.Message, "Longest_matching_prefix_for_0_is_1_6108", "Longest matching prefix for '{0}' is '{1}'."), + Loading_0_from_the_root_dir_1_candidate_location_2: diag(6109, ts.DiagnosticCategory.Message, "Loading_0_from_the_root_dir_1_candidate_location_2_6109", "Loading '{0}' from the root dir '{1}', candidate location '{2}'."), + Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."), + Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."), + Do_not_emit_use_strict_directives_in_module_output: diag(6112, ts.DiagnosticCategory.Message, "Do_not_emit_use_strict_directives_in_module_output_6112", "Do not emit 'use strict' directives in module output."), + Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."), + Unknown_option_excludes_Did_you_mean_exclude: diag(6114, ts.DiagnosticCategory.Error, "Unknown_option_excludes_Did_you_mean_exclude_6114", "Unknown option 'excludes'. Did you mean 'exclude'?"), + Raise_error_on_this_expressions_with_an_implied_any_type: diag(6115, ts.DiagnosticCategory.Message, "Raise_error_on_this_expressions_with_an_implied_any_type_6115", "Raise error on 'this' expressions with an implied 'any' type."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_2: diag(6116, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_2_6116", "======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========"), + Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."), + Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."), + Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2: diag(6119, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2_6119", "======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========"), + Type_reference_directive_0_was_not_resolved: diag(6120, ts.DiagnosticCategory.Message, "Type_reference_directive_0_was_not_resolved_6120", "======== Type reference directive '{0}' was not resolved. ========"), + Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."), + Root_directory_cannot_be_determined_skipping_primary_search_paths: diag(6122, ts.DiagnosticCategory.Message, "Root_directory_cannot_be_determined_skipping_primary_search_paths_6122", "Root directory cannot be determined, skipping primary search paths."), + Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set: diag(6123, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set_6123", "======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========"), + Type_declaration_files_to_be_included_in_compilation: diag(6124, ts.DiagnosticCategory.Message, "Type_declaration_files_to_be_included_in_compilation_6124", "Type declaration files to be included in compilation."), + Looking_up_in_node_modules_folder_initial_location_0: diag(6125, ts.DiagnosticCategory.Message, "Looking_up_in_node_modules_folder_initial_location_0_6125", "Looking up in 'node_modules' folder, initial location '{0}'."), + Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder: diag(6126, ts.DiagnosticCategory.Message, "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126", "Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder."), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1: diag(6127, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1_6127", "======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========"), + Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set: diag(6128, ts.DiagnosticCategory.Message, "Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set_6128", "======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========"), + The_config_file_0_found_doesn_t_contain_any_source_files: diag(6129, ts.DiagnosticCategory.Error, "The_config_file_0_found_doesn_t_contain_any_source_files_6129", "The config file '{0}' found doesn't contain any source files."), + Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), + Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), + File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), + _0_is_declared_but_never_used: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6133", "'{0}' is declared but never used."), + Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), + Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), + The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), + Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), + Property_0_is_declared_but_never_used: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_never_used_6138", "Property '{0}' is declared but never used."), + Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "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: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), + Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), + Module_0_was_resolved_to_1_but_allowJs_is_not_set: diag(6143, ts.DiagnosticCategory.Error, "Module_0_was_resolved_to_1_but_allowJs_is_not_set_6143", "Module '{0}' was resolved to '{1}', but '--allowJs' is not set."), + Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), + Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, ts.DiagnosticCategory.Message, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), + Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, ts.DiagnosticCategory.Message, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), + Resolution_for_module_0_was_found_in_cache: diag(6147, ts.DiagnosticCategory.Message, "Resolution_for_module_0_was_found_in_cache_6147", "Resolution for module '{0}' was found in cache."), + Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, ts.DiagnosticCategory.Message, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), + Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."), + Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."), + Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file: diag(6151, ts.DiagnosticCategory.Message, "Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file_6151", "Emit a single file with source maps instead of having a separate file."), + Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set: diag(6152, ts.DiagnosticCategory.Message, "Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap__6152", "Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set."), + Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule: diag(6153, ts.DiagnosticCategory.Message, "Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule_6153", "Transpile each file as a separate module (similar to 'ts.transpileModule')."), + Print_names_of_generated_files_part_of_the_compilation: diag(6154, ts.DiagnosticCategory.Message, "Print_names_of_generated_files_part_of_the_compilation_6154", "Print names of generated files part of the compilation."), + Print_names_of_files_part_of_the_compilation: diag(6155, ts.DiagnosticCategory.Message, "Print_names_of_files_part_of_the_compilation_6155", "Print names of files part of the compilation."), + The_locale_used_when_displaying_messages_to_the_user_e_g_en_us: diag(6156, ts.DiagnosticCategory.Message, "The_locale_used_when_displaying_messages_to_the_user_e_g_en_us_6156", "The locale used when displaying messages to the user (e.g. 'en-us')"), + Do_not_generate_custom_helper_functions_like_extends_in_compiled_output: diag(6157, ts.DiagnosticCategory.Message, "Do_not_generate_custom_helper_functions_like_extends_in_compiled_output_6157", "Do not generate custom helper functions like '__extends' in compiled output."), + Do_not_include_the_default_library_file_lib_d_ts: diag(6158, ts.DiagnosticCategory.Message, "Do_not_include_the_default_library_file_lib_d_ts_6158", "Do not include the default library file (lib.d.ts)."), + Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files: diag(6159, ts.DiagnosticCategory.Message, "Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files_6159", "Do not add triple-slash references or imported modules to the list of compiled files."), + Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files: diag(6160, ts.DiagnosticCategory.Message, "Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files_6160", "[Deprecated] Use '--skipLibCheck' instead. Skip type checking of default library declaration files."), + List_of_folders_to_include_type_definitions_from: diag(6161, ts.DiagnosticCategory.Message, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), + Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), + The_character_set_of_the_input_files: diag(6163, ts.DiagnosticCategory.Message, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."), + Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), + Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), + A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, ts.DiagnosticCategory.Message, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), + List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime: diag(6168, ts.DiagnosticCategory.Message, "List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime_6168", "List of root folders whose combined content represents the structure of the project at runtime."), + Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."), + Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file: diag(6170, ts.DiagnosticCategory.Message, "Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file_6170", "[Deprecated] Use '--outFile' instead. Concatenate and emit output to single file"), + Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"), + Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"), + Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"), + Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"), + Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"), + Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"), + Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"), + Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"), + Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3: diag(6179, ts.DiagnosticCategory.Message, "Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3_6179", "Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'."), + Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."), + List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."), + Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"), + Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."), + Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."), + Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."), + Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), + Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), + Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), + new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type: diag(7009, ts.DiagnosticCategory.Error, "new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type_7009", "'new' expression, whose target lacks a construct signature, implicitly has an 'any' type."), + _0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type: diag(7010, ts.DiagnosticCategory.Error, "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010", "'{0}', which lacks return-type annotation, implicitly has an '{1}' return type."), + Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type: diag(7011, ts.DiagnosticCategory.Error, "Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type_7011", "Function expression, which lacks return-type annotation, implicitly has an '{0}' return type."), + Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7013, ts.DiagnosticCategory.Error, "Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7013", "Construct signature, which lacks return-type annotation, implicitly has an 'any' return type."), + Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number: diag(7015, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number_7015", "Element implicitly has an 'any' type because index expression is not of type 'number'."), + Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type: diag(7016, ts.DiagnosticCategory.Error, "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016", "Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type."), + Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature: diag(7017, ts.DiagnosticCategory.Error, "Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature_7017", "Element implicitly has an 'any' type because type '{0}' has no index signature."), + Object_literal_s_property_0_implicitly_has_an_1_type: diag(7018, ts.DiagnosticCategory.Error, "Object_literal_s_property_0_implicitly_has_an_1_type_7018", "Object literal's property '{0}' implicitly has an '{1}' type."), + Rest_parameter_0_implicitly_has_an_any_type: diag(7019, ts.DiagnosticCategory.Error, "Rest_parameter_0_implicitly_has_an_any_type_7019", "Rest parameter '{0}' implicitly has an 'any[]' type."), + Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: diag(7020, ts.DiagnosticCategory.Error, "Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type_7020", "Call signature, which lacks return-type annotation, implicitly has an 'any' return type."), + _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, ts.DiagnosticCategory.Error, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), + _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: diag(7023, ts.DiagnosticCategory.Error, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{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."), + 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), + Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), + JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), + Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), + Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), + Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: diag(7032, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation."), + Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: diag(7033, ts.DiagnosticCategory.Error, "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation."), + Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), + Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), + Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), + You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), + import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), + export_can_only_be_used_in_a_ts_file: diag(8003, ts.DiagnosticCategory.Error, "export_can_only_be_used_in_a_ts_file_8003", "'export=' can only be used in a .ts file."), + type_parameter_declarations_can_only_be_used_in_a_ts_file: diag(8004, ts.DiagnosticCategory.Error, "type_parameter_declarations_can_only_be_used_in_a_ts_file_8004", "'type parameter declarations' can only be used in a .ts file."), + implements_clauses_can_only_be_used_in_a_ts_file: diag(8005, ts.DiagnosticCategory.Error, "implements_clauses_can_only_be_used_in_a_ts_file_8005", "'implements clauses' can only be used in a .ts file."), + interface_declarations_can_only_be_used_in_a_ts_file: diag(8006, ts.DiagnosticCategory.Error, "interface_declarations_can_only_be_used_in_a_ts_file_8006", "'interface declarations' can only be used in a .ts file."), + module_declarations_can_only_be_used_in_a_ts_file: diag(8007, ts.DiagnosticCategory.Error, "module_declarations_can_only_be_used_in_a_ts_file_8007", "'module declarations' can only be used in a .ts file."), + type_aliases_can_only_be_used_in_a_ts_file: diag(8008, ts.DiagnosticCategory.Error, "type_aliases_can_only_be_used_in_a_ts_file_8008", "'type aliases' can only be used in a .ts file."), + _0_can_only_be_used_in_a_ts_file: diag(8009, ts.DiagnosticCategory.Error, "_0_can_only_be_used_in_a_ts_file_8009", "'{0}' can only be used in a .ts file."), + types_can_only_be_used_in_a_ts_file: diag(8010, ts.DiagnosticCategory.Error, "types_can_only_be_used_in_a_ts_file_8010", "'types' can only be used in a .ts file."), + type_arguments_can_only_be_used_in_a_ts_file: diag(8011, ts.DiagnosticCategory.Error, "type_arguments_can_only_be_used_in_a_ts_file_8011", "'type arguments' can only be used in a .ts file."), + parameter_modifiers_can_only_be_used_in_a_ts_file: diag(8012, ts.DiagnosticCategory.Error, "parameter_modifiers_can_only_be_used_in_a_ts_file_8012", "'parameter modifiers' can only be used in a .ts file."), + non_null_assertions_can_only_be_used_in_a_ts_file: diag(8013, ts.DiagnosticCategory.Error, "non_null_assertions_can_only_be_used_in_a_ts_file_8013", "'non-null assertions' can only be used in a .ts file."), + enum_declarations_can_only_be_used_in_a_ts_file: diag(8015, ts.DiagnosticCategory.Error, "enum_declarations_can_only_be_used_in_a_ts_file_8015", "'enum declarations' can only be used in a .ts file."), + type_assertion_expressions_can_only_be_used_in_a_ts_file: diag(8016, ts.DiagnosticCategory.Error, "type_assertion_expressions_can_only_be_used_in_a_ts_file_8016", "'type assertion expressions' can only be used in a .ts file."), + Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: diag(8017, ts.DiagnosticCategory.Error, "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", "Octal literal types must use ES2015 syntax. Use the syntax '{0}'."), + Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0: diag(8018, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0_8018", "Octal literals are not allowed in enums members initializer. Use the syntax '{0}'."), + Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."), + JSDoc_types_can_only_be_used_inside_documentation_comments: diag(8020, ts.DiagnosticCategory.Error, "JSDoc_types_can_only_be_used_inside_documentation_comments_8020", "JSDoc types can only be used inside documentation comments."), + Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), + class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), + Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), + JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17000, ts.DiagnosticCategory.Error, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), + JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, ts.DiagnosticCategory.Error, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), + Expected_corresponding_JSX_closing_tag_for_0: diag(17002, ts.DiagnosticCategory.Error, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), + JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."), + Cannot_use_JSX_unless_the_jsx_flag_is_provided: diag(17004, ts.DiagnosticCategory.Error, "Cannot_use_JSX_unless_the_jsx_flag_is_provided_17004", "Cannot use JSX unless the '--jsx' flag is provided."), + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: diag(17005, ts.DiagnosticCategory.Error, "A_constructor_cannot_contain_a_super_call_when_its_class_extends_null_17005", "A constructor cannot contain a 'super' call when its class extends 'null'."), + An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17006, ts.DiagnosticCategory.Error, "An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_ex_17006", "An unary expression with the '{0}' operator is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses: diag(17007, ts.DiagnosticCategory.Error, "A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Con_17007", "A type assertion expression is not allowed in the left-hand side of an exponentiation expression. Consider enclosing the expression in parentheses."), + JSX_element_0_has_no_corresponding_closing_tag: diag(17008, ts.DiagnosticCategory.Error, "JSX_element_0_has_no_corresponding_closing_tag_17008", "JSX element '{0}' has no corresponding closing tag."), + super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: diag(17009, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", "'super' must be called before accessing 'this' in the constructor of a derived class."), + Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."), + super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class: diag(17011, ts.DiagnosticCategory.Error, "super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class_17011", "'super' must be called before accessing a property of 'super' in the constructor of a derived class."), + _0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2: diag(17012, ts.DiagnosticCategory.Error, "_0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2_17012", "'{0}' is not a valid meta-property for keyword '{1}'. Did you mean '{2}'?"), + Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor: diag(17013, ts.DiagnosticCategory.Error, "Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constru_17013", "Meta-property '{0}' is only allowed in the body of a function declaration, function expression, or constructor."), + Circularity_detected_while_resolving_configuration_Colon_0: diag(18000, ts.DiagnosticCategory.Error, "Circularity_detected_while_resolving_configuration_Colon_0_18000", "Circularity detected while resolving configuration: {0}"), + A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."), + The_files_list_in_config_file_0_is_empty: diag(18002, ts.DiagnosticCategory.Error, "The_files_list_in_config_file_0_is_empty_18002", "The 'files' list in config file '{0}' is empty."), + No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2: diag(18003, ts.DiagnosticCategory.Error, "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003", "No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'."), + Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call."), + Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor."), + Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'."), + Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'."), + Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'."), + Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class."), + Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable."), + Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(90009, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__90009", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(90010, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_90010", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import {0} from {1}."), + Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change {0} to {1}."), + Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add {0} to existing import declaration from {1}."), + Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'."), + Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'."), + Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file."), + Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message."), + Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor."), + Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'."), + Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'."), + Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'."), + Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'."), + Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore."), + Rewrite_as_the_indexed_access_type_0: diag(90026, ts.DiagnosticCategory.Message, "Rewrite_as_the_indexed_access_type_0_90026", "Rewrite as the indexed access type '{0}'."), + Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), + Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), }; })(ts || (ts = {})); var ts; +(function (ts) { + ts.emptyArray = []; + ts.emptyMap = ts.createMap(); + ts.externalHelpersModuleNameText = "tslib"; + function getDeclarationOfKind(symbol, kind) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; + if (declaration.kind === kind) { + return declaration; + } + } + } + return undefined; + } + ts.getDeclarationOfKind = getDeclarationOfKind; + function findDeclaration(symbol, predicate) { + var declarations = symbol.declarations; + if (declarations) { + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; + if (predicate(declaration)) { + return declaration; + } + } + } + return undefined; + } + ts.findDeclaration = findDeclaration; + var stringWriter = createSingleLineStringWriter(); + var stringWriterAcquired = false; + function createSingleLineStringWriter() { + var str = ""; + var writeText = function (text) { return str += text; }; + return { + string: function () { return str; }, + writeKeyword: writeText, + writeOperator: writeText, + writePunctuation: writeText, + writeSpace: writeText, + writeStringLiteral: writeText, + writeParameter: writeText, + writeProperty: writeText, + writeSymbol: writeText, + writeLine: function () { return str += " "; }, + increaseIndent: ts.noop, + decreaseIndent: ts.noop, + clear: function () { return str = ""; }, + trackSymbol: ts.noop, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + }; + } + function usingSingleLineStringWriter(action) { + try { + ts.Debug.assert(!stringWriterAcquired); + stringWriterAcquired = true; + action(stringWriter); + return stringWriter.string(); + } + finally { + stringWriter.clear(); + stringWriterAcquired = false; + } + } + ts.usingSingleLineStringWriter = usingSingleLineStringWriter; + function getFullWidth(node) { + return node.end - node.pos; + } + ts.getFullWidth = getFullWidth; + function getResolvedModule(sourceFile, moduleNameText) { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); + } + ts.getResolvedModule = getResolvedModule; + function setResolvedModule(sourceFile, moduleNameText, resolvedModule) { + if (!sourceFile.resolvedModules) { + sourceFile.resolvedModules = ts.createMap(); + } + sourceFile.resolvedModules.set(moduleNameText, resolvedModule); + } + ts.setResolvedModule = setResolvedModule; + function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) { + if (!sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap(); + } + sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); + } + ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective; + function moduleResolutionIsEqualTo(oldResolution, newResolution) { + return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && + oldResolution.extension === newResolution.extension && + oldResolution.resolvedFileName === newResolution.resolvedFileName; + } + ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; + function typeDirectiveIsEqualTo(oldResolution, newResolution) { + return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; + } + ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo; + function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) { + 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]); + var changed = oldResolution + ? !newResolution || !comparer(oldResolution, newResolution) + : newResolution; + if (changed) { + return true; + } + } + return false; + } + ts.hasChangesInResolutions = hasChangesInResolutions; + function containsParseError(node) { + aggregateChildData(node); + return (node.flags & 131072) !== 0; + } + ts.containsParseError = containsParseError; + function aggregateChildData(node) { + if (!(node.flags & 262144)) { + var thisNodeOrAnySubNodesHasError = ((node.flags & 32768) !== 0) || + ts.forEachChild(node, containsParseError); + if (thisNodeOrAnySubNodesHasError) { + node.flags |= 131072; + } + node.flags |= 262144; + } + } + function getSourceFileOfNode(node) { + while (node && node.kind !== 265) { + node = node.parent; + } + return node; + } + ts.getSourceFileOfNode = getSourceFileOfNode; + function isStatementWithLocals(node) { + switch (node.kind) { + case 207: + case 235: + case 214: + case 215: + case 216: + return true; + } + return false; + } + ts.isStatementWithLocals = isStatementWithLocals; + function getStartPositionOfLine(line, sourceFile) { + ts.Debug.assert(line >= 0); + return ts.getLineStarts(sourceFile)[line]; + } + ts.getStartPositionOfLine = getStartPositionOfLine; + function nodePosToString(node) { + var file = getSourceFileOfNode(node); + var loc = ts.getLineAndCharacterOfPosition(file, node.pos); + return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")"; + } + ts.nodePosToString = nodePosToString; + function getStartPosOfNode(node) { + return node.pos; + } + ts.getStartPosOfNode = getStartPosOfNode; + function isDefined(value) { + return value !== undefined; + } + ts.isDefined = isDefined; + function getEndLinePosition(line, sourceFile) { + ts.Debug.assert(line >= 0); + var lineStarts = ts.getLineStarts(sourceFile); + var lineIndex = line; + var sourceText = sourceFile.text; + if (lineIndex + 1 === lineStarts.length) { + return sourceText.length - 1; + } + else { + var start = lineStarts[lineIndex]; + var pos = lineStarts[lineIndex + 1] - 1; + ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos))); + while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) { + pos--; + } + return pos; + } + } + ts.getEndLinePosition = getEndLinePosition; + function nodeIsMissing(node) { + if (node === undefined) { + return true; + } + return node.pos === node.end && node.pos >= 0 && node.kind !== 1; + } + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; + function getTokenPosOfNode(node, sourceFile, includeJsDoc) { + if (nodeIsMissing(node)) { + return node.pos; + } + if (ts.isJSDocNode(node)) { + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, false, true); + } + if (includeJsDoc && node.jsDoc && node.jsDoc.length > 0) { + return getTokenPosOfNode(node.jsDoc[0]); + } + if (node.kind === 286 && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); + } + ts.getTokenPosOfNode = getTokenPosOfNode; + function getNonDecoratorTokenPosOfNode(node, sourceFile) { + if (nodeIsMissing(node) || !node.decorators) { + return getTokenPosOfNode(node, sourceFile); + } + return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end); + } + ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode; + function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + if (nodeIsMissing(node)) { + return ""; + } + var text = sourceFile.text; + return text.substring(includeTrivia ? node.pos : ts.skipTrivia(text, node.pos), node.end); + } + ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; + function getTextOfNodeFromSourceText(sourceText, node) { + if (nodeIsMissing(node)) { + return ""; + } + return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); + } + ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText; + function getTextOfNode(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = false; } + return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); + } + ts.getTextOfNode = getTextOfNode; + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function getLiteralText(node, sourceFile) { + if (!nodeIsSynthesized(node) && node.parent) { + return getSourceTextOfNodeFromSourceFile(sourceFile, node); + } + var escapeText = getEmitFlags(node) & 16777216 ? escapeString : escapeNonAsciiString; + switch (node.kind) { + case 9: + return '"' + escapeText(node.text) + '"'; + case 13: + return "`" + escapeText(node.text) + "`"; + case 14: + return "`" + escapeText(node.text) + "${"; + case 15: + return "}" + escapeText(node.text) + "${"; + case 16: + return "}" + escapeText(node.text) + "`"; + case 8: + return node.text; + } + ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + } + ts.getLiteralText = getLiteralText; + function getTextOfConstantValue(value) { + return typeof value === "string" ? '"' + escapeNonAsciiString(value) + '"' : "" + value; + } + ts.getTextOfConstantValue = getTextOfConstantValue; + function escapeLeadingUnderscores(identifier) { + return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 && identifier.charCodeAt(1) === 95 ? "_" + identifier : identifier); + } + ts.escapeLeadingUnderscores = escapeLeadingUnderscores; + function escapeIdentifier(identifier) { + return identifier; + } + ts.escapeIdentifier = escapeIdentifier; + function makeIdentifierFromModuleName(moduleName) { + return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); + } + ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; + function isBlockOrCatchScoped(declaration) { + return (ts.getCombinedNodeFlags(declaration) & 3) !== 0 || + isCatchClauseVariableDeclarationOrBindingElement(declaration); + } + ts.isBlockOrCatchScoped = isBlockOrCatchScoped; + function isCatchClauseVariableDeclarationOrBindingElement(declaration) { + var node = getRootDeclaration(declaration); + return node.kind === 226 && node.parent.kind === 260; + } + ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; + function isAmbientModule(node) { + return node && node.kind === 233 && + (node.name.kind === 9 || isGlobalScopeAugmentation(node)); + } + ts.isAmbientModule = isAmbientModule; + function isNonGlobalAmbientModule(node) { + return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); + } + ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + function isShorthandAmbientModuleSymbol(moduleSymbol) { + return isShorthandAmbientModule(moduleSymbol.valueDeclaration); + } + ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; + function isShorthandAmbientModule(node) { + return node && node.kind === 233 && (!node.body); + } + function isBlockScopedContainerTopLevel(node) { + return node.kind === 265 || + node.kind === 233 || + ts.isFunctionLike(node); + } + ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; + function isGlobalScopeAugmentation(module) { + return !!(module.flags & 512); + } + ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation; + function isExternalModuleAugmentation(node) { + if (!node || !isAmbientModule(node)) { + return false; + } + switch (node.parent.kind) { + case 265: + return ts.isExternalModule(node.parent); + case 234: + return isAmbientModule(node.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); + } + return false; + } + ts.isExternalModuleAugmentation = isExternalModuleAugmentation; + function isEffectiveExternalModule(node, compilerOptions) { + return ts.isExternalModule(node) || compilerOptions.isolatedModules; + } + ts.isEffectiveExternalModule = isEffectiveExternalModule; + function isBlockScope(node, parentNode) { + switch (node.kind) { + case 265: + case 235: + case 260: + case 233: + case 214: + case 215: + case 216: + case 152: + case 151: + case 153: + case 154: + case 228: + case 186: + case 187: + return true; + case 207: + return parentNode && !ts.isFunctionLike(parentNode); + } + return false; + } + ts.isBlockScope = isBlockScope; + function getEnclosingBlockScopeContainer(node) { + var current = node.parent; + while (current) { + if (isBlockScope(current, current.parent)) { + return current; + } + current = current.parent; + } + } + ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; + function declarationNameToString(name) { + return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + } + ts.declarationNameToString = declarationNameToString; + function getNameFromIndexInfo(info) { + return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; + } + ts.getNameFromIndexInfo = getNameFromIndexInfo; + function getTextOfPropertyName(name) { + switch (name.kind) { + case 71: + return name.escapedText; + case 9: + case 8: + return escapeLeadingUnderscores(name.text); + case 144: + if (isStringOrNumericLiteral(name.expression)) { + return escapeLeadingUnderscores(name.expression.text); + } + } + return undefined; + } + ts.getTextOfPropertyName = getTextOfPropertyName; + function entityNameToString(name) { + switch (name.kind) { + case 71: + return getFullWidth(name) === 0 ? ts.unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); + case 143: + return entityNameToString(name.left) + "." + entityNameToString(name.right); + case 179: + return entityNameToString(name.expression) + "." + entityNameToString(name.name); + } + } + ts.entityNameToString = entityNameToString; + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + var sourceFile = getSourceFileOfNode(node); + return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNode = createDiagnosticForNode; + function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2) { + var span = getErrorSpanForNode(sourceFile, node); + return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); + } + ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; + function createDiagnosticForNodeFromMessageChain(node, messageChain) { + var sourceFile = getSourceFileOfNode(node); + var span = getErrorSpanForNode(sourceFile, node); + return { + file: sourceFile, + start: span.start, + length: span.length, + code: messageChain.code, + category: messageChain.category, + messageText: messageChain.next ? messageChain : messageChain.messageText + }; + } + ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; + function getSpanOfTokenAtPosition(sourceFile, pos) { + var scanner = ts.createScanner(sourceFile.languageVersion, true, sourceFile.languageVariant, sourceFile.text, undefined, pos); + scanner.scan(); + var start = scanner.getTokenPos(); + return ts.createTextSpanFromBounds(start, scanner.getTextPos()); + } + ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; + function getErrorSpanForArrowFunction(sourceFile, node) { + var pos = ts.skipTrivia(sourceFile.text, node.pos); + if (node.body && node.body.kind === 207) { + var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; + var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; + if (startLine < endLine) { + return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1); + } + } + return ts.createTextSpanFromBounds(pos, node.end); + } + function getErrorSpanForNode(sourceFile, node) { + var errorNode = node; + switch (node.kind) { + case 265: + var pos_1 = ts.skipTrivia(sourceFile.text, 0, false); + if (pos_1 === sourceFile.text.length) { + return ts.createTextSpan(0, 0); + } + return getSpanOfTokenAtPosition(sourceFile, pos_1); + case 226: + case 176: + case 229: + case 199: + case 230: + case 233: + case 232: + case 264: + case 228: + case 186: + case 151: + case 153: + case 154: + case 231: + errorNode = node.name; + break; + case 187: + return getErrorSpanForArrowFunction(sourceFile, node); + } + if (errorNode === undefined) { + return getSpanOfTokenAtPosition(sourceFile, node.pos); + } + var pos = nodeIsMissing(errorNode) + ? errorNode.pos + : ts.skipTrivia(sourceFile.text, errorNode.pos); + return ts.createTextSpanFromBounds(pos, errorNode.end); + } + ts.getErrorSpanForNode = getErrorSpanForNode; + function isExternalOrCommonJsModule(file) { + return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; + } + ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; + function isConstEnumDeclaration(node) { + return node.kind === 232 && isConst(node); + } + ts.isConstEnumDeclaration = isConstEnumDeclaration; + function isConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2) + || !!(ts.getCombinedModifierFlags(node) & 2048); + } + ts.isConst = isConst; + function isLet(node) { + return !!(ts.getCombinedNodeFlags(node) & 1); + } + ts.isLet = isLet; + function isSuperCall(n) { + return n.kind === 181 && n.expression.kind === 97; + } + ts.isSuperCall = isSuperCall; + function isImportCall(n) { + return n.kind === 181 && n.expression.kind === 91; + } + ts.isImportCall = isImportCall; + function isPrologueDirective(node) { + return node.kind === 210 + && node.expression.kind === 9; + } + ts.isPrologueDirective = isPrologueDirective; + function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { + return ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos); + } + ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; + function getLeadingCommentRangesOfNodeFromText(node, text) { + return ts.getLeadingCommentRanges(text, node.pos); + } + ts.getLeadingCommentRangesOfNodeFromText = getLeadingCommentRangesOfNodeFromText; + function getJSDocCommentRanges(node, text) { + var commentRanges = (node.kind === 146 || + node.kind === 145 || + node.kind === 186 || + node.kind === 187 || + node.kind === 185) ? + ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : + getLeadingCommentRangesOfNodeFromText(node, text); + return ts.filter(commentRanges, function (comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 42 && + text.charCodeAt(comment.pos + 3) !== 47; + }); + } + ts.getJSDocCommentRanges = getJSDocCommentRanges; + ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; + ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; + function isPartOfTypeNode(node) { + if (158 <= node.kind && node.kind <= 173) { + return true; + } + switch (node.kind) { + case 119: + case 133: + case 136: + case 122: + case 137: + case 139: + case 130: + return true; + case 105: + return node.parent.kind !== 190; + case 201: + return !isExpressionWithTypeArgumentsInClassExtendsClause(node); + case 71: + if (node.parent.kind === 143 && node.parent.right === node) { + node = node.parent; + } + else if (node.parent.kind === 179 && node.parent.name === node) { + node = node.parent; + } + ts.Debug.assert(node.kind === 71 || node.kind === 143 || node.kind === 179, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + case 143: + case 179: + case 99: + var parent = node.parent; + if (parent.kind === 162) { + return false; + } + if (158 <= parent.kind && parent.kind <= 173) { + return true; + } + switch (parent.kind) { + case 201: + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); + case 145: + return node === parent.constraint; + case 149: + case 148: + case 146: + case 226: + return node === parent.type; + case 228: + case 186: + case 187: + case 152: + case 151: + case 150: + case 153: + case 154: + return node === parent.type; + case 155: + case 156: + case 157: + return node === parent.type; + case 184: + return node === parent.type; + case 181: + case 182: + return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + case 183: + return false; + } + } + return false; + } + ts.isPartOfTypeNode = isPartOfTypeNode; + function isChildOfNodeWithKind(node, kind) { + while (node) { + if (node.kind === kind) { + return true; + } + node = node.parent; + } + return false; + } + ts.isChildOfNodeWithKind = isChildOfNodeWithKind; + function forEachReturnStatement(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 219: + return visitor(node); + case 235: + case 207: + case 211: + case 212: + case 213: + case 214: + case 215: + case 216: + case 220: + case 221: + case 257: + case 258: + case 222: + case 224: + case 260: + return ts.forEachChild(node, traverse); + } + } + } + ts.forEachReturnStatement = forEachReturnStatement; + function forEachYieldExpression(body, visitor) { + return traverse(body); + function traverse(node) { + switch (node.kind) { + case 197: + visitor(node); + var operand = node.expression; + if (operand) { + traverse(operand); + } + return; + case 232: + case 230: + case 233: + case 231: + case 229: + case 199: + return; + default: + if (ts.isFunctionLike(node)) { + var name = node.name; + if (name && name.kind === 144) { + traverse(name.expression); + return; + } + } + else if (!isPartOfTypeNode(node)) { + ts.forEachChild(node, traverse); + } + } + } + } + ts.forEachYieldExpression = forEachYieldExpression; + function getRestParameterElementType(node) { + if (node && node.kind === 164) { + return node.elementType; + } + else if (node && node.kind === 159) { + return ts.singleOrUndefined(node.typeArguments); + } + else { + return undefined; + } + } + ts.getRestParameterElementType = getRestParameterElementType; + function isVariableLike(node) { + if (node) { + switch (node.kind) { + case 176: + case 264: + case 146: + case 261: + case 149: + case 148: + case 262: + case 226: + return true; + } + } + return false; + } + ts.isVariableLike = isVariableLike; + function introducesArgumentsExoticObject(node) { + switch (node.kind) { + case 151: + case 150: + case 152: + case 153: + case 154: + case 228: + case 186: + return true; + } + return false; + } + ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject; + function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) { + while (true) { + if (beforeUnwrapLabelCallback) { + beforeUnwrapLabelCallback(node); + } + if (node.statement.kind !== 222) { + return node.statement; + } + node = node.statement; + } + } + ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; + function isFunctionBlock(node) { + return node && node.kind === 207 && ts.isFunctionLike(node.parent); + } + ts.isFunctionBlock = isFunctionBlock; + function isObjectLiteralMethod(node) { + return node && node.kind === 151 && node.parent.kind === 178; + } + ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 151 && + (node.parent.kind === 178 || + node.parent.kind === 199); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; + function isIdentifierTypePredicate(predicate) { + return predicate && predicate.kind === 1; + } + ts.isIdentifierTypePredicate = isIdentifierTypePredicate; + function isThisTypePredicate(predicate) { + return predicate && predicate.kind === 0; + } + ts.isThisTypePredicate = isThisTypePredicate; + function getPropertyAssignment(objectLiteral, key, key2) { + return ts.filter(objectLiteral.properties, function (property) { + if (property.kind === 261) { + var propName = getTextOfPropertyName(property.name); + return key === propName || (key2 && key2 === propName); + } + }); + } + ts.getPropertyAssignment = getPropertyAssignment; + function getContainingFunction(node) { + while (true) { + node = node.parent; + if (!node || ts.isFunctionLike(node)) { + return node; + } + } + } + ts.getContainingFunction = getContainingFunction; + function getContainingClass(node) { + while (true) { + node = node.parent; + if (!node || ts.isClassLike(node)) { + return node; + } + } + } + ts.getContainingClass = getContainingClass; + function getThisContainer(node, includeArrowFunctions) { + while (true) { + node = node.parent; + if (!node) { + return undefined; + } + switch (node.kind) { + case 144: + if (ts.isClassLike(node.parent.parent)) { + return node; + } + node = node.parent; + break; + case 147: + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + node = node.parent; + } + break; + case 187: + if (!includeArrowFunctions) { + continue; + } + case 228: + case 186: + case 233: + case 149: + case 148: + case 151: + case 150: + case 152: + case 153: + case 154: + case 155: + case 156: + case 157: + case 232: + case 265: + return node; + } + } + } + ts.getThisContainer = getThisContainer; + function getNewTargetContainer(node) { + var container = getThisContainer(node, false); + if (container) { + switch (container.kind) { + case 152: + case 228: + case 186: + return container; + } + } + return undefined; + } + ts.getNewTargetContainer = getNewTargetContainer; + function getSuperContainer(node, stopOnFunctions) { + while (true) { + node = node.parent; + if (!node) { + return node; + } + switch (node.kind) { + case 144: + node = node.parent; + break; + case 228: + case 186: + case 187: + if (!stopOnFunctions) { + continue; + } + case 149: + case 148: + case 151: + case 150: + case 152: + case 153: + case 154: + return node; + case 147: + if (node.parent.kind === 146 && ts.isClassElement(node.parent.parent)) { + node = node.parent.parent; + } + else if (ts.isClassElement(node.parent)) { + node = node.parent; + } + break; + } + } + } + ts.getSuperContainer = getSuperContainer; + function getImmediatelyInvokedFunctionExpression(func) { + if (func.kind === 186 || func.kind === 187) { + var prev = func; + var parent = func.parent; + while (parent.kind === 185) { + prev = parent; + parent = parent.parent; + } + if (parent.kind === 181 && parent.expression === prev) { + return parent; + } + } + } + ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperProperty(node) { + var kind = node.kind; + return (kind === 179 || kind === 180) + && node.expression.kind === 97; + } + ts.isSuperProperty = isSuperProperty; + function getEntityNameFromTypeNode(node) { + switch (node.kind) { + case 159: + return node.typeName; + case 201: + return isEntityNameExpression(node.expression) + ? node.expression + : undefined; + case 71: + case 143: + return node; + } + return undefined; + } + ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; + function getInvokedExpression(node) { + if (node.kind === 183) { + return node.tag; + } + else if (ts.isJsxOpeningLikeElement(node)) { + return node.tagName; + } + return node.expression; + } + ts.getInvokedExpression = getInvokedExpression; + function nodeCanBeDecorated(node) { + switch (node.kind) { + case 229: + return true; + case 149: + return node.parent.kind === 229; + case 153: + case 154: + case 151: + return node.body !== undefined + && node.parent.kind === 229; + case 146: + return node.parent.body !== undefined + && (node.parent.kind === 152 + || node.parent.kind === 151 + || node.parent.kind === 154) + && node.parent.parent.kind === 229; + } + return false; + } + ts.nodeCanBeDecorated = nodeCanBeDecorated; + function nodeIsDecorated(node) { + return node.decorators !== undefined + && nodeCanBeDecorated(node); + } + ts.nodeIsDecorated = nodeIsDecorated; + function nodeOrChildIsDecorated(node) { + return nodeIsDecorated(node) || childIsDecorated(node); + } + ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; + function childIsDecorated(node) { + switch (node.kind) { + case 229: + return ts.forEach(node.members, nodeOrChildIsDecorated); + case 151: + case 154: + return ts.forEach(node.parameters, nodeIsDecorated); + } + } + ts.childIsDecorated = childIsDecorated; + function isJSXTagName(node) { + var parent = node.parent; + if (parent.kind === 251 || + parent.kind === 250 || + parent.kind === 252) { + return parent.tagName === node; + } + return false; + } + ts.isJSXTagName = isJSXTagName; + function isPartOfExpression(node) { + switch (node.kind) { + case 97: + case 95: + case 101: + case 86: + case 12: + case 177: + case 178: + case 179: + case 180: + case 181: + case 182: + case 183: + case 202: + case 184: + case 203: + case 185: + case 186: + case 199: + case 187: + case 190: + case 188: + case 189: + case 192: + case 193: + case 194: + case 195: + case 198: + case 196: + case 13: + case 200: + case 249: + case 250: + case 197: + case 191: + case 204: + return true; + case 143: + while (node.parent.kind === 143) { + node = node.parent; + } + return node.parent.kind === 162 || isJSXTagName(node); + case 71: + if (node.parent.kind === 162 || isJSXTagName(node)) { + return true; + } + case 8: + case 9: + case 99: + var parent = node.parent; + switch (parent.kind) { + case 226: + case 146: + case 149: + case 148: + case 264: + case 261: + case 176: + return parent.initializer === node; + case 210: + case 211: + case 212: + case 213: + case 219: + case 220: + case 221: + case 257: + case 223: + return parent.expression === node; + case 214: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 227) || + forStatement.condition === node || + forStatement.incrementor === node; + case 215: + case 216: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 227) || + forInStatement.expression === node; + case 184: + case 202: + return node === parent.expression; + case 205: + return node === parent.expression; + case 144: + return node === parent.expression; + case 147: + case 256: + case 255: + case 263: + return true; + case 201: + return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); + default: + if (isPartOfExpression(parent)) { + return true; + } + } + } + return false; + } + ts.isPartOfExpression = isPartOfExpression; + function isExternalModuleImportEqualsDeclaration(node) { + return node.kind === 237 && node.moduleReference.kind === 248; + } + ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; + function getExternalModuleImportEqualsDeclarationExpression(node) { + ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); + return node.moduleReference.expression; + } + ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; + function isInternalModuleImportEqualsDeclaration(node) { + return node.kind === 237 && node.moduleReference.kind !== 248; + } + ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; + function isSourceFileJavaScript(file) { + return isInJavaScriptFile(file); + } + ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isInJavaScriptFile(node) { + return node && !!(node.flags & 65536); + } + ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJSDoc(node) { + return node && !!(node.flags & 1048576); + } + ts.isInJSDoc = isInJSDoc; + function isRequireCall(callExpression, checkArgumentIsStringLiteral) { + if (callExpression.kind !== 181) { + return false; + } + var _a = callExpression, expression = _a.expression, args = _a.arguments; + if (expression.kind !== 71 || expression.escapedText !== "require") { + return false; + } + if (args.length !== 1) { + return false; + } + var arg = args[0]; + return !checkArgumentIsStringLiteral || arg.kind === 9 || arg.kind === 13; + } + ts.isRequireCall = isRequireCall; + function isSingleOrDoubleQuote(charCode) { + return charCode === 39 || charCode === 34; + } + ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote; + function isDeclarationOfFunctionOrClassExpression(s) { + if (s.valueDeclaration && s.valueDeclaration.kind === 226) { + var declaration = s.valueDeclaration; + return declaration.initializer && (declaration.initializer.kind === 186 || declaration.initializer.kind === 199); + } + return false; + } + ts.isDeclarationOfFunctionOrClassExpression = isDeclarationOfFunctionOrClassExpression; + function getRightMostAssignedExpression(node) { + while (isAssignmentExpression(node, true)) { + node = node.right; + } + return node; + } + ts.getRightMostAssignedExpression = getRightMostAssignedExpression; + function isExportsIdentifier(node) { + return ts.isIdentifier(node) && node.escapedText === "exports"; + } + ts.isExportsIdentifier = isExportsIdentifier; + function isModuleExportsPropertyAccessExpression(node) { + return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; + } + ts.isModuleExportsPropertyAccessExpression = isModuleExportsPropertyAccessExpression; + function getSpecialPropertyAssignmentKind(expression) { + if (!isInJavaScriptFile(expression)) { + return 0; + } + var expr = expression; + if (expr.operatorToken.kind !== 58 || expr.left.kind !== 179) { + return 0; + } + var lhs = expr.left; + if (lhs.expression.kind === 71) { + var lhsId = lhs.expression; + if (lhsId.escapedText === "exports") { + return 1; + } + else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { + return 2; + } + else { + return 5; + } + } + else if (lhs.expression.kind === 99) { + return 4; + } + else if (lhs.expression.kind === 179) { + var innerPropertyAccess = lhs.expression; + if (innerPropertyAccess.expression.kind === 71) { + var innerPropertyAccessIdentifier = innerPropertyAccess.expression; + if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { + return 1; + } + if (innerPropertyAccess.name.escapedText === "prototype") { + return 3; + } + } + } + return 0; + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getExternalModuleName(node) { + if (node.kind === 238) { + return node.moduleSpecifier; + } + if (node.kind === 237) { + var reference = node.moduleReference; + if (reference.kind === 248) { + return reference.expression; + } + } + if (node.kind === 244) { + return node.moduleSpecifier; + } + if (node.kind === 233 && node.name.kind === 9) { + return node.name; + } + } + ts.getExternalModuleName = getExternalModuleName; + function getNamespaceDeclarationNode(node) { + if (node.kind === 237) { + return node; + } + var importClause = node.importClause; + if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 240) { + return importClause.namedBindings; + } + } + ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; + function isDefaultImport(node) { + return node.kind === 238 + && node.importClause + && !!node.importClause.name; + } + ts.isDefaultImport = isDefaultImport; + function hasQuestionToken(node) { + if (node) { + switch (node.kind) { + case 146: + case 151: + case 150: + case 262: + case 261: + case 149: + case 148: + return node.questionToken !== undefined; + } + } + return false; + } + ts.hasQuestionToken = hasQuestionToken; + function isJSDocConstructSignature(node) { + return node.kind === 273 && + node.parameters.length > 0 && + node.parameters[0].name && + node.parameters[0].name.escapedText === "new"; + } + ts.isJSDocConstructSignature = isJSDocConstructSignature; + function hasJSDocParameterTags(node) { + return !!getFirstJSDocTag(node, 279); + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; + function getFirstJSDocTag(node, kind) { + var tags = getJSDocTags(node); + return ts.find(tags, function (doc) { return doc.kind === kind; }); + } + function getAllJSDocs(node) { + if (ts.isJSDocTypedefTag(node)) { + return [node.parent]; + } + return getJSDocCommentsAndTags(node); + } + ts.getAllJSDocs = getAllJSDocs; + function getJSDocTags(node) { + var tags = node.jsDocCache; + if (tags === undefined) { + node.jsDocCache = tags = ts.flatMap(getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + } + return tags; + } + ts.getJSDocTags = getJSDocTags; + function getJSDocCommentsAndTags(node) { + var result; + getJSDocCommentsAndTagsWorker(node); + return result || ts.emptyArray; + function getJSDocCommentsAndTagsWorker(node) { + var parent = node.parent; + var isInitializerOfVariableDeclarationInStatement = isVariableLike(parent) && + parent.initializer === node && + parent.parent.parent.kind === 208; + var isVariableOfVariableDeclarationStatement = isVariableLike(node) && + parent.parent.kind === 208; + var variableStatementNode = isInitializerOfVariableDeclarationInStatement ? parent.parent.parent : + isVariableOfVariableDeclarationStatement ? parent.parent : + undefined; + if (variableStatementNode) { + getJSDocCommentsAndTagsWorker(variableStatementNode); + } + var isSourceOfAssignmentExpressionStatement = parent && parent.parent && + parent.kind === 194 && + parent.operatorToken.kind === 58 && + parent.parent.kind === 210; + if (isSourceOfAssignmentExpressionStatement) { + getJSDocCommentsAndTagsWorker(parent.parent); + } + var isModuleDeclaration = node.kind === 233 && + parent && parent.kind === 233; + var isPropertyAssignmentExpression = parent && parent.kind === 261; + if (isModuleDeclaration || isPropertyAssignmentExpression) { + getJSDocCommentsAndTagsWorker(parent); + } + if (node.kind === 146) { + result = ts.addRange(result, getJSDocParameterTags(node)); + } + if (isVariableLike(node) && node.initializer) { + result = ts.addRange(result, node.initializer.jsDoc); + } + result = ts.addRange(result, node.jsDoc); + } + } + function getJSDocParameterTags(param) { + if (param.name && ts.isIdentifier(param.name)) { + var name_1 = param.name.escapedText; + return getJSDocTags(param.parent).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; }); + } + return undefined; + } + ts.getJSDocParameterTags = getJSDocParameterTags; + function getParameterSymbolFromJSDoc(node) { + if (node.symbol) { + return node.symbol; + } + if (!ts.isIdentifier(node.name)) { + return undefined; + } + var name = node.name.escapedText; + ts.Debug.assert(node.parent.kind === 275); + var func = node.parent.parent; + if (!ts.isFunctionLike(func)) { + return undefined; + } + var parameter = ts.find(func.parameters, function (p) { + return p.name.kind === 71 && p.name.escapedText === name; + }); + return parameter && parameter.symbol; + } + ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; + function getTypeParameterFromJsDoc(node) { + var name = node.name.escapedText; + var typeParameters = node.parent.parent.parent.typeParameters; + return ts.find(typeParameters, function (p) { return p.name.escapedText === name; }); + } + ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; + function getJSDocType(node) { + var tag = getFirstJSDocTag(node, 281); + if (!tag && node.kind === 146) { + var paramTags = getJSDocParameterTags(node); + if (paramTags) { + tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); + } + } + return tag && tag.typeExpression && tag.typeExpression.type; + } + ts.getJSDocType = getJSDocType; + function getJSDocAugmentsTag(node) { + return getFirstJSDocTag(node, 277); + } + ts.getJSDocAugmentsTag = getJSDocAugmentsTag; + function getJSDocClassTag(node) { + return getFirstJSDocTag(node, 278); + } + ts.getJSDocClassTag = getJSDocClassTag; + function getJSDocReturnTag(node) { + return getFirstJSDocTag(node, 280); + } + ts.getJSDocReturnTag = getJSDocReturnTag; + function getJSDocReturnType(node) { + var returnTag = getJSDocReturnTag(node); + return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + } + ts.getJSDocReturnType = getJSDocReturnType; + function getJSDocTemplateTag(node) { + return getFirstJSDocTag(node, 282); + } + ts.getJSDocTemplateTag = getJSDocTemplateTag; + function hasRestParameter(s) { + return isRestParameter(ts.lastOrUndefined(s.parameters)); + } + ts.hasRestParameter = hasRestParameter; + function hasDeclaredRestParameter(s) { + return isDeclaredRestParam(ts.lastOrUndefined(s.parameters)); + } + ts.hasDeclaredRestParameter = hasDeclaredRestParameter; + function isRestParameter(node) { + if (isInJavaScriptFile(node)) { + if (node.type && node.type.kind === 274 || + ts.forEach(getJSDocParameterTags(node), function (t) { return t.typeExpression && t.typeExpression.type.kind === 274; })) { + return true; + } + } + return isDeclaredRestParam(node); + } + ts.isRestParameter = isRestParameter; + function isDeclaredRestParam(node) { + return node && node.dotDotDotToken !== undefined; + } + ts.isDeclaredRestParam = isDeclaredRestParam; + function getAssignmentTargetKind(node) { + var parent = node.parent; + while (true) { + switch (parent.kind) { + case 194: + var binaryOperator = parent.operatorToken.kind; + return isAssignmentOperator(binaryOperator) && parent.left === node ? + binaryOperator === 58 ? 1 : 2 : + 0; + case 192: + case 193: + var unaryOperator = parent.operator; + return unaryOperator === 43 || unaryOperator === 44 ? 2 : 0; + case 215: + case 216: + return parent.initializer === node ? 1 : 0; + case 185: + case 177: + case 198: + node = parent; + break; + case 262: + if (parent.name !== node) { + return 0; + } + node = parent.parent; + break; + case 261: + if (parent.name === node) { + return 0; + } + node = parent.parent; + break; + default: + return 0; + } + parent = node.parent; + } + } + ts.getAssignmentTargetKind = getAssignmentTargetKind; + function isAssignmentTarget(node) { + return getAssignmentTargetKind(node) !== 0; + } + ts.isAssignmentTarget = isAssignmentTarget; + function isDeleteTarget(node) { + if (node.kind !== 179 && node.kind !== 180) { + return false; + } + node = node.parent; + while (node && node.kind === 185) { + node = node.parent; + } + return node && node.kind === 188; + } + ts.isDeleteTarget = isDeleteTarget; + function isNodeDescendantOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendantOf = isNodeDescendantOf; + function isInAmbientContext(node) { + while (node) { + if (hasModifier(node, 2) || (node.kind === 265 && node.isDeclarationFile)) { + return true; + } + node = node.parent; + } + return false; + } + ts.isInAmbientContext = isInAmbientContext; + function isDeclarationName(name) { + switch (name.kind) { + case 71: + case 9: + case 8: + return ts.isDeclaration(name.parent) && name.parent.name === name; + default: + return false; + } + } + ts.isDeclarationName = isDeclarationName; + function isAnyDeclarationName(name) { + switch (name.kind) { + case 71: + case 9: + case 8: + if (ts.isDeclaration(name.parent)) { + return name.parent.name === name; + } + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 && ts.getNameOfDeclaration(binExp) === name; + default: + return false; + } + } + ts.isAnyDeclarationName = isAnyDeclarationName; + function isLiteralComputedPropertyDeclarationName(node) { + return (node.kind === 9 || node.kind === 8) && + node.parent.kind === 144 && + ts.isDeclaration(node.parent.parent); + } + ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; + function isIdentifierName(node) { + var parent = node.parent; + switch (parent.kind) { + case 149: + case 148: + case 151: + case 150: + case 153: + case 154: + case 264: + case 261: + case 179: + return parent.name === node; + case 143: + if (parent.right === node) { + while (parent.kind === 143) { + parent = parent.parent; + } + return parent.kind === 162; + } + return false; + case 176: + case 242: + return parent.propertyName === node; + case 246: + case 253: + return true; + } + return false; + } + ts.isIdentifierName = isIdentifierName; + function isAliasSymbolDeclaration(node) { + return node.kind === 237 || + node.kind === 236 || + node.kind === 239 && !!node.name || + node.kind === 240 || + node.kind === 242 || + node.kind === 246 || + node.kind === 243 && exportAssignmentIsAlias(node); + } + ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; + function exportAssignmentIsAlias(node) { + return isEntityNameExpression(node.expression); + } + ts.exportAssignmentIsAlias = exportAssignmentIsAlias; + function getClassExtendsHeritageClauseElement(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 85); + return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; + } + ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; + function getClassImplementsHeritageClauseElements(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 108); + return heritageClause ? heritageClause.types : undefined; + } + ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + function getInterfaceBaseTypeNodes(node) { + var heritageClause = getHeritageClause(node.heritageClauses, 85); + return heritageClause ? heritageClause.types : undefined; + } + ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; + function getHeritageClause(clauses, kind) { + if (clauses) { + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; + if (clause.token === kind) { + return clause; + } + } + } + return undefined; + } + ts.getHeritageClause = getHeritageClause; + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { + var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); + return host.getSourceFile(referenceFileName); + } + } + ts.tryResolveScriptReference = tryResolveScriptReference; + function getAncestor(node, kind) { + while (node) { + if (node.kind === kind) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.getAncestor = getAncestor; + function getFileReferenceFromReferencePath(comment, commentRange) { + var simpleReferenceRegEx = /^\/\/\/\s*/gim; + if (simpleReferenceRegEx.test(comment)) { + if (isNoDefaultLibRegEx.test(comment)) { + return { isNoDefaultLib: true }; + } + else { + var refMatchResult = ts.fullTripleSlashReferencePathRegEx.exec(comment); + var refLibResult = !refMatchResult && ts.fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment); + var match = refMatchResult || refLibResult; + if (match) { + var pos = commentRange.pos + match[1].length + match[2].length; + return { + fileReference: { + pos: pos, + end: pos + match[3].length, + fileName: match[3] + }, + isNoDefaultLib: false, + isTypeReferenceDirective: !!refLibResult + }; + } + return { + diagnosticMessage: ts.Diagnostics.Invalid_reference_directive_syntax, + isNoDefaultLib: false + }; + } + } + return undefined; + } + ts.getFileReferenceFromReferencePath = getFileReferenceFromReferencePath; + function isKeyword(token) { + return 72 <= token && token <= 142; + } + ts.isKeyword = isKeyword; + function isTrivia(token) { + return 2 <= token && token <= 7; + } + ts.isTrivia = isTrivia; + function getFunctionFlags(node) { + if (!node) { + return 4; + } + var flags = 0; + switch (node.kind) { + case 228: + case 186: + case 151: + if (node.asteriskToken) { + flags |= 1; + } + case 187: + if (hasModifier(node, 256)) { + flags |= 2; + } + break; + } + if (!node.body) { + flags |= 4; + } + return flags; + } + ts.getFunctionFlags = getFunctionFlags; + function isAsyncFunction(node) { + switch (node.kind) { + case 228: + case 186: + case 187: + case 151: + return node.body !== undefined + && node.asteriskToken === undefined + && hasModifier(node, 256); + } + return false; + } + ts.isAsyncFunction = isAsyncFunction; + function isStringOrNumericLiteral(node) { + var kind = node.kind; + return kind === 9 + || kind === 8; + } + ts.isStringOrNumericLiteral = isStringOrNumericLiteral; + function hasDynamicName(declaration) { + var name = ts.getNameOfDeclaration(declaration); + return name && isDynamicName(name); + } + ts.hasDynamicName = hasDynamicName; + function isDynamicName(name) { + return name.kind === 144 && + !isStringOrNumericLiteral(name.expression) && + !isWellKnownSymbolSyntactically(name.expression); + } + ts.isDynamicName = isDynamicName; + function isWellKnownSymbolSyntactically(node) { + return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression); + } + ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically; + function getPropertyNameForPropertyNameNode(name) { + if (name.kind === 71) { + return name.escapedText; + } + if (name.kind === 9 || name.kind === 8) { + return escapeLeadingUnderscores(name.text); + } + if (name.kind === 144) { + var nameExpression = name.expression; + if (isWellKnownSymbolSyntactically(nameExpression)) { + var rightHandSideName = nameExpression.name.escapedText; + return getPropertyNameForKnownSymbolName(ts.unescapeLeadingUnderscores(rightHandSideName)); + } + else if (nameExpression.kind === 9 || nameExpression.kind === 8) { + return escapeLeadingUnderscores(nameExpression.text); + } + } + return undefined; + } + ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode; + function getTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return ts.unescapeLeadingUnderscores(node.escapedText); + } + if (node.kind === 9 || + node.kind === 8) { + return node.text; + } + } + return undefined; + } + ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral; + function getEscapedTextOfIdentifierOrLiteral(node) { + if (node) { + if (node.kind === 71) { + return node.escapedText; + } + if (node.kind === 9 || + node.kind === 8) { + return escapeLeadingUnderscores(node.text); + } + } + return undefined; + } + ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral; + function getPropertyNameForKnownSymbolName(symbolName) { + return "__@" + symbolName; + } + ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isESSymbolIdentifier(node) { + return node.kind === 71 && node.escapedText === "Symbol"; + } + ts.isESSymbolIdentifier = isESSymbolIdentifier; + function isPushOrUnshiftIdentifier(node) { + return node.escapedText === "push" || node.escapedText === "unshift"; + } + ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; + function isParameterDeclaration(node) { + var root = getRootDeclaration(node); + return root.kind === 146; + } + ts.isParameterDeclaration = isParameterDeclaration; + function getRootDeclaration(node) { + while (node.kind === 176) { + node = node.parent.parent; + } + return node; + } + ts.getRootDeclaration = getRootDeclaration; + function nodeStartsNewLexicalEnvironment(node) { + var kind = node.kind; + return kind === 152 + || kind === 186 + || kind === 228 + || kind === 187 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 233 + || kind === 265; + } + ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; + function nodeIsSynthesized(node) { + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); + } + ts.nodeIsSynthesized = nodeIsSynthesized; + function getOriginalSourceFile(sourceFile) { + return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; + } + ts.getOriginalSourceFile = getOriginalSourceFile; + function getOriginalSourceFiles(sourceFiles) { + return ts.sameMap(sourceFiles, getOriginalSourceFile); + } + ts.getOriginalSourceFiles = getOriginalSourceFiles; + function getExpressionAssociativity(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + return getOperatorAssociativity(expression.kind, operator, hasArguments); + } + ts.getExpressionAssociativity = getExpressionAssociativity; + function getOperatorAssociativity(kind, operator, hasArguments) { + switch (kind) { + case 182: + return hasArguments ? 0 : 1; + case 192: + case 189: + case 190: + case 188: + case 191: + case 195: + case 197: + return 1; + case 194: + switch (operator) { + case 40: + case 58: + case 59: + case 60: + case 62: + case 61: + case 63: + case 64: + case 65: + case 66: + case 67: + case 68: + case 70: + case 69: + return 1; + } + } + return 0; + } + ts.getOperatorAssociativity = getOperatorAssociativity; + function getExpressionPrecedence(expression) { + var operator = getOperator(expression); + var hasArguments = expression.kind === 182 && expression.arguments !== undefined; + return getOperatorPrecedence(expression.kind, operator, hasArguments); + } + ts.getExpressionPrecedence = getExpressionPrecedence; + function getOperator(expression) { + if (expression.kind === 194) { + return expression.operatorToken.kind; + } + else if (expression.kind === 192 || expression.kind === 193) { + return expression.operator; + } + else { + return expression.kind; + } + } + ts.getOperator = getOperator; + function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { + switch (nodeKind) { + case 99: + case 97: + case 71: + case 95: + case 101: + case 86: + case 8: + case 9: + case 177: + case 178: + case 186: + case 187: + case 199: + case 249: + case 250: + case 12: + case 13: + case 196: + case 185: + case 200: + return 19; + case 183: + case 179: + case 180: + return 18; + case 182: + return hasArguments ? 18 : 17; + case 181: + return 17; + case 193: + return 16; + case 192: + case 189: + case 190: + case 188: + case 191: + return 15; + case 194: + switch (operatorKind) { + case 51: + case 52: + return 15; + case 40: + case 39: + case 41: + case 42: + return 14; + case 37: + case 38: + return 13; + case 45: + case 46: + case 47: + return 12; + case 27: + case 30: + case 29: + case 31: + case 92: + case 93: + return 11; + case 32: + case 34: + case 33: + case 35: + return 10; + case 48: + return 9; + case 50: + return 8; + case 49: + return 7; + case 53: + return 6; + case 54: + return 5; + case 58: + case 59: + case 60: + case 62: + case 61: + case 63: + case 64: + case 65: + case 66: + case 67: + case 68: + case 70: + case 69: + return 3; + case 26: + return 0; + default: + return -1; + } + case 195: + return 4; + case 197: + return 2; + case 198: + return 1; + case 289: + return 0; + default: + return -1; + } + } + ts.getOperatorPrecedence = getOperatorPrecedence; + function createDiagnosticCollection() { + var nonFileDiagnostics = []; + var fileDiagnostics = ts.createMap(); + var diagnosticsModified = false; + var modificationCount = 0; + return { + add: add, + getGlobalDiagnostics: getGlobalDiagnostics, + getDiagnostics: getDiagnostics, + getModificationCount: getModificationCount, + reattachFileDiagnostics: reattachFileDiagnostics + }; + function getModificationCount() { + return modificationCount; + } + function reattachFileDiagnostics(newFile) { + ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); + } + function add(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + if (!diagnostics) { + diagnostics = []; + fileDiagnostics.set(diagnostic.file.fileName, diagnostics); + } + } + else { + diagnostics = nonFileDiagnostics; + } + diagnostics.push(diagnostic); + diagnosticsModified = true; + modificationCount++; + } + function getGlobalDiagnostics() { + sortAndDeduplicate(); + return nonFileDiagnostics; + } + function getDiagnostics(fileName) { + sortAndDeduplicate(); + if (fileName) { + return fileDiagnostics.get(fileName) || []; + } + var allDiagnostics = []; + function pushDiagnostic(d) { + allDiagnostics.push(d); + } + ts.forEach(nonFileDiagnostics, pushDiagnostic); + fileDiagnostics.forEach(function (diagnostics) { + ts.forEach(diagnostics, pushDiagnostic); + }); + return ts.sortAndDeduplicateDiagnostics(allDiagnostics); + } + function sortAndDeduplicate() { + if (!diagnosticsModified) { + return; + } + diagnosticsModified = false; + nonFileDiagnostics = ts.sortAndDeduplicateDiagnostics(nonFileDiagnostics); + fileDiagnostics.forEach(function (diagnostics, key) { + fileDiagnostics.set(key, ts.sortAndDeduplicateDiagnostics(diagnostics)); + }); + } + } + ts.createDiagnosticCollection = createDiagnosticCollection; + var escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + var escapedCharsMap = ts.createMapFromTemplate({ + "\0": "\\0", + "\t": "\\t", + "\v": "\\v", + "\f": "\\f", + "\b": "\\b", + "\r": "\\r", + "\n": "\\n", + "\\": "\\\\", + "\"": "\\\"", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\u0085": "\\u0085" + }); + function escapeString(s) { + return s.replace(escapedCharsRegExp, getReplacement); + } + ts.escapeString = escapeString; + function getReplacement(c) { + return escapedCharsMap.get(c) || get16BitUnicodeEscapeSequence(c.charCodeAt(0)); + } + function isIntrinsicJsxName(name) { + var ch = name.substr(0, 1); + return ch.toLowerCase() === ch; + } + ts.isIntrinsicJsxName = isIntrinsicJsxName; + function get16BitUnicodeEscapeSequence(charCode) { + var hexCharCode = charCode.toString(16).toUpperCase(); + var paddedHexCode = ("0000" + hexCharCode).slice(-4); + return "\\u" + paddedHexCode; + } + var nonAsciiCharacters = /[^\u0000-\u007F]/g; + function escapeNonAsciiString(s) { + s = escapeString(s); + return nonAsciiCharacters.test(s) ? + s.replace(nonAsciiCharacters, function (c) { return get16BitUnicodeEscapeSequence(c.charCodeAt(0)); }) : + s; + } + ts.escapeNonAsciiString = escapeNonAsciiString; + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + ts.getIndentSize = getIndentSize; + function createTextWriter(newLine) { + var output; + var indent; + var lineStart; + var lineCount; + var linePos; + function write(s) { + if (s && s.length) { + if (lineStart) { + output += getIndentString(indent); + lineStart = false; + } + output += s; + } + } + function reset() { + output = ""; + indent = 0; + lineStart = true; + lineCount = 0; + linePos = 0; + } + function rawWrite(s) { + if (s !== undefined) { + if (lineStart) { + lineStart = false; + } + output += s; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); + } + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + function writeTextOfNode(text, node) { + write(getTextOfNodeFromSourceText(text, node)); + } + reset(); + return { + write: write, + rawWrite: rawWrite, + writeTextOfNode: writeTextOfNode, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { indent++; }, + decreaseIndent: function () { indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount + 1; }, + getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getText: function () { return output; }, + isAtStartOfLine: function () { return lineStart; }, + reset: reset + }; + } + ts.createTextWriter = createTextWriter; + function getResolvedExternalModuleName(host, file) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + } + ts.getResolvedExternalModuleName = getResolvedExternalModuleName; + function getExternalModuleNameFromDeclaration(host, resolver, declaration) { + var file = resolver.getExternalModuleFileFromDeclaration(declaration); + if (!file || file.isDeclarationFile) { + return undefined; + } + return getResolvedExternalModuleName(host, file); + } + ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; + function getExternalModuleNameFromPath(host, fileName) { + var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; + var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); + var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); + return ts.removeFileExtension(relativePath); + } + ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; + function getOwnEmitOutputFilePath(sourceFile, host, extension) { + var compilerOptions = host.getCompilerOptions(); + var emitOutputFilePathWithoutExtension; + if (compilerOptions.outDir) { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + } + else { + emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + } + return emitOutputFilePathWithoutExtension + extension; + } + ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; + function getDeclarationEmitOutputFilePath(sourceFile, host) { + var options = host.getCompilerOptions(); + var outputDir = options.declarationDir || options.outDir; + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; + } + ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getSourceFilesToEmit(host, targetSourceFile) { + var options = host.getCompilerOptions(); + var isSourceFileFromExternalLibrary = function (file) { return host.isSourceFileFromExternalLibrary(file); }; + if (options.outFile || options.out) { + var moduleKind = ts.getEmitModuleKind(options); + var moduleEmitEnabled_1 = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; + return ts.filter(host.getSourceFiles(), function (sourceFile) { + return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) && sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); + }); + } + else { + var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile]; + return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary); }); + } + } + ts.getSourceFilesToEmit = getSourceFilesToEmit; + function sourceFileMayBeEmitted(sourceFile, options, isSourceFileFromExternalLibrary) { + return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + } + ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; + function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { + var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); + var commonSourceDirectory = host.getCommonSourceDirectory(); + var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; + return ts.combinePaths(newDirPath, sourceFilePath); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { + host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); + }, sourceFiles); + } + ts.writeFile = writeFile; + function getLineOfLocalPosition(currentSourceFile, pos) { + return ts.getLineAndCharacterOfPosition(currentSourceFile, pos).line; + } + ts.getLineOfLocalPosition = getLineOfLocalPosition; + function getLineOfLocalPositionFromLineMap(lineMap, pos) { + return ts.computeLineAndCharacterOfPosition(lineMap, pos).line; + } + ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; + function getFirstConstructorWithBody(node) { + return ts.forEach(node.members, function (member) { + if (member.kind === 152 && nodeIsPresent(member.body)) { + return member; + } + }); + } + ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + function getSetAccessorValueParameter(accessor) { + if (accessor && accessor.parameters.length > 0) { + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); + return accessor.parameters[hasThis ? 1 : 0]; + } + } + function getSetAccessorTypeAnnotationNode(accessor) { + var parameter = getSetAccessorValueParameter(accessor); + return parameter && parameter.type; + } + ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 71 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 99; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; + function getAllAccessorDeclarations(declarations, accessor) { + var firstAccessor; + var secondAccessor; + var getAccessor; + var setAccessor; + if (hasDynamicName(accessor)) { + firstAccessor = accessor; + if (accessor.kind === 153) { + getAccessor = accessor; + } + else if (accessor.kind === 154) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(declarations, function (member) { + if ((member.kind === 153 || member.kind === 154) + && hasModifier(member, 32) === hasModifier(accessor, 32)) { + var memberName = getPropertyNameForPropertyNameNode(member.name); + var accessorName = getPropertyNameForPropertyNameNode(accessor.name); + if (memberName === accessorName) { + if (!firstAccessor) { + firstAccessor = member; + } + else if (!secondAccessor) { + secondAccessor = member; + } + if (member.kind === 153 && !getAccessor) { + getAccessor = member; + } + if (member.kind === 154 && !setAccessor) { + setAccessor = member; + } + } + } + }); + } + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + ts.getAllAccessorDeclarations = getAllAccessorDeclarations; + function getEffectiveTypeAnnotationNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocType(node); + } + } + ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getEffectiveReturnTypeNode(node) { + if (node.type) { + return node.type; + } + if (isInJavaScriptFile(node)) { + return getJSDocReturnType(node); + } + } + ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; + function getEffectiveTypeParameterDeclarations(node) { + if (node.typeParameters) { + return node.typeParameters; + } + if (isInJavaScriptFile(node)) { + var templateTag = getJSDocTemplateTag(node); + return templateTag && templateTag.typeParameters; + } + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; + function getEffectiveSetAccessorTypeAnnotationNode(node) { + var parameter = getSetAccessorValueParameter(node); + return parameter && getEffectiveTypeAnnotationNode(parameter); + } + ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode; + function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) { + emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); + } + ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments; + function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) { + if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition; + function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) { + if (pos !== commentPos && + getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { + writer.writeLine(); + } + } + ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition; + function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) { + if (comments && comments.length > 0) { + if (leadingSeparator) { + writer.write(" "); + } + var emitInterveningSeparator = false; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; + if (emitInterveningSeparator) { + writer.write(" "); + emitInterveningSeparator = false; + } + writeComment(text, lineMap, writer, comment.pos, comment.end, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else { + emitInterveningSeparator = true; + } + } + if (emitInterveningSeparator && trailingSeparator) { + writer.write(" "); + } + } + } + ts.emitComments = emitComments; + function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedComment); + } + } + else { + leadingComments = ts.getLeadingCommentRanges(text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment = void 0; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end); + var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos); + if (commentLine >= lastCommentLine + 2) { + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); + emitComments(text, lineMap, writer, detachedComments, false, true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedComment(comment) { + return text.charCodeAt(comment.pos + 1) === 42 && + text.charCodeAt(comment.pos + 2) === 33; + } + } + ts.emitDetachedComments = emitDetachedComments; + function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (text.charCodeAt(commentPos + 1) === 42) { + var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); + var lineCount = lineMap.length; + var firstCommentLineIndent = void 0; + for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) { + var nextLineStart = (currentLine + 1) === lineCount + ? text.length + 1 + : lineMap[currentLine + 1]; + if (pos !== commentPos) { + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos); + } + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + writer.rawWrite(indentSizeSpaceString); + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + writer.rawWrite(""); + } + } + writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart); + pos = nextLineStart; + } + } + else { + writer.write(text.substring(commentPos, commentEnd)); + } + } + ts.writeCommentRange = writeCommentRange; + function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) { + var end = Math.min(commentEnd, nextLineStart - 1); + var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + if (currentLineText) { + writer.write(currentLineText); + if (end !== commentEnd) { + writer.writeLine(); + } + } + else { + writer.writeLiteral(newLine); + } + } + function calculateIndent(text, pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) { + if (text.charCodeAt(pos) === 9) { + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + currentLineIndent++; + } + } + return currentLineIndent; + } + function hasModifiers(node) { + return getModifierFlags(node) !== 0; + } + ts.hasModifiers = hasModifiers; + function hasModifier(node, flags) { + return (getModifierFlags(node) & flags) !== 0; + } + ts.hasModifier = hasModifier; + function getModifierFlags(node) { + if (node.modifierFlagsCache & 536870912) { + return node.modifierFlagsCache & ~536870912; + } + var flags = getModifierFlagsNoCache(node); + node.modifierFlagsCache = flags | 536870912; + return flags; + } + ts.getModifierFlags = getModifierFlags; + function getModifierFlagsNoCache(node) { + var flags = 0; + if (node.modifiers) { + for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { + var modifier = _a[_i]; + flags |= modifierToFlag(modifier.kind); + } + } + if (node.flags & 4 || (node.kind === 71 && node.isInJSDocNamespace)) { + flags |= 1; + } + return flags; + } + ts.getModifierFlagsNoCache = getModifierFlagsNoCache; + function modifierToFlag(token) { + switch (token) { + case 115: return 32; + case 114: return 4; + case 113: return 16; + case 112: return 8; + case 117: return 128; + case 84: return 1; + case 124: return 2; + case 76: return 2048; + case 79: return 512; + case 120: return 256; + case 131: return 64; + } + return 0; + } + ts.modifierToFlag = modifierToFlag; + function isLogicalOperator(token) { + return token === 54 + || token === 53 + || token === 51; + } + ts.isLogicalOperator = isLogicalOperator; + function isAssignmentOperator(token) { + return token >= 58 && token <= 70; + } + ts.isAssignmentOperator = isAssignmentOperator; + function tryGetClassExtendingExpressionWithTypeArguments(node) { + if (node.kind === 201 && + node.parent.token === 85 && + ts.isClassLike(node.parent.parent)) { + return node.parent.parent; + } + } + ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments; + function isAssignmentExpression(node, excludeCompoundAssignment) { + return ts.isBinaryExpression(node) + && (excludeCompoundAssignment + ? node.operatorToken.kind === 58 + : isAssignmentOperator(node.operatorToken.kind)) + && ts.isLeftHandSideExpression(node.left); + } + ts.isAssignmentExpression = isAssignmentExpression; + function isDestructuringAssignment(node) { + if (isAssignmentExpression(node, true)) { + var kind = node.left.kind; + return kind === 178 + || kind === 177; + } + return false; + } + ts.isDestructuringAssignment = isDestructuringAssignment; + function isSupportedExpressionWithTypeArguments(node) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + ts.isSupportedExpressionWithTypeArguments = isSupportedExpressionWithTypeArguments; + function isSupportedExpressionWithTypeArgumentsRest(node) { + if (node.kind === 71) { + return true; + } + else if (ts.isPropertyAccessExpression(node)) { + return isSupportedExpressionWithTypeArgumentsRest(node.expression); + } + else { + return false; + } + } + function isExpressionWithTypeArgumentsInClassExtendsClause(node) { + return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; + } + ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; + function isExpressionWithTypeArgumentsInClassImplementsClause(node) { + return node.kind === 201 + && isEntityNameExpression(node.expression) + && node.parent + && node.parent.token === 108 + && node.parent.parent + && ts.isClassLike(node.parent.parent); + } + ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; + function isEntityNameExpression(node) { + return node.kind === 71 || + node.kind === 179 && isEntityNameExpression(node.expression); + } + ts.isEntityNameExpression = isEntityNameExpression; + function isRightSideOfQualifiedNameOrPropertyAccess(node) { + return (node.parent.kind === 143 && node.parent.right === node) || + (node.parent.kind === 179 && node.parent.name === node); + } + ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; + function isEmptyObjectLiteral(expression) { + return expression.kind === 178 && + expression.properties.length === 0; + } + ts.isEmptyObjectLiteral = isEmptyObjectLiteral; + function isEmptyArrayLiteral(expression) { + return expression.kind === 177 && + expression.elements.length === 0; + } + ts.isEmptyArrayLiteral = isEmptyArrayLiteral; + function getLocalSymbolForExportDefault(symbol) { + return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined; + } + ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; + function isExportDefaultSymbol(symbol) { + return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512); + } + function tryExtractTypeScriptExtension(fileName) { + return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.tryExtractTypeScriptExtension = tryExtractTypeScriptExtension; + function getExpandedCharCodes(input) { + var output = []; + var length = input.length; + for (var i = 0; i < length; i++) { + var charCode = input.charCodeAt(i); + if (charCode < 0x80) { + output.push(charCode); + } + else if (charCode < 0x800) { + output.push((charCode >> 6) | 192); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x10000) { + output.push((charCode >> 12) | 224); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else if (charCode < 0x20000) { + output.push((charCode >> 18) | 240); + output.push(((charCode >> 12) & 63) | 128); + output.push(((charCode >> 6) & 63) | 128); + output.push((charCode & 63) | 128); + } + else { + ts.Debug.assert(false, "Unexpected code point"); + } + } + return output; + } + var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + function convertToBase64(input) { + var result = ""; + var charCodes = getExpandedCharCodes(input); + var i = 0; + var length = charCodes.length; + var byte1, byte2, byte3, byte4; + while (i < length) { + byte1 = charCodes[i] >> 2; + byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4; + byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6; + byte4 = charCodes[i + 2] & 63; + if (i + 1 >= length) { + byte3 = byte4 = 64; + } + else if (i + 2 >= length) { + byte4 = 64; + } + result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4); + i += 3; + } + return result; + } + ts.convertToBase64 = convertToBase64; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; + function getNewLineCharacter(options) { + switch (options.newLine) { + case 0: + return carriageReturnLineFeed; + case 1: + return lineFeed; + } + if (ts.sys) { + return ts.sys.newLine; + } + return carriageReturnLineFeed; + } + ts.getNewLineCharacter = getNewLineCharacter; + function isSimpleExpression(node) { + return isSimpleExpressionWorker(node, 0); + } + ts.isSimpleExpression = isSimpleExpression; + function isSimpleExpressionWorker(node, depth) { + if (depth <= 5) { + var kind = node.kind; + if (kind === 9 + || kind === 8 + || kind === 12 + || kind === 13 + || kind === 71 + || kind === 99 + || kind === 97 + || kind === 101 + || kind === 86 + || kind === 95) { + return true; + } + else if (kind === 179) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 180) { + return isSimpleExpressionWorker(node.expression, depth + 1) + && isSimpleExpressionWorker(node.argumentExpression, depth + 1); + } + else if (kind === 192 + || kind === 193) { + return isSimpleExpressionWorker(node.operand, depth + 1); + } + else if (kind === 194) { + return node.operatorToken.kind !== 40 + && isSimpleExpressionWorker(node.left, depth + 1) + && isSimpleExpressionWorker(node.right, depth + 1); + } + else if (kind === 195) { + return isSimpleExpressionWorker(node.condition, depth + 1) + && isSimpleExpressionWorker(node.whenTrue, depth + 1) + && isSimpleExpressionWorker(node.whenFalse, depth + 1); + } + else if (kind === 190 + || kind === 189 + || kind === 188) { + return isSimpleExpressionWorker(node.expression, depth + 1); + } + else if (kind === 177) { + return node.elements.length === 0; + } + else if (kind === 178) { + return node.properties.length === 0; + } + else if (kind === 181) { + if (!isSimpleExpressionWorker(node.expression, depth + 1)) { + return false; + } + for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (!isSimpleExpressionWorker(argument, depth + 1)) { + return false; + } + } + return true; + } + } + return false; + } + function formatEnum(value, enumObject, isFlags) { + if (value === void 0) { value = 0; } + var members = getEnumMembers(enumObject); + if (value === 0) { + return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0"; + } + if (isFlags) { + var result = ""; + var remainingFlags = value; + for (var i = members.length - 1; i >= 0 && remainingFlags !== 0; i--) { + var _a = members[i], enumValue = _a[0], enumName = _a[1]; + if (enumValue !== 0 && (remainingFlags & enumValue) === enumValue) { + remainingFlags &= ~enumValue; + result = "" + enumName + (result ? ", " : "") + result; + } + } + if (remainingFlags === 0) { + return result; + } + } + else { + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var _b = members_1[_i], enumValue = _b[0], enumName = _b[1]; + if (enumValue === value) { + return enumName; + } + } + } + return value.toString(); + } + function getEnumMembers(enumObject) { + var result = []; + for (var name in enumObject) { + var value = enumObject[name]; + if (typeof value === "number") { + result.push([value, name]); + } + } + return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); }); + } + function formatSyntaxKind(kind) { + return formatEnum(kind, ts.SyntaxKind, false); + } + ts.formatSyntaxKind = formatSyntaxKind; + function formatModifierFlags(flags) { + return formatEnum(flags, ts.ModifierFlags, true); + } + ts.formatModifierFlags = formatModifierFlags; + function formatTransformFlags(flags) { + return formatEnum(flags, ts.TransformFlags, true); + } + ts.formatTransformFlags = formatTransformFlags; + function formatEmitFlags(flags) { + return formatEnum(flags, ts.EmitFlags, true); + } + ts.formatEmitFlags = formatEmitFlags; + function formatSymbolFlags(flags) { + return formatEnum(flags, ts.SymbolFlags, true); + } + ts.formatSymbolFlags = formatSymbolFlags; + function formatTypeFlags(flags) { + return formatEnum(flags, ts.TypeFlags, true); + } + ts.formatTypeFlags = formatTypeFlags; + function formatObjectFlags(flags) { + return formatEnum(flags, ts.ObjectFlags, true); + } + ts.formatObjectFlags = formatObjectFlags; + function getRangePos(range) { + return range ? range.pos : -1; + } + ts.getRangePos = getRangePos; + function getRangeEnd(range) { + return range ? range.end : -1; + } + ts.getRangeEnd = getRangeEnd; + function movePos(pos, value) { + return ts.positionIsSynthesized(pos) ? -1 : pos + value; + } + ts.movePos = movePos; + function createRange(pos, end) { + return { pos: pos, end: end }; + } + ts.createRange = createRange; + function moveRangeEnd(range, end) { + return createRange(range.pos, end); + } + ts.moveRangeEnd = moveRangeEnd; + function moveRangePos(range, pos) { + return createRange(pos, range.end); + } + ts.moveRangePos = moveRangePos; + function moveRangePastDecorators(node) { + return node.decorators && node.decorators.length > 0 + ? moveRangePos(node, node.decorators.end) + : node; + } + ts.moveRangePastDecorators = moveRangePastDecorators; + function moveRangePastModifiers(node) { + return node.modifiers && node.modifiers.length > 0 + ? moveRangePos(node, node.modifiers.end) + : moveRangePastDecorators(node); + } + ts.moveRangePastModifiers = moveRangePastModifiers; + function isCollapsedRange(range) { + return range.pos === range.end; + } + ts.isCollapsedRange = isCollapsedRange; + function collapseRangeToStart(range) { + return isCollapsedRange(range) ? range : moveRangeEnd(range, range.pos); + } + ts.collapseRangeToStart = collapseRangeToStart; + function collapseRangeToEnd(range) { + return isCollapsedRange(range) ? range : moveRangePos(range, range.end); + } + ts.collapseRangeToEnd = collapseRangeToEnd; + function createTokenRange(pos, token) { + return createRange(pos, pos + ts.tokenToString(token).length); + } + ts.createTokenRange = createTokenRange; + function rangeIsOnSingleLine(range, sourceFile) { + return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); + } + ts.rangeIsOnSingleLine = rangeIsOnSingleLine; + function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine; + function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, range2.end, sourceFile); + } + ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine; + function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) { + return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile), range2.end, sourceFile); + } + ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd; + function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) { + return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile), sourceFile); + } + ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart; + function positionsAreOnSameLine(pos1, pos2, sourceFile) { + return pos1 === pos2 || + getLineOfLocalPosition(sourceFile, pos1) === getLineOfLocalPosition(sourceFile, pos2); + } + ts.positionsAreOnSameLine = positionsAreOnSameLine; + function getStartPositionOfRange(range, sourceFile) { + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + } + ts.getStartPositionOfRange = getStartPositionOfRange; + function isDeclarationNameOfEnumOrNamespace(node) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode) { + switch (parseNode.parent.kind) { + case 232: + case 233: + return parseNode === parseNode.parent.name; + } + } + return false; + } + ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace; + function getInitializedVariables(node) { + return ts.filter(node.declarations, isInitializedVariable); + } + ts.getInitializedVariables = getInitializedVariables; + function isInitializedVariable(node) { + return node.initializer !== undefined; + } + function isMergedWithClass(node) { + if (node.symbol) { + for (var _i = 0, _a = node.symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (declaration.kind === 229 && declaration !== node) { + return true; + } + } + } + return false; + } + ts.isMergedWithClass = isMergedWithClass; + function isFirstDeclarationOfKind(node, kind) { + return node.symbol && getDeclarationOfKind(node.symbol, kind) === node; + } + ts.isFirstDeclarationOfKind = isFirstDeclarationOfKind; + function isWatchSet(options) { + return options.watch && options.hasOwnProperty("watch"); + } + ts.isWatchSet = isWatchSet; + function getCheckFlags(symbol) { + return symbol.flags & 33554432 ? 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 & 4194304) { + 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; + function skipAlias(symbol, checker) { + return symbol.flags & 2097152 ? checker.getAliasedSymbol(symbol) : symbol; + } + ts.skipAlias = skipAlias; + function getCombinedLocalAndExportSymbolFlags(symbol) { + return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; + } + ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags; +})(ts || (ts = {})); +(function (ts) { + function getDefaultLibFileName(options) { + switch (options.target) { + case 5: + return "lib.esnext.full.d.ts"; + case 4: + return "lib.es2017.full.d.ts"; + case 3: + return "lib.es2016.full.d.ts"; + case 2: + return "lib.es6.d.ts"; + default: + return "lib.d.ts"; + } + } + ts.getDefaultLibFileName = getDefaultLibFileName; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + var overlapStart = Math.max(span.start, other.start); + var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + return overlapStart < overlapEnd; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlapStart = Math.max(span1.start, span2.start); + var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (overlapStart < overlapEnd) { + return createTextSpanFromBounds(overlapStart, overlapEnd); + } + return undefined; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + var end = start + length; + return start <= textSpanEnd(span) && end >= span.start; + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { + var end1 = start1 + length1; + var end2 = start2 + length2; + return start2 <= end1 && end2 >= start1; + } + ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var intersectStart = Math.max(span1.start, span2.start); + var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (intersectStart <= intersectEnd) { + return createTextSpanFromBounds(intersectStart, intersectEnd); + } + return undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; + function getTypeParameterOwner(d) { + if (d && d.kind === 145) { + for (var current = d; current; current = current.parent) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 230) { + return current; + } + } + } + } + ts.getTypeParameterOwner = getTypeParameterOwner; + function isParameterPropertyDeclaration(node) { + return ts.hasModifier(node, 92) && node.parent.kind === 152 && ts.isClassLike(node.parent.parent); + } + ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 176 || ts.isBindingPattern(node))) { + node = node.parent; + } + return node; + } + function getCombinedModifierFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = ts.getModifierFlags(node); + if (node.kind === 226) { + node = node.parent; + } + if (node && node.kind === 227) { + flags |= ts.getModifierFlags(node); + node = node.parent; + } + if (node && node.kind === 208) { + flags |= ts.getModifierFlags(node); + } + return flags; + } + ts.getCombinedModifierFlags = getCombinedModifierFlags; + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 226) { + node = node.parent; + } + if (node && node.kind === 227) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 208) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; + function validateLocaleAndSetLanguage(locale, sys, errors) { + var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + if (!matchResult) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + } + return; + } + var language = matchResult[1]; + var territory = matchResult[3]; + if (!trySetLanguageAndTerritory(language, territory, errors)) { + trySetLanguageAndTerritory(language, undefined, errors); + } + function trySetLanguageAndTerritory(language, territory, errors) { + var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath()); + var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath); + var filePath = ts.combinePaths(containingDirectoryPath, language); + if (territory) { + filePath = filePath + "-" + territory; + } + filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json")); + if (!sys.fileExists(filePath)) { + return false; + } + var fileContents = ""; + try { + fileContents = sys.readFile(filePath); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath)); + } + return false; + } + try { + ts.localizedDiagnosticMessages = JSON.parse(fileContents); + } + catch (e) { + if (errors) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); + } + return false; + } + return true; + } + } + ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage; + function getOriginalNode(node, nodeTest) { + if (node) { + while (node.original !== undefined) { + node = node.original; + } + } + return !nodeTest || nodeTest(node) ? node : undefined; + } + ts.getOriginalNode = getOriginalNode; + function isParseTreeNode(node) { + return (node.flags & 8) === 0; + } + ts.isParseTreeNode = isParseTreeNode; + function getParseTreeNode(node, nodeTest) { + if (node === undefined || isParseTreeNode(node)) { + return node; + } + node = getOriginalNode(node); + if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) { + return node; + } + return undefined; + } + ts.getParseTreeNode = getParseTreeNode; + function unescapeLeadingUnderscores(identifier) { + var id = identifier; + return id.length >= 3 && id.charCodeAt(0) === 95 && id.charCodeAt(1) === 95 && id.charCodeAt(2) === 95 ? id.substr(1) : id; + } + ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores; + function unescapeIdentifier(id) { + return id; + } + ts.unescapeIdentifier = unescapeIdentifier; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (ts.isJSDocPropertyLikeTag(declaration) && declaration.name.kind === 143) { + return declaration.name.right; + } + if (declaration.kind === 194) { + var expr = declaration; + switch (ts.getSpecialPropertyAssignmentKind(expr)) { + case 1: + case 4: + case 5: + case 3: + return expr.left.name; + default: + return undefined; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; +})(ts || (ts = {})); +(function (ts) { + function isNumericLiteral(node) { + return node.kind === 8; + } + ts.isNumericLiteral = isNumericLiteral; + function isStringLiteral(node) { + return node.kind === 9; + } + ts.isStringLiteral = isStringLiteral; + function isJsxText(node) { + return node.kind === 10; + } + ts.isJsxText = isJsxText; + function isRegularExpressionLiteral(node) { + return node.kind === 12; + } + ts.isRegularExpressionLiteral = isRegularExpressionLiteral; + function isNoSubstitutionTemplateLiteral(node) { + return node.kind === 13; + } + ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral; + function isTemplateHead(node) { + return node.kind === 14; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddle(node) { + return node.kind === 15; + } + ts.isTemplateMiddle = isTemplateMiddle; + function isTemplateTail(node) { + return node.kind === 16; + } + ts.isTemplateTail = isTemplateTail; + function isIdentifier(node) { + return node.kind === 71; + } + ts.isIdentifier = isIdentifier; + function isQualifiedName(node) { + return node.kind === 143; + } + ts.isQualifiedName = isQualifiedName; + function isComputedPropertyName(node) { + return node.kind === 144; + } + ts.isComputedPropertyName = isComputedPropertyName; + function isTypeParameterDeclaration(node) { + return node.kind === 145; + } + ts.isTypeParameterDeclaration = isTypeParameterDeclaration; + function isParameter(node) { + return node.kind === 146; + } + ts.isParameter = isParameter; + function isDecorator(node) { + return node.kind === 147; + } + ts.isDecorator = isDecorator; + function isPropertySignature(node) { + return node.kind === 148; + } + ts.isPropertySignature = isPropertySignature; + function isPropertyDeclaration(node) { + return node.kind === 149; + } + ts.isPropertyDeclaration = isPropertyDeclaration; + function isMethodSignature(node) { + return node.kind === 150; + } + ts.isMethodSignature = isMethodSignature; + function isMethodDeclaration(node) { + return node.kind === 151; + } + ts.isMethodDeclaration = isMethodDeclaration; + function isConstructorDeclaration(node) { + return node.kind === 152; + } + ts.isConstructorDeclaration = isConstructorDeclaration; + function isGetAccessorDeclaration(node) { + return node.kind === 153; + } + ts.isGetAccessorDeclaration = isGetAccessorDeclaration; + function isSetAccessorDeclaration(node) { + return node.kind === 154; + } + ts.isSetAccessorDeclaration = isSetAccessorDeclaration; + function isCallSignatureDeclaration(node) { + return node.kind === 155; + } + ts.isCallSignatureDeclaration = isCallSignatureDeclaration; + function isConstructSignatureDeclaration(node) { + return node.kind === 156; + } + ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; + function isIndexSignatureDeclaration(node) { + return node.kind === 157; + } + ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + function isTypePredicateNode(node) { + return node.kind === 158; + } + ts.isTypePredicateNode = isTypePredicateNode; + function isTypeReferenceNode(node) { + return node.kind === 159; + } + ts.isTypeReferenceNode = isTypeReferenceNode; + function isFunctionTypeNode(node) { + return node.kind === 160; + } + ts.isFunctionTypeNode = isFunctionTypeNode; + function isConstructorTypeNode(node) { + return node.kind === 161; + } + ts.isConstructorTypeNode = isConstructorTypeNode; + function isTypeQueryNode(node) { + return node.kind === 162; + } + ts.isTypeQueryNode = isTypeQueryNode; + function isTypeLiteralNode(node) { + return node.kind === 163; + } + ts.isTypeLiteralNode = isTypeLiteralNode; + function isArrayTypeNode(node) { + return node.kind === 164; + } + ts.isArrayTypeNode = isArrayTypeNode; + function isTupleTypeNode(node) { + return node.kind === 165; + } + ts.isTupleTypeNode = isTupleTypeNode; + function isUnionTypeNode(node) { + return node.kind === 166; + } + ts.isUnionTypeNode = isUnionTypeNode; + function isIntersectionTypeNode(node) { + return node.kind === 167; + } + ts.isIntersectionTypeNode = isIntersectionTypeNode; + function isParenthesizedTypeNode(node) { + return node.kind === 168; + } + ts.isParenthesizedTypeNode = isParenthesizedTypeNode; + function isThisTypeNode(node) { + return node.kind === 169; + } + ts.isThisTypeNode = isThisTypeNode; + function isTypeOperatorNode(node) { + return node.kind === 170; + } + ts.isTypeOperatorNode = isTypeOperatorNode; + function isIndexedAccessTypeNode(node) { + return node.kind === 171; + } + ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; + function isMappedTypeNode(node) { + return node.kind === 172; + } + ts.isMappedTypeNode = isMappedTypeNode; + function isLiteralTypeNode(node) { + return node.kind === 173; + } + ts.isLiteralTypeNode = isLiteralTypeNode; + function isObjectBindingPattern(node) { + return node.kind === 174; + } + ts.isObjectBindingPattern = isObjectBindingPattern; + function isArrayBindingPattern(node) { + return node.kind === 175; + } + ts.isArrayBindingPattern = isArrayBindingPattern; + function isBindingElement(node) { + return node.kind === 176; + } + ts.isBindingElement = isBindingElement; + function isArrayLiteralExpression(node) { + return node.kind === 177; + } + ts.isArrayLiteralExpression = isArrayLiteralExpression; + function isObjectLiteralExpression(node) { + return node.kind === 178; + } + ts.isObjectLiteralExpression = isObjectLiteralExpression; + function isPropertyAccessExpression(node) { + return node.kind === 179; + } + ts.isPropertyAccessExpression = isPropertyAccessExpression; + function isElementAccessExpression(node) { + return node.kind === 180; + } + ts.isElementAccessExpression = isElementAccessExpression; + function isCallExpression(node) { + return node.kind === 181; + } + ts.isCallExpression = isCallExpression; + function isNewExpression(node) { + return node.kind === 182; + } + ts.isNewExpression = isNewExpression; + function isTaggedTemplateExpression(node) { + return node.kind === 183; + } + ts.isTaggedTemplateExpression = isTaggedTemplateExpression; + function isTypeAssertion(node) { + return node.kind === 184; + } + ts.isTypeAssertion = isTypeAssertion; + function isParenthesizedExpression(node) { + return node.kind === 185; + } + ts.isParenthesizedExpression = isParenthesizedExpression; + function skipPartiallyEmittedExpressions(node) { + while (node.kind === 288) { + node = node.expression; + } + return node; + } + ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; + function isFunctionExpression(node) { + return node.kind === 186; + } + ts.isFunctionExpression = isFunctionExpression; + function isArrowFunction(node) { + return node.kind === 187; + } + ts.isArrowFunction = isArrowFunction; + function isDeleteExpression(node) { + return node.kind === 188; + } + ts.isDeleteExpression = isDeleteExpression; + function isTypeOfExpression(node) { + return node.kind === 191; + } + ts.isTypeOfExpression = isTypeOfExpression; + function isVoidExpression(node) { + return node.kind === 190; + } + ts.isVoidExpression = isVoidExpression; + function isAwaitExpression(node) { + return node.kind === 191; + } + ts.isAwaitExpression = isAwaitExpression; + function isPrefixUnaryExpression(node) { + return node.kind === 192; + } + ts.isPrefixUnaryExpression = isPrefixUnaryExpression; + function isPostfixUnaryExpression(node) { + return node.kind === 193; + } + ts.isPostfixUnaryExpression = isPostfixUnaryExpression; + function isBinaryExpression(node) { + return node.kind === 194; + } + ts.isBinaryExpression = isBinaryExpression; + function isConditionalExpression(node) { + return node.kind === 195; + } + ts.isConditionalExpression = isConditionalExpression; + function isTemplateExpression(node) { + return node.kind === 196; + } + ts.isTemplateExpression = isTemplateExpression; + function isYieldExpression(node) { + return node.kind === 197; + } + ts.isYieldExpression = isYieldExpression; + function isSpreadElement(node) { + return node.kind === 198; + } + ts.isSpreadElement = isSpreadElement; + function isClassExpression(node) { + return node.kind === 199; + } + ts.isClassExpression = isClassExpression; + function isOmittedExpression(node) { + return node.kind === 200; + } + ts.isOmittedExpression = isOmittedExpression; + function isExpressionWithTypeArguments(node) { + return node.kind === 201; + } + ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; + function isAsExpression(node) { + return node.kind === 202; + } + ts.isAsExpression = isAsExpression; + function isNonNullExpression(node) { + return node.kind === 203; + } + ts.isNonNullExpression = isNonNullExpression; + function isMetaProperty(node) { + return node.kind === 204; + } + ts.isMetaProperty = isMetaProperty; + function isTemplateSpan(node) { + return node.kind === 205; + } + ts.isTemplateSpan = isTemplateSpan; + function isSemicolonClassElement(node) { + return node.kind === 206; + } + ts.isSemicolonClassElement = isSemicolonClassElement; + function isBlock(node) { + return node.kind === 207; + } + ts.isBlock = isBlock; + function isVariableStatement(node) { + return node.kind === 208; + } + ts.isVariableStatement = isVariableStatement; + function isEmptyStatement(node) { + return node.kind === 209; + } + ts.isEmptyStatement = isEmptyStatement; + function isExpressionStatement(node) { + return node.kind === 210; + } + ts.isExpressionStatement = isExpressionStatement; + function isIfStatement(node) { + return node.kind === 211; + } + ts.isIfStatement = isIfStatement; + function isDoStatement(node) { + return node.kind === 212; + } + ts.isDoStatement = isDoStatement; + function isWhileStatement(node) { + return node.kind === 213; + } + ts.isWhileStatement = isWhileStatement; + function isForStatement(node) { + return node.kind === 214; + } + ts.isForStatement = isForStatement; + function isForInStatement(node) { + return node.kind === 215; + } + ts.isForInStatement = isForInStatement; + function isForOfStatement(node) { + return node.kind === 216; + } + ts.isForOfStatement = isForOfStatement; + function isContinueStatement(node) { + return node.kind === 217; + } + ts.isContinueStatement = isContinueStatement; + function isBreakStatement(node) { + return node.kind === 218; + } + ts.isBreakStatement = isBreakStatement; + function isReturnStatement(node) { + return node.kind === 219; + } + ts.isReturnStatement = isReturnStatement; + function isWithStatement(node) { + return node.kind === 220; + } + ts.isWithStatement = isWithStatement; + function isSwitchStatement(node) { + return node.kind === 221; + } + ts.isSwitchStatement = isSwitchStatement; + function isLabeledStatement(node) { + return node.kind === 222; + } + ts.isLabeledStatement = isLabeledStatement; + function isThrowStatement(node) { + return node.kind === 223; + } + ts.isThrowStatement = isThrowStatement; + function isTryStatement(node) { + return node.kind === 224; + } + ts.isTryStatement = isTryStatement; + function isDebuggerStatement(node) { + return node.kind === 225; + } + ts.isDebuggerStatement = isDebuggerStatement; + function isVariableDeclaration(node) { + return node.kind === 226; + } + ts.isVariableDeclaration = isVariableDeclaration; + function isVariableDeclarationList(node) { + return node.kind === 227; + } + ts.isVariableDeclarationList = isVariableDeclarationList; + function isFunctionDeclaration(node) { + return node.kind === 228; + } + ts.isFunctionDeclaration = isFunctionDeclaration; + function isClassDeclaration(node) { + return node.kind === 229; + } + ts.isClassDeclaration = isClassDeclaration; + function isInterfaceDeclaration(node) { + return node.kind === 230; + } + ts.isInterfaceDeclaration = isInterfaceDeclaration; + function isTypeAliasDeclaration(node) { + return node.kind === 231; + } + ts.isTypeAliasDeclaration = isTypeAliasDeclaration; + function isEnumDeclaration(node) { + return node.kind === 232; + } + ts.isEnumDeclaration = isEnumDeclaration; + function isModuleDeclaration(node) { + return node.kind === 233; + } + ts.isModuleDeclaration = isModuleDeclaration; + function isModuleBlock(node) { + return node.kind === 234; + } + ts.isModuleBlock = isModuleBlock; + function isCaseBlock(node) { + return node.kind === 235; + } + ts.isCaseBlock = isCaseBlock; + function isNamespaceExportDeclaration(node) { + return node.kind === 236; + } + ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; + function isImportEqualsDeclaration(node) { + return node.kind === 237; + } + ts.isImportEqualsDeclaration = isImportEqualsDeclaration; + function isImportDeclaration(node) { + return node.kind === 238; + } + ts.isImportDeclaration = isImportDeclaration; + function isImportClause(node) { + return node.kind === 239; + } + ts.isImportClause = isImportClause; + function isNamespaceImport(node) { + return node.kind === 240; + } + ts.isNamespaceImport = isNamespaceImport; + function isNamedImports(node) { + return node.kind === 241; + } + ts.isNamedImports = isNamedImports; + function isImportSpecifier(node) { + return node.kind === 242; + } + ts.isImportSpecifier = isImportSpecifier; + function isExportAssignment(node) { + return node.kind === 243; + } + ts.isExportAssignment = isExportAssignment; + function isExportDeclaration(node) { + return node.kind === 244; + } + ts.isExportDeclaration = isExportDeclaration; + function isNamedExports(node) { + return node.kind === 245; + } + ts.isNamedExports = isNamedExports; + function isExportSpecifier(node) { + return node.kind === 246; + } + ts.isExportSpecifier = isExportSpecifier; + function isMissingDeclaration(node) { + return node.kind === 247; + } + ts.isMissingDeclaration = isMissingDeclaration; + function isExternalModuleReference(node) { + return node.kind === 248; + } + ts.isExternalModuleReference = isExternalModuleReference; + function isJsxElement(node) { + return node.kind === 249; + } + ts.isJsxElement = isJsxElement; + function isJsxSelfClosingElement(node) { + return node.kind === 250; + } + ts.isJsxSelfClosingElement = isJsxSelfClosingElement; + function isJsxOpeningElement(node) { + return node.kind === 251; + } + ts.isJsxOpeningElement = isJsxOpeningElement; + function isJsxClosingElement(node) { + return node.kind === 252; + } + ts.isJsxClosingElement = isJsxClosingElement; + function isJsxAttribute(node) { + return node.kind === 253; + } + ts.isJsxAttribute = isJsxAttribute; + function isJsxAttributes(node) { + return node.kind === 254; + } + ts.isJsxAttributes = isJsxAttributes; + function isJsxSpreadAttribute(node) { + return node.kind === 255; + } + ts.isJsxSpreadAttribute = isJsxSpreadAttribute; + function isJsxExpression(node) { + return node.kind === 256; + } + ts.isJsxExpression = isJsxExpression; + function isCaseClause(node) { + return node.kind === 257; + } + ts.isCaseClause = isCaseClause; + function isDefaultClause(node) { + return node.kind === 258; + } + ts.isDefaultClause = isDefaultClause; + function isHeritageClause(node) { + return node.kind === 259; + } + ts.isHeritageClause = isHeritageClause; + function isCatchClause(node) { + return node.kind === 260; + } + ts.isCatchClause = isCatchClause; + function isPropertyAssignment(node) { + return node.kind === 261; + } + ts.isPropertyAssignment = isPropertyAssignment; + function isShorthandPropertyAssignment(node) { + return node.kind === 262; + } + ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; + function isSpreadAssignment(node) { + return node.kind === 263; + } + ts.isSpreadAssignment = isSpreadAssignment; + function isEnumMember(node) { + return node.kind === 264; + } + ts.isEnumMember = isEnumMember; + function isSourceFile(node) { + return node.kind === 265; + } + ts.isSourceFile = isSourceFile; + function isBundle(node) { + return node.kind === 266; + } + ts.isBundle = isBundle; + function isJSDocTypeExpression(node) { + return node.kind === 267; + } + ts.isJSDocTypeExpression = isJSDocTypeExpression; + function isJSDocAllType(node) { + return node.kind === 268; + } + ts.isJSDocAllType = isJSDocAllType; + function isJSDocUnknownType(node) { + return node.kind === 269; + } + ts.isJSDocUnknownType = isJSDocUnknownType; + function isJSDocNullableType(node) { + return node.kind === 270; + } + ts.isJSDocNullableType = isJSDocNullableType; + function isJSDocNonNullableType(node) { + return node.kind === 271; + } + ts.isJSDocNonNullableType = isJSDocNonNullableType; + function isJSDocOptionalType(node) { + return node.kind === 272; + } + ts.isJSDocOptionalType = isJSDocOptionalType; + function isJSDocFunctionType(node) { + return node.kind === 273; + } + ts.isJSDocFunctionType = isJSDocFunctionType; + function isJSDocVariadicType(node) { + return node.kind === 274; + } + ts.isJSDocVariadicType = isJSDocVariadicType; + function isJSDoc(node) { + return node.kind === 275; + } + ts.isJSDoc = isJSDoc; + function isJSDocAugmentsTag(node) { + return node.kind === 277; + } + ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocParameterTag(node) { + return node.kind === 279; + } + ts.isJSDocParameterTag = isJSDocParameterTag; + function isJSDocReturnTag(node) { + return node.kind === 280; + } + ts.isJSDocReturnTag = isJSDocReturnTag; + function isJSDocTypeTag(node) { + return node.kind === 281; + } + ts.isJSDocTypeTag = isJSDocTypeTag; + function isJSDocTemplateTag(node) { + return node.kind === 282; + } + ts.isJSDocTemplateTag = isJSDocTemplateTag; + function isJSDocTypedefTag(node) { + return node.kind === 283; + } + ts.isJSDocTypedefTag = isJSDocTypedefTag; + function isJSDocPropertyTag(node) { + return node.kind === 284; + } + ts.isJSDocPropertyTag = isJSDocPropertyTag; + function isJSDocPropertyLikeTag(node) { + return node.kind === 284 || node.kind === 279; + } + ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; + function isJSDocTypeLiteral(node) { + return node.kind === 285; + } + ts.isJSDocTypeLiteral = isJSDocTypeLiteral; +})(ts || (ts = {})); +(function (ts) { + function isSyntaxList(n) { + return n.kind === 286; + } + ts.isSyntaxList = isSyntaxList; + function isNode(node) { + return isNodeKind(node.kind); + } + ts.isNode = isNode; + function isNodeKind(kind) { + return kind >= 143; + } + ts.isNodeKind = isNodeKind; + function isToken(n) { + return n.kind >= 0 && n.kind <= 142; + } + ts.isToken = isToken; + function isNodeArray(array) { + return array.hasOwnProperty("pos") + && array.hasOwnProperty("end"); + } + ts.isNodeArray = isNodeArray; + function isLiteralKind(kind) { + return 8 <= kind && kind <= 13; + } + ts.isLiteralKind = isLiteralKind; + function isLiteralExpression(node) { + return isLiteralKind(node.kind); + } + ts.isLiteralExpression = isLiteralExpression; + function isTemplateLiteralKind(kind) { + return 13 <= kind && kind <= 16; + } + ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 15 + || kind === 16; + } + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; + function isStringTextContainingNode(node) { + switch (node.kind) { + case 9: + case 14: + case 15: + case 16: + case 13: + return true; + default: + return false; + } + } + ts.isStringTextContainingNode = isStringTextContainingNode; + function isGeneratedIdentifier(node) { + return ts.isIdentifier(node) && node.autoGenerateKind > 0; + } + ts.isGeneratedIdentifier = isGeneratedIdentifier; + function isModifierKind(token) { + switch (token) { + case 117: + case 120: + case 76: + case 124: + case 79: + case 84: + case 114: + case 112: + case 113: + case 131: + case 115: + return true; + } + return false; + } + ts.isModifierKind = isModifierKind; + function isModifier(node) { + return isModifierKind(node.kind); + } + ts.isModifier = isModifier; + function isEntityName(node) { + var kind = node.kind; + return kind === 143 + || kind === 71; + } + ts.isEntityName = isEntityName; + function isPropertyName(node) { + var kind = node.kind; + return kind === 71 + || kind === 9 + || kind === 8 + || kind === 144; + } + ts.isPropertyName = isPropertyName; + function isBindingName(node) { + var kind = node.kind; + return kind === 71 + || kind === 174 + || kind === 175; + } + ts.isBindingName = isBindingName; + function isFunctionLike(node) { + return node && isFunctionLikeKind(node.kind); + } + ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 152: + case 186: + case 228: + case 187: + case 151: + case 150: + case 153: + case 154: + case 155: + case 156: + case 157: + case 160: + case 273: + case 161: + return true; + } + return false; + } + ts.isFunctionLikeKind = isFunctionLikeKind; + function isClassElement(node) { + var kind = node.kind; + return kind === 152 + || kind === 149 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 157 + || kind === 206 + || kind === 247; + } + ts.isClassElement = isClassElement; + function isClassLike(node) { + return node && (node.kind === 229 || node.kind === 199); + } + ts.isClassLike = isClassLike; + function isAccessor(node) { + return node && (node.kind === 153 || node.kind === 154); + } + ts.isAccessor = isAccessor; + 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 + || kind === 262 + || kind === 263 + || kind === 151 + || kind === 153 + || kind === 154 + || kind === 247; + } + ts.isObjectLiteralElementLike = isObjectLiteralElementLike; + function isTypeNodeKind(kind) { + return (kind >= 158 && kind <= 173) + || kind === 119 + || kind === 133 + || kind === 134 + || kind === 122 + || kind === 136 + || kind === 137 + || kind === 99 + || kind === 105 + || kind === 139 + || kind === 95 + || kind === 130 + || kind === 201; + } + function isTypeNode(node) { + return isTypeNodeKind(node.kind); + } + ts.isTypeNode = isTypeNode; + function isFunctionOrConstructorTypeNode(node) { + switch (node.kind) { + case 160: + case 161: + return true; + } + return false; + } + ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode; + function isBindingPattern(node) { + if (node) { + var kind = node.kind; + return kind === 175 + || kind === 174; + } + return false; + } + ts.isBindingPattern = isBindingPattern; + function isAssignmentPattern(node) { + var kind = node.kind; + return kind === 177 + || kind === 178; + } + ts.isAssignmentPattern = isAssignmentPattern; + function isArrayBindingElement(node) { + var kind = node.kind; + return kind === 176 + || kind === 200; + } + ts.isArrayBindingElement = isArrayBindingElement; + function isDeclarationBindingElement(bindingElement) { + switch (bindingElement.kind) { + case 226: + case 146: + case 176: + return true; + } + return false; + } + ts.isDeclarationBindingElement = isDeclarationBindingElement; + function isBindingOrAssignmentPattern(node) { + return isObjectBindingOrAssignmentPattern(node) + || isArrayBindingOrAssignmentPattern(node); + } + ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern; + function isObjectBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 174: + case 178: + return true; + } + return false; + } + ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; + function isArrayBindingOrAssignmentPattern(node) { + switch (node.kind) { + case 175: + case 177: + return true; + } + return false; + } + ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + function isPropertyAccessOrQualifiedName(node) { + var kind = node.kind; + return kind === 179 + || kind === 143; + } + ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; + function isCallLikeExpression(node) { + switch (node.kind) { + case 251: + case 250: + case 181: + case 182: + case 183: + case 147: + return true; + default: + return false; + } + } + ts.isCallLikeExpression = isCallLikeExpression; + function isCallOrNewExpression(node) { + return node.kind === 181 || node.kind === 182; + } + ts.isCallOrNewExpression = isCallOrNewExpression; + function isTemplateLiteral(node) { + var kind = node.kind; + return kind === 196 + || kind === 13; + } + ts.isTemplateLiteral = isTemplateLiteral; + function isLeftHandSideExpressionKind(kind) { + return kind === 179 + || kind === 180 + || kind === 182 + || kind === 181 + || kind === 249 + || kind === 250 + || kind === 183 + || kind === 177 + || kind === 185 + || kind === 178 + || kind === 199 + || kind === 186 + || kind === 71 + || kind === 12 + || kind === 8 + || kind === 9 + || kind === 13 + || kind === 196 + || kind === 86 + || kind === 95 + || kind === 99 + || kind === 101 + || kind === 97 + || kind === 91 + || kind === 203 + || kind === 204; + } + function isLeftHandSideExpression(node) { + return isLeftHandSideExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isLeftHandSideExpression = isLeftHandSideExpression; + function isUnaryExpressionKind(kind) { + return kind === 192 + || kind === 193 + || kind === 188 + || kind === 189 + || kind === 190 + || kind === 191 + || kind === 184 + || isLeftHandSideExpressionKind(kind); + } + function isUnaryExpression(node) { + return isUnaryExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isUnaryExpression = isUnaryExpression; + function isExpressionKind(kind) { + return kind === 195 + || kind === 197 + || kind === 187 + || kind === 194 + || kind === 198 + || kind === 202 + || kind === 200 + || kind === 289 + || isUnaryExpressionKind(kind); + } + function isExpression(node) { + return isExpressionKind(ts.skipPartiallyEmittedExpressions(node).kind); + } + ts.isExpression = isExpression; + function isAssertionExpression(node) { + var kind = node.kind; + return kind === 184 + || kind === 202; + } + ts.isAssertionExpression = isAssertionExpression; + function isPartiallyEmittedExpression(node) { + return node.kind === 288; + } + ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; + function isNotEmittedStatement(node) { + return node.kind === 287; + } + ts.isNotEmittedStatement = isNotEmittedStatement; + function isNotEmittedOrPartiallyEmittedNode(node) { + return isNotEmittedStatement(node) + || isPartiallyEmittedExpression(node); + } + ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; + function isIterationStatement(node, lookInLabeledStatements) { + switch (node.kind) { + case 214: + case 215: + case 216: + case 212: + case 213: + return true; + case 222: + return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); + } + return false; + } + ts.isIterationStatement = isIterationStatement; + function isForInOrOfStatement(node) { + return node.kind === 215 || node.kind === 216; + } + ts.isForInOrOfStatement = isForInOrOfStatement; + function isConciseBody(node) { + return ts.isBlock(node) + || isExpression(node); + } + ts.isConciseBody = isConciseBody; + function isFunctionBody(node) { + return ts.isBlock(node); + } + ts.isFunctionBody = isFunctionBody; + function isForInitializer(node) { + return ts.isVariableDeclarationList(node) + || isExpression(node); + } + ts.isForInitializer = isForInitializer; + function isModuleBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233 + || kind === 71; + } + ts.isModuleBody = isModuleBody; + function isNamespaceBody(node) { + var kind = node.kind; + return kind === 234 + || kind === 233; + } + ts.isNamespaceBody = isNamespaceBody; + function isJSDocNamespaceBody(node) { + var kind = node.kind; + return kind === 71 + || kind === 233; + } + ts.isJSDocNamespaceBody = isJSDocNamespaceBody; + function isNamedImportBindings(node) { + var kind = node.kind; + return kind === 241 + || kind === 240; + } + ts.isNamedImportBindings = isNamedImportBindings; + function isModuleOrEnumDeclaration(node) { + return node.kind === 233 || node.kind === 232; + } + ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; + function isDeclarationKind(kind) { + return kind === 187 + || kind === 176 + || kind === 229 + || kind === 199 + || kind === 152 + || kind === 232 + || kind === 264 + || kind === 246 + || kind === 228 + || kind === 186 + || kind === 153 + || kind === 239 + || kind === 237 + || kind === 242 + || kind === 230 + || kind === 253 + || kind === 151 + || kind === 150 + || kind === 233 + || kind === 236 + || kind === 240 + || kind === 146 + || kind === 261 + || kind === 149 + || kind === 148 + || kind === 154 + || kind === 262 + || kind === 231 + || kind === 145 + || kind === 226 + || kind === 283; + } + function isDeclarationStatementKind(kind) { + return kind === 228 + || kind === 247 + || kind === 229 + || kind === 230 + || kind === 231 + || kind === 232 + || kind === 233 + || kind === 238 + || kind === 237 + || kind === 244 + || kind === 243 + || kind === 236; + } + function isStatementKindButNotDeclarationKind(kind) { + return kind === 218 + || kind === 217 + || kind === 225 + || kind === 212 + || kind === 210 + || kind === 209 + || kind === 215 + || kind === 216 + || kind === 214 + || kind === 211 + || kind === 222 + || kind === 219 + || kind === 221 + || kind === 223 + || kind === 224 + || kind === 208 + || kind === 213 + || kind === 220 + || kind === 287 + || kind === 291 + || kind === 290; + } + function isDeclaration(node) { + if (node.kind === 145) { + return node.parent.kind !== 282 || ts.isInJavaScriptFile(node); + } + return isDeclarationKind(node.kind); + } + ts.isDeclaration = isDeclaration; + function isDeclarationStatement(node) { + return isDeclarationStatementKind(node.kind); + } + ts.isDeclarationStatement = isDeclarationStatement; + function isStatementButNotDeclaration(node) { + return isStatementKindButNotDeclarationKind(node.kind); + } + ts.isStatementButNotDeclaration = isStatementButNotDeclaration; + function isStatement(node) { + var kind = node.kind; + return isStatementKindButNotDeclarationKind(kind) + || isDeclarationStatementKind(kind) + || kind === 207; + } + ts.isStatement = isStatement; + function isModuleReference(node) { + var kind = node.kind; + return kind === 248 + || kind === 143 + || kind === 71; + } + ts.isModuleReference = isModuleReference; + function isJsxTagNameExpression(node) { + var kind = node.kind; + return kind === 99 + || kind === 71 + || kind === 179; + } + ts.isJsxTagNameExpression = isJsxTagNameExpression; + function isJsxChild(node) { + var kind = node.kind; + return kind === 249 + || kind === 256 + || kind === 250 + || kind === 10; + } + ts.isJsxChild = isJsxChild; + function isJsxAttributeLike(node) { + var kind = node.kind; + return kind === 253 + || kind === 255; + } + ts.isJsxAttributeLike = isJsxAttributeLike; + function isStringLiteralOrJsxExpression(node) { + var kind = node.kind; + return kind === 9 + || kind === 256; + } + ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; + function isJsxOpeningLikeElement(node) { + var kind = node.kind; + return kind === 251 + || kind === 250; + } + ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; + function isCaseOrDefaultClause(node) { + var kind = node.kind; + return kind === 257 + || kind === 258; + } + ts.isCaseOrDefaultClause = isCaseOrDefaultClause; + function isJSDocNode(node) { + return node.kind >= 267 && node.kind <= 285; + } + ts.isJSDocNode = isJSDocNode; + function isJSDocCommentContainingNode(node) { + return node.kind === 275 || isJSDocTag(node); + } + ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; + function isJSDocTag(node) { + return node.kind >= 276 && node.kind <= 285; + } + ts.isJSDocTag = isJSDocTag; +})(ts || (ts = {})); +var ts; (function (ts) { function tokenIsIdentifierOrKeyword(token) { return token >= 71; @@ -4580,12 +8157,19 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character); + return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; - function computePositionOfLineAndCharacter(lineStarts, line, character) { + function computePositionOfLineAndCharacter(lineStarts, line, character, debugText) { ts.Debug.assert(line >= 0 && line < lineStarts.length); - return lineStarts[line] + character; + var res = lineStarts[line] + character; + if (line < lineStarts.length - 1) { + ts.Debug.assert(res < lineStarts[line + 1]); + } + else if (debugText !== undefined) { + ts.Debug.assert(res < debugText.length); + } + return res; } ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter; function getLineStarts(sourceFile) { @@ -4652,6 +8236,7 @@ var ts; case 32: case 47: case 60: + case 124: case 61: case 62: return true; @@ -4713,6 +8298,7 @@ var ts; } break; case 60: + case 124: case 61: case 62: if (isConflictMarkerTrivia(text, pos)) { @@ -4766,10 +8352,10 @@ var ts; } } else { - ts.Debug.assert(ch === 61); + ts.Debug.assert(ch === 124 || ch === 61); while (pos < len) { - var ch_1 = text.charCodeAt(pos); - if (ch_1 === 62 && isConflictMarkerTrivia(text, pos)) { + var currentChar = text.charCodeAt(pos); + if ((currentChar === 61 || currentChar === 62) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) { break; } pos++; @@ -5449,13 +9035,13 @@ var ts; pos += 2; var commentClosed = false; while (pos < end) { - var ch_2 = text.charCodeAt(pos); - if (ch_2 === 42 && text.charCodeAt(pos + 1) === 47) { + var ch_1 = text.charCodeAt(pos); + if (ch_1 === 42 && text.charCodeAt(pos + 1) === 47) { pos += 2; commentClosed = true; break; } - if (isLineBreak(ch_2)) { + if (isLineBreak(ch_1)) { precedingLineBreak = true; } pos++; @@ -5610,6 +9196,15 @@ var ts; pos++; return token = 17; case 124: + if (isConflictMarkerTrivia(text, pos)) { + pos = scanConflictMarkerTrivia(text, pos, error); + if (skipTrivia) { + continue; + } + else { + return token = 7; + } + } if (text.charCodeAt(pos + 1) === 124) { return pos += 2, token = 54; } @@ -5944,6 +9539,5237 @@ var ts; ts.createScanner = createScanner; })(ts || (ts = {})); var ts; +(function (ts) { + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + function createNode(kind, pos, end) { + if (kind === 265) { + return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); + } + else if (kind === 71) { + return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end); + } + else if (!ts.isNodeKind(kind)) { + return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end); + } + else { + return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end); + } + } + ts.createNode = createNode; + function visitNode(cbNode, node) { + return node && cbNode(node); + } + function visitNodes(cbNode, cbNodes, nodes) { + if (nodes) { + if (cbNodes) { + return cbNodes(nodes); + } + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + var result = cbNode(node); + if (result) { + return result; + } + } + } + } + function forEachChild(node, cbNode, cbNodes) { + if (!node || node.kind <= 142) { + return; + } + switch (node.kind) { + case 143: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.right); + case 145: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.constraint) || + visitNode(cbNode, node.default) || + visitNode(cbNode, node.expression); + case 262: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.equalsToken) || + visitNode(cbNode, node.objectAssignmentInitializer); + case 263: + return visitNode(cbNode, node.expression); + case 146: + case 149: + case 148: + case 261: + case 226: + case 176: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.initializer); + case 160: + case 161: + case 155: + case 156: + case 157: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 151: + case 150: + case 152: + case 153: + case 154: + case 186: + case 228: + case 187: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.questionToken) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) || + visitNode(cbNode, node.equalsGreaterThanToken) || + visitNode(cbNode, node.body); + case 159: + return visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 158: + return visitNode(cbNode, node.parameterName) || + visitNode(cbNode, node.type); + case 162: + return visitNode(cbNode, node.exprName); + case 163: + return visitNodes(cbNode, cbNodes, node.members); + case 164: + return visitNode(cbNode, node.elementType); + case 165: + return visitNodes(cbNode, cbNodes, node.elementTypes); + case 166: + case 167: + return visitNodes(cbNode, cbNodes, node.types); + case 168: + case 170: + return visitNode(cbNode, node.type); + case 171: + return visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType); + case 172: + return visitNode(cbNode, node.readonlyToken) || + visitNode(cbNode, node.typeParameter) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.type); + case 173: + return visitNode(cbNode, node.literal); + case 174: + case 175: + return visitNodes(cbNode, cbNodes, node.elements); + case 177: + return visitNodes(cbNode, cbNodes, node.elements); + case 178: + return visitNodes(cbNode, cbNodes, node.properties); + case 179: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.name); + case 180: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.argumentExpression); + case 181: + case 182: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) || + visitNodes(cbNode, cbNodes, node.arguments); + case 183: + return visitNode(cbNode, node.tag) || + visitNode(cbNode, node.template); + case 184: + return visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression); + case 185: + return visitNode(cbNode, node.expression); + case 188: + return visitNode(cbNode, node.expression); + case 189: + return visitNode(cbNode, node.expression); + case 190: + return visitNode(cbNode, node.expression); + case 192: + return visitNode(cbNode, node.operand); + case 197: + return visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression); + case 191: + return visitNode(cbNode, node.expression); + case 193: + return visitNode(cbNode, node.operand); + case 194: + return visitNode(cbNode, node.left) || + visitNode(cbNode, node.operatorToken) || + visitNode(cbNode, node.right); + case 202: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type); + case 203: + return visitNode(cbNode, node.expression); + case 204: + return visitNode(cbNode, node.name); + case 195: + return visitNode(cbNode, node.condition) || + visitNode(cbNode, node.questionToken) || + visitNode(cbNode, node.whenTrue) || + visitNode(cbNode, node.colonToken) || + visitNode(cbNode, node.whenFalse); + case 198: + return visitNode(cbNode, node.expression); + case 207: + case 234: + return visitNodes(cbNode, cbNodes, node.statements); + case 265: + return visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken); + case 208: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList); + case 227: + return visitNodes(cbNode, cbNodes, node.declarations); + case 210: + return visitNode(cbNode, node.expression); + case 211: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.thenStatement) || + visitNode(cbNode, node.elseStatement); + case 212: + return visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression); + case 213: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 214: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.condition) || + visitNode(cbNode, node.incrementor) || + visitNode(cbNode, node.statement); + case 215: + return visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 216: + return visitNode(cbNode, node.awaitModifier) || + visitNode(cbNode, node.initializer) || + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 217: + case 218: + return visitNode(cbNode, node.label); + case 219: + return visitNode(cbNode, node.expression); + case 220: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement); + case 221: + return visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock); + case 235: + return visitNodes(cbNode, cbNodes, node.clauses); + case 257: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements); + case 258: + return visitNodes(cbNode, cbNodes, node.statements); + case 222: + return visitNode(cbNode, node.label) || + visitNode(cbNode, node.statement); + case 223: + return visitNode(cbNode, node.expression); + case 224: + return visitNode(cbNode, node.tryBlock) || + visitNode(cbNode, node.catchClause) || + visitNode(cbNode, node.finallyBlock); + case 260: + return visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block); + case 147: + return visitNode(cbNode, node.expression); + case 229: + case 199: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 230: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.heritageClauses) || + visitNodes(cbNode, cbNodes, node.members); + case 231: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNode(cbNode, node.type); + case 232: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNodes(cbNode, cbNodes, node.members); + case 264: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 233: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.body); + case 237: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) || + visitNode(cbNode, node.moduleReference); + case 238: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.importClause) || + visitNode(cbNode, node.moduleSpecifier); + case 239: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings); + case 236: + return visitNode(cbNode, node.name); + case 240: + return visitNode(cbNode, node.name); + case 241: + case 245: + return visitNodes(cbNode, cbNodes, node.elements); + case 244: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.exportClause) || + visitNode(cbNode, node.moduleSpecifier); + case 242: + case 246: + return visitNode(cbNode, node.propertyName) || + visitNode(cbNode, node.name); + case 243: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression); + case 196: + return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); + case 205: + return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); + case 144: + return visitNode(cbNode, node.expression); + case 259: + return visitNodes(cbNode, cbNodes, node.types); + case 201: + return visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 248: + return visitNode(cbNode, node.expression); + case 247: + return visitNodes(cbNode, cbNodes, node.decorators); + case 289: + return visitNodes(cbNode, cbNodes, node.elements); + case 249: + return visitNode(cbNode, node.openingElement) || + visitNodes(cbNode, cbNodes, node.children) || + visitNode(cbNode, node.closingElement); + case 250: + case 251: + return visitNode(cbNode, node.tagName) || + visitNode(cbNode, node.attributes); + case 254: + return visitNodes(cbNode, cbNodes, node.properties); + case 253: + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.initializer); + case 255: + return visitNode(cbNode, node.expression); + case 256: + return visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression); + case 252: + return visitNode(cbNode, node.tagName); + case 267: + return visitNode(cbNode, node.type); + case 271: + return visitNode(cbNode, node.type); + case 270: + return visitNode(cbNode, node.type); + case 272: + return visitNode(cbNode, node.type); + case 273: + return visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 274: + return visitNode(cbNode, node.type); + case 275: + return visitNodes(cbNode, cbNodes, node.tags); + case 279: + case 284: + if (node.isNameFirst) { + return visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression); + } + else { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name); + } + case 280: + return visitNode(cbNode, node.typeExpression); + case 281: + return visitNode(cbNode, node.typeExpression); + case 277: + return visitNode(cbNode, node.typeExpression); + case 282: + return visitNodes(cbNode, cbNodes, node.typeParameters); + case 283: + if (node.typeExpression && + node.typeExpression.kind === 267) { + return visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.fullName); + } + else { + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + } + case 285: + for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { + var tag = _a[_i]; + visitNode(cbNode, tag); + } + return; + case 288: + return visitNode(cbNode, node.expression); + } + } + ts.forEachChild = forEachChild; + function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } + ts.performance.mark("beforeParse"); + var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, undefined, setParentNodes, scriptKind); + ts.performance.mark("afterParse"); + ts.performance.measure("Parse", "beforeParse", "afterParse"); + return result; + } + ts.createSourceFile = createSourceFile; + function parseIsolatedEntityName(text, languageVersion) { + return Parser.parseIsolatedEntityName(text, languageVersion); + } + ts.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + return Parser.parseJsonText(fileName, sourceText); + } + ts.parseJsonText = parseJsonText; + function isExternalModule(file) { + return file.externalModuleIndicator !== undefined; + } + ts.isExternalModule = isExternalModule; + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); + newSourceFile.flags |= (sourceFile.flags & 524288); + return newSourceFile; + } + ts.updateSourceFile = updateSourceFile; + function parseIsolatedJSDocComment(content, start, length) { + var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); + if (result && result.jsDoc) { + Parser.fixupParentReferences(result.jsDoc); + } + return result; + } + ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment; + function parseJSDocTypeExpressionForTests(content, start, length) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); + } + ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; + var Parser; + (function (Parser) { + var scanner = ts.createScanner(5, true); + var disallowInAndDecoratorContext = 2048 | 8192; + var NodeConstructor; + var TokenConstructor; + var IdentifierConstructor; + var SourceFileConstructor; + var sourceFile; + var parseDiagnostics; + var syntaxCursor; + var currentToken; + var sourceText; + var nodeCount; + var identifiers; + var identifierCount; + var parsingContext; + var contextFlags; + var parseErrorBeforeNextFinishedNode = false; + function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + scriptKind = ts.ensureScriptKind(fileName, scriptKind); + initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); + var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); + clearState(); + return result; + } + Parser.parseSourceFile = parseSourceFile; + function parseIsolatedEntityName(content, languageVersion) { + initializeState(content, languageVersion, undefined, 1); + nextToken(); + var entityName = parseEntityName(true); + var isInvalid = token() === 1 && !parseDiagnostics.length; + clearState(); + return isInvalid ? entityName : undefined; + } + Parser.parseIsolatedEntityName = parseIsolatedEntityName; + function parseJsonText(fileName, sourceText) { + initializeState(sourceText, 2, undefined, 6); + sourceFile = createSourceFile(fileName, 2, 6); + var result = sourceFile; + nextToken(); + if (token() === 1) { + sourceFile.endOfFileToken = parseTokenNode(); + } + else if (token() === 17 || + lookAhead(function () { return token() === 9; })) { + result.jsonObject = parseObjectLiteralExpression(); + sourceFile.endOfFileToken = parseExpectedToken(1, false, ts.Diagnostics.Unexpected_token); + } + else { + parseExpected(17); + } + sourceFile.parseDiagnostics = parseDiagnostics; + clearState(); + return result; + } + Parser.parseJsonText = parseJsonText; + function getLanguageVariant(scriptKind) { + return scriptKind === 4 || scriptKind === 2 || scriptKind === 1 || scriptKind === 6 ? 1 : 0; + } + function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) { + NodeConstructor = ts.objectAllocator.getNodeConstructor(); + TokenConstructor = ts.objectAllocator.getTokenConstructor(); + IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor(); + SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor(); + sourceText = _sourceText; + syntaxCursor = _syntaxCursor; + parseDiagnostics = []; + parsingContext = 0; + identifiers = ts.createMap(); + identifierCount = 0; + nodeCount = 0; + contextFlags = scriptKind === 1 || scriptKind === 2 || scriptKind === 6 ? 65536 : 0; + parseErrorBeforeNextFinishedNode = false; + scanner.setText(sourceText); + scanner.setOnError(scanError); + scanner.setScriptTarget(languageVersion); + scanner.setLanguageVariant(getLanguageVariant(scriptKind)); + } + function clearState() { + scanner.setText(""); + scanner.setOnError(undefined); + parseDiagnostics = undefined; + sourceFile = undefined; + identifiers = undefined; + syntaxCursor = undefined; + sourceText = undefined; + } + function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { + sourceFile = createSourceFile(fileName, languageVersion, scriptKind); + sourceFile.flags = contextFlags; + nextToken(); + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0, parseStatement); + ts.Debug.assert(token() === 1); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.identifiers = identifiers; + sourceFile.parseDiagnostics = parseDiagnostics; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; + } + function addJSDocComment(node) { + var comments = ts.getJSDocCommentRanges(node, sourceFile.text); + if (comments) { + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var comment = comments_2[_i]; + var jsDoc = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + if (!jsDoc) { + continue; + } + if (!node.jsDoc) { + node.jsDoc = []; + } + node.jsDoc.push(jsDoc); + } + } + return node; + } + function fixupParentReferences(rootNode) { + var parent = rootNode; + forEachChild(rootNode, visitNode); + return; + function visitNode(n) { + if (n.parent !== parent) { + n.parent = parent; + var saveParent = parent; + parent = n; + forEachChild(n, visitNode); + if (n.jsDoc) { + for (var _i = 0, _a = n.jsDoc; _i < _a.length; _i++) { + var jsDoc = _a[_i]; + jsDoc.parent = n; + parent = jsDoc; + forEachChild(jsDoc, visitNode); + } + } + parent = saveParent; + } + } + } + Parser.fixupParentReferences = fixupParentReferences; + function createSourceFile(fileName, languageVersion, scriptKind) { + var sourceFile = new SourceFileConstructor(265, 0, sourceText.length); + nodeCount++; + sourceFile.text = sourceText; + sourceFile.bindDiagnostics = []; + sourceFile.languageVersion = languageVersion; + sourceFile.fileName = ts.normalizePath(fileName); + sourceFile.languageVariant = getLanguageVariant(scriptKind); + sourceFile.isDeclarationFile = ts.fileExtensionIs(sourceFile.fileName, ".d.ts"); + sourceFile.scriptKind = scriptKind; + return sourceFile; + } + function setContextFlag(val, flag) { + if (val) { + contextFlags |= flag; + } + else { + contextFlags &= ~flag; + } + } + function setDisallowInContext(val) { + setContextFlag(val, 2048); + } + function setYieldContext(val) { + setContextFlag(val, 4096); + } + function setDecoratorContext(val) { + setContextFlag(val, 8192); + } + function setAwaitContext(val) { + setContextFlag(val, 16384); + } + function doOutsideOfContext(context, func) { + var contextFlagsToClear = context & contextFlags; + if (contextFlagsToClear) { + setContextFlag(false, contextFlagsToClear); + var result = func(); + setContextFlag(true, contextFlagsToClear); + return result; + } + return func(); + } + function doInsideOfContext(context, func) { + var contextFlagsToSet = context & ~contextFlags; + if (contextFlagsToSet) { + setContextFlag(true, contextFlagsToSet); + var result = func(); + setContextFlag(false, contextFlagsToSet); + return result; + } + return func(); + } + function allowInAnd(func) { + return doOutsideOfContext(2048, func); + } + function disallowInAnd(func) { + return doInsideOfContext(2048, func); + } + function doInYieldContext(func) { + return doInsideOfContext(4096, func); + } + function doInDecoratorContext(func) { + return doInsideOfContext(8192, func); + } + function doInAwaitContext(func) { + return doInsideOfContext(16384, func); + } + function doOutsideOfAwaitContext(func) { + return doOutsideOfContext(16384, func); + } + function doInYieldAndAwaitContext(func) { + return doInsideOfContext(4096 | 16384, func); + } + function inContext(flags) { + return (contextFlags & flags) !== 0; + } + function inYieldContext() { + return inContext(4096); + } + function inDisallowInContext() { + return inContext(2048); + } + function inDecoratorContext() { + return inContext(8192); + } + function inAwaitContext() { + return inContext(16384); + } + function parseErrorAtCurrentToken(message, arg0) { + var start = scanner.getTokenPos(); + var length = scanner.getTextPos() - start; + parseErrorAtPosition(start, length, message, arg0); + } + function parseErrorAtPosition(start, length, message, arg0) { + var lastError = ts.lastOrUndefined(parseDiagnostics); + if (!lastError || start !== lastError.start) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0)); + } + parseErrorBeforeNextFinishedNode = true; + } + function scanError(message, length) { + var pos = scanner.getTextPos(); + parseErrorAtPosition(pos, length || 0, message); + } + function getNodePos() { + return scanner.getStartPos(); + } + function getNodeEnd() { + return scanner.getStartPos(); + } + function token() { + return currentToken; + } + function nextToken() { + return currentToken = scanner.scan(); + } + function reScanGreaterToken() { + return currentToken = scanner.reScanGreaterToken(); + } + function reScanSlashToken() { + return currentToken = scanner.reScanSlashToken(); + } + function reScanTemplateToken() { + return currentToken = scanner.reScanTemplateToken(); + } + function scanJsxIdentifier() { + return currentToken = scanner.scanJsxIdentifier(); + } + function scanJsxText() { + return currentToken = scanner.scanJsxToken(); + } + function scanJsxAttributeValue() { + return currentToken = scanner.scanJsxAttributeValue(); + } + function speculationHelper(callback, isLookAhead) { + var saveToken = currentToken; + var saveParseDiagnosticsLength = parseDiagnostics.length; + var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + var saveContextFlags = contextFlags; + var result = isLookAhead + ? scanner.lookAhead(callback) + : scanner.tryScan(callback); + ts.Debug.assert(saveContextFlags === contextFlags); + if (!result || isLookAhead) { + currentToken = saveToken; + parseDiagnostics.length = saveParseDiagnosticsLength; + parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; + } + return result; + } + function lookAhead(callback) { + return speculationHelper(callback, true); + } + function tryParse(callback) { + return speculationHelper(callback, false); + } + function isIdentifier() { + if (token() === 71) { + return true; + } + if (token() === 116 && inYieldContext()) { + return false; + } + if (token() === 121 && inAwaitContext()) { + return false; + } + return token() > 107; + } + function parseExpected(kind, diagnosticMessage, shouldAdvance) { + if (shouldAdvance === void 0) { shouldAdvance = true; } + if (token() === kind) { + if (shouldAdvance) { + nextToken(); + } + return true; + } + if (diagnosticMessage) { + parseErrorAtCurrentToken(diagnosticMessage); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); + } + return false; + } + function parseOptional(t) { + if (token() === t) { + nextToken(); + return true; + } + return false; + } + function parseOptionalToken(t) { + if (token() === t) { + return parseTokenNode(); + } + return undefined; + } + function parseExpectedToken(t, reportAtCurrentPosition, diagnosticMessage, arg0) { + return parseOptionalToken(t) || + createMissingNode(t, reportAtCurrentPosition, diagnosticMessage, arg0); + } + function parseTokenNode() { + var node = createNode(token()); + nextToken(); + return finishNode(node); + } + function canParseSemicolon() { + if (token() === 25) { + return true; + } + return token() === 18 || token() === 1 || scanner.hasPrecedingLineBreak(); + } + function parseSemicolon() { + if (canParseSemicolon()) { + if (token() === 25) { + nextToken(); + } + return true; + } + else { + return parseExpected(25); + } + } + function createNode(kind, pos) { + nodeCount++; + if (!(pos >= 0)) { + pos = scanner.getStartPos(); + } + return ts.isNodeKind(kind) ? new NodeConstructor(kind, pos, pos) : + kind === 71 ? new IdentifierConstructor(kind, pos, pos) : + new TokenConstructor(kind, pos, pos); + } + function createNodeArray(elements, pos) { + var array = (elements || []); + if (!(pos >= 0)) { + pos = getNodePos(); + } + array.pos = pos; + array.end = pos; + return array; + } + function finishNode(node, end) { + node.end = end === undefined ? scanner.getStartPos() : end; + if (contextFlags) { + node.flags |= contextFlags; + } + if (parseErrorBeforeNextFinishedNode) { + parseErrorBeforeNextFinishedNode = false; + node.flags |= 32768; + } + return node; + } + function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) { + if (reportAtCurrentPosition) { + parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); + } + else { + parseErrorAtCurrentToken(diagnosticMessage, arg0); + } + var result = createNode(kind, scanner.getStartPos()); + if (kind === 71) { + result.escapedText = ""; + } + else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) { + result.text = ""; + } + return finishNode(result); + } + function internIdentifier(text) { + var identifier = identifiers.get(text); + if (identifier === undefined) { + identifiers.set(text, identifier = text); + } + return identifier; + } + function createIdentifier(isIdentifier, diagnosticMessage) { + identifierCount++; + if (isIdentifier) { + var node = createNode(71); + if (token() !== 71) { + node.originalKeywordKind = token(); + } + node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + nextToken(); + return finishNode(node); + } + return createMissingNode(71, false, diagnosticMessage || ts.Diagnostics.Identifier_expected); + } + function parseIdentifier(diagnosticMessage) { + return createIdentifier(isIdentifier(), diagnosticMessage); + } + function parseIdentifierName() { + return createIdentifier(ts.tokenIsIdentifierOrKeyword(token())); + } + function isLiteralPropertyName() { + return ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8; + } + function parsePropertyNameWorker(allowComputedPropertyNames) { + if (token() === 9 || token() === 8) { + var node = parseLiteralNode(); + node.text = internIdentifier(node.text); + return node; + } + if (allowComputedPropertyNames && token() === 21) { + return parseComputedPropertyName(); + } + return parseIdentifierName(); + } + function parsePropertyName() { + return parsePropertyNameWorker(true); + } + function parseComputedPropertyName() { + var node = createNode(144); + parseExpected(21); + node.expression = allowInAnd(parseExpression); + parseExpected(22); + return finishNode(node); + } + function parseContextualModifier(t) { + return token() === t && tryParse(nextTokenCanFollowModifier); + } + function nextTokenIsOnSameLineAndCanFollowModifier() { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + return canFollowModifier(); + } + function nextTokenCanFollowModifier() { + if (token() === 76) { + return nextToken() === 83; + } + if (token() === 84) { + nextToken(); + if (token() === 79) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 && token() !== 118 && token() !== 17 && canFollowModifier(); + } + if (token() === 79) { + return nextTokenCanFollowDefaultKeyword(); + } + if (token() === 115) { + nextToken(); + return canFollowModifier(); + } + return nextTokenIsOnSameLineAndCanFollowModifier(); + } + function parseAnyContextualModifier() { + return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); + } + function canFollowModifier() { + return token() === 21 + || token() === 17 + || token() === 39 + || token() === 24 + || isLiteralPropertyName(); + } + function nextTokenCanFollowDefaultKeyword() { + nextToken(); + return token() === 75 || token() === 89 || + token() === 109 || + (token() === 117 && lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === 120 && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + } + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { + case 0: + case 1: + case 3: + return !(token() === 25 && inErrorRecovery) && isStartOfStatement(); + case 2: + return token() === 73 || token() === 79; + case 4: + return lookAhead(isTypeMemberStart); + case 5: + return lookAhead(isClassMemberStart) || (token() === 25 && !inErrorRecovery); + case 6: + return token() === 21 || isLiteralPropertyName(); + case 12: + return token() === 21 || token() === 39 || token() === 24 || isLiteralPropertyName(); + case 17: + return isLiteralPropertyName(); + case 9: + return token() === 21 || token() === 24 || isLiteralPropertyName(); + case 7: + if (token() === 17) { + return lookAhead(isValidHeritageClauseObjectLiteral); + } + if (!inErrorRecovery) { + return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + else { + return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + } + case 8: + return isIdentifierOrPattern(); + case 10: + return token() === 26 || token() === 24 || isIdentifierOrPattern(); + case 18: + return isIdentifier(); + case 11: + case 15: + return token() === 26 || token() === 24 || isStartOfExpression(); + case 16: + return isStartOfParameter(); + case 19: + case 20: + return token() === 26 || isStartOfType(); + case 21: + return isHeritageClause(); + case 22: + return ts.tokenIsIdentifierOrKeyword(token()); + case 13: + return ts.tokenIsIdentifierOrKeyword(token()) || token() === 17; + case 14: + return true; + } + ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + } + function isValidHeritageClauseObjectLiteral() { + ts.Debug.assert(token() === 17); + if (nextToken() === 18) { + var next = nextToken(); + return next === 26 || next === 17 || next === 85 || next === 108; + } + return true; + } + function nextTokenIsIdentifier() { + nextToken(); + return isIdentifier(); + } + function nextTokenIsIdentifierOrKeyword() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()); + } + function isHeritageClauseExtendsOrImplementsKeyword() { + if (token() === 108 || + token() === 85) { + return lookAhead(nextTokenIsStartOfExpression); + } + return false; + } + function nextTokenIsStartOfExpression() { + nextToken(); + return isStartOfExpression(); + } + function isListTerminator(kind) { + if (token() === 1) { + return true; + } + switch (kind) { + case 1: + case 2: + case 4: + case 5: + case 6: + case 12: + case 9: + case 22: + return token() === 18; + case 3: + return token() === 18 || token() === 73 || token() === 79; + case 7: + return token() === 17 || token() === 85 || token() === 108; + case 8: + return isVariableDeclaratorListTerminator(); + case 18: + return token() === 29 || token() === 19 || token() === 17 || token() === 85 || token() === 108; + case 11: + return token() === 20 || token() === 25; + case 15: + case 20: + case 10: + return token() === 22; + case 16: + case 17: + return token() === 20 || token() === 22; + case 19: + return token() !== 26; + case 21: + return token() === 17 || token() === 18; + case 13: + return token() === 29 || token() === 41; + case 14: + return token() === 27 && lookAhead(nextTokenIsSlash); + } + } + function isVariableDeclaratorListTerminator() { + if (canParseSemicolon()) { + return true; + } + if (isInOrOfKeyword(token())) { + return true; + } + if (token() === 36) { + return true; + } + return false; + } + function isInSomeParsingContext() { + for (var kind = 0; kind < 23; kind++) { + if (parsingContext & (1 << kind)) { + if (isListElement(kind, true) || isListTerminator(kind)) { + return true; + } + } + } + return false; + } + function parseList(kind, parseElement) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + while (!isListTerminator(kind)) { + if (isListElement(kind, false)) { + var element = parseListElement(kind, parseElement); + result.push(element); + continue; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function parseListElement(parsingContext, parseElement) { + var node = currentNode(parsingContext); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + if (ts.nodeIsMissing(node)) { + return undefined; + } + if (node.intersectsChange) { + return undefined; + } + if (ts.containsParseError(node)) { + return undefined; + } + var nodeContextFlags = node.flags & 96256; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 5: + return isReusableClassMember(node); + case 2: + return isReusableSwitchClause(node); + case 0: + case 1: + case 3: + return isReusableStatement(node); + case 6: + return isReusableEnumMember(node); + case 4: + return isReusableTypeMember(node); + case 8: + return isReusableVariableDeclaration(node); + case 16: + return isReusableParameter(node); + case 17: + return false; + case 21: + case 18: + case 20: + case 19: + case 11: + case 12: + case 7: + case 13: + case 14: + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 152: + case 157: + case 153: + case 154: + case 149: + case 206: + return true; + case 151: + var methodDeclaration = node; + var nameIsConstructor = methodDeclaration.name.kind === 71 && + methodDeclaration.name.originalKeywordKind === 123; + return !nameIsConstructor; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 257: + case 258: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 228: + case 208: + case 207: + case 211: + case 210: + case 223: + case 219: + case 221: + case 218: + case 217: + case 215: + case 216: + case 214: + case 213: + case 220: + case 209: + case 224: + case 222: + case 212: + case 225: + case 238: + case 237: + case 244: + case 243: + case 233: + case 229: + case 230: + case 232: + case 231: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 264; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 156: + case 150: + case 157: + case 148: + case 155: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 226) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.initializer === undefined; + } + function isReusableParameter(node) { + if (node.kind !== 146) { + return false; + } + var parameter = node; + return parameter.initializer === undefined; + } + function abortParsingListOrMoveToNextToken(kind) { + parseErrorAtCurrentToken(parsingContextErrors(kind)); + if (isInSomeParsingContext()) { + return true; + } + nextToken(); + return false; + } + function parsingContextErrors(context) { + switch (context) { + case 0: return ts.Diagnostics.Declaration_or_statement_expected; + case 1: return ts.Diagnostics.Declaration_or_statement_expected; + case 2: return ts.Diagnostics.case_or_default_expected; + case 3: return ts.Diagnostics.Statement_expected; + case 17: + case 4: return ts.Diagnostics.Property_or_signature_expected; + case 5: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected; + case 6: return ts.Diagnostics.Enum_member_expected; + case 7: return ts.Diagnostics.Expression_expected; + case 8: return ts.Diagnostics.Variable_declaration_expected; + case 9: return ts.Diagnostics.Property_destructuring_pattern_expected; + case 10: return ts.Diagnostics.Array_element_destructuring_pattern_expected; + case 11: return ts.Diagnostics.Argument_expression_expected; + case 12: return ts.Diagnostics.Property_assignment_expected; + case 15: return ts.Diagnostics.Expression_or_comma_expected; + case 16: return ts.Diagnostics.Parameter_declaration_expected; + case 18: return ts.Diagnostics.Type_parameter_declaration_expected; + case 19: return ts.Diagnostics.Type_argument_expected; + case 20: return ts.Diagnostics.Type_expected; + case 21: return ts.Diagnostics.Unexpected_token_expected; + case 22: return ts.Diagnostics.Identifier_expected; + case 13: return ts.Diagnostics.Identifier_expected; + case 14: return ts.Diagnostics.Identifier_expected; + } + } + function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) { + var saveParsingContext = parsingContext; + parsingContext |= 1 << kind; + var result = createNodeArray(); + var commaStart = -1; + while (true) { + if (isListElement(kind, false)) { + var startPos = scanner.getStartPos(); + result.push(parseListElement(kind, parseElement)); + commaStart = scanner.getTokenPos(); + if (parseOptional(26)) { + continue; + } + commaStart = -1; + if (isListTerminator(kind)) { + break; + } + parseExpected(26); + if (considerSemicolonAsDelimiter && token() === 25 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + } + if (startPos === scanner.getStartPos()) { + nextToken(); + } + continue; + } + if (isListTerminator(kind)) { + break; + } + if (abortParsingListOrMoveToNextToken(kind)) { + break; + } + } + if (commaStart >= 0) { + result.hasTrailingComma = true; + } + result.end = getNodeEnd(); + parsingContext = saveParsingContext; + return result; + } + function createMissingList() { + return createNodeArray(); + } + function parseBracketedList(kind, parseElement, open, close) { + if (parseExpected(open)) { + var result = parseDelimitedList(kind, parseElement); + parseExpected(close); + return result; + } + return createMissingList(); + } + function parseEntityName(allowReservedWords, diagnosticMessage) { + var entity = allowReservedWords ? parseIdentifierName() : parseIdentifier(diagnosticMessage); + var dotPos = scanner.getStartPos(); + while (parseOptional(23)) { + if (token() === 27) { + entity.jsdocDotPos = dotPos; + break; + } + dotPos = scanner.getStartPos(); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); + } + return entity; + } + function createQualifiedName(entity, name) { + var node = createNode(143, entity.pos); + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames) { + if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) { + var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if (matchesPattern) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + } + return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); + } + function parseTemplateExpression() { + var template = createNode(196); + template.head = parseTemplateHead(); + ts.Debug.assert(template.head.kind === 14, "Template head has wrong token kind"); + var templateSpans = createNodeArray(); + do { + templateSpans.push(parseTemplateSpan()); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 15); + templateSpans.end = getNodeEnd(); + template.templateSpans = templateSpans; + return finishNode(template); + } + function parseTemplateSpan() { + var span = createNode(205); + span.expression = allowInAnd(parseExpression); + var literal; + if (token() === 18) { + reScanTemplateToken(); + literal = parseTemplateMiddleOrTemplateTail(); + } + else { + literal = parseExpectedToken(16, false, ts.Diagnostics._0_expected, ts.tokenToString(18)); + } + span.literal = literal; + return finishNode(span); + } + function parseLiteralNode() { + return parseLiteralLikeNode(token()); + } + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 14, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token()); + ts.Debug.assert(fragment.kind === 15 || fragment.kind === 16, "Template fragment has wrong token kind"); + return fragment; + } + function parseLiteralLikeNode(kind) { + var node = createNode(kind); + var text = scanner.getTokenValue(); + node.text = text; + if (scanner.hasExtendedUnicodeEscape()) { + node.hasExtendedUnicodeEscape = true; + } + if (scanner.isUnterminated()) { + node.isUnterminated = true; + } + if (node.kind === 8) { + node.numericLiteralFlags = scanner.getNumericLiteralFlags(); + } + nextToken(); + finishNode(node); + return node; + } + function parseTypeReference() { + var node = createNode(159); + node.typeName = parseEntityName(!!(contextFlags & 1048576), ts.Diagnostics.Type_expected); + if (!scanner.hasPrecedingLineBreak() && token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function parseThisTypePredicate(lhs) { + nextToken(); + var node = createNode(158, lhs.pos); + node.parameterName = lhs; + node.type = parseType(); + return finishNode(node); + } + function parseThisTypeNode() { + var node = createNode(169); + nextToken(); + return finishNode(node); + } + function parseJSDocAllType() { + var result = createNode(268); + nextToken(); + return finishNode(result); + } + function parseJSDocUnknownOrNullableType() { + var pos = scanner.getStartPos(); + nextToken(); + if (token() === 26 || + token() === 18 || + token() === 20 || + token() === 29 || + token() === 58 || + token() === 49) { + var result = createNode(269, pos); + return finishNode(result); + } + else { + var result = createNode(270, pos); + result.type = parseType(); + return finishNode(result); + } + } + function parseJSDocFunctionType() { + if (lookAhead(nextTokenIsOpenParen)) { + var result = createNode(273); + nextToken(); + fillSignature(56, 4 | 32, result); + return finishNode(result); + } + var node = createNode(159); + node.typeName = parseIdentifierName(); + return finishNode(node); + } + function parseJSDocParameter() { + var parameter = createNode(146); + if (token() === 99 || token() === 94) { + parameter.name = parseIdentifierName(); + parseExpected(56); + } + parameter.type = parseType(); + return finishNode(parameter); + } + function parseJSDocNodeWithType(kind) { + var result = createNode(kind); + nextToken(); + result.type = parseType(); + return finishNode(result); + } + function parseTypeQuery() { + var node = createNode(162); + parseExpected(103); + node.exprName = parseEntityName(true); + return finishNode(node); + } + function parseTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + if (parseOptional(85)) { + if (isStartOfType() || !isStartOfExpression()) { + node.constraint = parseType(); + } + else { + node.expression = parseUnaryExpressionOrHigher(); + } + } + if (parseOptional(58)) { + node.default = parseType(); + } + return finishNode(node); + } + function parseTypeParameters() { + if (token() === 27) { + return parseBracketedList(18, parseTypeParameter, 27, 29); + } + } + function parseParameterType() { + if (parseOptional(56)) { + return parseType(); + } + return undefined; + } + function isStartOfParameter() { + return token() === 24 || + isIdentifierOrPattern() || + ts.isModifierKind(token()) || + token() === 57 || isStartOfType(); + } + function parseParameter() { + var node = createNode(146); + if (token() === 99) { + node.name = createIdentifier(true); + node.type = parseParameterType(); + return finishNode(node); + } + node.decorators = parseDecorators(); + node.modifiers = parseModifiers(); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + if (ts.getFullWidth(node.name) === 0 && !ts.hasModifiers(node) && ts.isModifierKind(token())) { + nextToken(); + } + node.questionToken = parseOptionalToken(55); + node.type = parseParameterType(); + node.initializer = parseBindingElementInitializer(true); + return addJSDocComment(finishNode(node)); + } + function parseBindingElementInitializer(inParameter) { + return inParameter ? parseParameterInitializer() : parseNonParameterInitializer(); + } + function parseParameterInitializer() { + return parseInitializer(true); + } + function fillSignature(returnToken, flags, signature) { + if (!(flags & 32)) { + signature.typeParameters = parseTypeParameters(); + } + signature.parameters = parseParameterList(flags); + var returnTokenRequired = returnToken === 36; + if (returnTokenRequired) { + parseExpected(returnToken); + signature.type = parseTypeOrTypePredicate(); + } + else if (parseOptional(returnToken)) { + signature.type = parseTypeOrTypePredicate(); + } + else if (flags & 4) { + var start = scanner.getTokenPos(); + var length_1 = scanner.getTextPos() - start; + var backwardToken = parseOptional(returnToken === 56 ? 36 : 56); + if (backwardToken) { + signature.type = parseTypeOrTypePredicate(); + parseErrorAtPosition(start, length_1, ts.Diagnostics._0_expected, ts.tokenToString(returnToken)); + } + } + } + function parseParameterList(flags) { + if (parseExpected(19)) { + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1)); + setAwaitContext(!!(flags & 2)); + var result = parseDelimitedList(16, flags & 32 ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + if (!parseExpected(20) && (flags & 8)) { + return undefined; + } + return result; + } + return (flags & 8) ? undefined : createMissingList(); + } + function parseTypeMemberSemicolon() { + if (parseOptional(26)) { + return; + } + parseSemicolon(); + } + function parseSignatureMember(kind) { + var node = createNode(kind); + if (kind === 156) { + parseExpected(94); + } + fillSignature(56, 4, node); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(node)); + } + function isIndexSignature() { + if (token() !== 21) { + return false; + } + return lookAhead(isUnambiguouslyIndexSignature); + } + function isUnambiguouslyIndexSignature() { + nextToken(); + if (token() === 24 || token() === 22) { + return true; + } + if (ts.isModifierKind(token())) { + nextToken(); + if (isIdentifier()) { + return true; + } + } + else if (!isIdentifier()) { + return false; + } + else { + nextToken(); + } + if (token() === 56 || token() === 26) { + return true; + } + if (token() !== 55) { + return false; + } + nextToken(); + return token() === 56 || token() === 26 || token() === 22; + } + function parseIndexSignatureDeclaration(fullStart, decorators, modifiers) { + var node = createNode(157, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.parameters = parseBracketedList(16, parseParameter, 21, 22); + node.type = parseTypeAnnotation(); + parseTypeMemberSemicolon(); + return finishNode(node); + } + function parsePropertyOrMethodSignature(fullStart, modifiers) { + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (token() === 19 || token() === 27) { + var method = createNode(150, fullStart); + method.modifiers = modifiers; + method.name = name; + method.questionToken = questionToken; + fillSignature(56, 4, method); + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(method)); + } + else { + var property = createNode(148, fullStart); + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + if (token() === 58) { + property.initializer = parseNonParameterInitializer(); + } + parseTypeMemberSemicolon(); + return addJSDocComment(finishNode(property)); + } + } + function isTypeMemberStart() { + if (token() === 19 || token() === 27) { + return true; + } + var idToken; + while (ts.isModifierKind(token())) { + idToken = true; + nextToken(); + } + if (token() === 21) { + return true; + } + if (isLiteralPropertyName()) { + idToken = true; + nextToken(); + } + if (idToken) { + return token() === 19 || + token() === 27 || + token() === 55 || + token() === 56 || + token() === 26 || + canParseSemicolon(); + } + return false; + } + function parseTypeMember() { + if (token() === 19 || token() === 27) { + return parseSignatureMember(155); + } + if (token() === 94 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + return parseSignatureMember(156); + } + var fullStart = getNodePos(); + var modifiers = parseModifiers(); + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, undefined, modifiers); + } + return parsePropertyOrMethodSignature(fullStart, modifiers); + } + function nextTokenIsOpenParenOrLessThan() { + nextToken(); + return token() === 19 || token() === 27; + } + function parseTypeLiteral() { + var node = createNode(163); + node.members = parseObjectTypeMembers(); + return finishNode(node); + } + function parseObjectTypeMembers() { + var members; + if (parseExpected(17)) { + members = parseList(4, parseTypeMember); + parseExpected(18); + } + else { + members = createMissingList(); + } + return members; + } + function isStartOfMappedType() { + nextToken(); + if (token() === 131) { + nextToken(); + } + return token() === 21 && nextTokenIsIdentifier() && nextToken() === 92; + } + function parseMappedTypeParameter() { + var node = createNode(145); + node.name = parseIdentifier(); + parseExpected(92); + node.constraint = parseType(); + return finishNode(node); + } + function parseMappedType() { + var node = createNode(172); + parseExpected(17); + node.readonlyToken = parseOptionalToken(131); + parseExpected(21); + node.typeParameter = parseMappedTypeParameter(); + parseExpected(22); + node.questionToken = parseOptionalToken(55); + node.type = parseTypeAnnotation(); + parseSemicolon(); + parseExpected(18); + return finishNode(node); + } + function parseTupleType() { + var node = createNode(165); + node.elementTypes = parseBracketedList(20, parseType, 21, 22); + return finishNode(node); + } + function parseParenthesizedType() { + var node = createNode(168); + parseExpected(19); + node.type = parseType(); + parseExpected(20); + return finishNode(node); + } + function parseFunctionOrConstructorType(kind) { + var node = createNode(kind); + if (kind === 161) { + parseExpected(94); + } + fillSignature(36, 4, node); + return finishNode(node); + } + function parseKeywordAndNoDot() { + var node = parseTokenNode(); + return token() === 23 ? undefined : node; + } + function parseLiteralTypeNode() { + var node = createNode(173); + node.literal = parseSimpleUnaryExpression(); + finishNode(node); + return node; + } + function nextTokenIsNumericLiteral() { + return nextToken() === 8; + } + function parseNonArrayType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 139: + case 130: + case 134: + return tryParse(parseKeywordAndNoDot) || parseTypeReference(); + case 39: + return parseJSDocAllType(); + case 55: + return parseJSDocUnknownOrNullableType(); + case 89: + return parseJSDocFunctionType(); + case 24: + return parseJSDocNodeWithType(274); + case 51: + return parseJSDocNodeWithType(271); + case 9: + case 8: + case 101: + case 86: + return parseLiteralTypeNode(); + case 38: + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + case 105: + case 95: + return parseTokenNode(); + case 99: { + var thisKeyword = parseThisTypeNode(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + return parseThisTypePredicate(thisKeyword); + } + else { + return thisKeyword; + } + } + case 103: + return parseTypeQuery(); + case 17: + return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + case 21: + return parseTupleType(); + case 19: + return parseParenthesizedType(); + default: + return parseTypeReference(); + } + } + function isStartOfType() { + switch (token()) { + case 119: + case 136: + case 133: + case 122: + case 137: + case 105: + case 139: + case 95: + case 99: + case 103: + case 130: + case 17: + case 21: + case 27: + case 49: + case 48: + case 94: + case 9: + case 8: + case 101: + case 86: + case 134: + return true; + case 38: + return lookAhead(nextTokenIsNumericLiteral); + case 19: + return lookAhead(isStartOfParenthesizedOrFunctionType); + default: + return isIdentifier(); + } + } + function isStartOfParenthesizedOrFunctionType() { + nextToken(); + return token() === 20 || isStartOfParameter() || isStartOfType(); + } + function parseJSDocPostfixTypeOrHigher() { + var type = parseNonArrayType(); + var kind = getKind(token()); + if (!kind) + return type; + nextToken(); + var postfix = createNode(kind, type.pos); + postfix.type = type; + return finishNode(postfix); + function getKind(tokenKind) { + switch (tokenKind) { + case 58: + return contextFlags & 1048576 ? 272 : undefined; + case 51: + return 271; + case 55: + return 270; + } + } + } + function parseArrayTypeOrHigher() { + var type = parseJSDocPostfixTypeOrHigher(); + while (!scanner.hasPrecedingLineBreak() && parseOptional(21)) { + if (isStartOfType()) { + var node = createNode(171, type.pos); + node.objectType = type; + node.indexType = parseType(); + parseExpected(22); + type = finishNode(node); + } + else { + var node = createNode(164, type.pos); + node.elementType = type; + parseExpected(22); + type = finishNode(node); + } + } + return type; + } + function parseTypeOperator(operator) { + var node = createNode(170); + parseExpected(operator); + node.operator = operator; + node.type = parseTypeOperatorOrHigher(); + return finishNode(node); + } + function parseTypeOperatorOrHigher() { + switch (token()) { + case 127: + return parseTypeOperator(127); + } + return parseArrayTypeOrHigher(); + } + function parseUnionOrIntersectionType(kind, parseConstituentType, operator) { + parseOptional(operator); + var type = parseConstituentType(); + if (token() === operator) { + var types = createNodeArray([type], type.pos); + while (parseOptional(operator)) { + types.push(parseConstituentType()); + } + types.end = getNodeEnd(); + var node = createNode(kind, type.pos); + node.types = types; + type = finishNode(node); + } + return type; + } + function parseIntersectionTypeOrHigher() { + return parseUnionOrIntersectionType(167, parseTypeOperatorOrHigher, 48); + } + function parseUnionTypeOrHigher() { + return parseUnionOrIntersectionType(166, parseIntersectionTypeOrHigher, 49); + } + function isStartOfFunctionType() { + if (token() === 27) { + return true; + } + return token() === 19 && lookAhead(isUnambiguouslyStartOfFunctionType); + } + function skipParameterStart() { + if (ts.isModifierKind(token())) { + parseModifiers(); + } + if (isIdentifier() || token() === 99) { + nextToken(); + return true; + } + if (token() === 21 || token() === 17) { + var previousErrorCount = parseDiagnostics.length; + parseIdentifierOrPattern(); + return previousErrorCount === parseDiagnostics.length; + } + return false; + } + function isUnambiguouslyStartOfFunctionType() { + nextToken(); + if (token() === 20 || token() === 24) { + return true; + } + if (skipParameterStart()) { + if (token() === 56 || token() === 26 || + token() === 55 || token() === 58) { + return true; + } + if (token() === 20) { + nextToken(); + if (token() === 36) { + return true; + } + } + } + return false; + } + function parseTypeOrTypePredicate() { + var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); + var type = parseType(); + if (typePredicateVariable) { + var node = createNode(158, typePredicateVariable.pos); + node.parameterName = typePredicateVariable; + node.type = type; + return finishNode(node); + } + else { + return type; + } + } + function parseTypePredicatePrefix() { + var id = parseIdentifier(); + if (token() === 126 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + return id; + } + } + function parseType() { + return doOutsideOfContext(20480, parseTypeWorker); + } + function parseTypeWorker() { + if (isStartOfFunctionType()) { + return parseFunctionOrConstructorType(160); + } + if (token() === 94) { + return parseFunctionOrConstructorType(161); + } + return parseUnionTypeOrHigher(); + } + function parseTypeAnnotation() { + return parseOptional(56) ? parseType() : undefined; + } + function isStartOfLeftHandSideExpression() { + switch (token()) { + case 99: + case 97: + case 95: + case 101: + case 86: + case 8: + case 9: + case 13: + case 14: + case 19: + case 21: + case 17: + case 89: + case 75: + case 94: + case 41: + case 63: + case 71: + return true; + case 91: + return lookAhead(nextTokenIsOpenParenOrLessThan); + default: + return isIdentifier(); + } + } + function isStartOfExpression() { + if (isStartOfLeftHandSideExpression()) { + return true; + } + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 43: + case 44: + case 27: + case 121: + case 116: + return true; + default: + if (isBinaryOperator()) { + return true; + } + return isIdentifier(); + } + } + function isStartOfExpressionStatement() { + return token() !== 17 && + token() !== 89 && + token() !== 75 && + token() !== 57 && + isStartOfExpression(); + } + function parseExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var expr = parseAssignmentExpressionOrHigher(); + var operatorToken; + while ((operatorToken = parseOptionalToken(26))) { + expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher()); + } + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return expr; + } + function parseInitializer(inParameter) { + if (token() !== 58) { + if (scanner.hasPrecedingLineBreak() || (inParameter && token() === 17) || !isStartOfExpression()) { + return undefined; + } + } + parseExpected(58); + return parseAssignmentExpressionOrHigher(); + } + function parseAssignmentExpressionOrHigher() { + if (isYieldExpression()) { + return parseYieldExpression(); + } + var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); + if (arrowExpression) { + return arrowExpression; + } + var expr = parseBinaryExpressionOrHigher(0); + if (expr.kind === 71 && token() === 36) { + return parseSimpleArrowFunctionExpression(expr); + } + if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { + return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); + } + return parseConditionalExpressionRest(expr); + } + function isYieldExpression() { + if (token() === 116) { + if (inYieldContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function nextTokenIsIdentifierOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && isIdentifier(); + } + function parseYieldExpression() { + var node = createNode(197); + nextToken(); + if (!scanner.hasPrecedingLineBreak() && + (token() === 39 || isStartOfExpression())) { + node.asteriskToken = parseOptionalToken(39); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + else { + return finishNode(node); + } + } + function parseSimpleArrowFunctionExpression(identifier, asyncModifier) { + ts.Debug.assert(token() === 36, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + var node; + if (asyncModifier) { + node = createNode(187, asyncModifier.pos); + node.modifiers = asyncModifier; + } + else { + node = createNode(187, identifier.pos); + } + var parameter = createNode(146, identifier.pos); + parameter.name = identifier; + finishNode(parameter); + node.parameters = createNodeArray([parameter], parameter.pos); + node.parameters.end = parameter.end; + node.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + node.body = parseArrowFunctionExpressionBody(!!asyncModifier); + return addJSDocComment(finishNode(node)); + } + function tryParseParenthesizedArrowFunctionExpression() { + var triState = isParenthesizedArrowFunctionExpression(); + if (triState === 0) { + return undefined; + } + var arrowFunction = triState === 1 + ? parseParenthesizedArrowFunctionExpressionHead(true) + : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); + if (!arrowFunction) { + return undefined; + } + var isAsync = !!(ts.getModifierFlags(arrowFunction) & 256); + var lastToken = token(); + arrowFunction.equalsGreaterThanToken = parseExpectedToken(36, false, ts.Diagnostics._0_expected, "=>"); + arrowFunction.body = (lastToken === 36 || lastToken === 17) + ? parseArrowFunctionExpressionBody(isAsync) + : parseIdentifier(); + return addJSDocComment(finishNode(arrowFunction)); + } + function isParenthesizedArrowFunctionExpression() { + if (token() === 19 || token() === 27 || token() === 120) { + return lookAhead(isParenthesizedArrowFunctionExpressionWorker); + } + if (token() === 36) { + return 1; + } + return 0; + } + function isParenthesizedArrowFunctionExpressionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return 0; + } + if (token() !== 19 && token() !== 27) { + return 0; + } + } + var first = token(); + var second = nextToken(); + if (first === 19) { + if (second === 20) { + var third = nextToken(); + switch (third) { + case 36: + case 56: + case 17: + return 1; + default: + return 0; + } + } + if (second === 21 || second === 17) { + return 2; + } + if (second === 24) { + return 1; + } + if (!isIdentifier()) { + return 0; + } + if (nextToken() === 56) { + return 1; + } + return 2; + } + else { + ts.Debug.assert(first === 27); + if (!isIdentifier()) { + return 0; + } + if (sourceFile.languageVariant === 1) { + var isArrowFunctionInJsx = lookAhead(function () { + var third = nextToken(); + if (third === 85) { + var fourth = nextToken(); + switch (fourth) { + case 58: + case 29: + return false; + default: + return true; + } + } + else if (third === 26) { + return true; + } + return false; + }); + if (isArrowFunctionInJsx) { + return 1; + } + return 0; + } + return 2; + } + } + function parsePossibleParenthesizedArrowFunctionExpressionHead() { + return parseParenthesizedArrowFunctionExpressionHead(false); + } + function tryParseAsyncSimpleArrowFunctionExpression() { + if (token() === 120) { + var isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); + if (isUnParenthesizedAsyncArrowFunction === 1) { + var asyncModifier = parseModifiersForArrowFunction(); + var expr = parseBinaryExpressionOrHigher(0); + return parseSimpleArrowFunctionExpression(expr, asyncModifier); + } + } + return undefined; + } + function isUnParenthesizedAsyncArrowFunctionWorker() { + if (token() === 120) { + nextToken(); + if (scanner.hasPrecedingLineBreak() || token() === 36) { + return 0; + } + var expr = parseBinaryExpressionOrHigher(0); + if (!scanner.hasPrecedingLineBreak() && expr.kind === 71 && token() === 36) { + return 1; + } + } + return 0; + } + function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { + var node = createNode(187); + node.modifiers = parseModifiersForArrowFunction(); + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + fillSignature(56, isAsync | (allowAmbiguity ? 0 : 8), node); + if (!node.parameters) { + return undefined; + } + if (!allowAmbiguity && token() !== 36 && token() !== 17) { + return undefined; + } + return node; + } + function parseArrowFunctionExpressionBody(isAsync) { + if (token() === 17) { + return parseFunctionBlock(isAsync ? 2 : 0); + } + if (token() !== 25 && + token() !== 89 && + token() !== 75 && + isStartOfStatement() && + !isStartOfExpressionStatement()) { + return parseFunctionBlock(16 | (isAsync ? 2 : 0)); + } + return isAsync + ? doInAwaitContext(parseAssignmentExpressionOrHigher) + : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher); + } + function parseConditionalExpressionRest(leftOperand) { + var questionToken = parseOptionalToken(55); + if (!questionToken) { + return leftOperand; + } + var node = createNode(195, leftOperand.pos); + node.condition = leftOperand; + node.questionToken = questionToken; + node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); + node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); + node.whenFalse = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseBinaryExpressionOrHigher(precedence) { + var leftOperand = parseUnaryExpressionOrHigher(); + return parseBinaryExpressionRest(precedence, leftOperand); + } + function isInOrOfKeyword(t) { + return t === 92 || t === 142; + } + function parseBinaryExpressionRest(precedence, leftOperand) { + while (true) { + reScanGreaterToken(); + var newPrecedence = getBinaryOperatorPrecedence(); + var consumeCurrentOperator = token() === 40 ? + newPrecedence >= precedence : + newPrecedence > precedence; + if (!consumeCurrentOperator) { + break; + } + if (token() === 92 && inDisallowInContext()) { + break; + } + if (token() === 118) { + if (scanner.hasPrecedingLineBreak()) { + break; + } + else { + nextToken(); + leftOperand = makeAsExpression(leftOperand, parseType()); + } + } + else { + leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence)); + } + } + return leftOperand; + } + function isBinaryOperator() { + if (inDisallowInContext() && token() === 92) { + return false; + } + return getBinaryOperatorPrecedence() > 0; + } + function getBinaryOperatorPrecedence() { + switch (token()) { + case 54: + return 1; + case 53: + return 2; + case 49: + return 3; + case 50: + return 4; + case 48: + return 5; + case 32: + case 33: + case 34: + case 35: + return 6; + case 27: + case 29: + case 30: + case 31: + case 93: + case 92: + case 118: + return 7; + case 45: + case 46: + case 47: + return 8; + case 37: + case 38: + return 9; + case 39: + case 41: + case 42: + return 10; + case 40: + return 11; + } + return -1; + } + function makeBinaryExpression(left, operatorToken, right) { + var node = createNode(194, left.pos); + node.left = left; + node.operatorToken = operatorToken; + node.right = right; + return finishNode(node); + } + function makeAsExpression(left, right) { + var node = createNode(202, left.pos); + node.expression = left; + node.type = right; + return finishNode(node); + } + function parsePrefixUnaryExpression() { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseDeleteExpression() { + var node = createNode(188); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseTypeOfExpression() { + var node = createNode(189); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseVoidExpression() { + var node = createNode(190); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function isAwaitExpression() { + if (token() === 121) { + if (inAwaitContext()) { + return true; + } + return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine); + } + return false; + } + function parseAwaitExpression() { + var node = createNode(191); + nextToken(); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseUnaryExpressionOrHigher() { + if (isUpdateExpression()) { + var updateExpression = parseUpdateExpression(); + return token() === 40 ? + parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + updateExpression; + } + var unaryOperator = token(); + var simpleUnaryExpression = parseSimpleUnaryExpression(); + if (token() === 40) { + var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + if (simpleUnaryExpression.kind === 184) { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + } + else { + parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + } + } + return simpleUnaryExpression; + } + function parseSimpleUnaryExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + return parsePrefixUnaryExpression(); + case 80: + return parseDeleteExpression(); + case 103: + return parseTypeOfExpression(); + case 105: + return parseVoidExpression(); + case 27: + return parseTypeAssertion(); + case 121: + if (isAwaitExpression()) { + return parseAwaitExpression(); + } + default: + return parseUpdateExpression(); + } + } + function isUpdateExpression() { + switch (token()) { + case 37: + case 38: + case 52: + case 51: + case 80: + case 103: + case 105: + case 121: + return false; + case 27: + if (sourceFile.languageVariant !== 1) { + return false; + } + default: + return true; + } + } + function parseUpdateExpression() { + if (token() === 43 || token() === 44) { + var node = createNode(192); + node.operator = token(); + nextToken(); + node.operand = parseLeftHandSideExpressionOrHigher(); + return finishNode(node); + } + else if (sourceFile.languageVariant === 1 && token() === 27 && lookAhead(nextTokenIsIdentifierOrKeyword)) { + return parseJsxElementOrSelfClosingElement(true); + } + var expression = parseLeftHandSideExpressionOrHigher(); + ts.Debug.assert(ts.isLeftHandSideExpression(expression)); + if ((token() === 43 || token() === 44) && !scanner.hasPrecedingLineBreak()) { + var node = createNode(193, expression.pos); + node.operand = expression; + node.operator = token(); + nextToken(); + return finishNode(node); + } + return expression; + } + function parseLeftHandSideExpressionOrHigher() { + var expression; + if (token() === 91 && lookAhead(nextTokenIsOpenParenOrLessThan)) { + sourceFile.flags |= 524288; + expression = parseTokenNode(); + } + else { + expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + } + return parseCallExpressionRest(expression); + } + function parseMemberExpressionOrHigher() { + var expression = parsePrimaryExpression(); + return parseMemberExpressionRest(expression); + } + function parseSuperExpression() { + var expression = parseTokenNode(); + if (token() === 19 || token() === 23 || token() === 21) { + return expression; + } + var node = createNode(179, expression.pos); + node.expression = expression; + parseExpectedToken(23, false, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + node.name = parseRightSideOfDot(true); + return finishNode(node); + } + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { + return false; + } + if (lhs.kind === 71) { + return lhs.escapedText === rhs.escapedText; + } + if (lhs.kind === 99) { + return true; + } + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); + } + function parseJsxElementOrSelfClosingElement(inExpressionContext) { + var opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + var result; + if (opening.kind === 251) { + var node = createNode(249, opening.pos); + node.openingElement = opening; + node.children = parseJsxChildren(node.openingElement.tagName); + node.closingElement = parseJsxClosingElement(inExpressionContext); + if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { + parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + } + result = finishNode(node); + } + else { + ts.Debug.assert(opening.kind === 250); + result = opening; + } + if (inExpressionContext && token() === 27) { + var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElement(true); }); + if (invalidElement) { + parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); + var badNode = createNode(194, result.pos); + badNode.end = invalidElement.end; + badNode.left = result; + badNode.right = invalidElement; + badNode.operatorToken = createMissingNode(26, false, undefined); + badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; + return badNode; + } + } + return result; + } + function parseJsxText() { + var node = createNode(10, scanner.getStartPos()); + node.containsOnlyWhiteSpaces = currentToken === 11; + currentToken = scanner.scanJsxToken(); + return finishNode(node); + } + function parseJsxChild() { + switch (token()) { + case 10: + case 11: + return parseJsxText(); + case 17: + return parseJsxExpression(false); + case 27: + return parseJsxElementOrSelfClosingElement(false); + } + ts.Debug.fail("Unknown JSX child kind " + token()); + } + function parseJsxChildren(openingTagName) { + var result = createNodeArray(); + var saveParsingContext = parsingContext; + parsingContext |= 1 << 14; + while (true) { + currentToken = scanner.reScanJsxToken(); + if (token() === 28) { + break; + } + else if (token() === 1) { + parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); + break; + } + else if (token() === 7) { + break; + } + var child = parseJsxChild(); + if (child) { + result.push(child); + } + } + result.end = scanner.getTokenPos(); + parsingContext = saveParsingContext; + return result; + } + function parseJsxAttributes() { + var jsxAttributes = createNode(254); + jsxAttributes.properties = parseList(13, parseJsxAttribute); + return finishNode(jsxAttributes); + } + function parseJsxOpeningOrSelfClosingElement(inExpressionContext) { + var fullStart = scanner.getStartPos(); + parseExpected(27); + var tagName = parseJsxElementName(); + var attributes = parseJsxAttributes(); + var node; + if (token() === 29) { + node = createNode(251, fullStart); + scanJsxText(); + } + else { + parseExpected(41); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + node = createNode(250, fullStart); + } + node.tagName = tagName; + node.attributes = attributes; + return finishNode(node); + } + function parseJsxElementName() { + scanJsxIdentifier(); + var expression = token() === 99 ? + parseTokenNode() : parseIdentifierName(); + while (parseOptional(23)) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + } + return expression; + } + function parseJsxExpression(inExpressionContext) { + var node = createNode(256); + parseExpected(17); + if (token() !== 18) { + node.dotDotDotToken = parseOptionalToken(24); + node.expression = parseAssignmentExpressionOrHigher(); + } + if (inExpressionContext) { + parseExpected(18); + } + else { + parseExpected(18, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseJsxAttribute() { + if (token() === 17) { + return parseJsxSpreadAttribute(); + } + scanJsxIdentifier(); + var node = createNode(253); + node.name = parseIdentifierName(); + if (token() === 58) { + switch (scanJsxAttributeValue()) { + case 9: + node.initializer = parseLiteralNode(); + break; + default: + node.initializer = parseJsxExpression(true); + break; + } + } + return finishNode(node); + } + function parseJsxSpreadAttribute() { + var node = createNode(255); + parseExpected(17); + parseExpected(24); + node.expression = parseExpression(); + parseExpected(18); + return finishNode(node); + } + function parseJsxClosingElement(inExpressionContext) { + var node = createNode(252); + parseExpected(28); + node.tagName = parseJsxElementName(); + if (inExpressionContext) { + parseExpected(29); + } + else { + parseExpected(29, undefined, false); + scanJsxText(); + } + return finishNode(node); + } + function parseTypeAssertion() { + var node = createNode(184); + parseExpected(27); + node.type = parseType(); + parseExpected(29); + node.expression = parseSimpleUnaryExpression(); + return finishNode(node); + } + function parseMemberExpressionRest(expression) { + while (true) { + var dotToken = parseOptionalToken(23); + if (dotToken) { + var propertyAccess = createNode(179, expression.pos); + propertyAccess.expression = expression; + propertyAccess.name = parseRightSideOfDot(true); + expression = finishNode(propertyAccess); + continue; + } + if (token() === 51 && !scanner.hasPrecedingLineBreak()) { + nextToken(); + var nonNullExpression = createNode(203, expression.pos); + nonNullExpression.expression = expression; + expression = finishNode(nonNullExpression); + continue; + } + if (!inDecoratorContext() && parseOptional(21)) { + var indexedAccess = createNode(180, expression.pos); + indexedAccess.expression = expression; + if (token() !== 22) { + indexedAccess.argumentExpression = allowInAnd(parseExpression); + if (indexedAccess.argumentExpression.kind === 9 || indexedAccess.argumentExpression.kind === 8) { + var literal = indexedAccess.argumentExpression; + literal.text = internIdentifier(literal.text); + } + } + parseExpected(22); + expression = finishNode(indexedAccess); + continue; + } + if (token() === 13 || token() === 14) { + var tagExpression = createNode(183, expression.pos); + tagExpression.tag = expression; + tagExpression.template = token() === 13 + ? parseLiteralNode() + : parseTemplateExpression(); + expression = finishNode(tagExpression); + continue; + } + return expression; + } + } + function parseCallExpressionRest(expression) { + while (true) { + expression = parseMemberExpressionRest(expression); + if (token() === 27) { + var typeArguments = tryParse(parseTypeArgumentsInExpression); + if (!typeArguments) { + return expression; + } + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.typeArguments = typeArguments; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + else if (token() === 19) { + var callExpr = createNode(181, expression.pos); + callExpr.expression = expression; + callExpr.arguments = parseArgumentList(); + expression = finishNode(callExpr); + continue; + } + return expression; + } + } + function parseArgumentList() { + parseExpected(19); + var result = parseDelimitedList(11, parseArgumentExpression); + parseExpected(20); + return result; + } + function parseTypeArgumentsInExpression() { + if (!parseOptional(27)) { + return undefined; + } + var typeArguments = parseDelimitedList(19, parseType); + if (!parseExpected(29)) { + return undefined; + } + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; + } + function canFollowTypeArgumentsInExpression() { + switch (token()) { + case 19: + case 23: + case 20: + case 22: + case 56: + case 25: + case 55: + case 32: + case 34: + case 33: + case 35: + case 53: + case 54: + case 50: + case 48: + case 49: + case 18: + case 1: + return true; + case 26: + case 17: + default: + return false; + } + } + function parsePrimaryExpression() { + switch (token()) { + case 8: + case 9: + case 13: + return parseLiteralNode(); + case 99: + case 97: + case 95: + case 101: + case 86: + return parseTokenNode(); + case 19: + return parseParenthesizedExpression(); + case 21: + return parseArrayLiteralExpression(); + case 17: + return parseObjectLiteralExpression(); + case 120: + if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) { + break; + } + return parseFunctionExpression(); + case 75: + return parseClassExpression(); + case 89: + return parseFunctionExpression(); + case 94: + return parseNewExpression(); + case 41: + case 63: + if (reScanSlashToken() === 12) { + return parseLiteralNode(); + } + break; + case 14: + return parseTemplateExpression(); + } + return parseIdentifier(ts.Diagnostics.Expression_expected); + } + function parseParenthesizedExpression() { + var node = createNode(185); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + return addJSDocComment(finishNode(node)); + } + function parseSpreadElement() { + var node = createNode(198); + parseExpected(24); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); + } + function parseArgumentOrArrayLiteralElement() { + return token() === 24 ? parseSpreadElement() : + token() === 26 ? createNode(200) : + parseAssignmentExpressionOrHigher(); + } + function parseArgumentExpression() { + return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + } + function parseArrayLiteralExpression() { + var node = createNode(177); + parseExpected(21); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); + parseExpected(22); + return finishNode(node); + } + function tryParseAccessorDeclaration(fullStart, decorators, modifiers) { + if (parseContextualModifier(125)) { + return parseAccessorDeclaration(153, fullStart, decorators, modifiers); + } + else if (parseContextualModifier(135)) { + return parseAccessorDeclaration(154, fullStart, decorators, modifiers); + } + return undefined; + } + function parseObjectLiteralElement() { + var fullStart = scanner.getStartPos(); + var dotDotDotToken = parseOptionalToken(24); + if (dotDotDotToken) { + var spreadElement = createNode(263, fullStart); + spreadElement.expression = parseAssignmentExpressionOrHigher(); + return addJSDocComment(finishNode(spreadElement)); + } + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + var asteriskToken = parseOptionalToken(39); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); + } + var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 || token() === 18 || token() === 58); + if (isShorthandPropertyAssignment) { + var shorthandDeclaration = createNode(262, fullStart); + shorthandDeclaration.name = propertyName; + shorthandDeclaration.questionToken = questionToken; + var equalsToken = parseOptionalToken(58); + if (equalsToken) { + shorthandDeclaration.equalsToken = equalsToken; + shorthandDeclaration.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher); + } + return addJSDocComment(finishNode(shorthandDeclaration)); + } + else { + var propertyAssignment = createNode(261, fullStart); + propertyAssignment.modifiers = modifiers; + propertyAssignment.name = propertyName; + propertyAssignment.questionToken = questionToken; + parseExpected(56); + propertyAssignment.initializer = allowInAnd(parseAssignmentExpressionOrHigher); + return addJSDocComment(finishNode(propertyAssignment)); + } + } + function parseObjectLiteralExpression() { + var node = createNode(178); + parseExpected(17); + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); + parseExpected(18); + return finishNode(node); + } + function parseFunctionExpression() { + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var node = createNode(186); + node.modifiers = parseModifiers(); + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = (ts.getModifierFlags(node) & 256) ? 2 : 0; + node.name = + isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : + isGenerator ? doInYieldContext(parseOptionalIdentifier) : + isAsync ? doInAwaitContext(parseOptionalIdentifier) : + parseOptionalIdentifier(); + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlock(isGenerator | isAsync); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + return addJSDocComment(finishNode(node)); + } + function parseOptionalIdentifier() { + return isIdentifier() ? parseIdentifier() : undefined; + } + function parseNewExpression() { + var fullStart = scanner.getStartPos(); + parseExpected(94); + if (parseOptional(23)) { + var node_1 = createNode(204, fullStart); + node_1.keywordToken = 94; + node_1.name = parseIdentifierName(); + return finishNode(node_1); + } + var node = createNode(182, fullStart); + node.expression = parseMemberExpressionOrHigher(); + node.typeArguments = tryParse(parseTypeArgumentsInExpression); + if (node.typeArguments || token() === 19) { + node.arguments = parseArgumentList(); + } + return finishNode(node); + } + function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { + var node = createNode(207); + if (parseExpected(17, diagnosticMessage) || ignoreMissingOpenBrace) { + if (scanner.hasPrecedingLineBreak()) { + node.multiLine = true; + } + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseFunctionBlock(flags, diagnosticMessage) { + var savedYieldContext = inYieldContext(); + setYieldContext(!!(flags & 1)); + var savedAwaitContext = inAwaitContext(); + setAwaitContext(!!(flags & 2)); + var saveDecoratorContext = inDecoratorContext(); + if (saveDecoratorContext) { + setDecoratorContext(false); + } + var block = parseBlock(!!(flags & 16), diagnosticMessage); + if (saveDecoratorContext) { + setDecoratorContext(true); + } + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return block; + } + function parseEmptyStatement() { + var node = createNode(209); + parseExpected(25); + return finishNode(node); + } + function parseIfStatement() { + var node = createNode(211); + parseExpected(90); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.thenStatement = parseStatement(); + node.elseStatement = parseOptional(82) ? parseStatement() : undefined; + return finishNode(node); + } + function parseDoStatement() { + var node = createNode(212); + parseExpected(81); + node.statement = parseStatement(); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + parseOptional(25); + return finishNode(node); + } + function parseWhileStatement() { + var node = createNode(213); + parseExpected(106); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseForOrForInOrForOfStatement() { + var pos = getNodePos(); + parseExpected(88); + var awaitToken = parseOptionalToken(121); + parseExpected(19); + var initializer = undefined; + if (token() !== 25) { + if (token() === 104 || token() === 110 || token() === 76) { + initializer = parseVariableDeclarationList(true); + } + else { + initializer = disallowInAnd(parseExpression); + } + } + var forOrForInOrForOfStatement; + if (awaitToken ? parseExpected(142) : parseOptional(142)) { + var forOfStatement = createNode(216, pos); + forOfStatement.awaitModifier = awaitToken; + forOfStatement.initializer = initializer; + forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); + parseExpected(20); + forOrForInOrForOfStatement = forOfStatement; + } + else if (parseOptional(92)) { + var forInStatement = createNode(215, pos); + forInStatement.initializer = initializer; + forInStatement.expression = allowInAnd(parseExpression); + parseExpected(20); + forOrForInOrForOfStatement = forInStatement; + } + else { + var forStatement = createNode(214, pos); + forStatement.initializer = initializer; + parseExpected(25); + if (token() !== 25 && token() !== 20) { + forStatement.condition = allowInAnd(parseExpression); + } + parseExpected(25); + if (token() !== 20) { + forStatement.incrementor = allowInAnd(parseExpression); + } + parseExpected(20); + forOrForInOrForOfStatement = forStatement; + } + forOrForInOrForOfStatement.statement = parseStatement(); + return finishNode(forOrForInOrForOfStatement); + } + function parseBreakOrContinueStatement(kind) { + var node = createNode(kind); + parseExpected(kind === 218 ? 72 : 77); + if (!canParseSemicolon()) { + node.label = parseIdentifier(); + } + parseSemicolon(); + return finishNode(node); + } + function parseReturnStatement() { + var node = createNode(219); + parseExpected(96); + if (!canParseSemicolon()) { + node.expression = allowInAnd(parseExpression); + } + parseSemicolon(); + return finishNode(node); + } + function parseWithStatement() { + var node = createNode(220); + parseExpected(107); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + node.statement = parseStatement(); + return finishNode(node); + } + function parseCaseClause() { + var node = createNode(257); + parseExpected(73); + node.expression = allowInAnd(parseExpression); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseDefaultClause() { + var node = createNode(258); + parseExpected(79); + parseExpected(56); + node.statements = parseList(3, parseStatement); + return finishNode(node); + } + function parseCaseOrDefaultClause() { + return token() === 73 ? parseCaseClause() : parseDefaultClause(); + } + function parseSwitchStatement() { + var node = createNode(221); + parseExpected(98); + parseExpected(19); + node.expression = allowInAnd(parseExpression); + parseExpected(20); + var caseBlock = createNode(235, scanner.getStartPos()); + parseExpected(17); + caseBlock.clauses = parseList(2, parseCaseOrDefaultClause); + parseExpected(18); + node.caseBlock = finishNode(caseBlock); + return finishNode(node); + } + function parseThrowStatement() { + var node = createNode(223); + parseExpected(100); + node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + parseSemicolon(); + return finishNode(node); + } + function parseTryStatement() { + var node = createNode(224); + parseExpected(102); + node.tryBlock = parseBlock(false); + node.catchClause = token() === 74 ? parseCatchClause() : undefined; + if (!node.catchClause || token() === 87) { + parseExpected(87); + node.finallyBlock = parseBlock(false); + } + return finishNode(node); + } + function parseCatchClause() { + var result = createNode(260); + parseExpected(74); + if (parseExpected(19)) { + result.variableDeclaration = parseVariableDeclaration(); + } + parseExpected(20); + result.block = parseBlock(false); + return finishNode(result); + } + function parseDebuggerStatement() { + var node = createNode(225); + parseExpected(78); + parseSemicolon(); + return finishNode(node); + } + function parseExpressionOrLabeledStatement() { + var fullStart = scanner.getStartPos(); + var expression = allowInAnd(parseExpression); + if (expression.kind === 71 && parseOptional(56)) { + var labeledStatement = createNode(222, fullStart); + labeledStatement.label = expression; + labeledStatement.statement = parseStatement(); + return addJSDocComment(finishNode(labeledStatement)); + } + else { + var expressionStatement = createNode(210, fullStart); + expressionStatement.expression = expression; + parseSemicolon(); + return addJSDocComment(finishNode(expressionStatement)); + } + } + function nextTokenIsIdentifierOrKeywordOnSameLine() { + nextToken(); + return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsClassKeywordOnSameLine() { + nextToken(); + return token() === 75 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsFunctionKeywordOnSameLine() { + nextToken(); + return token() === 89 && !scanner.hasPrecedingLineBreak(); + } + function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { + nextToken(); + return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 || token() === 9) && !scanner.hasPrecedingLineBreak(); + } + function isDeclaration() { + while (true) { + switch (token()) { + case 104: + case 110: + case 76: + case 89: + case 75: + case 83: + return true; + case 109: + case 138: + return nextTokenIsIdentifierOnSameLine(); + case 128: + case 129: + return nextTokenIsIdentifierOrStringLiteralOnSameLine(); + case 117: + case 120: + case 124: + case 112: + case 113: + case 114: + case 131: + nextToken(); + if (scanner.hasPrecedingLineBreak()) { + return false; + } + continue; + case 141: + nextToken(); + return token() === 17 || token() === 71 || token() === 84; + case 91: + nextToken(); + return token() === 9 || token() === 39 || + token() === 17 || ts.tokenIsIdentifierOrKeyword(token()); + case 84: + nextToken(); + if (token() === 58 || token() === 39 || + token() === 17 || token() === 79 || + token() === 118) { + return true; + } + continue; + case 115: + nextToken(); + continue; + default: + return false; + } + } + } + function isStartOfDeclaration() { + return lookAhead(isDeclaration); + } + function isStartOfStatement() { + switch (token()) { + case 57: + case 25: + case 17: + case 104: + case 110: + case 89: + case 75: + case 83: + case 90: + case 81: + case 106: + case 88: + case 77: + case 72: + case 96: + case 107: + case 98: + case 100: + case 102: + case 78: + case 74: + case 87: + return true; + case 91: + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + case 76: + case 84: + return isStartOfDeclaration(); + case 120: + case 124: + case 109: + case 128: + case 129: + case 138: + case 141: + return true; + case 114: + case 112: + case 113: + case 115: + case 131: + return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + default: + return isStartOfExpression(); + } + } + function nextTokenIsIdentifierOrStartOfDestructuring() { + nextToken(); + return isIdentifier() || token() === 17 || token() === 21; + } + function isLetDeclaration() { + return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring); + } + function parseStatement() { + switch (token()) { + case 25: + return parseEmptyStatement(); + case 17: + return parseBlock(false); + case 104: + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + case 110: + if (isLetDeclaration()) { + return parseVariableStatement(scanner.getStartPos(), undefined, undefined); + } + break; + case 89: + return parseFunctionDeclaration(scanner.getStartPos(), undefined, undefined); + case 75: + return parseClassDeclaration(scanner.getStartPos(), undefined, undefined); + case 90: + return parseIfStatement(); + case 81: + return parseDoStatement(); + case 106: + return parseWhileStatement(); + case 88: + return parseForOrForInOrForOfStatement(); + case 77: + return parseBreakOrContinueStatement(217); + case 72: + return parseBreakOrContinueStatement(218); + case 96: + return parseReturnStatement(); + case 107: + return parseWithStatement(); + case 98: + return parseSwitchStatement(); + case 100: + return parseThrowStatement(); + case 102: + case 74: + case 87: + return parseTryStatement(); + case 78: + return parseDebuggerStatement(); + case 57: + return parseDeclaration(); + case 120: + case 109: + case 138: + case 128: + case 129: + case 124: + case 76: + case 83: + case 84: + case 91: + case 112: + case 113: + case 114: + case 117: + case 115: + case 131: + case 141: + if (isStartOfDeclaration()) { + return parseDeclaration(); + } + break; + } + return parseExpressionOrLabeledStatement(); + } + function parseDeclaration() { + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(); + switch (token()) { + case 104: + case 110: + case 76: + return parseVariableStatement(fullStart, decorators, modifiers); + case 89: + return parseFunctionDeclaration(fullStart, decorators, modifiers); + case 75: + return parseClassDeclaration(fullStart, decorators, modifiers); + case 109: + return parseInterfaceDeclaration(fullStart, decorators, modifiers); + case 138: + return parseTypeAliasDeclaration(fullStart, decorators, modifiers); + case 83: + return parseEnumDeclaration(fullStart, decorators, modifiers); + case 141: + case 128: + case 129: + return parseModuleDeclaration(fullStart, decorators, modifiers); + case 91: + return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers); + case 84: + nextToken(); + switch (token()) { + case 79: + case 58: + return parseExportAssignment(fullStart, decorators, modifiers); + case 118: + return parseNamespaceExportDeclaration(fullStart, decorators, modifiers); + default: + return parseExportDeclaration(fullStart, decorators, modifiers); + } + default: + if (decorators || modifiers) { + var node = createMissingNode(247, true, ts.Diagnostics.Declaration_expected); + node.pos = fullStart; + node.decorators = decorators; + node.modifiers = modifiers; + return finishNode(node); + } + } + } + function nextTokenIsIdentifierOrStringLiteralOnSameLine() { + nextToken(); + return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 9); + } + function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) { + if (token() !== 17 && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(flags, diagnosticMessage); + } + function parseArrayBindingElement() { + if (token() === 26) { + return createNode(200); + } + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + node.name = parseIdentifierOrPattern(); + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingElement() { + var node = createNode(176); + node.dotDotDotToken = parseOptionalToken(24); + var tokenIsIdentifier = isIdentifier(); + var propertyName = parsePropertyName(); + if (tokenIsIdentifier && token() !== 56) { + node.name = propertyName; + } + else { + parseExpected(56); + node.propertyName = propertyName; + node.name = parseIdentifierOrPattern(); + } + node.initializer = parseBindingElementInitializer(false); + return finishNode(node); + } + function parseObjectBindingPattern() { + var node = createNode(174); + parseExpected(17); + node.elements = parseDelimitedList(9, parseObjectBindingElement); + parseExpected(18); + return finishNode(node); + } + function parseArrayBindingPattern() { + var node = createNode(175); + parseExpected(21); + node.elements = parseDelimitedList(10, parseArrayBindingElement); + parseExpected(22); + return finishNode(node); + } + function isIdentifierOrPattern() { + return token() === 17 || token() === 21 || isIdentifier(); + } + function parseIdentifierOrPattern() { + if (token() === 21) { + return parseArrayBindingPattern(); + } + if (token() === 17) { + return parseObjectBindingPattern(); + } + return parseIdentifier(); + } + function parseVariableDeclaration() { + var node = createNode(226); + node.name = parseIdentifierOrPattern(); + node.type = parseTypeAnnotation(); + if (!isInOrOfKeyword(token())) { + node.initializer = parseInitializer(false); + } + return finishNode(node); + } + function parseVariableDeclarationList(inForStatementInitializer) { + var node = createNode(227); + switch (token()) { + case 104: + break; + case 110: + node.flags |= 1; + break; + case 76: + node.flags |= 2; + break; + default: + ts.Debug.fail(); + } + nextToken(); + if (token() === 142 && lookAhead(canFollowContextualOfKeyword)) { + node.declarations = createMissingList(); + } + else { + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(inForStatementInitializer); + node.declarations = parseDelimitedList(8, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + } + return finishNode(node); + } + function canFollowContextualOfKeyword() { + return nextTokenIsIdentifier() && nextToken() === 20; + } + function parseVariableStatement(fullStart, decorators, modifiers) { + var node = createNode(208, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.declarationList = parseVariableDeclarationList(false); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseFunctionDeclaration(fullStart, decorators, modifiers) { + var node = createNode(228, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(89); + node.asteriskToken = parseOptionalToken(39); + node.name = ts.hasModifier(node, 512) ? parseOptionalIdentifier() : parseIdentifier(); + var isGenerator = node.asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(node, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, node); + node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseConstructorDeclaration(pos, decorators, modifiers) { + var node = createNode(152, pos); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(123); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0, ts.Diagnostics.or_expected); + return addJSDocComment(finishNode(node)); + } + function parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { + var method = createNode(151, fullStart); + method.decorators = decorators; + method.modifiers = modifiers; + method.asteriskToken = asteriskToken; + method.name = name; + method.questionToken = questionToken; + var isGenerator = asteriskToken ? 1 : 0; + var isAsync = ts.hasModifier(method, 256) ? 2 : 0; + fillSignature(56, isGenerator | isAsync, method); + method.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + return addJSDocComment(finishNode(method)); + } + function parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken) { + var property = createNode(149, fullStart); + property.decorators = decorators; + property.modifiers = modifiers; + property.name = name; + property.questionToken = questionToken; + property.type = parseTypeAnnotation(); + property.initializer = ts.hasModifier(property, 32) + ? allowInAnd(parseNonParameterInitializer) + : doOutsideOfContext(4096 | 2048, parseNonParameterInitializer); + parseSemicolon(); + return addJSDocComment(finishNode(property)); + } + function parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers) { + var asteriskToken = parseOptionalToken(39); + var name = parsePropertyName(); + var questionToken = parseOptionalToken(55); + if (asteriskToken || token() === 19 || token() === 27) { + return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); + } + else { + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, questionToken); + } + } + function parseNonParameterInitializer() { + return parseInitializer(false); + } + function parseAccessorDeclaration(kind, fullStart, decorators, modifiers) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + node.name = parsePropertyName(); + fillSignature(56, 0, node); + node.body = parseFunctionBlockOrSemicolon(0); + return addJSDocComment(finishNode(node)); + } + function isClassMemberModifier(idToken) { + switch (idToken) { + case 114: + case 112: + case 113: + case 115: + case 131: + return true; + default: + return false; + } + } + function isClassMemberStart() { + var idToken; + if (token() === 57) { + return true; + } + while (ts.isModifierKind(token())) { + idToken = token(); + if (isClassMemberModifier(idToken)) { + return true; + } + nextToken(); + } + if (token() === 39) { + return true; + } + if (isLiteralPropertyName()) { + idToken = token(); + nextToken(); + } + if (token() === 21) { + return true; + } + if (idToken !== undefined) { + if (!ts.isKeyword(idToken) || idToken === 135 || idToken === 125) { + return true; + } + switch (token()) { + case 19: + case 27: + case 56: + case 58: + case 55: + return true; + default: + return canParseSemicolon(); + } + } + return false; + } + function parseDecorators() { + var decorators; + while (true) { + var decoratorStart = getNodePos(); + if (!parseOptional(57)) { + break; + } + var decorator = createNode(147, decoratorStart); + decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); + finishNode(decorator); + if (!decorators) { + decorators = createNodeArray([decorator], decoratorStart); + } + else { + decorators.push(decorator); + } + } + if (decorators) { + decorators.end = getNodeEnd(); + } + return decorators; + } + function parseModifiers(permitInvalidConstAsModifier) { + var modifiers; + while (true) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + if (token() === 76 && permitInvalidConstAsModifier) { + if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) { + break; + } + } + else { + if (!parseAnyContextualModifier()) { + break; + } + } + var modifier = finishNode(createNode(modifierKind, modifierStart)); + if (!modifiers) { + modifiers = createNodeArray([modifier], modifierStart); + } + else { + modifiers.push(modifier); + } + } + if (modifiers) { + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseModifiersForArrowFunction() { + var modifiers; + if (token() === 120) { + var modifierStart = scanner.getStartPos(); + var modifierKind = token(); + nextToken(); + var modifier = finishNode(createNode(modifierKind, modifierStart)); + modifiers = createNodeArray([modifier], modifierStart); + modifiers.end = scanner.getStartPos(); + } + return modifiers; + } + function parseClassElement() { + if (token() === 25) { + var result = createNode(206); + nextToken(); + return finishNode(result); + } + var fullStart = getNodePos(); + var decorators = parseDecorators(); + var modifiers = parseModifiers(true); + var accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + if (accessor) { + return accessor; + } + if (token() === 123) { + return parseConstructorDeclaration(fullStart, decorators, modifiers); + } + if (isIndexSignature()) { + return parseIndexSignatureDeclaration(fullStart, decorators, modifiers); + } + if (ts.tokenIsIdentifierOrKeyword(token()) || + token() === 9 || + token() === 8 || + token() === 39 || + token() === 21) { + return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); + } + if (decorators || modifiers) { + var name = createMissingNode(71, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name, undefined); + } + ts.Debug.fail("Should not have attempted to parse class member declaration."); + } + function parseClassExpression() { + return parseClassDeclarationOrExpression(scanner.getStartPos(), undefined, undefined, 199); + } + function parseClassDeclaration(fullStart, decorators, modifiers) { + return parseClassDeclarationOrExpression(fullStart, decorators, modifiers, 229); + } + function parseClassDeclarationOrExpression(fullStart, decorators, modifiers, kind) { + var node = createNode(kind, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(75); + node.name = parseNameOfClassDeclarationOrExpression(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + if (parseExpected(17)) { + node.members = parseClassMembers(); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseNameOfClassDeclarationOrExpression() { + return isIdentifier() && !isImplementsClause() + ? parseIdentifier() + : undefined; + } + function isImplementsClause() { + return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); + } + function parseHeritageClauses() { + if (isHeritageClause()) { + return parseList(21, parseHeritageClause); + } + return undefined; + } + function parseHeritageClause() { + var tok = token(); + if (tok === 85 || tok === 108) { + var node = createNode(259); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7, parseExpressionWithTypeArguments); + return finishNode(node); + } + return undefined; + } + function parseExpressionWithTypeArguments() { + var node = createNode(201); + node.expression = parseLeftHandSideExpressionOrHigher(); + if (token() === 27) { + node.typeArguments = parseBracketedList(19, parseType, 27, 29); + } + return finishNode(node); + } + function isHeritageClause() { + return token() === 85 || token() === 108; + } + function parseClassMembers() { + return parseList(5, parseClassElement); + } + function parseInterfaceDeclaration(fullStart, decorators, modifiers) { + var node = createNode(230, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(109); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + node.heritageClauses = parseHeritageClauses(); + node.members = parseObjectTypeMembers(); + return addJSDocComment(finishNode(node)); + } + function parseTypeAliasDeclaration(fullStart, decorators, modifiers) { + var node = createNode(231, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(138); + node.name = parseIdentifier(); + node.typeParameters = parseTypeParameters(); + parseExpected(58); + node.type = parseType(); + parseSemicolon(); + return addJSDocComment(finishNode(node)); + } + function parseEnumMember() { + var node = createNode(264, scanner.getStartPos()); + node.name = parsePropertyName(); + node.initializer = allowInAnd(parseNonParameterInitializer); + return addJSDocComment(finishNode(node)); + } + function parseEnumDeclaration(fullStart, decorators, modifiers) { + var node = createNode(232, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + parseExpected(83); + node.name = parseIdentifier(); + if (parseExpected(17)) { + node.members = parseDelimitedList(6, parseEnumMember); + parseExpected(18); + } + else { + node.members = createMissingList(); + } + return addJSDocComment(finishNode(node)); + } + function parseModuleBlock() { + var node = createNode(234, scanner.getStartPos()); + if (parseExpected(17)) { + node.statements = parseList(1, parseStatement); + parseExpected(18); + } + else { + node.statements = createMissingList(); + } + return finishNode(node); + } + function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { + var node = createNode(233, fullStart); + var namespaceFlag = flags & 16; + node.decorators = decorators; + node.modifiers = modifiers; + node.flags |= flags; + node.name = parseIdentifier(); + node.body = parseOptional(23) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 4 | namespaceFlag) + : parseModuleBlock(); + return addJSDocComment(finishNode(node)); + } + function parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers) { + var node = createNode(233, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (token() === 141) { + node.name = parseIdentifier(); + node.flags |= 512; + } + else { + node.name = parseLiteralNode(); + node.name.text = internIdentifier(node.name.text); + } + if (token() === 17) { + node.body = parseModuleBlock(); + } + else { + parseSemicolon(); + } + return finishNode(node); + } + function parseModuleDeclaration(fullStart, decorators, modifiers) { + var flags = 0; + if (token() === 141) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + else if (parseOptional(129)) { + flags |= 16; + } + else { + parseExpected(128); + if (token() === 9) { + return parseAmbientExternalModuleDeclaration(fullStart, decorators, modifiers); + } + } + return parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags); + } + function isExternalModuleReference() { + return token() === 132 && + lookAhead(nextTokenIsOpenParen); + } + function nextTokenIsOpenParen() { + return nextToken() === 19; + } + function nextTokenIsSlash() { + return nextToken() === 41; + } + function parseNamespaceExportDeclaration(fullStart, decorators, modifiers) { + var exportDeclaration = createNode(236, fullStart); + exportDeclaration.decorators = decorators; + exportDeclaration.modifiers = modifiers; + parseExpected(118); + parseExpected(129); + exportDeclaration.name = parseIdentifier(); + parseSemicolon(); + return finishNode(exportDeclaration); + } + function parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers) { + parseExpected(91); + var afterImportPos = scanner.getStartPos(); + var identifier; + if (isIdentifier()) { + identifier = parseIdentifier(); + if (token() !== 26 && token() !== 140) { + return parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier); + } + } + var importDeclaration = createNode(238, fullStart); + importDeclaration.decorators = decorators; + importDeclaration.modifiers = modifiers; + if (identifier || + token() === 39 || + token() === 17) { + importDeclaration.importClause = parseImportClause(identifier, afterImportPos); + parseExpected(140); + } + importDeclaration.moduleSpecifier = parseModuleSpecifier(); + parseSemicolon(); + return finishNode(importDeclaration); + } + function parseImportEqualsDeclaration(fullStart, decorators, modifiers, identifier) { + var importEqualsDeclaration = createNode(237, fullStart); + importEqualsDeclaration.decorators = decorators; + importEqualsDeclaration.modifiers = modifiers; + importEqualsDeclaration.name = identifier; + parseExpected(58); + importEqualsDeclaration.moduleReference = parseModuleReference(); + parseSemicolon(); + return addJSDocComment(finishNode(importEqualsDeclaration)); + } + function parseImportClause(identifier, fullStart) { + var importClause = createNode(239, fullStart); + if (identifier) { + importClause.name = identifier; + } + if (!importClause.name || + parseOptional(26)) { + importClause.namedBindings = token() === 39 ? parseNamespaceImport() : parseNamedImportsOrExports(241); + } + return finishNode(importClause); + } + function parseModuleReference() { + return isExternalModuleReference() + ? parseExternalModuleReference() + : parseEntityName(false); + } + function parseExternalModuleReference() { + var node = createNode(248); + parseExpected(132); + parseExpected(19); + node.expression = parseModuleSpecifier(); + parseExpected(20); + return finishNode(node); + } + function parseModuleSpecifier() { + if (token() === 9) { + var result = parseLiteralNode(); + result.text = internIdentifier(result.text); + return result; + } + else { + return parseExpression(); + } + } + function parseNamespaceImport() { + var namespaceImport = createNode(240); + parseExpected(39); + parseExpected(118); + namespaceImport.name = parseIdentifier(); + return finishNode(namespaceImport); + } + function parseNamedImportsOrExports(kind) { + var node = createNode(kind); + node.elements = parseBracketedList(22, kind === 241 ? parseImportSpecifier : parseExportSpecifier, 17, 18); + return finishNode(node); + } + function parseExportSpecifier() { + return parseImportOrExportSpecifier(246); + } + function parseImportSpecifier() { + return parseImportOrExportSpecifier(242); + } + function parseImportOrExportSpecifier(kind) { + var node = createNode(kind); + var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + var checkIdentifierStart = scanner.getTokenPos(); + var checkIdentifierEnd = scanner.getTextPos(); + var identifierName = parseIdentifierName(); + if (token() === 118) { + node.propertyName = identifierName; + parseExpected(118); + checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier(); + checkIdentifierStart = scanner.getTokenPos(); + checkIdentifierEnd = scanner.getTextPos(); + node.name = parseIdentifierName(); + } + else { + node.name = identifierName; + } + if (kind === 242 && checkIdentifierIsKeyword) { + parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + } + return finishNode(node); + } + function parseExportDeclaration(fullStart, decorators, modifiers) { + var node = createNode(244, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(39)) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + else { + node.exportClause = parseNamedImportsOrExports(245); + if (token() === 140 || (token() === 9 && !scanner.hasPrecedingLineBreak())) { + parseExpected(140); + node.moduleSpecifier = parseModuleSpecifier(); + } + } + parseSemicolon(); + return finishNode(node); + } + function parseExportAssignment(fullStart, decorators, modifiers) { + var node = createNode(243, fullStart); + node.decorators = decorators; + node.modifiers = modifiers; + if (parseOptional(58)) { + node.isExportEquals = true; + } + else { + parseExpected(79); + } + node.expression = parseAssignmentExpressionOrHigher(); + parseSemicolon(); + return finishNode(node); + } + function processReferenceComments(sourceFile) { + var triviaScanner = ts.createScanner(sourceFile.languageVersion, false, 0, sourceText); + var referencedFiles = []; + var typeReferenceDirectives = []; + var amdDependencies = []; + var amdModuleName; + var checkJsDirective = undefined; + while (true) { + var kind = triviaScanner.scan(); + if (kind !== 2) { + if (ts.isTrivia(kind)) { + continue; + } + else { + break; + } + } + var range = { + kind: triviaScanner.getToken(), + pos: triviaScanner.getTokenPos(), + end: triviaScanner.getTextPos(), + }; + var comment = sourceText.substring(range.pos, range.end); + var referencePathMatchResult = ts.getFileReferenceFromReferencePath(comment, range); + if (referencePathMatchResult) { + var fileReference = referencePathMatchResult.fileReference; + sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; + var diagnosticMessage = referencePathMatchResult.diagnosticMessage; + if (fileReference) { + if (referencePathMatchResult.isTypeReferenceDirective) { + typeReferenceDirectives.push(fileReference); + } + else { + referencedFiles.push(fileReference); + } + } + if (diagnosticMessage) { + parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage)); + } + } + else { + var amdModuleNameRegEx = /^\/\/\/\s*= 0); + ts.Debug.assert(start <= end); + ts.Debug.assert(end <= content.length); + var tags; + var comments = []; + var result; + if (!isJsDocStart(content, start)) { + return result; + } + scanner.scanRange(start + 3, length - 5, function () { + var advanceToken = true; + var state = 1; + var margin = undefined; + var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + nextJSDocToken(); + while (token() === 5) { + nextJSDocToken(); + } + if (token() === 4) { + state = 0; + indent = 0; + nextJSDocToken(); + } + while (token() !== 1) { + switch (token()) { + case 57: + if (state === 0 || state === 1) { + removeTrailingNewlines(comments); + parseTag(indent); + state = 0; + advanceToken = false; + margin = undefined; + indent++; + } + else { + pushComment(scanner.getTokenText()); + } + break; + case 4: + comments.push(scanner.getTokenText()); + state = 0; + indent = 0; + break; + case 39: + var asterisk = scanner.getTokenText(); + if (state === 1 || state === 2) { + state = 2; + pushComment(asterisk); + } + else { + state = 1; + indent += asterisk.length; + } + break; + case 71: + pushComment(scanner.getTokenText()); + state = 2; + break; + case 5: + var whitespace = scanner.getTokenText(); + if (state === 2) { + comments.push(whitespace); + } + else if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + break; + case 1: + break; + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (advanceToken) { + nextJSDocToken(); + } + else { + advanceToken = true; + } + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + result = createJSDocComment(); + }); + return result; + function removeLeadingNewlines(comments) { + while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + comments.shift(); + } + } + function removeTrailingNewlines(comments) { + while (comments.length && (comments[comments.length - 1] === "\n" || comments[comments.length - 1] === "\r")) { + comments.pop(); + } + } + function isJsDocStart(content, start) { + return content.charCodeAt(start) === 47 && + content.charCodeAt(start + 1) === 42 && + content.charCodeAt(start + 2) === 42 && + content.charCodeAt(start + 3) !== 42; + } + function createJSDocComment() { + var result = createNode(275, start); + result.tags = tags; + result.comment = comments.length ? comments.join("") : undefined; + return finishNode(result, end); + } + function skipWhitespace() { + while (token() === 5 || token() === 4) { + nextJSDocToken(); + } + } + function parseTag(indent) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getTokenPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return; + } + var tag; + if (tagName) { + switch (tagName.escapedText) { + case "augments": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + tag = parseParameterOrPropertyTag(atToken, tagName, 1); + break; + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; + } + } + else { + tag = parseUnknownTag(atToken, tagName); + } + if (!tag) { + return; + } + addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + } + function parseTagComments(indent) { + var comments = []; + var state = 0; + var margin; + function pushComment(text) { + if (!margin) { + margin = indent; + } + comments.push(text); + indent += text.length; + } + while (token() !== 57 && token() !== 1) { + switch (token()) { + case 4: + if (state >= 1) { + state = 0; + comments.push(scanner.getTokenText()); + } + indent = 0; + break; + case 57: + break; + case 5: + if (state === 2) { + pushComment(scanner.getTokenText()); + } + else { + var whitespace = scanner.getTokenText(); + if (margin !== undefined && indent + whitespace.length > margin) { + comments.push(whitespace.slice(margin - indent - 1)); + } + indent += whitespace.length; + } + break; + case 39: + if (state === 0) { + state = 1; + indent += scanner.getTokenText().length; + break; + } + default: + state = 2; + pushComment(scanner.getTokenText()); + break; + } + if (token() === 57) { + break; + } + nextJSDocToken(); + } + removeLeadingNewlines(comments); + removeTrailingNewlines(comments); + return comments; + } + function parseUnknownTag(atToken, tagName) { + var result = createNode(276, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + return finishNode(result); + } + function addTag(tag, comments) { + tag.comment = comments.join(""); + if (!tags) { + tags = createNodeArray([tag], tag.pos); + } + else { + tags.push(tag); + } + tags.end = tag.end; + } + function tryParseTypeExpression() { + return tryParse(function () { + skipWhitespace(); + if (token() !== 17) { + return undefined; + } + return parseJSDocTypeExpression(); + }); + } + function parseBracketNameInPropertyAndParamTag() { + var isBracketed = parseOptional(21); + var name = parseJSDocEntityName(); + if (isBracketed) { + skipWhitespace(); + if (parseOptionalToken(58)) { + parseExpression(); + } + parseExpected(22); + } + return { name: name, isBracketed: isBracketed }; + } + function isObjectOrObjectArrayTypeReference(node) { + switch (node.kind) { + case 134: + return true; + case 164: + return isObjectOrObjectArrayTypeReference(node.elementType); + default: + return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + function parseParameterOrPropertyTag(atToken, tagName, target) { + var typeExpression = tryParseTypeExpression(); + var isNameFirst = !typeExpression; + skipWhitespace(); + var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed; + skipWhitespace(); + if (isNameFirst) { + typeExpression = tryParseTypeExpression(); + } + var result = target === 1 ? + createNode(279, atToken.pos) : + createNode(284, atToken.pos); + var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + result.name = name; + result.isNameFirst = isNameFirst; + result.isBracketed = isBracketed; + return finishNode(result); + } + function parseNestedTypeLiteral(typeExpression, name) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var typeLiteralExpression = createNode(267, scanner.getTokenPos()); + var child = void 0; + var jsdocTypeLiteral = void 0; + var start_2 = scanner.getStartPos(); + var children = void 0; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1, name); })) { + if (!children) { + children = []; + } + children.push(child); + } + if (children) { + jsdocTypeLiteral = createNode(285, start_2); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } + } + function parseReturnTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 280; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(280, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseTypeTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 281; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var result = createNode(281, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = tryParseTypeExpression(); + return finishNode(result); + } + function parseAugmentsTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + var result = createNode(277, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeExpression = typeExpression; + return finishNode(result); + } + function parseClassTag(atToken, tagName) { + var tag = createNode(278, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName) { + var typeExpression = tryParseTypeExpression(); + skipWhitespace(); + var typedefTag = createNode(283, atToken.pos); + typedefTag.atToken = atToken; + typedefTag.tagName = tagName; + typedefTag.fullName = parseJSDocTypeNameWithNamespace(0); + if (typedefTag.fullName) { + var rightNode = typedefTag.fullName; + while (true) { + if (rightNode.kind === 71 || !rightNode.body) { + typedefTag.name = rightNode.kind === 71 ? rightNode : rightNode.name; + break; + } + rightNode = rightNode.body; + } + } + skipWhitespace(); + typedefTag.typeExpression = typeExpression; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + var child = void 0; + var jsdocTypeLiteral = void 0; + var alreadyHasTypeTag = false; + var start_3 = scanner.getStartPos(); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0); })) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(285, start_3); + } + if (child.kind === 281) { + if (alreadyHasTypeTag) { + break; + } + else { + jsdocTypeLiteral.jsDocTypeTag = child; + alreadyHasTypeTag = true; + } + } + else { + if (!jsdocTypeLiteral.jsDocPropertyTags) { + jsdocTypeLiteral.jsDocPropertyTags = []; + } + jsdocTypeLiteral.jsDocPropertyTags.push(child); + } + } + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === 164) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = finishNode(jsdocTypeLiteral); + } + } + return finishNode(typedefTag); + function parseJSDocTypeNameWithNamespace(flags) { + var pos = scanner.getTokenPos(); + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (typeNameOrNamespaceName && parseOptional(23)) { + var jsDocNamespaceNode = createNode(233, pos); + jsDocNamespaceNode.flags |= flags; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4); + return finishNode(jsDocNamespaceNode); + } + if (typeNameOrNamespaceName && flags & 4) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + } + function escapedTextsEqual(a, b) { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } + function parseChildParameterOrPropertyTag(target, name) { + var canParseTag = true; + var seenAsterisk = false; + while (true) { + nextJSDocToken(); + switch (token()) { + case 57: + if (canParseTag) { + var child = tryParseChildTag(target); + if (child && child.kind === 279 && + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case 4: + canParseTag = true; + seenAsterisk = false; + break; + case 39: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case 71: + canParseTag = false; + break; + case 1: + return false; + } + } + } + function tryParseChildTag(target) { + ts.Debug.assert(token() === 57); + var atToken = createNode(57, scanner.getStartPos()); + atToken.end = scanner.getTextPos(); + nextJSDocToken(); + var tagName = parseJSDocIdentifierName(); + skipWhitespace(); + if (!tagName) { + return false; + } + switch (tagName.escapedText) { + case "type": + return target === 0 && parseTypeTag(atToken, tagName); + case "prop": + case "property": + return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + case "arg": + case "argument": + case "param": + return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + } + return false; + } + function parseTemplateTag(atToken, tagName) { + if (ts.forEach(tags, function (t) { return t.kind === 282; })) { + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + } + var typeParameters = createNodeArray(); + while (true) { + var name = parseJSDocIdentifierName(); + skipWhitespace(); + if (!name) { + parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); + return undefined; + } + var typeParameter = createNode(145, name.pos); + typeParameter.name = name; + finishNode(typeParameter); + typeParameters.push(typeParameter); + if (token() === 26) { + nextJSDocToken(); + skipWhitespace(); + } + else { + break; + } + } + var result = createNode(282, atToken.pos); + result.atToken = atToken; + result.tagName = tagName; + result.typeParameters = typeParameters; + finishNode(result); + typeParameters.end = result.end; + return result; + } + function nextJSDocToken() { + return currentToken = scanner.scanJSDocToken(); + } + function parseJSDocEntityName() { + var entity = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + while (parseOptional(23)) { + var name = parseJSDocIdentifierName(true); + if (parseOptional(21)) { + parseExpected(22); + } + entity = createQualifiedName(entity, name); + } + return entity; + } + function parseJSDocIdentifierName(createIfMissing) { + if (createIfMissing === void 0) { createIfMissing = false; } + if (!ts.tokenIsIdentifierOrKeyword(token())) { + if (createIfMissing) { + return createMissingNode(71, true, ts.Diagnostics.Identifier_expected); + } + else { + parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); + return undefined; + } + } + var pos = scanner.getTokenPos(); + var end = scanner.getTextPos(); + var result = createNode(71, pos); + result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + finishNode(result, end); + nextJSDocToken(); + return result; + } + } + JSDocParser.parseJSDocCommentWorker = parseJSDocCommentWorker; + })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {})); + })(Parser || (Parser = {})); + var IncrementalParser; + (function (IncrementalParser) { + function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2); + checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, undefined, true, sourceFile.scriptKind); + } + var incrementalSourceFile = sourceFile; + ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); + incrementalSourceFile.hasBeenIncrementallyParsed = true; + var oldText = sourceFile.text; + var syntaxCursor = createSyntaxCursor(sourceFile); + var changeRange = extendToAffectedRange(sourceFile, textChangeRange); + checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); + ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start); + ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span)); + ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange))); + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, true, sourceFile.scriptKind); + return result; + } + IncrementalParser.updateSourceFile = updateSourceFile; + function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) { + if (isArray) { + visitArray(element); + } + else { + visitNode(element); + } + return; + function visitNode(node) { + var text = ""; + if (aggressiveChecks && shouldCheckNode(node)) { + text = oldText.substring(node.pos, node.end); + } + if (node._children) { + node._children = undefined; + } + node.pos += delta; + node.end += delta; + if (aggressiveChecks && shouldCheckNode(node)) { + ts.Debug.assert(text === newText.substring(node.pos, node.end)); + } + forEachChild(node, visitNode, visitArray); + if (node.jsDoc) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + forEachChild(jsDocComment, visitNode, visitArray); + } + } + checkNodePositions(node, aggressiveChecks); + } + function visitArray(array) { + array._children = undefined; + array.pos += delta; + array.end += delta; + for (var _i = 0, array_9 = array; _i < array_9.length; _i++) { + var node = array_9[_i]; + visitNode(node); + } + } + } + function shouldCheckNode(node) { + switch (node.kind) { + case 9: + case 8: + case 71: + return true; + } + return false; + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + ts.Debug.assert(element.pos <= element.end); + element.pos = Math.min(element.pos, changeRangeNewEnd); + if (element.end >= changeRangeOldEnd) { + element.end += delta; + } + else { + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function checkNodePositions(node, aggressiveChecks) { + if (aggressiveChecks) { + var pos_2 = node.pos; + forEachChild(node, function (child) { + ts.Debug.assert(child.pos >= pos_2); + pos_2 = child.end; + }); + ts.Debug.assert(pos_2 <= node.end); + } + } + function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) { + visitNode(sourceFile); + return; + function visitNode(child) { + ts.Debug.assert(child.pos <= child.end); + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(child, false, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + child._children = undefined; + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + checkNodePositions(child, aggressiveChecks); + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + function visitArray(array) { + ts.Debug.assert(array.pos <= array.end); + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(array, true, delta, oldText, newText, aggressiveChecks); + return; + } + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + array._children = undefined; + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var _i = 0, array_10 = array; _i < array_10.length; _i++) { + var node = array_10[_i]; + visitNode(node); + } + return; + } + ts.Debug.assert(fullEnd < changeStart); + } + } + function extendToAffectedRange(sourceFile, changeRange) { + var maxLookahead = 1; + var start = changeRange.span.start; + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + ts.Debug.assert(nearestNode.pos <= start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } + else { + ts.Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + return true; + } + } + } + function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) { + var oldText = sourceFile.text; + if (textChangeRange) { + ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + if (aggressiveChecks || ts.Debug.shouldAssert(3)) { + var oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + var newTextPrefix = newText.substr(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length); + var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1; + return { + currentNode: function (position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = undefined; + currentArrayIndex = -1; + current = undefined; + forEachChild(sourceFile, visitNode, visitArray); + return; + function visitNode(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode, visitArray); + return true; + } + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + for (var i = 0; i < array.length; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + return false; + } + } + } + })(IncrementalParser || (IncrementalParser = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ @@ -6035,11 +14861,12 @@ var ts; "umd": ts.ModuleKind.UMD, "es6": ts.ModuleKind.ES2015, "es2015": ts.ModuleKind.ES2015, + "esnext": ts.ModuleKind.ESNext }), paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, }, { name: "lib", @@ -6532,6 +15359,12 @@ var ts; category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, { name: "plugins", type: "list", @@ -6602,12 +15435,14 @@ var ts; optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; return optionNameMapCache; } - ts.getOptionNameMap = getOptionNameMap; function createCompilerDiagnosticForInvalidCustomType(opt) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return ts.createCompilerDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); } ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } function parseCustomTypeOption(opt, value, errors) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } @@ -6636,7 +15471,6 @@ var ts; var options = {}; var fileNames = []; var errors = []; - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; parseStrings(commandLine); return { options: options, @@ -6652,12 +15486,7 @@ var ts; parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === 45) { - s = s.slice(s.charCodeAt(1) === 45 ? 2 : 1).toLowerCase(); - var short = shortOptionNames.get(s); - if (short !== undefined) { - s = short; - } - var opt = optionNameMap.get(s); + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 ? 2 : 1), true); if (opt) { if (opt.isTSConfigOnly) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -6741,36 +15570,234 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } function readConfigFile(fileName, readFile) { - var text = ""; + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return typeof textOrDiagnostic === "string" ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; try { text = readFile(fileName); } catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message) }; + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); } - return parseConfigFileTextToJson(fileName, text); + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; } - ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText, stripComments) { - if (stripComments === void 0) { stripComments = true; } - try { - var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; - return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]); } - catch (e) { - return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; + return _tsconfigRootOptions; + } + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, undefined, undefined); + } + ts.convertToObject = convertToObject; + function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.jsonObject) { + return {}; + } + return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, undefined, undefined); + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = {}; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 261) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; + } + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined" && typeof value !== "undefined") { + result[keyText] = value; + if (jsonConversionNotifier && + (parentOption || knownOptions === knownRootOptions)) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (knownOptions === knownRootOptions) { + if (isValidOptionValue) { + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101: + reportInvalidOptionValue(option && option.type !== "boolean"); + return true; + case 86: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95: + reportInvalidOptionValue(!!option); + return null; + case 9: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + reportInvalidOptionValue(option && (typeof option.type === "string" && option.type !== "string")); + var text = valueExpression.text; + if (option && typeof option.type !== "string") { + var customOption = option; + if (!customOption.type.has(text)) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 178: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, undefined, undefined, undefined); + } + case 177: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + if (option) { + reportInvalidOptionValue(true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return node.kind === 9 && ts.getSourceTextOfNodeFromSourceFile(sourceFile, node).charCodeAt(0) === 34; + } + } + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + typeof option.type === "string" ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = typeof option.type === "string" ? option.type : "string"; + return typeof value === expectedType; } } - ts.parseConfigFileTextToJson = parseConfigFileTextToJson; function generateTSConfig(options, fileNames, newLine) { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var configurations = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - configurations.files = fileNames; - } + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition) { if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { @@ -6791,35 +15818,33 @@ var ts; }); } function serializeCompilerOptions(options) { - var result = {}; + var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - for (var name in options) { + var _loop_3 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - continue; + return "continue"; } var value = options[name]; var optionDefinition = optionsNameMap.get(name.toLowerCase()); if (optionDefinition) { - var customTypeMap = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap) { - result[name] = value; + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + result.set(name, value); } else { if (optionDefinition.type === "list") { - var convertedValue = []; - for (var _i = 0, _a = value; _i < _a.length; _i++) { - var element = _a[_i]; - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name] = convertedValue; + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); } else { - result[name] = getNameOfCompilerOptionValue(value, customTypeMap); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); } } } } + }; + for (var name in options) { + _loop_3(name); } return result; } @@ -6836,37 +15861,37 @@ var ts; case "object": return {}; default: - return ts.arrayFrom(option.type.keys())[0]; + return option.type.keys().next().value; } } function makePadding(paddingLength) { return Array(paddingLength + 1).join(" "); } function writeConfigurations() { - var categorizedOptions = ts.reduceLeft(ts.filter(ts.optionDeclarations, function (o) { return o.category !== ts.Diagnostics.Command_line_Options && o.category !== ts.Diagnostics.Advanced_Options; }), function (memo, value) { - if (value.category) { - var name = ts.getLocaleSpecificMessage(value.category); - (memo[name] || (memo[name] = [])).push(value); + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); } - return memo; - }, {}); + } var marginLength = 0; var seenKnownKeys = 0; var nameColumn = []; var descriptionColumn = []; - var knownKeysCount = ts.getOwnKeys(configurations.compilerOptions).length; - for (var category in categorizedOptions) { + categorizedOptions.forEach(function (options, category) { if (nameColumn.length !== 0) { nameColumn.push(""); descriptionColumn.push(""); } nameColumn.push("/* " + category + " */"); descriptionColumn.push(""); - for (var _i = 0, _a = categorizedOptions[category]; _i < _a.length; _i++) { - var option = _a[_i]; + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; var optionName = void 0; - if (ts.hasProperty(configurations.compilerOptions, option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(configurations.compilerOptions[option.name]) + ((seenKnownKeys += 1) === knownKeysCount ? "" : ","); + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); } else { optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; @@ -6875,7 +15900,7 @@ var ts; descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); marginLength = Math.max(optionName.length, marginLength); } - } + }); var tab = makePadding(2); var result = []; result.push("{"); @@ -6883,13 +15908,13 @@ var ts; for (var i = 0; i < nameColumn.length; i++) { var optionName = nameColumn[i]; var description = descriptionColumn[i]; - result.push(tab + tab + optionName + makePadding(marginLength - optionName.length + 2) + description); + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); } - if (configurations.files && configurations.files.length) { + if (fileNames.length) { result.push(tab + "},"); result.push(tab + "\"files\": ["); - for (var i = 0; i < configurations.files.length; i++) { - result.push("" + tab + tab + JSON.stringify(configurations.files[i]) + (i === configurations.files.length - 1 ? "" : ",")); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); } result.push(tab + "]"); } @@ -6901,169 +15926,250 @@ var ts; } } ts.generateTSConfig = generateTSConfig; - function removeComments(jsonText) { - var output = ""; - var scanner = ts.createScanner(1, false, 0, jsonText); - var token; - while ((token = scanner.scan()) !== 1) { - switch (token) { - case 2: - case 3: - output += scanner.getTokenText().replace(/\S/g, " "); - break; - default: - output += scanner.getTokenText(); - break; - } - } - return output; - } function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { if (existingOptions === void 0) { existingOptions = {}; } if (resolutionStack === void 0) { resolutionStack = []; } if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); var errors = []; - 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); + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName; - var jsonOptions = json["typeAcquisition"] || json["typingOptions"]; - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + setConfigFileInOptions(options, sourceFile); var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories; - var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, - typeAcquisition: typeAcquisition, - raw: json, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, errors: errors, wildcardDirectories: wildcardDirectories, - compileOnSave: compileOnSave + compileOnSave: !!raw.compileOnSave }; function getFileNames() { var fileNames; - if (ts.hasProperty(json, "files")) { - if (ts.isArray(json["files"])) { - fileNames = json["files"]; + if (ts.hasProperty(raw, "files")) { + if (ts.isArray(raw["files"])) { + fileNames = raw["files"]; if (fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); } } var includeSpecs; - if (ts.hasProperty(json, "include")) { - if (ts.isArray(json["include"])) { - includeSpecs = json["include"]; + if (ts.hasProperty(raw, "include")) { + if (ts.isArray(raw["include"])) { + includeSpecs = raw["include"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } var excludeSpecs; - if (ts.hasProperty(json, "exclude")) { - if (ts.isArray(json["exclude"])) { - excludeSpecs = json["exclude"]; + if (ts.hasProperty(raw, "exclude")) { + if (ts.isArray(raw["exclude"])) { + excludeSpecs = raw["exclude"]; } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array")); + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); } } else { - excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; - var outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"]; + var specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; + var outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - excludeSpecs.push(outDir); + specs.push(outDir); } + excludeSpecs = specs; } if (fileNames === undefined && includeSpecs === undefined) { includeSpecs = ["**/*"]; } - var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions); - if (result.fileNames.length === 0 && !ts.hasProperty(json, "files") && resolutionStack.length === 0) { + var result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || []))); } return result; } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + } } - ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - function parseConfig(json, host, basePath, configFileName, resolutionStack, errors) { + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + function parseConfig(json, sourceFile, 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 }; + return { raw: json || convertToObject(sourceFile, errors) }; } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors); + if (ownConfig.extendedConfigPath) { + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, getCanonicalFileName, configFileName, errors) { 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; + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json["typeAcquisition"] || json["typingOptions"], basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; 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); + if (typeof json.extends !== "string") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + extendedConfigPath = getExtendsConfigPath(json.extends, host, basePath, getCanonicalFileName, errors, ts.createCompilerDiagnostic); } } - return { include: include, exclude: exclude, files: files, options: options, compileOnSave: compileOnSave }; + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; } - 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")); + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, getCanonicalFileName, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + extendedConfigPath = getExtendsConfigPath(value, host, basePath, getCanonicalFileName, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, getCanonicalFileName, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); 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); + 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, extended)); + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return undefined; } } - var extendedResult = readConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (extendedResult.error) { - errors.push(extendedResult.error); + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, getCanonicalFileName, resolutionStack, errors) { + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); 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 }; + var extendedConfig = parseConfig(undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, getCanonicalFileName); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + var _a; } function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return false; + return undefined; } var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); if (typeof result === "boolean" && result) { @@ -7071,7 +16177,6 @@ var ts; } return false; } - ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -7084,15 +16189,23 @@ var ts; return { options: options, errors: errors }; } ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultCompilerOptions(configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + function getDefaultTypeAcquisition(configFileName) { var options = { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + return options; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); return options; @@ -7101,7 +16214,7 @@ var ts; if (!jsonOptions) { return; } - var optionNameMap = ts.arrayToMap(optionDeclarations, function (opt) { return opt.name; }); + var optionNameMap = commandLineOptionsToMap(optionDeclarations); for (var id in jsonOptions) { var opt = optionNameMap.get(id); if (opt) { @@ -7113,28 +16226,41 @@ var ts; } } function convertJsonOption(opt, value, basePath, errors) { - var optType = opt.type; - var expectedType = typeof optType === "string" ? optType : "string"; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); - } - else if (typeof value === expectedType) { - if (typeof optType !== "string") { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (typeof optType !== "string") { return convertJsonOptionOfCustomType(opt, value, errors); } - else { - if (opt.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; - } - } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || typeof listOption_1.element.type !== "string") { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); } return value; } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType)); + else if (typeof option.type !== "string") { + return option.type.get(value); } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; } function convertJsonOptionOfCustomType(opt, value, errors) { var key = value.toLowerCase(); @@ -7157,16 +16283,16 @@ var ts; var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions) { + function matchFileNames(fileNames, include, exclude, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { basePath = ts.normalizePath(basePath); var keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; var literalFileMap = ts.createMap(); var wildcardFileMap = ts.createMap(); if (include) { - include = validateSpecs(include, errors, false); + include = validateSpecs(include, errors, false, jsonSourceFile, "include"); } if (exclude) { - exclude = validateSpecs(exclude, errors, true); + exclude = validateSpecs(exclude, errors, true, jsonSourceFile, "exclude"); } var wildcardDirectories = getWildcardDirectories(include, exclude, basePath, host.useCaseSensitiveFileNames); var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); @@ -7178,7 +16304,7 @@ var ts; } } if (include && include.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include); _a < _b.length; _a++) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, exclude, include, undefined); _a < _b.length; _a++) { var file = _b[_a]; if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { continue; @@ -7197,24 +16323,40 @@ var ts; wildcardDirectories: wildcardDirectories }; } - function validateSpecs(specs, errors, allowTrailingRecursion) { + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { var validSpecs = []; for (var _i = 0, specs_1 = specs; _i < specs_1.length; _i++) { var spec = specs_1[_i]; if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidMultipleRecursionPatterns.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, spec)); } else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); + errors.push(createDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec)); } else { validSpecs.push(spec); } } return validSpecs; + function createDiagnostic(message, spec) { + if (jsonSourceFile && jsonSourceFile.jsonObject) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isArrayLiteralExpression(property.initializer)) { + for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { + var element = _c[_b]; + if (ts.isStringLiteral(element) && element.text === spec) { + return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); + } + } + } + } + } + return ts.createCompilerDiagnostic(message, spec); + } } function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); @@ -7240,7 +16382,7 @@ var ts; } } } - for (var key in wildcardDirectories) + for (var key in wildcardDirectories) { if (ts.hasProperty(wildcardDirectories, key)) { for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { var recursiveKey = recursiveKeys_1[_a]; @@ -7249,6 +16391,7 @@ var ts; } } } + } } return wildcardDirectories; } @@ -7292,13 +16435,45 @@ var ts; function caseInsensitiveKeyMapper(key) { return key.toLowerCase(); } + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": + return ""; + case "string": + return ""; + case "number": + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); + } + } })(ts || (ts = {})); var ts; (function (ts) { var JsTyping; (function (JsTyping) { - var safeList; - var EmptySafeList = ts.createMap(); JsTyping.nodeCoreModuleList = [ "buffer", "querystring", "events", "http", "cluster", "zlib", "os", "https", "punycode", "repl", "readline", @@ -7308,58 +16483,53 @@ var ts; "constants", "process", "v8", "timers", "console" ]; var nodeCoreModules = ts.arrayToMap(JsTyping.nodeCoreModuleList, function (x) { return x; }); - function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { - var inferredTypings = ts.createMap(); + function loadSafeList(host, safeListPath) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + return ts.createMapFromTemplate(result.config); + } + JsTyping.loadSafeList = loadSafeList; + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports) { if (!typeAcquisition || !typeAcquisition.enable) { return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { - var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); - return kind === 1 || kind === 2; + var inferredTypings = ts.createMap(); + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } }); - if (!safeList) { - var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = result.config ? ts.createMapFromTemplate(result.config) : EmptySafeList; - } var filesToWatch = []; - var searchDirs = []; - var exclude = []; - mergeTypings(typeAcquisition.include); - exclude = typeAcquisition.exclude || []; - var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); - if (projectRootPath) { - possibleSearchDirs.push(projectRootPath); - } - searchDirs = ts.deduplicate(possibleSearchDirs); - for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { - var searchDir = searchDirs_1[_i]; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { var packageJsonPath = ts.combinePaths(searchDir, "package.json"); getTypingNamesFromJson(packageJsonPath, filesToWatch); var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); getTypingNamesFromJson(bowerJsonPath, filesToWatch); var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath); - } + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); getTypingNamesFromSourceFileNames(fileNames); if (unresolvedImports) { - for (var _a = 0, unresolvedImports_1 = unresolvedImports; _a < unresolvedImports_1.length; _a++) { - var moduleId = unresolvedImports_1[_a]; - var typingName = nodeCoreModules.has(moduleId) ? "node" : moduleId; - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; })); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); } packageNameToTypingLocation.forEach(function (typingLocation, name) { if (inferredTypings.has(name) && inferredTypings.get(name) === undefined) { inferredTypings.set(name, typingLocation); } }); - for (var _b = 0, exclude_1 = exclude; _b < exclude_1.length; _b++) { - var excludeTypingName = exclude_1[_b]; - inferredTypings.delete(excludeTypingName); + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); } var newTypingNames = []; var cachedTypingPaths = []; @@ -7371,58 +16541,56 @@ var ts; newTypingNames.push(typing); } }); - return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - function mergeTypings(typingNames) { - if (!typingNames) { - return; - } - for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { - var typing = typingNames_1[_i]; - if (!inferredTypings.has(typing)) { - inferredTypings.set(typing, undefined); - } + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); } } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (host.fileExists(jsonPath)) { - filesToWatch.push(jsonPath); - } - var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); - if (result.config) { - var jsonConfig = result.config; - if (jsonConfig.dependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); - } - if (jsonConfig.devDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); - } - if (jsonConfig.optionalDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); - } - if (jsonConfig.peerDependencies) { - mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); - } + if (!host.fileExists(jsonPath)) { + return; } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); } function getTypingNamesFromSourceFileNames(fileNames) { - var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); - var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); - var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList !== EmptySafeList) { - mergeTypings(ts.filter(cleanedTypingNames, function (f) { return safeList.has(f); })); + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = inferredTypingName.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx"); }); if (hasJsxFile) { - mergeTypings(["react"]); + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); } } - function getTypingNamesFromPackagesFolder(packagesFolderPath) { + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { filesToWatch.push(packagesFolderPath); if (!host.directoryExists(packagesFolderPath)) { return; } - var typingNames = []; var fileNames = host.readDirectory(packagesFolderPath, [".json"], undefined, undefined, 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -7430,11 +16598,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - if (!result.config) { - continue; - } - var packageJson = result.config; + var result_2 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_2.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -7442,15 +16607,18 @@ var ts; if (!packageJson.name) { continue; } - if (packageJson.typings) { - var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); inferredTypings.set(packageJson.name, absolutePath); } else { - typingNames.push(packageJson.name); + packageNames.push(packageJson.name); } } - mergeTypings(typingNames); + addInferredTypings(packageNames, " Found package names"); } } JsTyping.discoverTypings = discoverTypings; @@ -7471,6 +16639,7 @@ var ts; Arguments.LogFile = "--logFile"; Arguments.EnableTelemetry = "--enableTelemetry"; Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.NpmLocation = "--npmLocation"; })(Arguments = server.Arguments || (server.Arguments = {})); function hasArgument(argumentName) { return ts.sys.args.indexOf(argumentName) >= 0; @@ -7514,10 +16683,6 @@ var ts; failedLookupLocations: failedLookupLocations }; } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - ts.moduleHasNonRelativeName = moduleHasNonRelativeName; function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); @@ -7584,11 +16749,7 @@ var ts; var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - traceEnabled: traceEnabled - }; + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled }; var typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { if (containingFile === undefined) { @@ -7695,7 +16856,7 @@ var ts; } ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createModuleResolutionCache(currentDirectory, getCanonicalFileName) { - var directoryToModuleNameMap = ts.createFileMap(); + var directoryToModuleNameMap = ts.createMap(); var moduleNameToDirectoryMap = ts.createMap(); return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName }; function getOrCreateCacheForDirectory(directoryName) { @@ -7708,7 +16869,7 @@ var ts; return perFolderCache; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { - if (!moduleHasNonRelativeName(nonRelativeModuleName)) { + if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { return undefined; } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); @@ -7719,14 +16880,14 @@ var ts; return perModuleNameCache; } function createPerModuleNameCache() { - var directoryPathMap = ts.createFileMap(); + var directoryPathMap = ts.createMap(); return { get: get, set: set }; function get(directory) { return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName)); } function set(directory, result) { var path = ts.toPath(directory, currentDirectory, getCanonicalFileName); - if (directoryPathMap.contains(path)) { + if (directoryPathMap.has(path)) { return; } directoryPathMap.set(path, result); @@ -7735,7 +16896,7 @@ var ts; var current = path; while (true) { var parent = ts.getDirectoryPath(current); - if (parent === current || directoryPathMap.contains(parent)) { + if (parent === current || directoryPathMap.has(parent)) { break; } directoryPathMap.set(parent, result); @@ -7819,7 +16980,7 @@ var ts; } ts.resolveModuleName = resolveModuleName; function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state) { - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); } else { @@ -7914,10 +17075,12 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); } - var tsExtension = ts.tryGetExtensionFromPath(candidate); - if (tsExtension !== undefined) { + var extension = ts.tryGetExtensionFromPath(candidate); + if (extension !== undefined) { var path_1 = tryFile(candidate, failedLookupLocations, false, state); - return path_1 && { path: path_1, extension: tsExtension }; + if (path_1 !== undefined) { + return { path: path_1, extension: extension }; + } } return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); }); @@ -7958,7 +17121,7 @@ var ts; if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { if (traceEnabled) { trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } @@ -8039,14 +17202,14 @@ var ts; } switch (extensions) { case Extensions.DtsOnly: - return tryExtension(".d.ts", ts.Extension.Dts); + return tryExtension(".d.ts"); case Extensions.TypeScript: - return tryExtension(".ts", ts.Extension.Ts) || tryExtension(".tsx", ts.Extension.Tsx) || tryExtension(".d.ts", ts.Extension.Dts); + return tryExtension(".ts") || tryExtension(".tsx") || tryExtension(".d.ts"); case Extensions.JavaScript: - return tryExtension(".js", ts.Extension.Js) || tryExtension(".jsx", ts.Extension.Jsx); + return tryExtension(".js") || tryExtension(".jsx"); } - function tryExtension(ext, extension) { - var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + function tryExtension(extension) { + var path = tryFile(candidate + extension, failedLookupLocations, onlyRecordFailures, state); return path && { path: path, extension: extension }; } } @@ -8116,11 +17279,11 @@ var ts; function extensionIsOk(extensions, extension) { switch (extensions) { case Extensions.JavaScript: - return extension === ts.Extension.Js || extension === ts.Extension.Jsx; + return extension === ".js" || extension === ".jsx"; case Extensions.TypeScript: - return extension === ts.Extension.Ts || extension === ts.Extension.Tsx || extension === ts.Extension.Dts; + return extension === ".ts" || extension === ".tsx" || extension === ".d.ts"; case Extensions.DtsOnly: - return extension === ts.Extension.Dts; + return extension === ".d.ts"; } } function pathToPackageJson(directory) { @@ -8172,9 +17335,10 @@ var ts; return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, failedLookupLocations, state); } } + var mangledScopedPackageSeparator = "__"; function mangleScopedPackage(moduleName, state) { if (ts.startsWith(moduleName, "@")) { - var replaceSlash = moduleName.replace(ts.directorySeparator, "__"); + var replaceSlash = moduleName.replace(ts.directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== moduleName) { var mangled = replaceSlash.slice(1); if (state.traceEnabled) { @@ -8185,6 +17349,16 @@ var ts; } return moduleName; } + function getPackageNameFromAtTypesDirectory(mangledName) { + var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); + if (withoutAtTypePrefix !== mangledName) { + return withoutAtTypePrefix.indexOf(mangledScopedPackageSeparator) !== -1 ? + "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + withoutAtTypePrefix; + } + return mangledName; + } + ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -8207,7 +17381,7 @@ var ts; return { value: resolvedUsingSettings }; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); - if (moduleHasNonRelativeName(moduleName)) { + if (!ts.isExternalModuleNameRelative(moduleName)) { var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { @@ -8366,7 +17540,10 @@ var ts; } this.processCacheLocation(req.cachePath); } - var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, req.fileNames, req.projectRootPath, this.safeListPath, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports); + if (this.safeList === undefined) { + this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath); + } + var discoverTypingsResult = ts.JsTyping.discoverTypings(this.installTypingHost, this.log.isEnabled() ? this.log.writeLine : undefined, req.fileNames, req.projectRootPath, this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports); if (this.log.isEnabled()) { this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult)); } @@ -8609,7 +17786,7 @@ var ts; }; TypingsInstaller.prototype.executeWithThrottling = function () { var _this = this; - var _loop_3 = function () { + var _loop_4 = function () { this_1.inFlightRequestCount++; var request = this_1.pendingRunRequests.pop(); this_1.installWorker(request.requestId, request.args, request.cwd, function (ok) { @@ -8620,17 +17797,16 @@ var ts; }; var this_1 = this; while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { - _loop_3(); + _loop_4(); } }; return TypingsInstaller; }()); typingsInstaller.TypingsInstaller = TypingsInstaller; function typingsName(packageName) { - return "@types/" + packageName + "@ts" + versionMajorMinor; + return "@types/" + packageName + "@ts" + ts.versionMajorMinor; } typingsInstaller.typingsName = typingsName; - var versionMajorMinor = ts.version.split(".").slice(0, 2).join("."); })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); @@ -8660,7 +17836,7 @@ var ts; }; return FileLog; }()); - function getNPMLocation(processName) { + function getDefaultNPMLocation(processName) { if (path.basename(processName).indexOf("node") === 0) { return "\"" + path.join(path.dirname(process.argv[0]), "npm") + "\""; } @@ -8692,12 +17868,16 @@ var ts; } var NodeTypingsInstaller = (function (_super) { __extends(NodeTypingsInstaller, _super); - function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, throttleLimit, log) { + function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, npmLocation, throttleLimit, log) { var _this = _super.call(this, ts.sys, globalTypingsCacheLocation, typingSafeListLocation ? ts.toPath(typingSafeListLocation, "", ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)) : ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; + _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]); + if (_this.npmPath.indexOf(" ") !== -1 && _this.npmPath[0] !== "\"") { + _this.npmPath = "\"" + _this.npmPath + "\""; + } if (_this.log.isEnabled()) { _this.log.writeLine("Process id: " + process.pid); + _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)"); } - _this.npmPath = getNPMLocation(process.argv[0]); (_this.execSync = require("child_process").execSync); _this.ensurePackageDirectoryExists(globalTypingsCacheLocation); try { @@ -8774,6 +17954,7 @@ var ts; var logFilePath = server.findArgument(server.Arguments.LogFile); var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation); var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation); + var npmLocation = server.findArgument(server.Arguments.NpmLocation); var log = new FileLog(logFilePath); if (log.isEnabled()) { process.on("uncaughtException", function (e) { @@ -8786,10 +17967,8 @@ var ts; } process.exit(0); }); - var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, 5, log); + var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, npmLocation, 5, log); installer.listen(); })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {})); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); - -//# sourceMappingURL=typingsInstaller.js.map diff --git a/lib/watchGuard.js b/lib/watchGuard.js index c9b3e69882b..11a70cd8e94 100644 --- a/lib/watchGuard.js +++ b/lib/watchGuard.js @@ -13,6 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +"use strict"; if (process.argv.length < 3) { process.exit(1); } diff --git a/package.json b/package.json index 5a3bc7ad58c..a114ac68a2d 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,6 @@ "gulp-newer": "latest", "gulp-sourcemaps": "latest", "gulp-typescript": "latest", - "into-stream": "latest", "istanbul": "latest", "jake": "latest", "merge2": "latest", diff --git a/scripts/processDiagnosticMessages.ts b/scripts/processDiagnosticMessages.ts index db7a9e0f1f2..ff4047d310d 100644 --- a/scripts/processDiagnosticMessages.ts +++ b/scripts/processDiagnosticMessages.ts @@ -6,9 +6,7 @@ interface DiagnosticDetails { isEarly?: boolean; } -interface InputDiagnosticMessageTable { - [msg: string]: DiagnosticDetails; -} +type InputDiagnosticMessageTable = ts.Map; function main(): void { var sys = ts.sys; @@ -28,101 +26,66 @@ function main(): void { var inputFilePath = sys.args[0].replace(/\\/g, "/"); var inputStr = sys.readFile(inputFilePath); - var diagnosticMessages: InputDiagnosticMessageTable = JSON.parse(inputStr); + var diagnosticMessagesJson: { [key: string]: DiagnosticDetails } = JSON.parse(inputStr); + // Check that there are no duplicates. + const seenNames = ts.createMap(); + for (const name of Object.keys(diagnosticMessagesJson)) { + if (seenNames.has(name)) + throw new Error(`Name ${name} appears twice`); + seenNames.set(name, true); + } - var names = Utilities.getObjectKeys(diagnosticMessages); - var nameMap = buildUniqueNameMap(names); + const diagnosticMessages: InputDiagnosticMessageTable = ts.createMapFromTemplate(diagnosticMessagesJson); - var infoFileOutput = buildInfoFileOutput(diagnosticMessages, nameMap); - checkForUniqueCodes(names, diagnosticMessages); + var infoFileOutput = buildInfoFileOutput(diagnosticMessages); + checkForUniqueCodes(diagnosticMessages); writeFile("diagnosticInformationMap.generated.ts", infoFileOutput); - var messageOutput = buildDiagnosticMessageOutput(diagnosticMessages, nameMap); + var messageOutput = buildDiagnosticMessageOutput(diagnosticMessages); writeFile("diagnosticMessages.generated.json", messageOutput); } -function checkForUniqueCodes(messages: string[], diagnosticTable: InputDiagnosticMessageTable) { - const originalMessageForCode: string[] = []; - let numConflicts = 0; - - for (const currentMessage of messages) { - const code = diagnosticTable[currentMessage].code; - - if (code in originalMessageForCode) { - const originalMessage = originalMessageForCode[code]; - ts.sys.write("\x1b[91m"); // High intensity red. - ts.sys.write("Error"); - ts.sys.write("\x1b[0m"); // Reset formatting. - ts.sys.write(`: Diagnostic code '${code}' conflicts between "${originalMessage}" and "${currentMessage}".`); - ts.sys.write(ts.sys.newLine + ts.sys.newLine); - - numConflicts++; - } - else { - originalMessageForCode[code] = currentMessage; - } - } - - if (numConflicts > 0) { - throw new Error(`Found ${numConflicts} conflict(s) in diagnostic codes.`); - } +function checkForUniqueCodes(diagnosticTable: InputDiagnosticMessageTable) { + const allCodes: { [key: number]: true | undefined } = []; + diagnosticTable.forEach(({ code }) => { + if (allCodes[code]) + throw new Error(`Diagnostic code ${code} appears more than once.`); + allCodes[code] = true; + }); } -function buildUniqueNameMap(names: string[]): ts.Map { - var nameMap = ts.createMap(); - - var uniqueNames = NameGenerator.ensureUniqueness(names, /* isCaseSensitive */ false, /* isFixed */ undefined); - - for (var i = 0; i < names.length; i++) { - nameMap.set(names[i], uniqueNames[i]); - } - - return nameMap; -} - -function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, nameMap: ts.Map): string { +function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable): string { var result = '// \r\n' + '/// \r\n' + '/* @internal */\r\n' + 'namespace ts {\r\n' + + " function diag(code: number, category: DiagnosticCategory, key: string, message: string): DiagnosticMessage {\r\n" + + " return { code, category, key, message };\r\n" + + " }\r\n" + ' export const Diagnostics = {\r\n'; - var names = Utilities.getObjectKeys(messageTable); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - var diagnosticDetails = messageTable[name]; - var propName = convertPropertyName(nameMap.get(name)); - - result += - ' ' + propName + - ': { code: ' + diagnosticDetails.code + - ', category: DiagnosticCategory.' + diagnosticDetails.category + - ', key: "' + createKey(propName, diagnosticDetails.code) + '"' + - ', message: "' + name.replace(/[\"]/g, '\\"') + '"' + - ' },\r\n'; - } + messageTable.forEach(({ code, category }, name) => { + const propName = convertPropertyName(name); + result += ` ${propName}: diag(${code}, DiagnosticCategory.${category}, "${createKey(propName, code)}", ${JSON.stringify(name)}),\r\n`; + }); result += ' };\r\n}'; return result; } -function buildDiagnosticMessageOutput(messageTable: InputDiagnosticMessageTable, nameMap: ts.Map): string { - var result = - '{'; - var names = Utilities.getObjectKeys(messageTable); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - var diagnosticDetails = messageTable[name]; - var propName = convertPropertyName(nameMap.get(name)); +function buildDiagnosticMessageOutput(messageTable: InputDiagnosticMessageTable): string { + let result = '{'; + messageTable.forEach(({ code }, name) => { + const propName = convertPropertyName(name); + result += `\r\n "${createKey(propName, code)}" : "${name.replace(/[\"]/g, '\\"')}",`; + }); - result += '\r\n "' + createKey(propName, diagnosticDetails.code) + '"' + ' : "' + name.replace(/[\"]/g, '\\"') + '"'; - if (i !== names.length - 1) { - result += ','; - } - } + // Shave trailing comma, then add newline and ending brace + result = result.slice(0, result.length - 1) + '\r\n}'; - result += '\r\n}'; + // Assert that we generated valid JSON + JSON.parse(result); return result; } @@ -139,7 +102,6 @@ function convertPropertyName(origName: string): string { return /\w/.test(char) ? char : "_"; }).join(""); - // get rid of all multi-underscores result = result.replace(/_+/g, "_"); @@ -152,93 +114,4 @@ function convertPropertyName(origName: string): string { return result; } -module NameGenerator { - export function ensureUniqueness(names: string[], isCaseSensitive: boolean, isFixed?: boolean[]): string[]{ - if (!isFixed) { - isFixed = names.map(() => false) - } - - var names = names.slice(); - ensureUniquenessInPlace(names, isCaseSensitive, isFixed); - return names; - } - - function ensureUniquenessInPlace(names: string[], isCaseSensitive: boolean, isFixed: boolean[]): void { - for (var i = 0; i < names.length; i++) { - var name = names[i]; - var collisionIndices = Utilities.collectMatchingIndices(name, names, isCaseSensitive); - - // We will always have one "collision" because getCollisionIndices returns the index of name itself as well; - // so if we only have one collision, then there are no issues. - if (collisionIndices.length < 2) { - continue; - } - - handleCollisions(name, names, isFixed, collisionIndices, isCaseSensitive); - } - } - - function handleCollisions(name: string, proposedNames: string[], isFixed: boolean[], collisionIndices: number[], isCaseSensitive: boolean): void { - var suffix = 1; - - for (var i = 0; i < collisionIndices.length; i++) { - var collisionIndex = collisionIndices[i]; - - if (isFixed[collisionIndex]) { - // can't do anything about this name. - continue; - } - - while (true) { - var newName = name + suffix; - suffix++; - - // Check if we've synthesized a unique name, and if so - // replace the conflicting name with the new one. - if (!proposedNames.some(name => Utilities.stringEquals(name, newName, isCaseSensitive))) { - proposedNames[collisionIndex] = newName; - break; - } - } - } - } -} - -module Utilities { - /// Return a list of all indices where a string occurs. - export function collectMatchingIndices(name: string, proposedNames: string[], isCaseSensitive: boolean): number[] { - var matchingIndices: number[] = []; - - for (var i = 0; i < proposedNames.length; i++) { - if (stringEquals(name, proposedNames[i], isCaseSensitive)) { - matchingIndices.push(i); - } - } - - return matchingIndices; - } - - export function stringEquals(s1: string, s2: string, caseSensitive: boolean): boolean { - if (caseSensitive) { - s1 = s1.toLowerCase(); - s2 = s2.toLowerCase(); - } - - return s1 == s2; - } - - // Like Object.keys - export function getObjectKeys(obj: any): string[] { - var result: string[] = []; - - for (var name in obj) { - if (obj.hasOwnProperty(name)) { - result.push(name); - } - } - - return result; - } -} - main(); \ No newline at end of file diff --git a/scripts/types/ambient.d.ts b/scripts/types/ambient.d.ts index 4f4b118c432..f99bf010198 100644 --- a/scripts/types/ambient.d.ts +++ b/scripts/types/ambient.d.ts @@ -13,13 +13,5 @@ declare module "gulp-insert" { export function transform(cb: (contents: string, file: {path: string, relative: string}) => string): NodeJS.ReadWriteStream; // file is a vinyl file } -declare module "into-stream" { - function IntoStream(content: string | Buffer | (string | Buffer)[]): NodeJS.ReadableStream; - namespace IntoStream { - export function obj(content: any): NodeJS.ReadableStream - } - export = IntoStream; -} - declare module "sorcery"; declare module "travis-fold"; diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 0b58f080fe2..2fbd0c3e141 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -242,7 +242,7 @@ namespace ts { } Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); - return getPropertyNameForKnownSymbolName(unescapeLeadingUnderscores((nameExpression).name.text)); + return getPropertyNameForKnownSymbolName(unescapeLeadingUnderscores((nameExpression).name.escapedText)); } return getEscapedTextOfIdentifierOrLiteral(name); } @@ -287,8 +287,8 @@ namespace ts { if (parentNode && parentNode.kind === SyntaxKind.VariableStatement) { if ((parentNode).declarationList.declarations.length > 0) { const nameIdentifier = (parentNode).declarationList.declarations[0].name; - if (nameIdentifier.kind === SyntaxKind.Identifier) { - nameFromParentNode = (nameIdentifier).text; + if (isIdentifier(nameIdentifier)) { + nameFromParentNode = nameIdentifier.escapedText; } } } @@ -1031,7 +1031,7 @@ namespace ts { function bindBreakOrContinueStatement(node: BreakOrContinueStatement): void { bind(node.label); if (node.label) { - const activeLabel = findActiveLabel(node.label.text); + const activeLabel = findActiveLabel(node.label.escapedText); if (activeLabel) { activeLabel.referenced = true; bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); @@ -1192,7 +1192,7 @@ namespace ts { const postStatementLabel = createBranchLabel(); bind(node.label); addAntecedent(preStatementLabel, currentFlow); - const activeLabel = pushActiveLabel(node.label.text, postStatementLabel, preStatementLabel); + const activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); bind(node.statement); popActiveLabel(); if (!activeLabel.referenced && !options.allowUnusedLabels) { @@ -1504,9 +1504,9 @@ namespace ts { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); case SyntaxKind.TypeLiteral: + case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.JsxAttributes: // Interface/Object-types always have their children added to the 'members' of // their container. They are only accessible through an instance of their @@ -1649,7 +1649,7 @@ namespace ts { const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type); addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral); typeLiteralSymbol.members = createSymbolTable(); - typeLiteralSymbol.members.set(symbol.name, symbol); + typeLiteralSymbol.members.set(symbol.escapedName, symbol); } function bindObjectLiteralExpression(node: ObjectLiteralExpression) { @@ -1680,9 +1680,9 @@ namespace ts { ? ElementKind.Property : ElementKind.Accessor; - const existingKind = seen.get(identifier.text); + const existingKind = seen.get(identifier.escapedText); if (!existingKind) { - seen.set(identifier.text, currentKind); + seen.set(identifier.escapedText, currentKind); continue; } @@ -1792,8 +1792,7 @@ namespace ts { } function isEvalOrArgumentsIdentifier(node: Node): boolean { - return node.kind === SyntaxKind.Identifier && - ((node).text === "eval" || (node).text === "arguments"); + return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode: Node, name: Node) { @@ -1804,7 +1803,7 @@ namespace ts { // otherwise report generic error message. const span = getErrorSpanForNode(file, name); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, - getStrictModeEvalOrArgumentsMessage(contextNode), unescapeLeadingUnderscores(identifier.text))); + getStrictModeEvalOrArgumentsMessage(contextNode), unescapeLeadingUnderscores(identifier.escapedText))); } } } @@ -2104,8 +2103,9 @@ namespace ts { case SyntaxKind.ConstructorType: return bindFunctionOrConstructorType(node); case SyntaxKind.TypeLiteral: + case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.MappedType: - return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode); + return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral); case SyntaxKind.ObjectLiteralExpression: return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: @@ -2163,13 +2163,17 @@ namespace ts { case SyntaxKind.ModuleBlock: return updateStrictModeStatementList((node).statements); + case SyntaxKind.JSDocParameterTag: + if (node.parent.kind !== SyntaxKind.JSDocTypeLiteral) { + break; + } + // falls through case SyntaxKind.JSDocPropertyTag: - return declareSymbolAndAddToSymbolTable(node as JSDocPropertyTag, - (node as JSDocPropertyTag).isBracketed || ((node as JSDocPropertyTag).typeExpression && (node as JSDocPropertyTag).typeExpression.type.kind === SyntaxKind.JSDocOptionalType) ? - SymbolFlags.Property | SymbolFlags.Optional : SymbolFlags.Property, - SymbolFlags.PropertyExcludes); - case SyntaxKind.JSDocTypeLiteral: - return bindAnonymousTypeWorker(node as JSDocTypeLiteral); + const propTag = node as JSDocPropertyLikeTag; + const flags = propTag.isBracketed || propTag.typeExpression.type.kind === SyntaxKind.JSDocOptionalType ? + SymbolFlags.Property | SymbolFlags.Optional : + SymbolFlags.Property; + return declareSymbolAndAddToSymbolTable(propTag, flags, SymbolFlags.PropertyExcludes); case SyntaxKind.JSDocTypedefTag: { const { fullName } = node as JSDocTypedefTag; if (!fullName || fullName.kind === SyntaxKind.Identifier) { @@ -2295,14 +2299,10 @@ namespace ts { } function isNameOfExportsOrModuleExportsAliasDeclaration(node: Node) { - if (node.kind === SyntaxKind.Identifier) { - const symbol = lookupSymbolForName((node).text); - if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === SyntaxKind.VariableDeclaration) { - const declaration = symbol.valueDeclaration as VariableDeclaration; - if (declaration.initializer) { - return isExportsOrModuleExportsOrAliasOrAssignment(declaration.initializer); - } - } + if (isIdentifier(node)) { + const symbol = lookupSymbolForName(node.escapedText); + return symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && + symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(symbol.valueDeclaration.initializer); } return false; } @@ -2369,7 +2369,7 @@ namespace ts { constructorFunction.parent = classPrototype; classPrototype.parent = leftSideOfAssignment; - bindPropertyAssignment(constructorFunction.text, leftSideOfAssignment, /*isPrototypeProperty*/ true); + bindPropertyAssignment(constructorFunction.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ true); } function bindStaticPropertyAssignment(node: BinaryExpression) { @@ -2391,7 +2391,7 @@ namespace ts { bindExportsPropertyAssignment(node); } else { - bindPropertyAssignment(target.text, leftSideOfAssignment, /*isPrototypeProperty*/ false); + bindPropertyAssignment(target.escapedText, leftSideOfAssignment, /*isPrototypeProperty*/ false); } } @@ -2432,11 +2432,11 @@ namespace ts { bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); } else { - const bindingName = node.name ? node.name.text : InternalSymbolName.Class; + const bindingName = node.name ? node.name.escapedText : InternalSymbolName.Class; bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName); // Add name of class expression into the map for semantic classifier if (node.name) { - classifiableNames.set(node.name.text, true); + classifiableNames.set(node.name.escapedText, true); } } @@ -2452,14 +2452,14 @@ namespace ts { // module might have an exported variable called 'prototype'. We can't allow that as // that would clash with the built-in 'prototype' for the class. const prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype" as __String); - const symbolExport = symbol.exports.get(prototypeSymbol.name); + const symbolExport = symbol.exports.get(prototypeSymbol.escapedName); if (symbolExport) { if (node.name) { node.name.parent = node; } - file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(prototypeSymbol.name))); + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(prototypeSymbol.escapedName))); } - symbol.exports.set(prototypeSymbol.name, prototypeSymbol); + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); prototypeSymbol.parent = symbol; } @@ -2545,7 +2545,7 @@ namespace ts { node.flowNode = currentFlow; } checkStrictModeFunctionName(node); - const bindingName = node.name ? node.name.text : InternalSymbolName.Function; + const bindingName = node.name ? node.name.escapedText : InternalSymbolName.Function; return bindAnonymousDeclaration(node, SymbolFlags.Function, bindingName); } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 043e9755ce2..a8af11e7803 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -212,6 +212,7 @@ namespace ts { return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: (name, symbol) => tryGetMemberInModuleExports(escapeLeadingUnderscores(name), symbol), + tryGetMemberInModuleExportsAndProperties: (name, symbol) => tryGetMemberInModuleExportsAndProperties(escapeLeadingUnderscores(name), symbol), tryFindAmbientModuleWithoutAugmentations: moduleName => { // we deliberately exclude augmentations // since we are only interested in declarations of the module itself @@ -490,7 +491,7 @@ namespace ts { } const builtinGlobals = createSymbolTable(); - builtinGlobals.set(undefinedSymbol.name, undefinedSymbol); + builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); initializeTypeChecker(); @@ -502,7 +503,7 @@ namespace ts { if (compilerOptions.jsxFactory) { _jsxFactoryEntity = parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).text; + _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -567,7 +568,7 @@ namespace ts { } function cloneSymbol(symbol: Symbol): Symbol { - const result = createSymbol(symbol.flags, symbol.name); + const result = createSymbol(symbol.flags, symbol.escapedName); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -935,7 +936,7 @@ namespace ts { // name of that export default matches. if (result = moduleExports.get("default" as __String)) { const localSymbol = getLocalSymbolForExportDefault(result); - if (localSymbol && (result.flags & meaning) && localSymbol.name === name) { + if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) { break loop; } result = undefined; @@ -1007,7 +1008,7 @@ namespace ts { } if (location.kind === SyntaxKind.ClassExpression && meaning & SymbolFlags.Class) { const className = (location).name; - if (className && name === className.text) { + if (className && name === className.escapedText) { result = location.symbol; break loop; } @@ -1052,7 +1053,7 @@ namespace ts { if (meaning & SymbolFlags.Function) { const functionName = (location).name; - if (functionName && name === functionName.text) { + if (functionName && name === functionName.escapedText) { result = location.symbol; break loop; } @@ -1239,7 +1240,22 @@ namespace ts { function checkAndReportErrorForUsingTypeAsNamespace(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean { if (meaning === SymbolFlags.Namespace) { const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined)); + const parent = errorLocation.parent; if (symbol) { + if (isQualifiedName(parent)) { + Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace"); + const propName = parent.right.escapedText; + const propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName); + if (propType) { + error( + parent, + Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1, + unescapeLeadingUnderscores(name), + unescapeLeadingUnderscores(propName), + ); + return true; + } + } error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, unescapeLeadingUnderscores(name)); return true; } @@ -1385,7 +1401,7 @@ namespace ts { if (valueSymbol.flags & (SymbolFlags.Type | SymbolFlags.Namespace)) { return valueSymbol; } - const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); + const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); result.declarations = concatenate(valueSymbol.declarations, typeSymbol.declarations); result.parent = valueSymbol.parent || typeSymbol.parent; if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; @@ -1414,7 +1430,7 @@ namespace ts { const targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { const name = specifier.propertyName || specifier.name; - if (name.text) { + if (name.escapedText) { if (isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } @@ -1422,16 +1438,16 @@ namespace ts { let symbolFromVariable: Symbol; // First check if module was specified with "export=". If so, get the member from the resolved type if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" as __String)) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); } // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - let symbolFromModule = getExportOfModule(targetSymbol, name.text, dontResolveAlias); + let symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.text === "default") { + if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } const symbol = symbolFromModule && symbolFromVariable ? @@ -1591,7 +1607,7 @@ namespace ts { if (name.kind === SyntaxKind.Identifier) { const message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, (name).text, meaning, ignoreErrors ? undefined : message, name); + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { return undefined; } @@ -1621,7 +1637,7 @@ namespace ts { else if (namespace === unknownSymbol) { return namespace; } - symbol = getSymbol(getExportsOfSymbol(namespace), right.text, meaning); + symbol = getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning); if (!symbol) { if (!ignoreErrors) { error(right, Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), declarationNameToString(right)); @@ -1776,6 +1792,17 @@ namespace ts { } } + function tryGetMemberInModuleExportsAndProperties(memberName: __String, moduleSymbol: Symbol): Symbol | undefined { + const symbol = tryGetMemberInModuleExports(memberName, moduleSymbol); + if (!symbol) { + const exportEquals = resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) { + return getPropertyOfType(getTypeOfSymbol(exportEquals), memberName); + } + } + return symbol; + } + function getExportsOfSymbol(symbol: Symbol): SymbolTable { return symbol.flags & SymbolFlags.Module ? getExportsOfModule(symbol) : symbol.exports || emptySymbols; } @@ -2042,14 +2069,14 @@ namespace ts { function trySymbolTable(symbols: SymbolTable) { // If symbol is directly available by its name in the symbol table - if (isAccessible(symbols.get(symbol.name))) { + if (isAccessible(symbols.get(symbol.escapedName))) { return [symbol]; } // Check if symbol is any of the alias return forEachEntry(symbols, symbolFromSymbolTable => { if (symbolFromSymbolTable.flags & SymbolFlags.Alias - && symbolFromSymbolTable.name !== "export=" + && symbolFromSymbolTable.escapedName !== "export=" && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)) { if (!useOnlyExternalAliasing || // We can use any type of alias to get the name // Is this external alias, then use it to name @@ -2072,10 +2099,8 @@ namespace ts { } } - if (symbol) { - if (!(isPropertyOrMethodDeclarationSymbol(symbol))) { - return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); - } + if (symbol && !isPropertyOrMethodDeclarationSymbol(symbol)) { + return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); } } @@ -2083,7 +2108,7 @@ namespace ts { let qualify = false; forEachSymbolTableInScope(enclosingDeclaration, symbolTable => { // If symbol of this name is not available in the symbol table we are ok - let symbolFromSymbolTable = symbolTable.get(symbol.name); + let symbolFromSymbolTable = symbolTable.get(symbol.escapedName); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -2263,7 +2288,7 @@ namespace ts { } const firstIdentifier = getFirstIdentifier(entityName); - const symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + const symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -2558,10 +2583,8 @@ namespace ts { } function createTypeNodeFromObjectType(type: ObjectType): TypeNode { - if (type.objectFlags & ObjectFlags.Mapped) { - if (getConstraintTypeFromMappedType(type).flags & (TypeFlags.TypeParameter | TypeFlags.Index)) { - return createMappedTypeNodeFromType(type); - } + if (isGenericMappedType(type)) { + return createMappedTypeNodeFromType(type); } const resolved = resolveStructuredTypeMembers(type); @@ -2599,7 +2622,7 @@ namespace ts { 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(""); + const entityName = symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, SymbolFlags.Type, /*expectsIdentifier*/ false) : createIdentifier(""); return entityName; } @@ -2621,9 +2644,10 @@ namespace ts { return createTupleTypeNode(tupleConstituentNodes); } } - if (!context.encounteredError && !(context.flags & NodeBuilderFlags.AllowEmptyTuple)) { - context.encounteredError = true; + if (context.encounteredError || (context.flags & NodeBuilderFlags.AllowEmptyTuple)) { + return createTupleTypeNode([]); } + context.encounteredError = true; return undefined; } else { @@ -2850,7 +2874,7 @@ namespace ts { parameterDeclaration.name.kind === SyntaxKind.Identifier ? setEmitFlags(getSynthesizedClone(parameterDeclaration.name), EmitFlags.NoAsciiEscaping) : cloneBindingName(parameterDeclaration.name) : - unescapeLeadingUnderscores(parameterSymbol.name); + unescapeLeadingUnderscores(parameterSymbol.escapedName); const questionToken = isOptionalParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : undefined; let parameterType = getTypeOfSymbol(parameterSymbol); @@ -2986,7 +3010,7 @@ namespace ts { return "(Anonymous function)"; } } - return unescapeLeadingUnderscores(symbol.name); + return unescapeLeadingUnderscores(symbol.escapedName); } } @@ -3070,7 +3094,7 @@ namespace ts { return "(Anonymous function)"; } } - return unescapeLeadingUnderscores(symbol.name); + return unescapeLeadingUnderscores(symbol.escapedName); } function getSymbolDisplayBuilder(): SymbolDisplayBuilder { @@ -3282,7 +3306,7 @@ namespace ts { function writeSymbolTypeReference(symbol: Symbol, typeArguments: Type[], pos: number, end: number, flags: TypeFormatFlags) { // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.name)) { + if (symbol.flags & SymbolFlags.Class || !isReservedMemberName(symbol.escapedName)) { buildSymbolDisplay(symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags); } if (pos < end) { @@ -3463,11 +3487,9 @@ namespace ts { } function writeLiteralType(type: ObjectType, flags: TypeFormatFlags) { - if (type.objectFlags & ObjectFlags.Mapped) { - if (getConstraintTypeFromMappedType(type).flags & (TypeFlags.TypeParameter | TypeFlags.Index)) { - writeMappedType(type); - return; - } + if (isGenericMappedType(type)) { + writeMappedType(type); + return; } const resolved = resolveStructuredTypeMembers(type); @@ -3533,7 +3555,7 @@ namespace ts { continue; } if (getDeclarationModifierFlagsFromSymbol(p) & (ModifierFlags.Private | ModifierFlags.Protected)) { - writer.reportPrivateInBaseOfClassExpression(unescapeLeadingUnderscores(p.name)); + writer.reportPrivateInBaseOfClassExpression(unescapeLeadingUnderscores(p.escapedName)); } } const t = getTypeOfSymbol(p); @@ -3920,7 +3942,7 @@ namespace ts { function collectLinkedAliases(node: Identifier): Node[] { let exportSymbol: Symbol; if (node.parent && node.parent.kind === SyntaxKind.ExportAssignment) { - exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, Diagnostics.Cannot_find_name_0, node); + exportSymbol = resolveName(node.parent, node.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === SyntaxKind.ExportSpecifier) { exportSymbol = getTargetOfExportSpecifier(node.parent, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); @@ -3943,7 +3965,7 @@ namespace ts { // Add the referenced top container visible const internalModuleReference = (declaration).moduleReference; const firstIdentifier = getFirstIdentifier(internalModuleReference); - const importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, + const importSymbol = resolveName(declaration, firstIdentifier.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, undefined, undefined); if (importSymbol) { buildVisibleNodeList(importSymbol.declarations); @@ -4081,11 +4103,11 @@ namespace ts { names.set(getTextOfPropertyName(name), true); } for (const prop of getPropertiesOfType(source)) { - const inNamesToRemove = names.has(prop.name); + const inNamesToRemove = names.has(prop.escapedName); const isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected); const isSetOnlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { - members.set(prop.name, prop); + members.set(prop.escapedName, prop); } } const stringIndexInfo = getIndexInfoOfType(source, IndexKind.String); @@ -4272,7 +4294,7 @@ namespace ts { } // Use contextual parameter type if one is available let type: Type; - if (declaration.symbol.name === "this") { + if (declaration.symbol.escapedName === "this") { type = getContextualThisParameterType(func); } else { @@ -4392,7 +4414,7 @@ namespace ts { const symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; - members.set(symbol.name, symbol); + members.set(symbol.escapedName, symbol); }); const result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); if (includePatternInType) { @@ -4492,8 +4514,8 @@ namespace ts { if (declaration.kind === SyntaxKind.ExportAssignment) { return links.type = checkExpression((declaration).expression); } - if (isInJavaScriptFile(declaration) && declaration.kind === SyntaxKind.JSDocPropertyTag && (declaration).typeExpression) { - return links.type = getTypeFromTypeNode((declaration).typeExpression.type); + if (isInJavaScriptFile(declaration) && isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { + return links.type = getTypeFromTypeNode(declaration.typeExpression.type); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { @@ -5073,20 +5095,9 @@ namespace ts { return unknownType; } - let declaration: JSDocTypedefTag | TypeAliasDeclaration = getDeclarationOfKind(symbol, SyntaxKind.JSDocTypedefTag); - let type: Type; - if (declaration) { - if (declaration.jsDocTypeLiteral) { - type = getTypeFromTypeNode(declaration.jsDocTypeLiteral); - } - else { - type = getTypeFromTypeNode(declaration.typeExpression.type); - } - } - else { - declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); - type = getTypeFromTypeNode(declaration.type); - } + const declaration = findDeclaration( + symbol, d => d.kind === SyntaxKind.JSDocTypedefTag || d.kind === SyntaxKind.TypeAliasDeclaration); + let type = getTypeFromTypeNode(declaration.kind === SyntaxKind.JSDocTypedefTag ? declaration.typeExpression : declaration.type); if (popTypeResolution()) { const typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -5112,10 +5123,18 @@ namespace ts { if (!expr) { return !isInAmbientContext(member); } - 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 && (nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get((expr).text)); + switch (expr.kind) { + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + return true; + case SyntaxKind.PrefixUnaryExpression: + return (expr).operator === SyntaxKind.MinusToken && + (expr).operand.kind === SyntaxKind.NumericLiteral; + case SyntaxKind.Identifier: + return nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get((expr).escapedText); + default: + return false; + } } function getEnumKind(symbol: Symbol): EnumKind { @@ -5314,15 +5333,15 @@ namespace ts { function createInstantiatedSymbolTable(symbols: Symbol[], mapper: TypeMapper, mappingThisOnly: boolean): SymbolTable { const result = createSymbolTable(); for (const symbol of symbols) { - result.set(symbol.name, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); + result.set(symbol.escapedName, mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper)); } return result; } function addInheritedMembers(symbols: SymbolTable, baseSymbols: Symbol[]) { for (const s of baseSymbols) { - if (!symbols.has(s.name)) { - symbols.set(s.name, s); + if (!symbols.has(s.escapedName)) { + symbols.set(s.escapedName, s); } } } @@ -5764,12 +5783,12 @@ namespace ts { return type.modifiersType; } + function isPartialMappedType(type: Type) { + return getObjectFlags(type) & ObjectFlags.Mapped && !!(type).declaration.questionToken; + } + function isGenericMappedType(type: Type) { - if (getObjectFlags(type) & ObjectFlags.Mapped) { - const constraintType = getConstraintTypeFromMappedType(type); - return maybeTypeOfKind(constraintType, TypeFlags.TypeVariable | TypeFlags.Index); - } - return false; + return getObjectFlags(type) & ObjectFlags.Mapped && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type: StructuredType): ResolvedType { @@ -5824,10 +5843,10 @@ namespace ts { const members = createSymbolTable(); for (const current of type.types) { for (const prop of getPropertiesOfType(current)) { - if (!members.has(prop.name)) { - const combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.name); + if (!members.has(prop.escapedName)) { + const combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName); if (combinedProp) { - members.set(prop.name, combinedProp); + members.set(prop.escapedName, combinedProp); } } } @@ -5857,9 +5876,9 @@ namespace ts { continue; } - for (const { name } of getPropertiesOfType(memberType)) { - if (!props.has(name)) { - props.set(name, createUnionOrIntersectionProperty(type as UnionType, name)); + for (const { escapedName } of getPropertiesOfType(memberType)) { + if (!props.has(escapedName)) { + props.set(escapedName, createUnionOrIntersectionProperty(type as UnionType, escapedName)); } } } @@ -5881,6 +5900,10 @@ namespace ts { } function getConstraintOfIndexedAccess(type: IndexedAccessType) { + const transformed = getTransformedIndexedAccessType(type); + if (transformed) { + return transformed; + } const baseObjectType = getBaseConstraintOfType(type.objectType); const baseIndexType = getBaseConstraintOfType(type.indexType); return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; @@ -5952,11 +5975,18 @@ namespace ts { return stringType; } if (t.flags & TypeFlags.IndexedAccess) { + const transformed = getTransformedIndexedAccessType(t); + if (transformed) { + return getBaseConstraint(transformed); + } const baseObjectType = getBaseConstraint((t).objectType); const baseIndexType = getBaseConstraint((t).indexType); const baseIndexedAccess = baseObjectType && baseIndexType ? getIndexedAccessType(baseObjectType, baseIndexType) : undefined; return baseIndexedAccess && baseIndexedAccess !== unknownType ? getBaseConstraint(baseIndexedAccess) : undefined; } + if (isGenericMappedType(t)) { + return emptyObjectType; + } return t; } } @@ -6167,7 +6197,7 @@ namespace ts { if (isObjectLiteralType(type)) { const propTypes: Type[] = []; for (const prop of getPropertiesOfType(type)) { - if (kind === IndexKind.String || isNumericLiteralName(prop.name)) { + if (kind === IndexKind.String || isNumericLiteralName(prop.escapedName)) { propTypes.push(getTypeOfSymbol(prop)); } } @@ -6256,11 +6286,11 @@ namespace ts { } function createTypePredicateFromTypePredicateNode(node: TypePredicateNode): IdentifierTypePredicate | ThisTypePredicate { - if (node.parameterName.kind === SyntaxKind.Identifier) { - const parameterName = node.parameterName as Identifier; + const { parameterName } = node; + if (parameterName.kind === SyntaxKind.Identifier) { return { kind: TypePredicateKind.Identifier, - parameterName: parameterName ? parameterName.text : undefined, + parameterName: parameterName ? parameterName.escapedText : undefined, parameterIndex: parameterName ? getTypePredicateParameterIndex((node.parent as SignatureDeclaration).parameters, parameterName) : undefined, type: getTypeFromTypeNode(node.type) } as IdentifierTypePredicate; @@ -6344,10 +6374,10 @@ namespace ts { let paramSymbol = param.symbol; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & SymbolFlags.Property) && !isBindingPattern(param.name)) { - const resolvedSymbol = resolveName(param, paramSymbol.name, SymbolFlags.Value, undefined, undefined); + const resolvedSymbol = resolveName(param, paramSymbol.escapedName, SymbolFlags.Value, undefined, undefined); paramSymbol = resolvedSymbol; } - if (i === 0 && paramSymbol.name === "this") { + if (i === 0 && paramSymbol.escapedName === "this") { hasThisParameter = true; thisParameter = param.symbol; } @@ -6444,7 +6474,7 @@ namespace ts { if (!node) return false; switch (node.kind) { case SyntaxKind.Identifier: - return (node).text === "arguments" && isPartOfExpression(node); + return (node).escapedText === "arguments" && isPartOfExpression(node); case SyntaxKind.PropertyDeclaration: case SyntaxKind.MethodDeclaration: @@ -6880,7 +6910,7 @@ namespace ts { function getIntendedTypeFromJSDocTypeReference(node: TypeReferenceNode): Type { if (isIdentifier(node.typeName)) { - if (node.typeName.text === "Object") { + if (node.typeName.escapedText === "Object") { if (node.typeArguments && node.typeArguments.length === 2) { const indexed = getTypeFromTypeNode(node.typeArguments[0]); const target = getTypeFromTypeNode(node.typeArguments[1]); @@ -6891,7 +6921,7 @@ namespace ts { } return anyType; } - switch (node.typeName.text) { + switch (node.typeName.escapedText) { case "String": return stringType; case "Number": @@ -6979,11 +7009,11 @@ namespace ts { } const type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & TypeFlags.Object)) { - error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, unescapeLeadingUnderscores(symbol.name)); + error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, unescapeLeadingUnderscores(symbol.escapedName)); return arity ? emptyGenericType : emptyObjectType; } if (length((type).typeParameters) !== arity) { - error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, unescapeLeadingUnderscores(symbol.name), arity); + error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_have_1_type_parameter_s, unescapeLeadingUnderscores(symbol.escapedName), arity); return arity ? emptyGenericType : emptyObjectType; } return type; @@ -7467,9 +7497,9 @@ namespace ts { } function getLiteralTypeFromPropertyName(prop: Symbol) { - return getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier || startsWith(prop.name as string, "__@") ? + return getDeclarationModifierFlagsFromSymbol(prop) & ModifierFlags.NonPublicAccessibilityModifier || startsWith(prop.escapedName as string, "__@") ? neverType : - getLiteralType(unescapeLeadingUnderscores(prop.name)); + getLiteralType(unescapeLeadingUnderscores(prop.escapedName)); } function getLiteralTypeFromPropertyNames(type: Type) { @@ -7508,7 +7538,7 @@ namespace ts { const propName = indexType.flags & TypeFlags.StringOrNumberLiteral ? escapeLeadingUnderscores("" + (indexType).value) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - getPropertyNameForKnownSymbolName(unescapeLeadingUnderscores(((accessExpression.argumentExpression).name).text)) : + getPropertyNameForKnownSymbolName(unescapeLeadingUnderscores(((accessExpression.argumentExpression).name).escapedText)) : undefined; if (propName !== undefined) { const prop = getPropertyOfType(objectType, propName); @@ -7568,36 +7598,89 @@ namespace ts { } function getIndexedAccessForMappedType(type: MappedType, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode) { - const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; - if (accessExpression && isAssignmentTarget(accessExpression) && type.declaration.readonlyToken) { - error(accessExpression, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); - return unknownType; + if (accessNode) { + // Check if the index type is assignable to 'keyof T' for the object type. + if (!isTypeAssignableTo(indexType, getIndexType(type))) { + error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(type)); + return unknownType; + } + if (accessNode.kind === SyntaxKind.ElementAccessExpression && isAssignmentTarget(accessNode) && type.declaration.readonlyToken) { + error(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(type)); + return unknownType; + } } const mapper = createTypeMapper([getTypeParameterFromMappedType(type)], [indexType]); const templateMapper = type.mapper ? combineTypeMappers(type.mapper, mapper) : mapper; return instantiateType(getTemplateTypeFromMappedType(type), templateMapper); } - function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode) { - // If the index type is generic, if the object type is generic and doesn't originate in an expression, - // or if the object type is a mapped type with a generic constraint, we are performing a higher-order - // index access where we cannot meaningfully access the properties of the object type. Note that for a - // generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to - // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved - // eagerly using the constraint type of 'this' at the given location. - if (maybeTypeOfKind(indexType, TypeFlags.TypeVariable | TypeFlags.Index) || - maybeTypeOfKind(objectType, TypeFlags.TypeVariable) && !(accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression) || - isGenericMappedType(objectType)) { + function isGenericObjectType(type: Type): boolean { + return type.flags & TypeFlags.TypeVariable ? true : + getObjectFlags(type) & ObjectFlags.Mapped ? isGenericIndexType(getConstraintTypeFromMappedType(type)) : + type.flags & TypeFlags.UnionOrIntersection ? forEach((type).types, isGenericObjectType) : + false; + } + + function isGenericIndexType(type: Type): boolean { + return type.flags & (TypeFlags.TypeVariable | TypeFlags.Index) ? true : + type.flags & TypeFlags.UnionOrIntersection ? forEach((type).types, isGenericIndexType) : + false; + } + + // Return true if the given type is a non-generic object type with a string index signature and no + // other members. + function isStringIndexOnlyType(type: Type) { + if (type.flags & TypeFlags.Object && !isGenericMappedType(type)) { + const t = resolveStructuredTypeMembers(type); + return t.properties.length === 0 && + t.callSignatures.length === 0 && t.constructSignatures.length === 0 && + t.stringIndexInfo && !t.numberIndexInfo; + } + return false; + } + + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + function getTransformedIndexedAccessType(type: IndexedAccessType): Type { + const objectType = type.objectType; + if (objectType.flags & TypeFlags.Intersection && isGenericObjectType(objectType) && some((objectType).types, isStringIndexOnlyType)) { + const regularTypes: Type[] = []; + const stringIndexTypes: Type[] = []; + for (const t of (objectType).types) { + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, IndexKind.String)); + } + else { + regularTypes.push(t); + } + } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + return undefined; + } + + function getIndexedAccessType(objectType: Type, indexType: Type, accessNode?: ElementAccessExpression | IndexedAccessTypeNode): Type { + // If the object type is a mapped type { [P in K]: E }, where K is generic, we instantiate E using a mapper + // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we + // construct the type Box. + if (isGenericMappedType(objectType)) { + return getIndexedAccessForMappedType(objectType, indexType, accessNode); + } + // Otherwise, if the index type is generic, or if the object type is generic and doesn't originate in an + // expression, we are performing a higher-order index access where we cannot meaningfully access the properties + // of the object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates + // in an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]' + // has always been resolved eagerly using the constraint type of 'this' at the given location. + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression) && isGenericObjectType(objectType)) { if (objectType.flags & TypeFlags.Any) { return objectType; } - // If the object type is a mapped type { [P in K]: E }, we instantiate E using a mapper that substitutes - // the index type for P. For example, for an index access { [P in K]: Box }[X], we construct the - // type Box. - if (isGenericMappedType(objectType)) { - return getIndexedAccessForMappedType(objectType, indexType, accessNode); - } - // Otherwise we defer the operation by creating an indexed access type. + // Defer the operation by creating an indexed access type. const id = objectType.id + "," + indexType.id; let type = indexedAccessTypes.get(id); if (!type) { @@ -7653,9 +7736,12 @@ namespace ts { links.resolvedType = emptyTypeLiteralType; } else { - const type = createObjectType(ObjectFlags.Anonymous, node.symbol); + let type = createObjectType(ObjectFlags.Anonymous, node.symbol); type.aliasSymbol = aliasSymbol; type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + if (isJSDocTypeLiteral(node) && node.isArrayType) { + type = createArrayType(type); + } links.resolvedType = type; } } @@ -7714,34 +7800,34 @@ namespace ts { // we approximate own properties as non-methods plus methods that are inside the object literal const isSetterWithoutGetter = rightProp.flags & SymbolFlags.SetAccessor && !(rightProp.flags & SymbolFlags.GetAccessor); if (getDeclarationModifierFlagsFromSymbol(rightProp) & (ModifierFlags.Private | ModifierFlags.Protected)) { - skippedPrivateMembers.set(rightProp.name, true); + skippedPrivateMembers.set(rightProp.escapedName, true); } else if (!isClassMethod(rightProp) && !isSetterWithoutGetter) { - members.set(rightProp.name, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); } } for (const leftProp of getPropertiesOfType(left)) { if (leftProp.flags & SymbolFlags.SetAccessor && !(leftProp.flags & SymbolFlags.GetAccessor) - || skippedPrivateMembers.has(leftProp.name) + || skippedPrivateMembers.has(leftProp.escapedName) || isClassMethod(leftProp)) { continue; } - if (members.has(leftProp.name)) { - const rightProp = members.get(leftProp.name); + if (members.has(leftProp.escapedName)) { + const rightProp = members.get(leftProp.escapedName); const rightType = getTypeOfSymbol(rightProp); 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); + const result = createSymbol(flags, leftProp.escapedName); result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, TypeFacts.NEUndefined)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; - members.set(leftProp.name, result); + members.set(leftProp.escapedName, result); } } else { - members.set(leftProp.name, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); } } return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); @@ -7752,7 +7838,7 @@ namespace ts { return prop; } const flags = SymbolFlags.Property | (prop.flags & SymbolFlags.Optional); - const result = createSymbol(flags, prop.name); + const result = createSymbol(flags, prop.escapedName); result.type = getTypeOfSymbol(prop); result.declarations = prop.declarations; result.syntheticOrigin = prop; @@ -7889,7 +7975,8 @@ namespace ts { case SyntaxKind.ParenthesizedType: case SyntaxKind.JSDocNonNullableType: case SyntaxKind.JSDocOptionalType: - return getTypeFromTypeNode((node).type); + case SyntaxKind.JSDocTypeExpression: + return getTypeFromTypeNode((node).type); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.TypeLiteral: @@ -8069,7 +8156,7 @@ namespace ts { } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - const result = createSymbol(symbol.flags, symbol.name); + const result = createSymbol(symbol.flags, symbol.escapedName); result.checkFlags = CheckFlags.Instantiated; result.declarations = symbol.declarations; result.parent = symbol.parent; @@ -8486,8 +8573,8 @@ namespace ts { if (!related) { if (reportErrors) { errorReporter(Diagnostics.Types_of_parameters_0_and_1_are_incompatible, - unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].name), - unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].name)); + unescapeLeadingUnderscores(sourceParams[i < sourceMax ? i : sourceMax].escapedName), + unescapeLeadingUnderscores(targetParams[i < targetMax ? i : targetMax].escapedName)); } return Ternary.False; } @@ -8626,17 +8713,17 @@ namespace ts { if (relation !== undefined) { return relation; } - if (sourceSymbol.name !== targetSymbol.name || !(sourceSymbol.flags & SymbolFlags.RegularEnum) || !(targetSymbol.flags & SymbolFlags.RegularEnum)) { + if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & SymbolFlags.RegularEnum) || !(targetSymbol.flags & SymbolFlags.RegularEnum)) { enumRelation.set(id, false); return false; } const targetEnumType = getTypeOfSymbol(targetSymbol); for (const property of getPropertiesOfType(getTypeOfSymbol(sourceSymbol))) { if (property.flags & SymbolFlags.EnumMember) { - const targetProperty = getPropertyOfType(targetEnumType, property.name); + const targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & SymbolFlags.EnumMember)) { if (errorReporter) { - errorReporter(Diagnostics.Property_0_is_missing_in_type_1, unescapeLeadingUnderscores(property.name), + errorReporter(Diagnostics.Property_0_is_missing_in_type_1, unescapeLeadingUnderscores(property.escapedName), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType)); } enumRelation.set(id, false); @@ -8942,7 +9029,7 @@ namespace ts { return false; } for (const prop of getPropertiesOfObjectType(source)) { - if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { + if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in @@ -9005,10 +9092,10 @@ namespace ts { const sourceProperties = getPropertiesOfObjectType(source); if (sourceProperties) { for (const sourceProperty of sourceProperties) { - if (isDiscriminantProperty(target, sourceProperty.name)) { + if (isDiscriminantProperty(target, sourceProperty.escapedName)) { const sourceType = getTypeOfSymbol(sourceProperty); for (const type of target.types) { - const targetType = getTypeOfPropertyOfType(type, sourceProperty.name); + const targetType = getTypeOfPropertyOfType(type, sourceProperty.escapedName); if (targetType && isRelatedTo(sourceType, targetType)) { return type; } @@ -9253,8 +9340,12 @@ namespace ts { if (source.flags & (TypeFlags.Object | TypeFlags.Intersection) && target.flags & TypeFlags.Object) { // Report structural errors only if we haven't reported any errors yet const reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; - if (isGenericMappedType(source) || isGenericMappedType(target)) { - result = mappedTypeRelatedTo(source, target, reportStructuralErrors); + // An empty object type is related to any mapped type that includes a '?' modifier. + if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + result = Ternary.True; + } + else if (isGenericMappedType(target)) { + result = isGenericMappedType(source) ? mappedTypeRelatedTo(source, target, reportStructuralErrors) : Ternary.False; } else { result = propertiesRelatedTo(source, target, reportStructuralErrors); @@ -9283,33 +9374,19 @@ namespace ts { // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice // that S and T are contra-variant whereas X and Y are co-variant. - function mappedTypeRelatedTo(source: Type, target: Type, reportErrors: boolean): Ternary { - if (isGenericMappedType(target)) { - if (isGenericMappedType(source)) { - const sourceReadonly = !!(source).declaration.readonlyToken; - const sourceOptional = !!(source).declaration.questionToken; - const targetReadonly = !!(target).declaration.readonlyToken; - const targetOptional = !!(target).declaration.questionToken; - const modifiersRelated = relation === identityRelation ? - sourceReadonly === targetReadonly && sourceOptional === targetOptional : - relation === comparableRelation || !sourceOptional || targetOptional; - if (modifiersRelated) { - let result: Ternary; - if (result = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { - const mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); - } - } - } - else if ((target).declaration.questionToken && isEmptyObjectType(source)) { - return Ternary.True; - - } - } - else if (relation !== identityRelation) { - const resolved = resolveStructuredTypeMembers(target); - if (isEmptyResolvedType(resolved) || resolved.stringIndexInfo && resolved.stringIndexInfo.type.flags & TypeFlags.Any) { - return Ternary.True; + function mappedTypeRelatedTo(source: MappedType, target: MappedType, reportErrors: boolean): Ternary { + const sourceReadonly = !!source.declaration.readonlyToken; + const sourceOptional = !!source.declaration.questionToken; + const targetReadonly = !!target.declaration.readonlyToken; + const targetOptional = !!target.declaration.questionToken; + const modifiersRelated = relation === identityRelation ? + sourceReadonly === targetReadonly && sourceOptional === targetOptional : + relation === comparableRelation || !sourceOptional || targetOptional; + if (modifiersRelated) { + let result: Ternary; + if (result = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + const mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); + return result & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return Ternary.False; @@ -9323,7 +9400,7 @@ namespace ts { const properties = getPropertiesOfObjectType(target); const requireOptionalProperties = relation === subtypeRelation && !(getObjectFlags(source) & ObjectFlags.ObjectLiteral); for (const targetProp of properties) { - const sourceProp = getPropertyOfType(source, targetProp.name); + const sourceProp = getPropertyOfType(source, targetProp.escapedName); if (sourceProp !== targetProp) { if (!sourceProp) { if (!(targetProp.flags & SymbolFlags.Optional) || requireOptionalProperties) { @@ -9423,7 +9500,7 @@ namespace ts { function hasCommonProperties(source: Type, target: Type) { const isComparingJsxAttributes = !!(source.flags & TypeFlags.JsxAttributes); for (const prop of getPropertiesOfType(source)) { - if (isKnownProperty(target, prop.name, isComparingJsxAttributes)) { + if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { return true; } } @@ -9441,7 +9518,7 @@ namespace ts { } let result = Ternary.True; for (const sourceProp of sourceProperties) { - const targetProp = getPropertyOfObjectType(target, sourceProp.name); + const targetProp = getPropertyOfObjectType(target, sourceProp.escapedName); if (!targetProp) { return Ternary.False; } @@ -9558,7 +9635,7 @@ namespace ts { function eachPropertyRelatedTo(source: Type, target: Type, kind: IndexKind, reportErrors: boolean): Ternary { let result = Ternary.True; for (const prop of getPropertiesOfObjectType(source)) { - if (kind === IndexKind.String || isNumericLiteralName(prop.name)) { + if (kind === IndexKind.String || isNumericLiteralName(prop.escapedName)) { const related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors); if (!related) { if (reportErrors) { @@ -9661,7 +9738,7 @@ namespace ts { function forEachProperty(prop: Symbol, callback: (p: Symbol) => T): T { if (getCheckFlags(prop) & CheckFlags.Synthetic) { for (const t of (prop).containingType.types) { - const p = getPropertyOfType(t, prop.name); + const p = getPropertyOfType(t, prop.escapedName); const result = p && forEachProperty(p, callback); if (result) { return result; @@ -9999,7 +10076,7 @@ namespace ts { } function createSymbolWithType(source: Symbol, type: Type) { - const symbol = createSymbol(source.flags, source.name); + const symbol = createSymbol(source.flags, source.escapedName); symbol.declarations = source.declarations; symbol.parent = source.parent; symbol.type = type; @@ -10015,7 +10092,7 @@ namespace ts { for (const property of getPropertiesOfObjectType(type)) { const original = getTypeOfSymbol(property); const updated = f(original); - members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); + members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated)); } return members; } @@ -10059,7 +10136,7 @@ namespace ts { for (const prop of getPropertiesOfObjectType(type)) { // Since get accessors already widen their return value there is no need to // widen accessor based properties here. - members.set(prop.name, prop.flags & SymbolFlags.Property ? getWidenedProperty(prop) : prop); + members.set(prop.escapedName, prop.flags & SymbolFlags.Property ? getWidenedProperty(prop) : prop); } const stringIndexInfo = getIndexInfoOfType(type, IndexKind.String); const numberIndexInfo = getIndexInfoOfType(type, IndexKind.Number); @@ -10122,7 +10199,7 @@ namespace ts { const t = getTypeOfSymbol(p); if (t.flags & TypeFlags.ContainsWideningType) { if (!reportWideningErrorsInType(t)) { - error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, unescapeLeadingUnderscores(p.name), typeToString(getWidenedType(t))); + error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, unescapeLeadingUnderscores(p.escapedName), typeToString(getWidenedType(t))); } errorReported = true; } @@ -10283,11 +10360,11 @@ namespace ts { if (!inferredPropType) { return undefined; } - const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.name); + const inferredProp = createSymbol(SymbolFlags.Property | prop.flags & optionalMask, prop.escapedName); inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? CheckFlags.Readonly : 0; inferredProp.declarations = prop.declarations; inferredProp.type = inferredPropType; - members.set(prop.name, inferredProp); + members.set(prop.escapedName, inferredProp); } if (indexInfo) { const inferredIndexType = inferTargetType(indexInfo.type); @@ -10305,6 +10382,19 @@ namespace ts { } } + function isPossiblyAssignableTo(source: Type, target: Type) { + const properties = getPropertiesOfObjectType(target); + for (const targetProp of properties) { + if (!(targetProp.flags & (SymbolFlags.Optional | SymbolFlags.Prototype))) { + const sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); + if (!sourceProp) { + return false; + } + } + } + return true; + } + function inferTypes(inferences: InferenceInfo[], originalSource: Type, originalTarget: Type, priority: InferencePriority = 0) { let symbolStack: Symbol[]; let visited: Map; @@ -10498,16 +10588,20 @@ namespace ts { return; } } - inferFromProperties(source, target); - inferFromSignatures(source, target, SignatureKind.Call); - inferFromSignatures(source, target, SignatureKind.Construct); - inferFromIndexTypes(source, target); + // Infer from the members of source and target only if the two types are possibly related. We check + // in both directions because we may be inferring for a co-variant or a contra-variant position. + if (isPossiblyAssignableTo(source, target) || isPossiblyAssignableTo(target, source)) { + inferFromProperties(source, target); + inferFromSignatures(source, target, SignatureKind.Call); + inferFromSignatures(source, target, SignatureKind.Construct); + inferFromIndexTypes(source, target); + } } function inferFromProperties(source: Type, target: Type) { const properties = getPropertiesOfObjectType(target); for (const targetProp of properties) { - const sourceProp = getPropertyOfObjectType(source, targetProp.name); + const sourceProp = getPropertyOfObjectType(source, targetProp.escapedName); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -10658,7 +10752,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, Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; + links.resolvedSymbol = !nodeIsMissing(node) && resolveName(node, node.escapedText, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node, Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol; } return links.resolvedSymbol; } @@ -10688,7 +10782,7 @@ namespace ts { } if (node.kind === SyntaxKind.PropertyAccessExpression) { const key = getFlowCacheKey((node).expression); - return key && key + "." + unescapeLeadingUnderscores((node).name.text); + return key && key + "." + unescapeLeadingUnderscores((node).name.escapedText); } if (node.kind === SyntaxKind.BindingElement) { const container = (node as BindingElement).parent.parent; @@ -10716,10 +10810,9 @@ namespace ts { const name = element.propertyName || element.name; switch (name.kind) { case SyntaxKind.Identifier: - return unescapeLeadingUnderscores(name.text); + return unescapeLeadingUnderscores(name.escapedText); case SyntaxKind.ComputedPropertyName: - if (isComputedNonLiteralName(name as PropertyName)) return undefined; - return (name.expression as LiteralExpression).text; + return isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: return name.text; @@ -10745,12 +10838,12 @@ namespace ts { return target.kind === SyntaxKind.SuperKeyword; case SyntaxKind.PropertyAccessExpression: return target.kind === SyntaxKind.PropertyAccessExpression && - (source).name.text === (target).name.text && + (source).name.escapedText === (target).name.escapedText && isMatchingReference((source).expression, (target).expression); case SyntaxKind.BindingElement: if (target.kind !== SyntaxKind.PropertyAccessExpression) return false; const t = target as PropertyAccessExpression; - if (t.name.text !== getBindingElementNameText(source as BindingElement)) return false; + if (t.name.escapedText !== getBindingElementNameText(source as BindingElement)) return false; if (source.parent.parent.kind === SyntaxKind.BindingElement && isMatchingReference(source.parent.parent, t.expression)) { return true; } @@ -10779,7 +10872,7 @@ namespace ts { function containsMatchingReferenceDiscriminant(source: Node, target: Node) { return target.kind === SyntaxKind.PropertyAccessExpression && containsMatchingReference(source, (target).expression) && - isDiscriminantProperty(getDeclaredTypeOfReference((target).expression), (target).name.text); + isDiscriminantProperty(getDeclaredTypeOfReference((target).expression), (target).name.escapedText); } function getDeclaredTypeOfReference(expr: Node): Type { @@ -10788,7 +10881,7 @@ namespace ts { } if (expr.kind === SyntaxKind.PropertyAccessExpression) { const type = getDeclaredTypeOfReference((expr).expression); - return type && getTypeOfPropertyOfType(type, (expr).name.text); + return type && getTypeOfPropertyOfType(type, (expr).name.escapedText); } return undefined; } @@ -11277,7 +11370,7 @@ namespace ts { const root = getReferenceRoot(node); const parent = root.parent; const isLengthPushOrUnshift = parent.kind === SyntaxKind.PropertyAccessExpression && ( - (parent).name.text === "length" || + (parent).name.escapedText === "length" || parent.parent.kind === SyntaxKind.CallExpression && isPushOrUnshiftIdentifier((parent).name)); const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === root && @@ -11499,7 +11592,7 @@ namespace ts { if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr)) { + else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, t => narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd)); } return createFlowType(type, isIncomplete(flowType)); @@ -11619,15 +11712,15 @@ namespace ts { return result; } - function isMatchingReferenceDiscriminant(expr: Expression) { + function isMatchingReferenceDiscriminant(expr: Expression, computedType: Type) { return expr.kind === SyntaxKind.PropertyAccessExpression && - declaredType.flags & TypeFlags.Union && + computedType.flags & TypeFlags.Union && isMatchingReference(reference, (expr).expression) && - isDiscriminantProperty(declaredType, (expr).name.text); + isDiscriminantProperty(computedType, (expr).name.escapedText); } function narrowTypeByDiscriminant(type: Type, propAccess: PropertyAccessExpression, narrowType: (t: Type) => Type): Type { - const propName = propAccess.name.text; + const propName = propAccess.name.escapedText; const propType = getTypeOfPropertyOfType(type, propName); const narrowedPropType = propType && narrowType(propType); return propType === narrowedPropType ? type : filterType(type, t => isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType)); @@ -11637,7 +11730,7 @@ namespace ts { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy); } - if (isMatchingReferenceDiscriminant(expr)) { + if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy)); } if (containsMatchingReferenceDiscriminant(reference, expr)) { @@ -11669,10 +11762,10 @@ namespace ts { if (isMatchingReference(reference, right)) { return narrowTypeByEquality(type, operator, left, assumeTrue); } - if (isMatchingReferenceDiscriminant(left)) { + if (isMatchingReferenceDiscriminant(left, declaredType)) { return narrowTypeByDiscriminant(type, left, t => narrowTypeByEquality(t, operator, right, assumeTrue)); } - if (isMatchingReferenceDiscriminant(right)) { + if (isMatchingReferenceDiscriminant(right, declaredType)) { return narrowTypeByDiscriminant(type, right, t => narrowTypeByEquality(t, operator, left, assumeTrue)); } if (containsMatchingReferenceDiscriminant(reference, left) || containsMatchingReferenceDiscriminant(reference, right)) { @@ -12431,7 +12524,7 @@ namespace ts { const jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && - (jsDocFunctionType.parameters[0].name as Identifier).text === "this") { + (jsDocFunctionType.parameters[0].name as Identifier).escapedText === "this") { return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } @@ -12941,7 +13034,7 @@ namespace ts { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - const symbolName = getSymbolOfNode(element).name; + const symbolName = getSymbolOfNode(element).escapedName; const propertyType = getTypeOfPropertyOfContextualType(type, symbolName); if (propertyType) { return propertyType; @@ -12994,7 +13087,7 @@ namespace ts { if (isJsxAttribute(node.parent)) { // JSX expression is in JSX attribute - return getTypeOfPropertyOfType(attributesType, (node.parent as JsxAttribute).name.text); + return getTypeOfPropertyOfType(attributesType, node.parent.name.escapedText); } else if (node.parent.kind === SyntaxKind.JsxElement) { // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) @@ -13017,7 +13110,7 @@ namespace ts { if (!attributesType || isTypeAny(attributesType)) { return undefined; } - return getTypeOfPropertyOfType(attributesType, (attribute as JsxAttribute).name.text); + return getTypeOfPropertyOfType(attributesType, attribute.name.escapedText); } else { return attributesType; @@ -13283,7 +13376,17 @@ namespace ts { } function isNumericName(name: DeclarationName): boolean { - return name.kind === SyntaxKind.ComputedPropertyName ? isNumericComputedName(name) : isNumericLiteralName((name).text); + switch (name.kind) { + case SyntaxKind.ComputedPropertyName: + return isNumericComputedName(name); + case SyntaxKind.Identifier: + return isNumericLiteralName(name.escapedText); + case SyntaxKind.NumericLiteral: + case SyntaxKind.StringLiteral: + return isNumericLiteralName(name.text); + default: + return false; + } } function isNumericComputedName(name: ComputedPropertyName): boolean { @@ -13404,7 +13507,7 @@ namespace ts { } typeFlags |= type.flags; - const prop = createSymbol(SymbolFlags.Property | member.flags, member.name); + const prop = createSymbol(SymbolFlags.Property | member.flags, member.escapedName); if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. @@ -13421,7 +13524,7 @@ namespace ts { else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. - const impliedProp = getPropertyOfType(contextualType, member.name); + const impliedProp = getPropertyOfType(contextualType, member.escapedName); if (impliedProp) { prop.flags |= impliedProp.flags & SymbolFlags.Optional; } @@ -13481,7 +13584,7 @@ namespace ts { } } else { - propertiesTable.set(member.name, member); + propertiesTable.set(member.escapedName, member); } propertiesArray.push(member); } @@ -13490,12 +13593,12 @@ namespace ts { // type with those properties for which the binding pattern specifies a default value. if (contextualTypeHasPattern) { for (const prop of getPropertiesOfType(contextualType)) { - if (!propertiesTable.get(prop.name)) { + if (!propertiesTable.get(prop.escapedName)) { if (!(prop.flags & SymbolFlags.Optional)) { error(prop.valueDeclaration || (prop).bindingElement, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - propertiesTable.set(prop.name, prop); + propertiesTable.set(prop.escapedName, prop); propertiesArray.push(prop); } } @@ -13576,11 +13679,14 @@ namespace ts { */ function isJsxIntrinsicIdentifier(tagName: JsxTagNameExpression) { // TODO (yuisu): comment - if (tagName.kind === SyntaxKind.PropertyAccessExpression || tagName.kind === SyntaxKind.ThisKeyword) { - return false; - } - else { - return isIntrinsicJsxName((tagName).text); + switch (tagName.kind) { + case SyntaxKind.PropertyAccessExpression: + case SyntaxKind.ThisKeyword: + return false; + case SyntaxKind.Identifier: + return isIntrinsicJsxName((tagName).escapedText); + default: + Debug.fail(); } } @@ -13610,7 +13716,7 @@ namespace ts { checkExpression(attributeDecl.initializer, checkMode) : trueType; // is sugar for - const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); + const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; attributeSymbol.parent = member.parent; if (member.valueDeclaration) { @@ -13618,9 +13724,9 @@ namespace ts { } attributeSymbol.type = exprType; attributeSymbol.target = member; - attributesTable.set(attributeSymbol.name, attributeSymbol); + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); attributesArray.push(attributeSymbol); - if (attributeDecl.name.text === jsxChildrenPropertyName) { + if (attributeDecl.name.escapedText === jsxChildrenPropertyName) { explicitlySpecifyChildrenAttribute = true; } } @@ -13655,7 +13761,7 @@ namespace ts { attributesTable = createSymbolTable(); for (const attr of attributesArray) { if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); + attributesTable.set(attr.escapedName, attr); } } } @@ -13745,7 +13851,8 @@ namespace ts { const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements); if (intrinsicElementsType !== unknownType) { // Property case - const intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text); + if (!isIdentifier(node.tagName)) throw Debug.fail(); + const intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText); if (intrinsicProp) { links.jsxFlags |= JsxFlags.IntrinsicNamedElement; return links.resolvedSymbol = intrinsicProp; @@ -13759,7 +13866,7 @@ namespace ts { } // Wasn't found - error(node, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores((node.tagName).text), "JSX." + JsxNames.IntrinsicElements); + error(node, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(node.tagName.escapedText), "JSX." + JsxNames.IntrinsicElements); return links.resolvedSymbol = unknownSymbol; } else { @@ -13834,7 +13941,7 @@ namespace ts { // Element Attributes has one property, so the element attributes type will be the type of the corresponding // property of the class instance type else if (propertiesOfJsxElementAttribPropInterface.length === 1) { - return propertiesOfJsxElementAttribPropInterface[0].name; + return propertiesOfJsxElementAttribPropInterface[0].escapedName; } else if (propertiesOfJsxElementAttribPropInterface.length > 1) { // More than one property on ElementAttributesProperty is an error @@ -13945,8 +14052,8 @@ namespace ts { let shouldBeCandidate = true; for (const attribute of openingLikeElement.attributes.properties) { if (isJsxAttribute(attribute) && - isUnhyphenatedJsxName(attribute.name.text) && - !getPropertyOfType(paramType, attribute.name.text)) { + isUnhyphenatedJsxName(attribute.name.escapedText) && + !getPropertyOfType(paramType, attribute.name.escapedText)) { shouldBeCandidate = false; break; } @@ -14174,7 +14281,7 @@ namespace ts { */ function getJsxAttributePropertySymbol(attrib: JsxAttribute): Symbol { const attributesType = getAttributesTypeFromJsxOpeningLikeElement(attrib.parent.parent as JsxOpeningElement); - const prop = getPropertyOfType(attributesType, attrib.name.text); + const prop = getPropertyOfType(attributesType, attrib.name.escapedText); return prop || unknownSymbol; } @@ -14302,7 +14409,7 @@ namespace ts { // attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". const sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, attribute => { - return isUnhyphenatedJsxName(attribute.name) || !!(getPropertyOfType(targetAttributesType, attribute.name)); + return isUnhyphenatedJsxName(attribute.escapedName) || !!(getPropertyOfType(targetAttributesType, attribute.escapedName)); }); // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. @@ -14317,8 +14424,8 @@ namespace ts { // 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, unescapeLeadingUnderscores(attribute.name.text), typeToString(targetAttributesType)); + if (isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(attribute.name.escapedText), typeToString(targetAttributesType)); // We break here so that errors won't be cascading break; } @@ -14489,13 +14596,13 @@ namespace ts { // handle cases when type is Type parameter with invalid or any constraint return apparentType; } - const prop = getPropertyOfType(apparentType, right.text); + const prop = getPropertyOfType(apparentType, right.escapedText); if (!prop) { const stringIndexType = getIndexTypeOfType(apparentType, IndexKind.String); if (stringIndexType) { return stringIndexType; } - if (right.text && !checkAndReportErrorForExtendingInterface(node)) { + if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType ? apparentType : type); } return unknownType; @@ -14503,13 +14610,13 @@ namespace ts { if (prop.valueDeclaration) { if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, unescapeLeadingUnderscores(right.text)); + error(right, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, unescapeLeadingUnderscores(right.escapedText)); } if (prop.valueDeclaration.kind === SyntaxKind.ClassDeclaration && node.parent && node.parent.kind !== SyntaxKind.TypeReference && !isInAmbientContext(prop.valueDeclaration) && !isBlockScopedNameDeclaredBeforeUse(prop.valueDeclaration, right)) { - error(right, Diagnostics.Class_0_used_before_its_declaration, unescapeLeadingUnderscores(right.text)); + error(right, Diagnostics.Class_0_used_before_its_declaration, unescapeLeadingUnderscores(right.escapedText)); } } @@ -14524,7 +14631,7 @@ namespace ts { if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { - error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, unescapeLeadingUnderscores(right.text)); + error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, unescapeLeadingUnderscores(right.escapedText)); return unknownType; } } @@ -14545,7 +14652,7 @@ namespace ts { 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)) { + if (!getPropertyOfType(subtype, propNode.escapedText)) { errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype)); break; } @@ -14562,8 +14669,8 @@ namespace ts { } function getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): __String | undefined { - const suggestion = getSpellingSuggestionForName(unescapeLeadingUnderscores(node.text), getPropertiesOfType(containingType), SymbolFlags.Value); - return suggestion && suggestion.name; + const suggestion = getSpellingSuggestionForName(unescapeLeadingUnderscores(node.escapedText), getPropertiesOfType(containingType), SymbolFlags.Value); + return suggestion && suggestion.escapedName; } function getSuggestionForNonexistentSymbol(location: Node, name: __String, meaning: SymbolFlags): __String { @@ -14578,7 +14685,7 @@ namespace ts { return getSpellingSuggestionForName(unescapeLeadingUnderscores(name), arrayFrom(symbols.values()), meaning); }); if (result) { - return result.name; + return result.escapedName; } } @@ -14609,7 +14716,7 @@ namespace ts { } name = name.toLowerCase(); for (const candidate of symbols) { - let candidateName = unescapeLeadingUnderscores(candidate.name); + let candidateName = unescapeLeadingUnderscores(candidate.escapedName); if (candidate.flags & meaning && candidateName && Math.abs(candidateName.length - name.length) < maximumLengthDifference) { @@ -15178,7 +15285,7 @@ namespace ts { const attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*contextualMapper*/ undefined); const argProperties = getPropertiesOfType(attributesType); for (const arg of argProperties) { - if (!getPropertyOfType(paramType, arg.name) && isUnhyphenatedJsxName(arg.name)) { + if (!getPropertyOfType(paramType, arg.escapedName) && isUnhyphenatedJsxName(arg.escapedName)) { return false; } } @@ -15216,17 +15323,17 @@ namespace ts { if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) const paramType = getTypeAtPosition(signature, i); - let argType = getEffectiveArgumentType(node, i); - - // If the effective argument type is 'undefined', there is no synthetic type - // for the argument. In that case, we should check the argument. - if (argType === undefined) { - argType = checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - } - + // If the effective argument type is undefined, there is no synthetic type for the argument. + // In that case, we should check the argument. + const argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + const checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; // Use argument expression as error location when reporting errors const errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { return false; } } @@ -15428,13 +15535,13 @@ namespace ts { const element = node; switch (element.name.kind) { case SyntaxKind.Identifier: - return getLiteralType(unescapeLeadingUnderscores((element.name).text)); + return getLiteralType(unescapeLeadingUnderscores(element.name.escapedText)); case SyntaxKind.NumericLiteral: case SyntaxKind.StringLiteral: - return getLiteralType((element.name).text); + return getLiteralType(element.name.text); case SyntaxKind.ComputedPropertyName: - const nameType = checkComputedPropertyName(element.name); + const nameType = checkComputedPropertyName(element.name); if (isTypeOfKind(nameType, TypeFlags.ESSymbol)) { return nameType; } @@ -15598,6 +15705,7 @@ namespace ts { // For a decorator, no arguments are susceptible to contextual typing due to the fact // decorators are applied to a declaration by the emitter, and not to an expression. let excludeArgument: boolean[]; + let excludeCount = 0; if (!isDecorator) { // We do not need to call `getEffectiveArgumentCount` here as it only // applies when calculating the number of arguments for a decorator. @@ -15607,6 +15715,7 @@ namespace ts { excludeArgument = new Array(args.length); } excludeArgument[i] = true; + excludeCount++; } } } @@ -15781,12 +15890,17 @@ namespace ts { candidateForArgumentError = candidate; break; } - const index = excludeArgument ? indexOf(excludeArgument, /*value*/ true) : -1; - if (index < 0) { + if (excludeCount === 0) { candidates[candidateIndex] = candidate; return candidate; } - excludeArgument[index] = false; + excludeCount--; + if (excludeCount > 0) { + excludeArgument[indexOf(excludeArgument, /*value*/ true)] = false; + } + else { + excludeArgument = undefined; + } } } @@ -16297,8 +16411,9 @@ namespace ts { if (!isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { return false; } - // Make sure require is not a local function - const resolvedRequire = resolveName(node.expression, (node.expression).text, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + // Make sure require is not a local function + if (!isIdentifier(node.expression)) throw Debug.fail(); + const resolvedRequire = resolveName(node.expression, node.expression.escapedText, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (!resolvedRequire) { // project does not contain symbol named 'require' - assume commonjs require return true; @@ -16929,8 +17044,13 @@ namespace ts { if (operandType === silentNeverType) { return silentNeverType; } - if (node.operator === SyntaxKind.MinusToken && node.operand.kind === SyntaxKind.NumericLiteral) { - return getFreshTypeOfLiteralType(getLiteralType(-(node.operand).text)); + if (node.operand.kind === SyntaxKind.NumericLiteral) { + if (node.operator === SyntaxKind.MinusToken) { + return getFreshTypeOfLiteralType(getLiteralType(-(node.operand).text)); + } + else if (node.operator === SyntaxKind.PlusToken) { + return getFreshTypeOfLiteralType(getLiteralType(+(node.operand).text)); + } } switch (node.operator) { case SyntaxKind.PlusToken: @@ -17455,7 +17575,7 @@ namespace ts { } function isEvalNode(node: Expression) { - return node.kind === SyntaxKind.Identifier && (node as Identifier).text === "eval"; + return node.kind === SyntaxKind.Identifier && (node as Identifier).escapedText === "eval"; } // Return true if there was no error, false if there was an error. @@ -17559,7 +17679,7 @@ namespace ts { } if (functionFlags & FunctionFlags.Generator) { - const expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); + const expressionType = checkExpressionCached(node.expression); let expressionElementType: Type; const nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { @@ -17953,9 +18073,9 @@ namespace ts { if (node.questionToken && isBindingPattern(node.name) && (func as FunctionLikeDeclaration).body) { error(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } - if (node.name && ((node.name as Identifier).text === "this" || (node.name as Identifier).text === "new")) { + if (node.name && isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { if (indexOf(func.parameters, node) !== 0) { - error(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, (node.name as Identifier).text as string); + error(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText as string); } if (func.kind === SyntaxKind.Constructor || func.kind === SyntaxKind.ConstructSignature || func.kind === SyntaxKind.ConstructorType) { error(node, Diagnostics.A_constructor_cannot_have_a_this_parameter); @@ -17973,9 +18093,7 @@ namespace ts { if (parameterList) { for (let i = 0; i < parameterList.length; i++) { const param = parameterList[i]; - if (param.name.kind === SyntaxKind.Identifier && - (param.name).text === parameter.text) { - + if (param.name.kind === SyntaxKind.Identifier && param.name.escapedText === parameter.escapedText) { return i; } } @@ -18059,17 +18177,15 @@ namespace ts { } const name = element.name; - if (name.kind === SyntaxKind.Identifier && - (name).text === predicateVariableName) { + if (name.kind === SyntaxKind.Identifier && name.escapedText === predicateVariableName) { error(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === SyntaxKind.ArrayBindingPattern || - name.kind === SyntaxKind.ObjectBindingPattern) { + else if (name.kind === SyntaxKind.ArrayBindingPattern || name.kind === SyntaxKind.ObjectBindingPattern) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern( - name, + name, predicateVariableNode, predicateVariableName)) { return true; @@ -18177,8 +18293,8 @@ namespace ts { for (const member of node.members) { if (member.kind === SyntaxKind.Constructor) { for (const param of (member as ConstructorDeclaration).parameters) { - if (isParameterPropertyDeclaration(param)) { - addName(instanceNames, param.name, (param.name as Identifier).text, Declaration.Property); + if (isParameterPropertyDeclaration(param) && !isBindingPattern(param.name)) { + addName(instanceNames, param.name, param.name.escapedText, Declaration.Property); } } } @@ -18273,7 +18389,7 @@ namespace ts { memberName = member.name.text; break; case SyntaxKind.Identifier: - memberName = unescapeLeadingUnderscores(member.name.text); + memberName = unescapeLeadingUnderscores(member.name.escapedText); break; default: continue; @@ -18557,7 +18673,17 @@ namespace ts { forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { const symbol = getNodeLinks(node).resolvedSymbol; - const typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; + if (!symbol) { + // There is no resolved symbol cached if the type resolved to a builtin + // via JSDoc type reference resolution (eg, Boolean became boolean), none + // of which are generic when they have no associated symbol + error(node, Diagnostics.Type_0_is_not_generic, typeToString(type)); + return; + } + let typeParameters = symbol.flags & SymbolFlags.TypeAlias && getSymbolLinks(symbol).typeParameters; + if (!typeParameters && getObjectFlags(type) & ObjectFlags.Reference) { + typeParameters = (type).target.localTypeParameters; + } checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -18622,6 +18748,8 @@ namespace ts { } function checkIndexedAccessType(node: IndexedAccessTypeNode) { + checkSourceElement(node.objectType); + checkSourceElement(node.indexType); checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node); } @@ -18740,8 +18868,11 @@ namespace ts { if (subsequentNode && subsequentNode.pos === node.end) { if (subsequentNode.kind === node.kind) { const errorNode: Node = (subsequentNode).name || subsequentNode; - // TODO(jfreeman): These are methods, so handle computed name case - if (node.name && (subsequentNode).name && (node.name).text === ((subsequentNode).name).text) { + // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!) + const subsequentName = (subsequentNode).name; + if (node.name && subsequentName && + (isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) || + !isComputedPropertyName(node.name) && !isComputedPropertyName(subsequentName) && getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName))) { const reportError = (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && (getModifierFlags(node) & ModifierFlags.Static) !== (getModifierFlags(subsequentNode) & ModifierFlags.Static); @@ -19211,7 +19342,7 @@ namespace ts { const promiseConstructorSymbol = resolveEntityName(promiseConstructorName, SymbolFlags.Value, /*ignoreErrors*/ true); const promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; if (promiseConstructorType === unknownType) { - if (promiseConstructorName.kind === SyntaxKind.Identifier && promiseConstructorName.text === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { + if (promiseConstructorName.kind === SyntaxKind.Identifier && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { @@ -19235,10 +19366,10 @@ namespace ts { // Verify there is no local declaration that could collide with the promise constructor. const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); - const collidingSymbol = getSymbol(node.locals, rootName.text, SymbolFlags.Value); + const collidingSymbol = getSymbol(node.locals, rootName.escapedText, SymbolFlags.Value); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, - unescapeLeadingUnderscores(rootName.text), + unescapeLeadingUnderscores(rootName.escapedText), entityNameToString(promiseConstructorName)); return unknownType; } @@ -19308,7 +19439,7 @@ namespace ts { 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); + const rootSymbol = rootName && resolveName(rootName, rootName.escapedText, (typeName.kind === SyntaxKind.Identifier ? SymbolFlags.Type : SymbolFlags.Namespace) | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias && symbolIsValue(rootSymbol) @@ -19353,7 +19484,7 @@ namespace ts { // return undefined if they dont match because we would emit object if (!isIdentifier(commonEntityName) || !isIdentifier(individualEntityName) || - commonEntityName.text !== individualEntityName.text) { + commonEntityName.escapedText !== individualEntityName.escapedText) { return undefined; } } @@ -19488,10 +19619,9 @@ namespace ts { // Since the javascript won't do semantic analysis like typescript, // if the javascript file comes before the typescript file and both contain same name functions, // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function. - const firstDeclaration = forEach(localSymbol.declarations, + const firstDeclaration = find(localSymbol.declarations, // Get first non javascript function declaration - declaration => declaration.kind === node.kind && !isSourceFileJavaScript(getSourceFileOfNode(declaration)) ? - declaration : undefined); + declaration => declaration.kind === node.kind && !isSourceFileJavaScript(getSourceFileOfNode(declaration))); // Only type check the symbol once if (node === firstDeclaration) { @@ -19603,11 +19733,11 @@ namespace ts { !isParameterPropertyDeclaration(parameter) && !parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(name)) { - error(name, Diagnostics._0_is_declared_but_never_used, unescapeLeadingUnderscores(local.name)); + error(name, Diagnostics._0_is_declared_but_never_used, unescapeLeadingUnderscores(local.escapedName)); } } else if (compilerOptions.noUnusedLocals) { - forEach(local.declarations, d => errorUnusedLocal(getNameOfDeclaration(d) || d, unescapeLeadingUnderscores(local.name))); + forEach(local.declarations, d => errorUnusedLocal(getNameOfDeclaration(d) || d, unescapeLeadingUnderscores(local.escapedName))); } } }); @@ -19640,7 +19770,7 @@ namespace ts { } function isIdentifierThatStartsWithUnderScore(node: Node) { - return node.kind === SyntaxKind.Identifier && unescapeLeadingUnderscores((node).text).charCodeAt(0) === CharacterCodes._; + return node.kind === SyntaxKind.Identifier && unescapeLeadingUnderscores((node).escapedText).charCodeAt(0) === CharacterCodes._; } function checkUnusedClassMembers(node: ClassDeclaration | ClassExpression): void { @@ -19649,13 +19779,13 @@ namespace ts { for (const member of node.members) { if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.PropertyDeclaration) { if (!member.symbol.isReferenced && getModifierFlags(member) & ModifierFlags.Private) { - error(member.name, Diagnostics._0_is_declared_but_never_used, unescapeLeadingUnderscores(member.symbol.name)); + error(member.name, Diagnostics._0_is_declared_but_never_used, unescapeLeadingUnderscores(member.symbol.escapedName)); } } else if (member.kind === SyntaxKind.Constructor) { for (const parameter of (member).parameters) { if (!parameter.symbol.isReferenced && getModifierFlags(parameter) & ModifierFlags.Private) { - error(parameter.name, Diagnostics.Property_0_is_declared_but_never_used, unescapeLeadingUnderscores(parameter.symbol.name)); + error(parameter.name, Diagnostics.Property_0_is_declared_but_never_used, unescapeLeadingUnderscores(parameter.symbol.escapedName)); } } } @@ -19676,7 +19806,7 @@ namespace ts { } for (const typeParameter of node.typeParameters) { if (!getMergedSymbol(typeParameter.symbol).isReferenced) { - error(typeParameter.name, Diagnostics._0_is_declared_but_never_used, unescapeLeadingUnderscores(typeParameter.symbol.name)); + error(typeParameter.name, Diagnostics._0_is_declared_but_never_used, unescapeLeadingUnderscores(typeParameter.symbol.escapedName)); } } } @@ -19689,7 +19819,7 @@ namespace ts { if (!local.isReferenced && !local.exportSymbol) { for (const declaration of local.declarations) { if (!isAmbientModule(declaration)) { - errorUnusedLocal(getNameOfDeclaration(declaration), unescapeLeadingUnderscores(local.name)); + errorUnusedLocal(getNameOfDeclaration(declaration), unescapeLeadingUnderscores(local.escapedName)); } } } @@ -19715,14 +19845,14 @@ namespace ts { } forEach(node.parameters, p => { - if (p.name && !isBindingPattern(p.name) && (p.name).text === argumentsSymbol.name) { + if (p.name && !isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) { error(p, Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters); } }); } function needCollisionCheckForIdentifier(node: Node, identifier: Identifier, name: string): boolean { - if (!(identifier && identifier.text === name)) { + if (!(identifier && identifier.escapedText === name)) { return false; } @@ -19899,7 +20029,8 @@ namespace ts { const symbol = getSymbolOfNode(node); if (symbol.flags & SymbolFlags.FunctionScopedVariable) { - const localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + if (!isIdentifier(node.name)) throw Debug.fail(); + const localDeclarationSymbol = resolveName(node, node.name.escapedText, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & SymbolFlags.BlockScopedVariable) { @@ -19954,7 +20085,7 @@ namespace ts { else if (n.kind === SyntaxKind.Identifier) { // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name - const symbol = resolveName(n, (n).text, SymbolFlags.Value | SymbolFlags.Alias, /*nameNotFoundMessage*/undefined, /*nameArg*/undefined); + const symbol = resolveName(n, (n).escapedText, SymbolFlags.Value | SymbolFlags.Alias, /*nameNotFoundMessage*/undefined, /*nameArg*/undefined); if (!symbol || symbol === unknownSymbol || !symbol.valueDeclaration) { return; } @@ -20795,7 +20926,7 @@ namespace ts { if (isFunctionLike(current)) { return "quit"; } - if (current.kind === SyntaxKind.LabeledStatement && (current).label.text === node.label.text) { + if (current.kind === SyntaxKind.LabeledStatement && (current).label.escapedText === node.label.escapedText) { const sourceFile = getSourceFileOfNode(node); grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNodeFromSourceText(sourceFile.text, node.label)); return true; @@ -20915,7 +21046,7 @@ namespace ts { const propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { + if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { return; } @@ -20935,7 +21066,7 @@ namespace ts { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together - const someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind)); + const someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind)); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } @@ -20949,10 +21080,10 @@ namespace ts { } } - function checkTypeNameIsReserved(name: DeclarationName, message: DiagnosticMessage): void { + function checkTypeNameIsReserved(name: Identifier, message: DiagnosticMessage): void { // TS 1.0 spec (April 2014): 3.6.1 // The predefined type keywords are reserved and cannot be used as names of user defined types. - switch ((name).text) { + switch (name.escapedText) { case "any": case "number": case "boolean": @@ -20960,7 +21091,7 @@ namespace ts { case "symbol": case "void": case "object": - error(name, message, (name).text as string); + error(name, message, (name).escapedText as string); } } @@ -21033,7 +21164,7 @@ namespace ts { // If the type parameter node does not have the same as the resolved type // parameter at this position, we report an error. - if (source.name.text !== target.symbol.name) { + if (source.name.escapedText !== target.symbol.escapedName) { return false; } @@ -21226,7 +21357,7 @@ namespace ts { continue; } - const derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); + const derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); @@ -21297,15 +21428,15 @@ namespace ts { type InheritanceInfoMap = { prop: Symbol; containingType: Type }; const seen = createUnderscoreEscapedMap(); - forEach(resolveDeclaredMembers(type).declaredProperties, p => { seen.set(p.name, { prop: p, containingType: type }); }); + forEach(resolveDeclaredMembers(type).declaredProperties, p => { seen.set(p.escapedName, { prop: p, containingType: type }); }); let ok = true; for (const base of baseTypes) { const properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType)); for (const prop of properties) { - const existing = seen.get(prop.name); + const existing = seen.get(prop.escapedName); if (!existing) { - seen.set(prop.name, { prop, containingType: base }); + seen.set(prop.escapedName, { prop, containingType: base }); } else { const isInheritedProperty = existing.containingType !== type; @@ -21487,15 +21618,22 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return evaluate((expr).expression); case SyntaxKind.Identifier: - return nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), (expr).text); + return nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), (expr).escapedText); case SyntaxKind.ElementAccessExpression: case SyntaxKind.PropertyAccessExpression: - if (isConstantMemberAccess(expr)) { - const type = getTypeOfExpression((expr).expression); + const ex = expr; + if (isConstantMemberAccess(ex)) { + const type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & SymbolFlags.Enum) { - const name = expr.kind === SyntaxKind.PropertyAccessExpression ? - (expr).name.text : - ((expr).argumentExpression).text as __String; + let name: __String; + if (ex.kind === SyntaxKind.PropertyAccessExpression) { + name = ex.name.escapedText; + } + else { + const argument = ex.argumentExpression; + Debug.assert(isLiteralExpression(argument)); + name = escapeLeadingUnderscores((argument as LiteralExpression).text); + } return evaluateEnumMember(expr, type.symbol, name); } } @@ -21801,7 +21939,7 @@ namespace ts { Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; } - if (inAmbientExternalModule && isExternalModuleNameRelative((moduleName).text)) { + if (inAmbientExternalModule && isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(moduleName))) { // we have already reported errors on top level imports\exports in external module augmentations in checkModuleDeclaration // no need to do this again. if (!isTopLevelInExternalModuleAugmentation(node)) { @@ -21966,10 +22104,10 @@ namespace ts { if (!(node.parent.parent).moduleSpecifier) { const exportedName = node.propertyName || node.name; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) - const symbol = resolveName(exportedName, exportedName.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, + const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { - error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, unescapeLeadingUnderscores(exportedName.text)); + error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, unescapeLeadingUnderscores(exportedName.escapedText)); } else { markExportAsReferenced(node); @@ -22458,7 +22596,7 @@ namespace ts { */ function copySymbol(symbol: Symbol, meaning: SymbolFlags): void { if (getCombinedLocalAndExportSymbolFlags(symbol) & meaning) { - const id = symbol.name; + const id = symbol.escapedName; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array @@ -22616,8 +22754,7 @@ namespace ts { } if (entityName.parent!.kind === SyntaxKind.JSDocParameterTag) { - const parameter = getParameterFromJSDoc(entityName.parent as JSDocParameterTag); - return parameter && parameter.symbol; + return getParameterSymbolFromJSDoc(entityName.parent as JSDocParameterTag); } if (entityName.parent.kind === SyntaxKind.TypeParameter && entityName.parent.parent.kind === SyntaxKind.JSDocTemplateTag) { @@ -22696,7 +22833,7 @@ namespace ts { node.parent.parent.kind === SyntaxKind.ObjectBindingPattern && node === (node.parent).propertyName) { const typeOfPattern = getTypeOfNode(node.parent.parent); - const propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).text); + const propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -22888,7 +23025,7 @@ namespace ts { function getPropertySymbolOfDestructuringAssignment(location: Identifier) { // Get the type of the object or array literal and then look for property of given name in the type const typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); - return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.text); + return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText); } function getRegularTypeOfExpression(expr: Expression): Type { @@ -22916,8 +23053,8 @@ namespace ts { const propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, SignatureKind.Call).length || getSignaturesOfType(type, SignatureKind.Construct).length) { forEach(getPropertiesOfType(globalFunctionType), p => { - if (!propsByName.has(p.name)) { - propsByName.set(p.name, p); + if (!propsByName.has(p.escapedName)) { + propsByName.set(p.escapedName, p); } }); } @@ -22927,7 +23064,7 @@ namespace ts { function getRootSymbols(symbol: Symbol): Symbol[] { if (getCheckFlags(symbol) & CheckFlags.Synthetic) { const symbols: Symbol[] = []; - const name = symbol.name; + const name = symbol.escapedName; forEach(getSymbolLinks(symbol).containingType.types, t => { const symbol = getPropertyOfType(t, name); if (symbol) { @@ -23064,7 +23201,7 @@ namespace ts { const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (isStatementWithLocals(container)) { const nodeLinks = getNodeLinks(symbol.valueDeclaration); - if (!!resolveName(container.parent, symbol.name, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { + if (!!resolveName(container.parent, symbol.escapedName, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined)) { // redeclaration - always should be renamed links.isDeclarationWithCollidingName = true; } @@ -23365,7 +23502,7 @@ namespace ts { } } - return resolveName(location, reference.text, SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); + return resolveName(location, reference.escapedText, SymbolFlags.Value | SymbolFlags.ExportValue | SymbolFlags.Alias, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); } function getReferencedValueDeclaration(reference: Identifier): Declaration { @@ -24322,8 +24459,8 @@ namespace ts { const jsxAttr = (attr); const name = jsxAttr.name; - if (!seen.get(name.text)) { - seen.set(name.text, true); + if (!seen.get(name.escapedText)) { + seen.set(name.escapedText, true); } else { return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); @@ -24497,7 +24634,7 @@ namespace ts { switch (current.kind) { case SyntaxKind.LabeledStatement: - if (node.label && (current).label.text === node.label.text) { + if (node.label && (current).label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements const isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement @@ -24618,7 +24755,7 @@ namespace ts { function checkESModuleMarker(name: Identifier | BindingPattern): boolean { if (name.kind === SyntaxKind.Identifier) { - if (unescapeLeadingUnderscores(name.text) === "__esModule") { + if (unescapeLeadingUnderscores(name.escapedText) === "__esModule") { return grammarErrorOnNode(name, Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); } } @@ -24689,8 +24826,8 @@ namespace ts { function checkGrammarMetaProperty(node: MetaProperty) { if (node.keywordToken === SyntaxKind.NewKeyword) { - if (node.name.text !== "target") { - return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.text, tokenToString(node.keywordToken), "target"); + if (node.name.escapedText !== "target") { + return grammarErrorOnNode(node.name, Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, tokenToString(node.keywordToken), "target"); } } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 209562f842d..efb574ac971 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -728,12 +728,12 @@ namespace ts { } /* @internal */ - export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) { + export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Push) { return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); } /* @internal */ - export function parseListTypeOption(opt: CommandLineOptionOfListType, value = "", errors: Diagnostic[]): (string | number)[] | undefined { + export function parseListTypeOption(opt: CommandLineOptionOfListType, value = "", errors: Push): (string | number)[] | undefined { value = trimString(value); if (startsWith(value, "-")) { return undefined; @@ -752,7 +752,7 @@ namespace ts { } } - export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string | undefined): ParsedCommandLine { + export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { const options: CompilerOptions = {}; const fileNames: string[] = []; const errors: Diagnostic[] = []; @@ -764,7 +764,7 @@ namespace ts { errors }; - function parseStrings(args: string[]) { + function parseStrings(args: ReadonlyArray) { let i = 0; while (i < args.length) { const s = args[i]; @@ -916,7 +916,7 @@ namespace ts { return text === undefined ? createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; } - function commandLineOptionsToMap(options: CommandLineOption[]) { + function commandLineOptionsToMap(options: ReadonlyArray) { return arrayToMap(options, option => option.name); } @@ -1007,7 +1007,7 @@ namespace ts { /** * Convert the json syntax tree into the json value */ - export function convertToObject(sourceFile: JsonSourceFile, errors: Diagnostic[]): any { + export function convertToObject(sourceFile: JsonSourceFile, errors: Push): any { return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); } @@ -1016,7 +1016,7 @@ namespace ts { */ function convertToObjectWorker( sourceFile: JsonSourceFile, - errors: Diagnostic[], + errors: Push, knownRootOptions: Map | undefined, jsonConversionNotifier: JsonConversionNotifier | undefined): any { if (!sourceFile.jsonObject) { @@ -1085,11 +1085,7 @@ namespace ts { elements: NodeArray, elementOption: CommandLineOption | undefined ): any[] { - const result: any[] = []; - for (const element of elements) { - result.push(convertPropertyValueToJson(element, elementOption)); - } - return result; + return elements.map(element => convertPropertyValueToJson(element, elementOption)); } function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption): any { @@ -1202,17 +1198,9 @@ namespace ts { * @param fileNames array of filenames to be generated into tsconfig.json */ /* @internal */ - export function generateTSConfig(options: CompilerOptions, fileNames: string[], newLine: string): string { + export function generateTSConfig(options: CompilerOptions, fileNames: ReadonlyArray, newLine: string): string { const compilerOptions = extend(options, defaultInitCompilerOptions); - const configurations: { compilerOptions: MapLike; files?: string[] } = { - compilerOptions: serializeCompilerOptions(compilerOptions) - }; - if (fileNames && fileNames.length) { - // only set the files property if we have at least one file - configurations.files = fileNames; - } - - + const compilerOptionsMap = serializeCompilerOptions(compilerOptions); return writeConfigurations(); function getCustomTypeMapOfCommandLineOption(optionDefinition: CommandLineOption): Map | undefined { @@ -1237,8 +1225,8 @@ namespace ts { }); } - function serializeCompilerOptions(options: CompilerOptions): MapLike { - const result: ts.MapLike = {}; + function serializeCompilerOptions(options: CompilerOptions): Map { + const result = createMap(); const optionsNameMap = getOptionNameMap().optionNameMap; for (const name in options) { @@ -1255,19 +1243,15 @@ namespace ts { if (!customTypeMap) { // There is no map associated with this compiler option then use the value as-is // This is the case if the value is expect to be string, number, boolean or list of string - result[name] = value; + result.set(name, value); } else { if (optionDefinition.type === "list") { - const convertedValue: string[] = []; - for (const element of value as (string | number)[]) { - convertedValue.push(getNameOfCompilerOptionValue(element, customTypeMap)); - } - result[name] = convertedValue; + result.set(name, (value as ReadonlyArray).map(element => getNameOfCompilerOptionValue(element, customTypeMap))); } else { // There is a typeMap associated with this command-line option so use it to map value back to its name - result[name] = getNameOfCompilerOptionValue(value, customTypeMap); + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap)); } } } @@ -1299,33 +1283,30 @@ namespace ts { function writeConfigurations() { // Filter applicable options to place in the file - const categorizedOptions = reduceLeft( - filter(optionDeclarations, o => o.category !== Diagnostics.Command_line_Options && o.category !== Diagnostics.Advanced_Options), - (memo, value) => { - if (value.category) { - const name = getLocaleSpecificMessage(value.category); - (memo[name] || (memo[name] = [])).push(value); - } - return memo; - }, >{}); + const categorizedOptions = createMultiMap(); + for (const option of optionDeclarations) { + const { category } = option; + if (category !== undefined && category !== Diagnostics.Command_line_Options && category !== Diagnostics.Advanced_Options) { + categorizedOptions.add(getLocaleSpecificMessage(category), option); + } + } - // Serialize all options and thier descriptions + // Serialize all options and their descriptions let marginLength = 0; let seenKnownKeys = 0; const nameColumn: string[] = []; const descriptionColumn: string[] = []; - const knownKeysCount = getOwnKeys(configurations.compilerOptions).length; - for (const category in categorizedOptions) { + categorizedOptions.forEach((options, category) => { if (nameColumn.length !== 0) { nameColumn.push(""); descriptionColumn.push(""); } nameColumn.push(`/* ${category} */`); descriptionColumn.push(""); - for (const option of categorizedOptions[category]) { + for (const option of options) { let optionName; - if (hasProperty(configurations.compilerOptions, option.name)) { - optionName = `"${option.name}": ${JSON.stringify(configurations.compilerOptions[option.name])}${(seenKnownKeys += 1) === knownKeysCount ? "" : ","}`; + if (compilerOptionsMap.has(option.name)) { + optionName = `"${option.name}": ${JSON.stringify(compilerOptionsMap.get(option.name))}${(seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","}`; } else { optionName = `// "${option.name}": ${JSON.stringify(getDefaultValueForOption(option))},`; @@ -1334,7 +1315,7 @@ namespace ts { descriptionColumn.push(`/* ${option.description && getLocaleSpecificMessage(option.description) || option.name} */`); marginLength = Math.max(optionName.length, marginLength); } - } + }); // Write the output const tab = makePadding(2); @@ -1347,11 +1328,11 @@ namespace ts { const description = descriptionColumn[i]; result.push(optionName && `${tab}${tab}${optionName}${ description && (makePadding(marginLength - optionName.length + 2) + description)}`); } - if (configurations.files && configurations.files.length) { + if (fileNames.length) { result.push(`${tab}},`); result.push(`${tab}"files": [`); - for (let i = 0; i < configurations.files.length; i++) { - result.push(`${tab}${tab}${JSON.stringify(configurations.files[i])}${i === configurations.files.length - 1 ? "" : ","}`); + for (let i = 0; i < fileNames.length; i++) { + result.push(`${tab}${tab}${JSON.stringify(fileNames[i])}${i === fileNames.length - 1 ? "" : ","}`); } result.push(`${tab}]`); } @@ -1371,7 +1352,7 @@ namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - 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?: ReadonlyArray): ParsedCommandLine { return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); } @@ -1382,7 +1363,7 @@ namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - export function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine { + export function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine { return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); } @@ -1410,7 +1391,7 @@ namespace ts { existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], - extraFileExtensions: JsFileExtensionInfo[] = [], + extraFileExtensions: ReadonlyArray = [], ): ParsedCommandLine { Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); const errors: Diagnostic[] = []; @@ -1434,10 +1415,10 @@ namespace ts { }; function getFileNames(): ExpandResult { - let filesSpecs: string[]; + let filesSpecs: ReadonlyArray; if (hasProperty(raw, "files")) { if (isArray(raw["files"])) { - filesSpecs = raw["files"]; + filesSpecs = >raw["files"]; if (filesSpecs.length === 0) { createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } @@ -1447,20 +1428,20 @@ namespace ts { } } - let includeSpecs: string[]; + let includeSpecs: ReadonlyArray; if (hasProperty(raw, "include")) { if (isArray(raw["include"])) { - includeSpecs = raw["include"]; + includeSpecs = >raw["include"]; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); } } - let excludeSpecs: string[]; + let excludeSpecs: ReadonlyArray; if (hasProperty(raw, "exclude")) { if (isArray(raw["exclude"])) { - excludeSpecs = raw["exclude"]; + excludeSpecs = >raw["exclude"]; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); @@ -1468,12 +1449,13 @@ namespace ts { } else { // If no includes were specified, exclude common package folders and the outDir - excludeSpecs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; + const specs = includeSpecs ? [] : ["node_modules", "bower_components", "jspm_packages"]; const outDir = raw["compilerOptions"] && raw["compilerOptions"]["outDir"]; if (outDir) { - excludeSpecs.push(outDir); + specs.push(outDir); } + excludeSpecs = specs; } if (filesSpecs === undefined && includeSpecs === undefined) { @@ -1527,7 +1509,7 @@ namespace ts { configFileName: string, getCanonicalFileName: (fileName: string) => string, resolutionStack: Path[], - errors: Diagnostic[], + errors: Push, ): ParsedTsconfig { basePath = normalizeSlashes(basePath); const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName); @@ -1575,7 +1557,7 @@ namespace ts { basePath: string, getCanonicalFileName: (fileName: string) => string, configFileName: string, - errors: Diagnostic[] + errors: Push ): ParsedTsconfig { if (hasProperty(json, "excludes")) { errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); @@ -1605,7 +1587,7 @@ namespace ts { basePath: string, getCanonicalFileName: (fileName: string) => string, configFileName: string, - errors: Diagnostic[] + errors: Push ): ParsedTsconfig { const options = getDefaultCompilerOptions(configFileName); let typeAcquisition: TypeAcquisition, typingOptionstypeAcquisition: TypeAcquisition; @@ -1636,7 +1618,7 @@ namespace ts { ); return; case "files": - if ((value).length === 0) { + if ((>value).length === 0) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueNode, Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); } return; @@ -1672,7 +1654,7 @@ namespace ts { host: ParseConfigHost, basePath: string, getCanonicalFileName: (fileName: string) => string, - errors: Diagnostic[], + errors: Push, createDiagnostic: (message: DiagnosticMessage, arg1?: string) => Diagnostic) { extendedConfig = normalizeSlashes(extendedConfig); // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) @@ -1698,7 +1680,7 @@ namespace ts { basePath: string, getCanonicalFileName: (fileName: string) => string, resolutionStack: Path[], - errors: Diagnostic[], + errors: Push, ): ParsedTsconfig | undefined { const extendedResult = readJsonConfigFile(extendedConfigPath, path => host.readFile(path)); if (sourceFile) { @@ -1735,7 +1717,7 @@ namespace ts { return extendedConfig; } - function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean { + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Push): boolean { if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) { return undefined; } @@ -1766,7 +1748,7 @@ namespace ts { } function convertCompilerOptionsFromJsonWorker(jsonOptions: any, - basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions { + basePath: string, errors: Push, configFileName?: string): CompilerOptions { const options = getDefaultCompilerOptions(configFileName); convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors); @@ -1779,7 +1761,7 @@ namespace ts { } function convertTypeAcquisitionFromJsonWorker(jsonOptions: any, - basePath: string, errors: Diagnostic[], configFileName?: string): TypeAcquisition { + basePath: string, errors: Push, configFileName?: string): TypeAcquisition { const options = getDefaultTypeAcquisition(configFileName); const typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); @@ -1788,8 +1770,8 @@ namespace ts { return options; } - function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string, - defaultOptions: CompilerOptions | TypeAcquisition, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) { + function convertOptionsFromJson(optionDeclarations: ReadonlyArray, jsonOptions: any, basePath: string, + defaultOptions: CompilerOptions | TypeAcquisition, diagnosticMessage: DiagnosticMessage, errors: Push) { if (!jsonOptions) { return; @@ -1808,7 +1790,7 @@ namespace ts { } } - function convertJsonOption(opt: CommandLineOption, value: any, basePath: string, errors: Diagnostic[]): CompilerOptionsValue { + function convertJsonOption(opt: CommandLineOption, value: any, basePath: string, errors: Push): CompilerOptionsValue { if (isCompilerOptionsValue(opt, value)) { const optType = opt.type; if (optType === "list" && isArray(value)) { @@ -1848,7 +1830,7 @@ namespace ts { return value; } - function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) { + function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Push) { const key = value.toLowerCase(); const val = opt.type.get(key); if (val !== undefined) { @@ -1859,7 +1841,7 @@ namespace ts { } } - function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: any[], basePath: string, errors: Diagnostic[]): any[] { + function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: ReadonlyArray, basePath: string, errors: Push): any[] { return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v); } @@ -1950,9 +1932,19 @@ namespace ts { * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - function matchFileNames(filesSpecs: string[], includeSpecs: string[], excludeSpecs: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: JsFileExtensionInfo[], jsonSourceFile: JsonSourceFile): ExpandResult { + function matchFileNames( + filesSpecs: ReadonlyArray, + includeSpecs: ReadonlyArray, + excludeSpecs: ReadonlyArray, + basePath: string, + options: CompilerOptions, + host: ParseConfigHost, + errors: Push, + extraFileExtensions: ReadonlyArray, + jsonSourceFile: JsonSourceFile + ): ExpandResult { basePath = normalizePath(basePath); - let validatedIncludeSpecs: string[], validatedExcludeSpecs: string[]; + let validatedIncludeSpecs: ReadonlyArray, validatedExcludeSpecs: ReadonlyArray; // The exclude spec list is converted into a regular expression, which allows us to quickly // test whether a file or directory should be excluded before recursively traversing the @@ -1987,7 +1979,7 @@ namespace ts { * @param host The host used to resolve files and directories. * @param errors An array for diagnostic reporting. */ - export function getFileNamesFromConfigSpecs(spec: ConfigFileSpecs, basePath: string, options: CompilerOptions, host: ParseConfigHost, extraFileExtensions: JsFileExtensionInfo[]): ExpandResult { + export function getFileNamesFromConfigSpecs(spec: ConfigFileSpecs, basePath: string, options: CompilerOptions, host: ParseConfigHost, extraFileExtensions: ReadonlyArray): ExpandResult { basePath = normalizePath(basePath); const keyMapper = host.useCaseSensitiveFileNames ? caseSensitiveKeyMapper : caseInsensitiveKeyMapper; @@ -2051,7 +2043,7 @@ namespace ts { }; } - function validateSpecs(specs: string[], errors: Diagnostic[], allowTrailingRecursion: boolean, jsonSourceFile: JsonSourceFile, specKey: string) { + function validateSpecs(specs: ReadonlyArray, errors: Push, allowTrailingRecursion: boolean, jsonSourceFile: JsonSourceFile, specKey: string): ReadonlyArray { const validSpecs: string[] = []; for (const spec of specs) { if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { @@ -2075,7 +2067,7 @@ namespace ts { for (const property of getPropertyAssignment(jsonSourceFile.jsonObject, specKey)) { if (isArrayLiteralExpression(property.initializer)) { for (const element of property.initializer.elements) { - if (element.kind === SyntaxKind.StringLiteral && (element).text === spec) { + if (isStringLiteral(element) && element.text === spec) { return createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); } } @@ -2089,7 +2081,7 @@ namespace ts { /** * Gets directories in a set of include patterns that should be watched for changes. */ - function getWildcardDirectories(include: string[], exclude: string[], path: string, useCaseSensitiveFileNames: boolean): MapLike { + function getWildcardDirectories(include: ReadonlyArray, exclude: ReadonlyArray, path: string, useCaseSensitiveFileNames: boolean): MapLike { // We watch a directory recursively if it contains a wildcard anywhere in a directory segment // of the pattern: // diff --git a/src/compiler/core.ts b/src/compiler/core.ts index a5b5e2c7e21..54b772cc29c 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -59,7 +59,7 @@ namespace ts { const result = createMap() as SymbolTable; if (symbols) { for (const symbol of symbols) { - result.set(symbol.name, symbol); + result.set(symbol.escapedName, symbol); } } return result; @@ -718,7 +718,7 @@ namespace ts { * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted * based on the provided comparer. */ - export function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: (x: T, y: T) => Comparison = compareValues, offsetA = 0, offsetB = 0): T[] | undefined { + export function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: Comparer = compareValues, offsetA = 0, offsetB = 0): T[] | undefined { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; const result: T[] = []; outer: for (; offsetB < arrayB.length; offsetB++) { @@ -2313,7 +2313,7 @@ namespace ts { function Symbol(this: Symbol, flags: SymbolFlags, name: __String) { this.flags = flags; - this.name = name; + this.escapedName = name; this.declarations = undefined; } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 5f4b3175ca9..43f7446865f 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1164,7 +1164,7 @@ namespace ts { if (baseTypeNode && !isEntityNameExpression(baseTypeNode.expression)) { tempVarName = baseTypeNode.expression.kind === SyntaxKind.NullKeyword ? "null" : - emitTempVariableDeclaration(baseTypeNode.expression, `${node.name.text}_base`, { + emitTempVariableDeclaration(baseTypeNode.expression, `${node.name.escapedText}_base`, { diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: baseTypeNode, typeName: node.name diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index b2e2b882692..61c8da92ceb 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2192,6 +2192,10 @@ "category": "Error", "code": 2712 }, + "Cannot access '{0}.{1}' because '{0}' is a type, but not a namespace. Did you mean to retrieve the type of the property '{1}' in '{0}' with '{0}[\"{1}\"]'?": { + "category": "Error", + "code": 2713 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -3451,6 +3455,10 @@ "category": "Error", "code": 8012 }, + "'non-null assertions' can only be used in a .ts file.": { + "category": "Error", + "code": 8013 + }, "'enum declarations' can only be used in a .ts file.": { "category": "Error", "code": 8015 @@ -3649,6 +3657,10 @@ "category": "Message", "code": 90025 }, + "Rewrite as the indexed access type '{0}'.": { + "category": "Message", + "code": 90026 + }, "Convert function to an ES2015 class": { "category": "Message", diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 759fe9f0abc..4f07331a98e 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1346,7 +1346,9 @@ namespace ts { emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); + emitLeadingCommentsOfPosition(node.operatorToken.pos); writeTokenNode(node.operatorToken); + emitTrailingCommentsOfPosition(node.operatorToken.end); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); decreaseIndentIf(indentBeforeOperator, indentAfterOperator); @@ -2761,7 +2763,7 @@ namespace ts { return generateName(node); } else if (isIdentifier(node) && (nodeIsSynthesized(node) || !node.parent)) { - return unescapeLeadingUnderscores(node.text); + return unescapeLeadingUnderscores(node.escapedText); } else if (node.kind === SyntaxKind.StringLiteral && (node).textSourceNode) { return getTextOfNode((node).textSourceNode, includeTrivia); @@ -2917,8 +2919,8 @@ namespace ts { */ function generateNameForImportOrExportDeclaration(node: ImportDeclaration | ExportDeclaration) { const expr = getExternalModuleName(node); - const baseName = expr.kind === SyntaxKind.StringLiteral ? - makeIdentifierFromModuleName((expr).text) : "module"; + const baseName = isStringLiteral(expr) ? + makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); } @@ -2981,7 +2983,7 @@ namespace ts { case GeneratedIdentifierKind.Loop: return makeTempVariableName(TempFlags._i); case GeneratedIdentifierKind.Unique: - return makeUniqueName(unescapeLeadingUnderscores(name.text)); + return makeUniqueName(unescapeLeadingUnderscores(name.escapedText)); } Debug.fail("Unsupported GeneratedIdentifierKind."); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index d6d21254218..34727e4c414 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -114,7 +114,7 @@ namespace ts { export function createIdentifier(text: string, typeArguments: ReadonlyArray): Identifier; export function createIdentifier(text: string, typeArguments?: ReadonlyArray): Identifier { const node = createSynthesizedNode(SyntaxKind.Identifier); - node.text = escapeLeadingUnderscores(text); + node.escapedText = escapeLeadingUnderscores(text); node.originalKeywordKind = text ? stringToToken(text) : SyntaxKind.Unknown; node.autoGenerateKind = GeneratedIdentifierKind.None; node.autoGenerateId = 0; @@ -126,7 +126,7 @@ namespace ts { export function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier { return node.typeArguments !== typeArguments - ? updateNode(createIdentifier(unescapeLeadingUnderscores(node.text), typeArguments), node) + ? updateNode(createIdentifier(unescapeLeadingUnderscores(node.escapedText), typeArguments), node) : node; } @@ -2863,12 +2863,12 @@ namespace ts { function createJsxFactoryExpressionFromEntityName(jsxFactory: EntityName, parent: JsxOpeningLikeElement): Expression { if (isQualifiedName(jsxFactory)) { const left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent); - const right = createIdentifier(unescapeLeadingUnderscores(jsxFactory.right.text)); - right.text = jsxFactory.right.text; + const right = createIdentifier(unescapeLeadingUnderscores(jsxFactory.right.escapedText)); + right.escapedText = jsxFactory.right.escapedText; return createPropertyAccess(left, right); } else { - return createReactNamespace(unescapeLeadingUnderscores(jsxFactory.text), parent); + return createReactNamespace(unescapeLeadingUnderscores(jsxFactory.escapedText), parent); } } @@ -3477,7 +3477,7 @@ namespace ts { } function isUseStrictPrologue(node: ExpressionStatement): boolean { - return (node.expression as StringLiteral).text === "use strict"; + return isStringLiteral(node.expression) && node.expression.text === "use strict"; } /** diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 59afd8daff0..513c741ba09 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -13,12 +13,6 @@ namespace ts { return compilerOptions.traceResolution && host.trace !== undefined; } - /** Array that is only intended to be pushed to, never read. */ - /* @internal */ - export interface Push { - push(value: T): void; - } - /** * Result of trying to resolve a module. * At least one of `ts` and `js` should be defined, or the whole thing should be `undefined`. @@ -262,6 +256,8 @@ namespace ts { for (const typeDirectivePath of host.getDirectories(root)) { const normalized = normalizePath(typeDirectivePath); const packageJsonPath = pathToPackageJson(combinePaths(root, normalized)); + // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. + // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword const isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; if (!isNotNeededPackage) { diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 0be7734968f..49b682c7302 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -59,6 +59,9 @@ namespace ts { * @param node a given node to visit its children * @param cbNode a callback to be invoked for all child nodes * @param cbNodes a callback to be invoked for embedded array + * + * @remarks `forEachChild` must visit the children of a node in the order + * that they appear in the source code. The language service depends on this property to locate nodes by position. */ export function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { if (!node || node.kind <= SyntaxKind.LastToken) { @@ -407,9 +410,15 @@ namespace ts { case SyntaxKind.JSDocComment: return visitNodes(cbNode, cbNodes, (node).tags); case SyntaxKind.JSDocParameterTag: - return visitNode(cbNode, (node).preParameterName) || - visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).postParameterName); + case SyntaxKind.JSDocPropertyTag: + if ((node as JSDocPropertyLikeTag).isNameFirst) { + return visitNode(cbNode, (node).name) || + visitNode(cbNode, (node).typeExpression); + } + else { + return visitNode(cbNode, (node).typeExpression) || + visitNode(cbNode, (node).name); + } case SyntaxKind.JSDocReturnTag: return visitNode(cbNode, (node).typeExpression); case SyntaxKind.JSDocTypeTag: @@ -419,15 +428,20 @@ namespace ts { case SyntaxKind.JSDocTemplateTag: return visitNodes(cbNode, cbNodes, (node).typeParameters); case SyntaxKind.JSDocTypedefTag: - return visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).fullName) || - visitNode(cbNode, (node).name) || - visitNode(cbNode, (node).jsDocTypeLiteral); + if ((node as JSDocTypedefTag).typeExpression && + (node as JSDocTypedefTag).typeExpression.kind === SyntaxKind.JSDocTypeExpression) { + return visitNode(cbNode, (node).typeExpression) || + visitNode(cbNode, (node).fullName); + } + else { + return visitNode(cbNode, (node).fullName) || + visitNode(cbNode, (node).typeExpression); + } case SyntaxKind.JSDocTypeLiteral: - return visitNodes(cbNode, cbNodes, (node).jsDocPropertyTags); - case SyntaxKind.JSDocPropertyTag: - return visitNode(cbNode, (node).typeExpression) || - visitNode(cbNode, (node).name); + for (const tag of (node as JSDocTypeLiteral).jsDocPropertyTags) { + visitNode(cbNode, tag); + } + return; case SyntaxKind.PartiallyEmittedExpression: return visitNode(cbNode, (node).expression); } @@ -1149,7 +1163,7 @@ namespace ts { return node; } - function createMissingNode(kind: SyntaxKind, reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): Node { + function createMissingNode(kind: T["kind"], reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, arg0?: any): T { if (reportAtCurrentPosition) { parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); } @@ -1158,8 +1172,15 @@ namespace ts { } const result = createNode(kind, scanner.getStartPos()); - (result).text = "" as __String; - return finishNode(result); + + if (kind === SyntaxKind.Identifier) { + (result as Identifier).escapedText = "" as __String; + } + else if (isLiteralKind(kind) || isTemplateLiteralKind(kind)) { + (result as LiteralLikeNode).text = ""; + } + + return finishNode(result) as T; } function internIdentifier(text: string): string { @@ -1182,12 +1203,12 @@ namespace ts { if (token() !== SyntaxKind.Identifier) { node.originalKeywordKind = token(); } - node.text = escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); + node.escapedText = escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue())); nextToken(); return finishNode(node); } - return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, diagnosticMessage || Diagnostics.Identifier_expected); + return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, diagnosticMessage || Diagnostics.Identifier_expected); } function parseIdentifier(diagnosticMessage?: DiagnosticMessage): Identifier { @@ -1858,9 +1879,12 @@ namespace ts { let commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /*inErrorRecovery*/ false)) { + const startPos = scanner.getStartPos(); result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); + if (parseOptional(SyntaxKind.CommaToken)) { + // No need to check for a zero length node since we know we parsed a comma continue; } @@ -1881,6 +1905,13 @@ namespace ts { if (considerSemicolonAsDelimiter && token() === SyntaxKind.SemicolonToken && !scanner.hasPrecedingLineBreak()) { nextToken(); } + if (startPos === scanner.getStartPos()) { + // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever + // Consume a token to advance the parser in some way and avoid an infinite loop + // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions, + // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied + nextToken(); + } continue; } @@ -1932,14 +1963,18 @@ namespace ts { break; } dotPos = scanner.getStartPos(); - const node: QualifiedName = createNode(SyntaxKind.QualifiedName, entity.pos); - node.left = entity; - node.right = parseRightSideOfDot(allowReservedWords); - entity = finishNode(node); + entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords)); } return entity; } + function createQualifiedName(entity: EntityName, name: Identifier): QualifiedName { + const node = createNode(SyntaxKind.QualifiedName, entity.pos) as QualifiedName; + node.left = entity; + node.right = name; + return finishNode(node); + } + function parseRightSideOfDot(allowIdentifierNames: boolean): Identifier { // Technically a keyword is valid here as all identifiers and keywords are identifier names. // However, often we'll encounter this in error situations when the identifier or keyword @@ -1967,7 +2002,7 @@ namespace ts { // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); + return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); } } @@ -2026,7 +2061,7 @@ namespace ts { return fragment; } - function parseLiteralLikeNode(kind: SyntaxKind): LiteralLikeNode { + function parseLiteralLikeNode(kind: SyntaxKind): LiteralExpression | LiteralLikeNode { const node = createNode(kind); const text = scanner.getTokenValue(); node.text = text; @@ -2202,8 +2237,7 @@ namespace ts { return token() === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token()) || - token() === SyntaxKind.AtToken || token() === SyntaxKind.ThisKeyword || token() === SyntaxKind.NewKeyword || - token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral; + token() === SyntaxKind.AtToken || isStartOfType(); } function parseParameter(): ParameterDeclaration { @@ -2237,15 +2271,6 @@ namespace ts { node.type = parseParameterType(); node.initializer = parseBindingElementInitializer(/*inParameter*/ true); - // Do not check for initializers in an ambient context for parameters. This is not - // a grammar error because the grammar allows arbitrary call signatures in - // an ambient context. - // It is actually not necessary for this to be an error at all. The reason is that - // function/constructor implementations are syntactically disallowed in ambient - // contexts. In addition, parameter initializers are semantically disallowed in - // overload signatures. So parameter initializers are transitively disallowed in - // ambient contexts. - return addJSDocComment(finishNode(node)); } @@ -2586,11 +2611,31 @@ namespace ts { return token() === SyntaxKind.DotToken ? undefined : node; } - function parseLiteralTypeNode(): LiteralTypeNode { - const node = createNode(SyntaxKind.LiteralType); - node.literal = parseSimpleUnaryExpression(); - finishNode(node); - return node; + function parseLiteralTypeNode(negative?: boolean): LiteralTypeNode { + const node = createNode(SyntaxKind.LiteralType) as LiteralTypeNode; + let unaryMinusExpression: PrefixUnaryExpression; + if (negative) { + unaryMinusExpression = createNode(SyntaxKind.PrefixUnaryExpression) as PrefixUnaryExpression; + unaryMinusExpression.operator = SyntaxKind.MinusToken; + nextToken(); + } + let expression: UnaryExpression; + switch (token()) { + case SyntaxKind.StringLiteral: + case SyntaxKind.NumericLiteral: + expression = parseLiteralLikeNode(token()) as LiteralExpression; + break; + case SyntaxKind.TrueKeyword: + case SyntaxKind.FalseKeyword: + expression = parseTokenNode(); + } + if (negative) { + unaryMinusExpression.operand = expression; + finishNode(unaryMinusExpression); + expression = unaryMinusExpression; + } + node.literal = expression; + return finishNode(node); } function nextTokenIsNumericLiteral() { @@ -2625,7 +2670,7 @@ namespace ts { case SyntaxKind.FalseKeyword: return parseLiteralTypeNode(); case SyntaxKind.MinusToken: - return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode() : parseTypeReference(); + return lookAhead(nextTokenIsNumericLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); case SyntaxKind.VoidKeyword: case SyntaxKind.NullKeyword: return parseTokenNode(); @@ -2675,6 +2720,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.ObjectKeyword: + case SyntaxKind.AsteriskToken: return true; case SyntaxKind.MinusToken: return lookAhead(nextTokenIsNumericLiteral); @@ -3136,7 +3182,7 @@ namespace ts { return addJSDocComment(finishNode(node)); } - function tryParseParenthesizedArrowFunctionExpression(): Expression { + function tryParseParenthesizedArrowFunctionExpression(): Expression | undefined { const triState = isParenthesizedArrowFunctionExpression(); if (triState === Tristate.False) { // It's definitely not a parenthesized arrow function expression. @@ -3299,7 +3345,7 @@ namespace ts { return parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false); } - function tryParseAsyncSimpleArrowFunctionExpression(): ArrowFunction { + function tryParseAsyncSimpleArrowFunctionExpression(): ArrowFunction | undefined { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === SyntaxKind.AsyncKeyword) { const isUnParenthesizedAsyncArrowFunction = lookAhead(isUnParenthesizedAsyncArrowFunctionWorker); @@ -3896,7 +3942,7 @@ namespace ts { } if (lhs.kind === SyntaxKind.Identifier) { - return (lhs).text === (rhs).text; + return (lhs).escapedText === (rhs).escapedText; } if (lhs.kind === SyntaxKind.ThisKeyword) { @@ -3906,7 +3952,7 @@ namespace ts { // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element - return (lhs).name.text === (rhs).name.text && + return (lhs).name.escapedText === (rhs).name.escapedText && tagNamesAreEquivalent((lhs).expression as JsxTagNameExpression, (rhs).expression as JsxTagNameExpression); } @@ -4373,7 +4419,7 @@ namespace ts { return finishNode(node); } - function tryParseAccessorDeclaration(fullStart: number, decorators: NodeArray, modifiers: NodeArray): AccessorDeclaration { + function tryParseAccessorDeclaration(fullStart: number, decorators: NodeArray, modifiers: NodeArray): AccessorDeclaration | undefined { if (parseContextualModifier(SyntaxKind.GetKeyword)) { return parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, decorators, modifiers); } @@ -4486,7 +4532,7 @@ namespace ts { return addJSDocComment(finishNode(node)); } - function parseOptionalIdentifier() { + function parseOptionalIdentifier(): Identifier | undefined { return isIdentifier() ? parseIdentifier() : undefined; } @@ -5509,7 +5555,7 @@ namespace ts { if (decorators || modifiers) { // treat this as a property declaration with a missing name. - const name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); } @@ -5551,7 +5597,7 @@ namespace ts { return addJSDocComment(finishNode(node)); } - function parseNameOfClassDeclarationOrExpression(): Identifier { + function parseNameOfClassDeclarationOrExpression(): Identifier | undefined { // implements is a future reserved word so // 'class implements' might mean either // - class expression with omitted name, 'implements' starts heritage clause @@ -6091,7 +6137,7 @@ namespace ts { } export namespace JSDocParser { - export function parseJSDocTypeExpressionForTests(content: string, start: number, length: number) { + export function parseJSDocTypeExpressionForTests(content: string, start: number, length: number): { jsDocTypeExpression: JSDocTypeExpression, diagnostics: Diagnostic[] } | undefined { initializeState(content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS); sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS); scanner.setText(content, start, length); @@ -6116,7 +6162,7 @@ namespace ts { return finishNode(result); } - export function parseIsolatedJSDocComment(content: string, start: number, length: number) { + export function parseIsolatedJSDocComment(content: string, start: number, length: number): { jsDoc: JSDoc, diagnostics: Diagnostic[] } | undefined { initializeState(content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined, ScriptKind.JS); sourceFile = { languageVariant: LanguageVariant.Standard, text: content }; const jsDoc = parseJSDocCommentWorker(start, length); @@ -6155,6 +6201,11 @@ namespace ts { SavingComments, } + const enum PropertyLikeParse { + Property, + Parameter, + } + export function parseJSDocCommentWorker(start: number, length: number): JSDoc { const content = sourceText; start = start || 0; @@ -6323,7 +6374,7 @@ namespace ts { let tag: JSDocTag; if (tagName) { - switch (tagName.text) { + switch (tagName.escapedText) { case "augments": tag = parseAugmentsTag(atToken, tagName); break; @@ -6334,7 +6385,7 @@ namespace ts { case "arg": case "argument": case "param": - tag = parseParameterOrPropertyTag(atToken, tagName, /*shouldParseParamTag*/ true); + tag = parseParameterOrPropertyTag(atToken, tagName, PropertyLikeParse.Parameter); break; case "return": case "returns": @@ -6446,7 +6497,7 @@ namespace ts { tags.end = tag.end; } - function tryParseTypeExpression(): JSDocTypeExpression { + function tryParseTypeExpression(): JSDocTypeExpression | undefined { return tryParse(() => { skipWhitespace(); if (token() !== SyntaxKind.OpenBraceToken) { @@ -6457,10 +6508,10 @@ namespace ts { }); } - function parseBracketNameInPropertyAndParamTag(): { name: Identifier, isBracketed: boolean } { - // Looking for something like '[foo]' or 'foo' + function parseBracketNameInPropertyAndParamTag(): { name: EntityName, isBracketed: boolean } { + // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' const isBracketed = parseOptional(SyntaxKind.OpenBracketToken); - const name = parseJSDocIdentifierName(/*createIfMissing*/ true); + const name = parseJSDocEntityName(); if (isBracketed) { skipWhitespace(); @@ -6475,38 +6526,77 @@ namespace ts { return { name, isBracketed }; } - function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, shouldParseParamTag: boolean): JSDocPropertyTag | JSDocParameterTag { + function isObjectOrObjectArrayTypeReference(node: TypeNode): boolean { + switch (node.kind) { + case SyntaxKind.ObjectKeyword: + return true; + case SyntaxKind.ArrayType: + return isObjectOrObjectArrayTypeReference((node as ArrayTypeNode).elementType); + default: + return isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; + } + } + + function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse.Parameter): JSDocParameterTag; + function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse.Property): JSDocPropertyTag; + function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse): JSDocPropertyLikeTag { let typeExpression = tryParseTypeExpression(); + let isNameFirst = !typeExpression; skipWhitespace(); const { name, isBracketed } = parseBracketNameInPropertyAndParamTag(); skipWhitespace(); - let preName: Identifier, postName: Identifier; - if (typeExpression) { - postName = name; - } - else { - preName = name; + if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - const result = shouldParseParamTag ? + const result: JSDocPropertyLikeTag = target === PropertyLikeParse.Parameter ? createNode(SyntaxKind.JSDocParameterTag, atToken.pos) : createNode(SyntaxKind.JSDocPropertyTag, atToken.pos); + const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + if (nestedTypeLiteral) { + typeExpression = nestedTypeLiteral; + isNameFirst = true; + } result.atToken = atToken; result.tagName = tagName; - result.preParameterName = preName; result.typeExpression = typeExpression; - result.postParameterName = postName; - result.name = postName || preName; + result.name = name; + result.isNameFirst = isNameFirst; result.isBracketed = isBracketed; return finishNode(result); + + } + + function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression, name: EntityName) { + if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + const typeLiteralExpression = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); + let child: JSDocParameterTag | false; + let jsdocTypeLiteral: JSDocTypeLiteral; + const start = scanner.getStartPos(); + let children: JSDocParameterTag[]; + while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.Parameter, name))) { + if (!children) { + children = []; + } + children.push(child); + } + if (children) { + jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); + jsdocTypeLiteral.jsDocPropertyTags = children; + if (typeExpression.type.kind === SyntaxKind.ArrayType) { + jsdocTypeLiteral.isArrayType = true; + } + typeLiteralExpression.type = finishNode(jsdocTypeLiteral); + return finishNode(typeLiteralExpression); + } + } } function parseReturnTag(atToken: AtToken, tagName: Identifier): JSDocReturnTag { if (forEach(tags, t => t.kind === SyntaxKind.JSDocReturnTag)) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.escapedText); } const result = createNode(SyntaxKind.JSDocReturnTag, atToken.pos); @@ -6518,7 +6608,7 @@ namespace ts { function parseTypeTag(atToken: AtToken, tagName: Identifier): JSDocTypeTag { if (forEach(tags, t => t.kind === SyntaxKind.JSDocTypeTag)) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.escapedText); } const result = createNode(SyntaxKind.JSDocTypeTag, atToken.pos); @@ -6565,69 +6655,44 @@ namespace ts { rightNode = rightNode.body; } } - typedefTag.typeExpression = typeExpression; skipWhitespace(); - if (typeExpression) { - if (isObjectTypeReference(typeExpression.type)) { - typedefTag.jsDocTypeLiteral = scanChildTags(); + typedefTag.typeExpression = typeExpression; + if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { + let child: JSDocTypeTag | JSDocPropertyTag | false; + let jsdocTypeLiteral: JSDocTypeLiteral; + let alreadyHasTypeTag = false; + const start = scanner.getStartPos(); + while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.Property))) { + if (!jsdocTypeLiteral) { + jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); + } + if (child.kind === SyntaxKind.JSDocTypeTag) { + if (alreadyHasTypeTag) { + break; + } + else { + jsdocTypeLiteral.jsDocTypeTag = child; + alreadyHasTypeTag = true; + } + } + else { + if (!jsdocTypeLiteral.jsDocPropertyTags) { + jsdocTypeLiteral.jsDocPropertyTags = [] as MutableNodeArray; + } + (jsdocTypeLiteral.jsDocPropertyTags as MutableNodeArray).push(child); + } } - if (!typedefTag.jsDocTypeLiteral) { - typedefTag.jsDocTypeLiteral = typeExpression.type; + if (jsdocTypeLiteral) { + if (typeExpression && typeExpression.type.kind === SyntaxKind.ArrayType) { + jsdocTypeLiteral.isArrayType = true; + } + typedefTag.typeExpression = finishNode(jsdocTypeLiteral); } } - else { - typedefTag.jsDocTypeLiteral = scanChildTags(); - } return finishNode(typedefTag); - function isObjectTypeReference(node: TypeNode) { - return node.kind === SyntaxKind.ObjectKeyword || - isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.text === "Object"; - } - - function scanChildTags(): JSDocTypeLiteral { - const jsDocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, scanner.getStartPos()); - let resumePos = scanner.getStartPos(); - let canParseTag = true; - let seenAsterisk = false; - let parentTagTerminated = false; - - while (token() !== SyntaxKind.EndOfFileToken && !parentTagTerminated) { - nextJSDocToken(); - switch (token()) { - case SyntaxKind.AtToken: - if (canParseTag) { - parentTagTerminated = !tryParseChildTag(jsDocTypeLiteral); - if (!parentTagTerminated) { - resumePos = scanner.getStartPos(); - } - } - seenAsterisk = false; - break; - case SyntaxKind.NewLineTrivia: - resumePos = scanner.getStartPos() - 1; - canParseTag = true; - seenAsterisk = false; - break; - case SyntaxKind.AsteriskToken: - if (seenAsterisk) { - canParseTag = false; - } - seenAsterisk = true; - break; - case SyntaxKind.Identifier: - canParseTag = false; - break; - case SyntaxKind.EndOfFileToken: - break; - } - } - scanner.setTextPos(resumePos); - return finishNode(jsDocTypeLiteral); - } - function parseJSDocTypeNameWithNamespace(flags: NodeFlags) { const pos = scanner.getTokenPos(); const typeNameOrNamespaceName = parseJSDocIdentifierName(); @@ -6647,8 +6712,58 @@ namespace ts { } } + function escapedTextsEqual(a: EntityName, b: EntityName): boolean { + while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) { + if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) { + a = a.left; + b = b.left; + } + else { + return false; + } + } + return a.escapedText === b.escapedText; + } - function tryParseChildTag(parentTag: JSDocTypeLiteral): boolean { + function parseChildParameterOrPropertyTag(target: PropertyLikeParse.Property): JSDocTypeTag | JSDocPropertyTag | false; + function parseChildParameterOrPropertyTag(target: PropertyLikeParse.Parameter, name: EntityName): JSDocParameterTag | false; + function parseChildParameterOrPropertyTag(target: PropertyLikeParse, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { + let canParseTag = true; + let seenAsterisk = false; + while (true) { + nextJSDocToken(); + switch (token()) { + case SyntaxKind.AtToken: + if (canParseTag) { + const child = tryParseChildTag(target); + if (child && child.kind === SyntaxKind.JSDocParameterTag && + (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + return false; + } + return child; + } + seenAsterisk = false; + break; + case SyntaxKind.NewLineTrivia: + canParseTag = true; + seenAsterisk = false; + break; + case SyntaxKind.AsteriskToken: + if (seenAsterisk) { + canParseTag = false; + } + seenAsterisk = true; + break; + case SyntaxKind.Identifier: + canParseTag = false; + break; + case SyntaxKind.EndOfFileToken: + return false; + } + } + } + + function tryParseChildTag(target: PropertyLikeParse): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { Debug.assert(token() === SyntaxKind.AtToken); const atToken = createNode(SyntaxKind.AtToken, scanner.getStartPos()); atToken.end = scanner.getTextPos(); @@ -6659,34 +6774,23 @@ namespace ts { if (!tagName) { return false; } - - switch (tagName.text) { + switch (tagName.escapedText) { case "type": - if (parentTag.jsDocTypeTag) { - // already has a @type tag, terminate the parent tag now. - return false; - } - parentTag.jsDocTypeTag = parseTypeTag(atToken, tagName); - return true; + return target === PropertyLikeParse.Property && parseTypeTag(atToken, tagName); case "prop": case "property": - const propertyTag = parseParameterOrPropertyTag(atToken, tagName, /*shouldParseParamTag*/ false) as JSDocPropertyTag; - if (propertyTag) { - if (!parentTag.jsDocPropertyTags) { - parentTag.jsDocPropertyTags = >[]; - } - (parentTag.jsDocPropertyTags as MutableNodeArray).push(propertyTag); - return true; - } - // Error parsing property tag - return false; + return target === PropertyLikeParse.Property && parseParameterOrPropertyTag(atToken, tagName, target); + case "arg": + case "argument": + case "param": + return target === PropertyLikeParse.Parameter && parseParameterOrPropertyTag(atToken, tagName, target); } return false; } - function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag { + function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag | undefined { if (forEach(tags, t => t.kind === SyntaxKind.JSDocTemplateTag)) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); + parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' @@ -6728,14 +6832,30 @@ namespace ts { return currentToken = scanner.scanJSDocToken(); } - function parseJSDocIdentifierName(createIfMissing = false): Identifier { - return createJSDocIdentifier(tokenIsIdentifierOrKeyword(token()), createIfMissing); + function parseJSDocEntityName(): EntityName { + let entity: EntityName = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(SyntaxKind.OpenBracketToken)) { + parseExpected(SyntaxKind.CloseBracketToken); + // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. + // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}> + // but it's not worth it to enforce that restriction. + } + while (parseOptional(SyntaxKind.DotToken)) { + const name = parseJSDocIdentifierName(/*createIfMissing*/ true); + if (parseOptional(SyntaxKind.OpenBracketToken)) { + parseExpected(SyntaxKind.CloseBracketToken); + } + entity = createQualifiedName(entity, name); + } + return entity; } - function createJSDocIdentifier(isIdentifier: boolean, createIfMissing: boolean): Identifier { - if (!isIdentifier) { + function parseJSDocIdentifierName(): Identifier | undefined; + function parseJSDocIdentifierName(createIfMissing: true): Identifier; + function parseJSDocIdentifierName(createIfMissing = false): Identifier | undefined { + if (!tokenIsIdentifierOrKeyword(token())) { if (createIfMissing) { - return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); + return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); } else { parseErrorAtCurrentToken(Diagnostics.Identifier_expected); @@ -6746,7 +6866,7 @@ namespace ts { const pos = scanner.getTokenPos(); const end = scanner.getTextPos(); const result = createNode(SyntaxKind.Identifier, pos); - result.text = escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = escapeLeadingUnderscores(content.substring(pos, end)); finishNode(result, end); nextJSDocToken(); @@ -7114,7 +7234,7 @@ namespace ts { } } - function getLastChildWorker(node: Node): Node { + function getLastChildWorker(node: Node): Node | undefined { let last: Node = undefined; forEachChild(node, child => { if (nodeIsPresent(child)) { diff --git a/src/compiler/program.ts b/src/compiler/program.ts index f15baeefcdb..64e8eb0c803 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1196,10 +1196,14 @@ namespace ts { case SyntaxKind.EnumDeclaration: diagnostics.push(createDiagnosticForNode(node, Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); return; - case SyntaxKind.TypeAssertionExpression: - const typeAssertionExpression = node; - diagnostics.push(createDiagnosticForNode(typeAssertionExpression.type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + case SyntaxKind.NonNullExpression: + diagnostics.push(createDiagnosticForNode(node, Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); return; + case SyntaxKind.AsExpression: + diagnostics.push(createDiagnosticForNode((node as AsExpression).type, Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case SyntaxKind.TypeAssertionExpression: + Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. } const prevParent = parent; @@ -1441,19 +1445,20 @@ namespace ts { break; case SyntaxKind.ModuleDeclaration: if (isAmbientModule(node) && (inAmbientModule || hasModifier(node, ModifierFlags.Ambient) || file.isDeclarationFile)) { - const moduleName = (node).name; + const moduleName = (node).name; // TODO: GH#17347 + const nameText = ts.getTextOfIdentifierOrLiteral(moduleName); // Ambient module declarations can be interpreted as augmentations for some existing external modules. // This will happen in two cases: // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name // immediately nested in top level ambient module declaration . - if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(moduleName.text))) { + if (isExternalModuleFile || (inAmbientModule && !isExternalModuleNameRelative(nameText))) { (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); } else if (!inAmbientModule) { if (file.isDeclarationFile) { // for global .d.ts files record name of ambient module - (ambientModules || (ambientModules = [])).push(moduleName.text); + (ambientModules || (ambientModules = [])).push(nameText); } // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 16555ff7937..09defaaf773 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -234,7 +234,7 @@ namespace ts { const unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; const unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; - function lookupInUnicodeMap(code: number, map: number[]): boolean { + function lookupInUnicodeMap(code: number, map: ReadonlyArray): boolean { // Bail out quickly if it couldn't possibly be in the map. if (code < map[0]) { return false; @@ -330,7 +330,7 @@ namespace ts { } /* @internal */ - export function computePositionOfLineAndCharacter(lineStarts: number[], line: number, character: number, debugText?: string): number { + export function computePositionOfLineAndCharacter(lineStarts: ReadonlyArray, line: number, character: number, debugText?: string): number { Debug.assert(line >= 0 && line < lineStarts.length); const res = lineStarts[line] + character; if (line < lineStarts.length - 1) { @@ -351,7 +351,7 @@ namespace ts { /** * We assume the first line starts at position 0 and 'position' is non-negative. */ - export function computeLineAndCharacterOfPosition(lineStarts: number[], position: number) { + export function computeLineAndCharacterOfPosition(lineStarts: ReadonlyArray, position: number) { let lineNumber = binarySearch(lineStarts, position); if (lineNumber < 0) { // If the actual position was not found, diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 62ce272e96c..89cfb074bff 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -4,6 +4,18 @@ declare function setTimeout(handler: (...args: any[]) => void, timeout: number): declare function clearTimeout(handle: any): void; namespace ts { + /** + * Set a high stack trace limit to provide more information in case of an error. + * Called for command-line and server use cases. + * Not called if TypeScript is used as a library. + */ + /* @internal */ + export function setStackTraceLimit() { + if ((Error as any).stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist. + (Error as any).stackTraceLimit = 100; + } + } + export enum FileWatcherEventKind { Created, Changed, @@ -196,9 +208,16 @@ namespace ts { if (platform === "win32" || platform === "win64") { return false; } - // convert current file name to upper case / lower case and check if file exists - // (guards against cases when name is already all uppercase or lowercase) - return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + // If this file exists under a different case, we must be case-insensitve. + return !fileExists(swapCase(__filename)); + } + + /** Convert all lowercase chars to uppercase, and vice-versa */ + function swapCase(s: string): string { + return s.replace(/\w/g, (ch) => { + const up = ch.toUpperCase(); + return ch === up ? ch.toLowerCase() : up; + }); } const platform: string = _os.platform(); diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index 1f9b179dabb..45ad53ffbed 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -415,7 +415,7 @@ namespace ts { return createElementAccess(value, argumentExpression); } else { - const name = createIdentifier(unescapeLeadingUnderscores(propertyName.text)); + const name = createIdentifier(unescapeLeadingUnderscores(propertyName.escapedText)); return createPropertyAccess(value, name); } } diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 823b133a4cc..f97de018d4a 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -647,7 +647,7 @@ namespace ts { if (isGeneratedIdentifier(node)) { return node; } - if (node.text !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { + if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) { return node; } return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = createUniqueName("arguments")); @@ -661,7 +661,7 @@ namespace ts { // - break/continue is non-labeled and located in non-converted loop/switch statement const jump = node.kind === SyntaxKind.BreakStatement ? Jump.Break : Jump.Continue; const canUseBreakOrContinue = - (node.label && convertedLoopState.labels && convertedLoopState.labels.get(unescapeLeadingUnderscores(node.label.text))) || + (node.label && convertedLoopState.labels && convertedLoopState.labels.get(unescapeLeadingUnderscores(node.label.escapedText))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { @@ -679,12 +679,12 @@ namespace ts { } else { if (node.kind === SyntaxKind.BreakStatement) { - labelMarker = `break-${node.label.text}`; - setLabeledJump(convertedLoopState, /*isBreak*/ true, unescapeLeadingUnderscores(node.label.text), labelMarker); + labelMarker = `break-${node.label.escapedText}`; + setLabeledJump(convertedLoopState, /*isBreak*/ true, unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } else { - labelMarker = `continue-${node.label.text}`; - setLabeledJump(convertedLoopState, /*isBreak*/ false, unescapeLeadingUnderscores(node.label.text), labelMarker); + labelMarker = `continue-${node.label.escapedText}`; + setLabeledJump(convertedLoopState, /*isBreak*/ false, unescapeLeadingUnderscores(node.label.escapedText), labelMarker); } } let returnExpression: Expression = createLiteral(labelMarker); @@ -2236,11 +2236,11 @@ namespace ts { } function recordLabel(node: LabeledStatement) { - convertedLoopState.labels.set(unescapeLeadingUnderscores(node.label.text), true); + convertedLoopState.labels.set(unescapeLeadingUnderscores(node.label.escapedText), true); } function resetLabel(node: LabeledStatement) { - convertedLoopState.labels.set(unescapeLeadingUnderscores(node.label.text), false); + convertedLoopState.labels.set(unescapeLeadingUnderscores(node.label.escapedText), false); } function visitLabeledStatement(node: LabeledStatement): VisitResult { @@ -3053,7 +3053,7 @@ namespace ts { else { loopParameters.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); if (resolver.getNodeCheckFlags(decl) & NodeCheckFlags.NeedsLoopOutParameter) { - const outParamName = createUniqueName("out_" + unescapeLeadingUnderscores(name.text)); + const outParamName = createUniqueName("out_" + unescapeLeadingUnderscores(name.escapedText)); loopOutParameters.push({ originalName: name, outParamName }); } } @@ -3591,7 +3591,7 @@ namespace ts { if (isCallExpression(firstSegment) && isIdentifier(firstSegment.expression) && (getEmitFlags(firstSegment.expression) & EmitFlags.HelperName) - && firstSegment.expression.text === "___spread") { + && firstSegment.expression.escapedText === "___spread") { return segments[0]; } } @@ -3842,7 +3842,7 @@ namespace ts { } function visitMetaProperty(node: MetaProperty) { - if (node.keywordToken === SyntaxKind.NewKeyword && node.name.text === "target") { + if (node.keywordToken === SyntaxKind.NewKeyword && node.name.escapedText === "target") { if (hierarchyFacts & HierarchyFacts.ComputedPropertyName) { hierarchyFacts |= HierarchyFacts.NewTargetInComputedPropertyName; } @@ -4067,7 +4067,7 @@ namespace ts { } const expression = (callArgument).expression; - return isIdentifier(expression) && expression.text === "arguments"; + return isIdentifier(expression) && expression.escapedText === "arguments"; } } diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 79d0b57e764..43058358ee5 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -369,7 +369,7 @@ namespace ts { function substitutePropertyAccessExpression(node: PropertyAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { return createSuperAccessInAsyncMethod( - createLiteral(unescapeLeadingUnderscores(node.name.text)), + createLiteral(unescapeLeadingUnderscores(node.name.escapedText)), node ); } diff --git a/src/compiler/transformers/es5.ts b/src/compiler/transformers/es5.ts index 0fad9267587..290c9ae77c8 100644 --- a/src/compiler/transformers/es5.ts +++ b/src/compiler/transformers/es5.ts @@ -111,7 +111,7 @@ namespace ts { * @param name An Identifier */ function trySubstituteReservedName(name: Identifier) { - const token = name.originalKeywordKind || (nodeIsSynthesized(name) ? stringToToken(unescapeLeadingUnderscores(name.text)) : undefined); + const token = name.originalKeywordKind || (nodeIsSynthesized(name) ? stringToToken(unescapeLeadingUnderscores(name.escapedText)) : undefined); if (token >= SyntaxKind.FirstReservedWord && token <= SyntaxKind.LastReservedWord) { return setTextRange(createLiteral(name), name); } diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 732a613f1b4..3d884001932 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -776,7 +776,7 @@ namespace ts { function substitutePropertyAccessExpression(node: PropertyAccessExpression) { if (node.expression.kind === SyntaxKind.SuperKeyword) { return createSuperAccessInAsyncMethod( - createLiteral(unescapeLeadingUnderscores(node.name.text)), + createLiteral(unescapeLeadingUnderscores(node.name.escapedText)), node ); } diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index b120f5c8227..41edf24fe9e 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -1635,14 +1635,14 @@ namespace ts { } function transformAndEmitContinueStatement(node: ContinueStatement): void { - const label = findContinueTarget(node.label ? unescapeLeadingUnderscores(node.label.text) : undefined); + const label = findContinueTarget(node.label ? unescapeLeadingUnderscores(node.label.escapedText) : undefined); Debug.assert(label > 0, "Expected continue statment to point to a valid Label."); emitBreak(label, /*location*/ node); } function visitContinueStatement(node: ContinueStatement): Statement { if (inStatementContainingYield) { - const label = findContinueTarget(node.label && unescapeLeadingUnderscores(node.label.text)); + const label = findContinueTarget(node.label && unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -1652,14 +1652,14 @@ namespace ts { } function transformAndEmitBreakStatement(node: BreakStatement): void { - const label = findBreakTarget(node.label ? unescapeLeadingUnderscores(node.label.text) : undefined); + const label = findBreakTarget(node.label ? unescapeLeadingUnderscores(node.label.escapedText) : undefined); Debug.assert(label > 0, "Expected break statment to point to a valid Label."); emitBreak(label, /*location*/ node); } function visitBreakStatement(node: BreakStatement): Statement { if (inStatementContainingYield) { - const label = findBreakTarget(node.label && unescapeLeadingUnderscores(node.label.text)); + const label = findBreakTarget(node.label && unescapeLeadingUnderscores(node.label.escapedText)); if (label > 0) { return createInlineBreak(label, /*location*/ node); } @@ -1838,7 +1838,7 @@ namespace ts { // /*body*/ // .endlabeled // .mark endLabel - beginLabeledBlock(unescapeLeadingUnderscores(node.label.text)); + beginLabeledBlock(unescapeLeadingUnderscores(node.label.escapedText)); transformAndEmitEmbeddedStatement(node.statement); endLabeledBlock(); } @@ -1849,7 +1849,7 @@ namespace ts { function visitLabeledStatement(node: LabeledStatement) { if (inStatementContainingYield) { - beginScriptLabeledBlock(unescapeLeadingUnderscores(node.label.text)); + beginScriptLabeledBlock(unescapeLeadingUnderscores(node.label.escapedText)); } node = visitEachChild(node, visitor, context); @@ -1950,7 +1950,7 @@ namespace ts { } function substituteExpressionIdentifier(node: Identifier) { - if (!isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(unescapeLeadingUnderscores(node.text))) { + if (!isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(unescapeLeadingUnderscores(node.escapedText))) { const original = getOriginalNode(node); if (isIdentifier(original) && original.parent) { const declaration = resolver.getReferencedValueDeclaration(original); @@ -2123,7 +2123,7 @@ namespace ts { hoistVariableDeclaration(variable.name); } else { - const text = unescapeLeadingUnderscores((variable.name).text); + const text = unescapeLeadingUnderscores((variable.name).escapedText); name = declareLocal(text); if (!renamedCatchVariables) { renamedCatchVariables = createMap(); diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index efdf38009e0..d5bf20a525d 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -252,8 +252,8 @@ namespace ts { } else { const name = (node).tagName; - if (isIdentifier(name) && isIntrinsicJsxName(name.text)) { - return createLiteral(unescapeLeadingUnderscores(name.text)); + if (isIdentifier(name) && isIntrinsicJsxName(name.escapedText)) { + return createLiteral(unescapeLeadingUnderscores(name.escapedText)); } else { return createExpressionFromEntityName(name); @@ -268,11 +268,11 @@ namespace ts { */ function getAttributeName(node: JsxAttribute): StringLiteral | Identifier { const name = node.name; - if (/^[A-Za-z_]\w*$/.test(unescapeLeadingUnderscores(name.text))) { + if (/^[A-Za-z_]\w*$/.test(unescapeLeadingUnderscores(name.escapedText))) { return name; } else { - return createLiteral(unescapeLeadingUnderscores(name.text)); + return createLiteral(unescapeLeadingUnderscores(name.escapedText)); } } diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 1e73e3a4af6..2c3133de6f5 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -924,7 +924,7 @@ namespace ts { getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), /*typeParameters*/ undefined, visitNodes(node.heritageClauses, importCallExpressionVisitor), - node.members + visitNodes(node.members, importCallExpressionVisitor) ), node ), @@ -1225,7 +1225,7 @@ namespace ts { */ function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration): Statement[] | undefined { const name = getDeclarationName(decl); - const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(unescapeLeadingUnderscores(name.text)); + const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (const exportSpecifier of exportSpecifiers) { statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name); diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index 42898aba798..e1c239736d5 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -324,7 +324,7 @@ namespace ts { const exportedNames: ObjectLiteralElementLike[] = []; if (moduleInfo.exportedNames) { for (const exportedLocalName of moduleInfo.exportedNames) { - if (exportedLocalName.text === "default") { + if (exportedLocalName.escapedText === "default") { continue; } @@ -353,7 +353,7 @@ namespace ts { // write name of indirectly exported entry, i.e. 'export {x} from ...' exportedNames.push( createPropertyAssignment( - createLiteral(unescapeLeadingUnderscores((element.name || element.propertyName).text)), + createLiteral(unescapeLeadingUnderscores((element.name || element.propertyName).escapedText)), createTrue() ) ); @@ -504,10 +504,10 @@ namespace ts { for (const e of (entry).exportClause.elements) { properties.push( createPropertyAssignment( - createLiteral(unescapeLeadingUnderscores(e.name.text)), + createLiteral(unescapeLeadingUnderscores(e.name.escapedText)), createElementAccess( parameterName, - createLiteral(unescapeLeadingUnderscores((e.propertyName || e.name).text)) + createLiteral(unescapeLeadingUnderscores((e.propertyName || e.name).escapedText)) ) ) ); @@ -1028,7 +1028,7 @@ namespace ts { let excludeName: string; if (exportSelf) { statements = appendExportStatement(statements, decl.name, getLocalName(decl)); - excludeName = unescapeLeadingUnderscores(decl.name.text); + excludeName = unescapeLeadingUnderscores(decl.name.escapedText); } statements = appendExportsOfDeclaration(statements, decl, excludeName); @@ -1080,10 +1080,10 @@ namespace ts { } const name = getDeclarationName(decl); - const exportSpecifiers = moduleInfo.exportSpecifiers.get(unescapeLeadingUnderscores(name.text)); + const exportSpecifiers = moduleInfo.exportSpecifiers.get(unescapeLeadingUnderscores(name.escapedText)); if (exportSpecifiers) { for (const exportSpecifier of exportSpecifiers) { - if (exportSpecifier.name.text !== excludeName) { + if (exportSpecifier.name.escapedText !== excludeName) { statements = appendExportStatement(statements, exportSpecifier.name, name); } } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 4c20807fa86..19ba8b1f2d2 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1692,7 +1692,7 @@ namespace ts { const numParameters = parameters.length; for (let i = 0; i < numParameters; i++) { const parameter = parameters[i]; - if (i === 0 && isIdentifier(parameter.name) && parameter.name.text === "this") { + if (i === 0 && isIdentifier(parameter.name) && parameter.name.escapedText === "this") { continue; } if (parameter.dotDotDotToken) { @@ -1841,7 +1841,7 @@ namespace ts { for (const typeNode of node.types) { const serializedIndividual = serializeTypeNode(typeNode); - if (isIdentifier(serializedIndividual) && serializedIndividual.text === "Object") { + if (isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") { // One of the individual is global object, return immediately return serializedIndividual; } @@ -1851,7 +1851,7 @@ namespace ts { // Different types if (!isIdentifier(serializedUnion) || !isIdentifier(serializedIndividual) || - serializedUnion.text !== serializedIndividual.text) { + serializedUnion.escapedText !== serializedIndividual.escapedText) { return createIdentifier("Object"); } } @@ -2007,7 +2007,7 @@ namespace ts { : (name).expression; } else if (isIdentifier(name)) { - return createLiteral(unescapeLeadingUnderscores(name.text)); + return createLiteral(unescapeLeadingUnderscores(name.escapedText)); } else { return getSynthesizedClone(name); @@ -2644,7 +2644,7 @@ namespace ts { * on symbol names. */ function recordEmittedDeclarationInScope(node: Node) { - const name = node.symbol && node.symbol.name; + const name = node.symbol && node.symbol.escapedName; if (name) { if (!currentScopeFirstDeclarationsOfName) { currentScopeFirstDeclarationsOfName = createUnderscoreEscapedMap(); @@ -2662,7 +2662,7 @@ namespace ts { */ function isFirstEmittedDeclarationInScope(node: Node) { if (currentScopeFirstDeclarationsOfName) { - const name = node.symbol && node.symbol.name; + const name = node.symbol && node.symbol.escapedName; if (name) { return currentScopeFirstDeclarationsOfName.get(name) === node; } @@ -3210,7 +3210,7 @@ namespace ts { function getClassAliasIfNeeded(node: ClassDeclaration) { if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithConstructorReference) { enableSubstitutionForClassAliases(); - const classAlias = createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? unescapeLeadingUnderscores(node.name.text) : "default"); + const classAlias = createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? unescapeLeadingUnderscores(node.name.escapedText) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; hoistVariableDeclaration(classAlias); return classAlias; diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index d3743274d65..be99df62b67 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -58,9 +58,9 @@ namespace ts { else { // export { x, y } for (const specifier of (node).exportClause.elements) { - if (!uniqueExports.get(unescapeLeadingUnderscores(specifier.name.text))) { + if (!uniqueExports.get(unescapeLeadingUnderscores(specifier.name.escapedText))) { const name = specifier.propertyName || specifier.name; - exportSpecifiers.add(unescapeLeadingUnderscores(name.text), specifier); + exportSpecifiers.add(unescapeLeadingUnderscores(name.escapedText), specifier); const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); @@ -69,7 +69,7 @@ namespace ts { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - uniqueExports.set(unescapeLeadingUnderscores(specifier.name.text), true); + uniqueExports.set(unescapeLeadingUnderscores(specifier.name.escapedText), true); exportedNames = append(exportedNames, specifier.name); } } @@ -103,9 +103,9 @@ namespace ts { else { // export function x() { } const name = (node).name; - if (!uniqueExports.get(unescapeLeadingUnderscores(name.text))) { + if (!uniqueExports.get(unescapeLeadingUnderscores(name.escapedText))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(unescapeLeadingUnderscores(name.text), true); + uniqueExports.set(unescapeLeadingUnderscores(name.escapedText), true); exportedNames = append(exportedNames, name); } } @@ -124,9 +124,9 @@ namespace ts { else { // export class x { } const name = (node).name; - if (!uniqueExports.get(unescapeLeadingUnderscores(name.text))) { + if (!uniqueExports.get(unescapeLeadingUnderscores(name.escapedText))) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(unescapeLeadingUnderscores(name.text), true); + uniqueExports.set(unescapeLeadingUnderscores(name.escapedText), true); exportedNames = append(exportedNames, name); } } @@ -158,8 +158,8 @@ namespace ts { } } else if (!isGeneratedIdentifier(decl.name)) { - if (!uniqueExports.get(unescapeLeadingUnderscores(decl.name.text))) { - uniqueExports.set(unescapeLeadingUnderscores(decl.name.text), true); + if (!uniqueExports.get(unescapeLeadingUnderscores(decl.name.escapedText))) { + uniqueExports.set(unescapeLeadingUnderscores(decl.name.escapedText), true); exportedNames = append(exportedNames, decl.name); } } diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 8cc2e5c5ef6..db25afe45b6 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -665,6 +665,8 @@ namespace ts { } } +ts.setStackTraceLimit(); + if (ts.Debug.isDebugging) { ts.Debug.enableDebugInfo(); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index c70e7632201..8929b19bfe3 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -31,6 +31,11 @@ namespace ts { next(): { value: T, done: false } | { value: never, done: true }; } + /** Array that is only intended to be pushed to, never read. */ + export interface Push { + push(...values: T[]): void; + } + // branded string type used to store absolute, normalized and canonicalized paths // arbitrary file name can be converted to Path via toPath function export type Path = string & { __pathBrand: any }; @@ -505,22 +510,22 @@ namespace ts { flags: NodeFlags; /* @internal */ modifierFlagsCache?: ModifierFlags; /* @internal */ transformFlags?: TransformFlags; - decorators?: NodeArray; // Array of decorators (in document order) - modifiers?: ModifiersArray; // Array of modifiers - /* @internal */ id?: number; // Unique id (used to look up NodeLinks) - parent?: Node; // Parent node (initialized by binding) - /* @internal */ original?: Node; // The original node if this is an updated node. - /* @internal */ startsOnNewLine?: boolean; // Whether a synthesized node should start on a new line (used by transforms). - /* @internal */ jsDoc?: JSDoc[]; // JSDoc that directly precedes this node - /* @internal */ jsDocCache?: JSDocTag[]; // Cache for getJSDocTags - /* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding) - /* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding) - /* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding) - /* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes) - /* @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding) - /* @internal */ emitNode?: EmitNode; // Associated EmitNode (initialized by transforms) - /* @internal */ contextualType?: Type; // Used to temporarily assign a contextual type during overload resolution - /* @internal */ contextualMapper?: TypeMapper; // Mapper for contextual type + decorators?: NodeArray; // Array of decorators (in document order) + modifiers?: ModifiersArray; // Array of modifiers + /* @internal */ id?: number; // Unique id (used to look up NodeLinks) + parent?: Node; // Parent node (initialized by binding) + /* @internal */ original?: Node; // The original node if this is an updated node. + /* @internal */ startsOnNewLine?: boolean; // Whether a synthesized node should start on a new line (used by transforms). + /* @internal */ jsDoc?: JSDoc[]; // JSDoc that directly precedes this node + /* @internal */ jsDocCache?: ReadonlyArray; // Cache for getJSDocTags + /* @internal */ symbol?: Symbol; // Symbol declared by node (initialized by binding) + /* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding) + /* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding) + /* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes) + /* @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding) + /* @internal */ emitNode?: EmitNode; // Associated EmitNode (initialized by transforms) + /* @internal */ contextualType?: Type; // Used to temporarily assign a contextual type during overload resolution + /* @internal */ contextualMapper?: TypeMapper; // Mapper for contextual type } /* @internal */ @@ -574,10 +579,10 @@ namespace ts { export 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. + * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) + * Text of identifier, but if the identifier begins with two underscores, this will begin with three. */ - text: __String; + escapedText: __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. @@ -680,7 +685,7 @@ namespace ts { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; // Present on rest parameter - name?: BindingName; // Declared parameter name. Missing if this is a parameter in a JSDocFunctionType. + name: BindingName; // Declared parameter name. questionToken?: QuestionToken; // Present on optional parameter type?: TypeNode; // Optional type annotation initializer?: Expression; // Optional initializer @@ -755,6 +760,7 @@ namespace ts { // SyntaxKind.ShorthandPropertyAssignment // SyntaxKind.EnumMember // SyntaxKind.JSDocPropertyTag + // SyntaxKind.JSDocParameterTag export interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; @@ -2031,7 +2037,7 @@ namespace ts { } // represents a top level: { type } expression in a JSDoc comment. - export interface JSDocTypeExpression extends Node { + export interface JSDocTypeExpression extends TypeNode { kind: SyntaxKind.JSDocTypeExpression; type: TypeNode; } @@ -2120,38 +2126,32 @@ namespace ts { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; - typeExpression?: JSDocTypeExpression; - jsDocTypeLiteral?: JSDocTypeLiteral; + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } - export interface JSDocPropertyTag extends JSDocTag, TypeElement { + export interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; - kind: SyntaxKind.JSDocPropertyTag; - name: Identifier; - /** the parameter name, if provided *before* the type (TypeScript-style) */ - preParameterName?: Identifier; - /** the parameter name, if provided *after* the type (JSDoc-standard) */ - postParameterName?: Identifier; + name: EntityName; typeExpression: JSDocTypeExpression; + /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ + isNameFirst: boolean; isBracketed: boolean; } + export interface JSDocPropertyTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocPropertyTag; + } + + export interface JSDocParameterTag extends JSDocPropertyLikeTag { + kind: SyntaxKind.JSDocParameterTag; + } + export interface JSDocTypeLiteral extends JSDocType { kind: SyntaxKind.JSDocTypeLiteral; - jsDocPropertyTags?: NodeArray; + jsDocPropertyTags?: ReadonlyArray; jsDocTypeTag?: JSDocTypeTag; - } - - export interface JSDocParameterTag extends JSDocTag { - kind: SyntaxKind.JSDocParameterTag; - /** the parameter name, if provided *before* the type (TypeScript-style) */ - preParameterName?: Identifier; - typeExpression?: JSDocTypeExpression; - /** the parameter name, if provided *after* the type (JSDoc-standard) */ - postParameterName?: Identifier; - /** the parameter name, regardless of the location it was provided */ - name: Identifier; - isBracketed: boolean; + /** If true, then this type literal represents an *array* of its type. */ + isArrayType?: boolean; } export const enum FlowFlags { @@ -2360,7 +2360,7 @@ namespace ts { } export interface WriteFileCallback { - (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void; + (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray): void; } export class OperationCanceledException { } @@ -2581,6 +2581,8 @@ namespace ts { getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + /** Unlike `tryGetMemberInModuleExports`, this includes properties of an `export =` value. */ + /* @internal */ tryGetMemberInModuleExportsAndProperties(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; @@ -2894,7 +2896,7 @@ namespace ts { export interface Symbol { flags: SymbolFlags; // Symbol flags - name: __String; // Name of symbol + escapedName: __String; // Name of symbol declarations?: Declaration[]; // Declarations associated with this symbol valueDeclaration?: Declaration; // First value declaration of the symbol members?: SymbolTable; // Class, interface or literal instance members @@ -3685,11 +3687,11 @@ namespace ts { } export interface ConfigFileSpecs { - filesSpecs: string[]; - includeSpecs: string[]; - excludeSpecs: string[]; - validatedIncludeSpecs: string[]; - validatedExcludeSpecs: string[]; + filesSpecs: ReadonlyArray; + includeSpecs: ReadonlyArray; + excludeSpecs: ReadonlyArray; + validatedIncludeSpecs: ReadonlyArray; + validatedExcludeSpecs: ReadonlyArray; wildcardDirectories: MapLike; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index e001ec43f62..76d242e8b08 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3,6 +3,7 @@ /* @internal */ namespace ts { export const emptyArray: never[] = [] as never[]; + export const emptyMap: ReadonlyMap = createMap(); export const externalHelpersModuleNameText = "tslib"; @@ -91,12 +92,8 @@ namespace ts { return node.end - node.pos; } - export function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean { - return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText)); - } - - export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModuleFull { - return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules.get(moduleNameText) : undefined; + export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModuleFull | undefined { + return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText); } export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull): void { @@ -128,7 +125,11 @@ namespace ts { } /* @internal */ - export function hasChangesInResolutions(names: string[], newResolutions: T[], oldResolutions: Map, comparer: (oldResolution: T, newResolution: T) => boolean): boolean { + export function hasChangesInResolutions( + names: ReadonlyArray, + newResolutions: ReadonlyArray, + oldResolutions: ReadonlyMap, + comparer: (oldResolution: T, newResolution: T) => boolean): boolean { Debug.assert(names.length === newResolutions.length); for (let i = 0; i < names.length; i++) { @@ -363,11 +364,11 @@ namespace ts { } /** - * @deprecated + * @deprecated Use `id.escapedText` to get the escaped text of an Identifier. * @param identifier The identifier to escape */ export function escapeIdentifier(identifier: string): string { - return escapeLeadingUnderscores(identifier) as string; + return identifier; } // Make an identifier from an external module name by extracting the string after the last "/" and replacing @@ -391,6 +392,11 @@ namespace ts { ((node).name.kind === SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node)); } + /* @internal */ + export function isNonGlobalAmbientModule(node: Node): node is ModuleDeclaration & { name: StringLiteral } { + return isModuleDeclaration(node) && isStringLiteral(node.name); + } + /** Given a symbol for a module, checks that it is a shorthand ambient module. */ export function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); @@ -485,7 +491,7 @@ namespace ts { export function getTextOfPropertyName(name: PropertyName): __String { switch (name.kind) { case SyntaxKind.Identifier: - return (name).text; + return (name).escapedText; case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: return escapeLeadingUnderscores((name).text); @@ -501,7 +507,7 @@ namespace ts { export function entityNameToString(name: EntityNameOrEntityNameExpression): string { switch (name.kind) { case SyntaxKind.Identifier: - return getFullWidth(name) === 0 ? unescapeLeadingUnderscores(name.text) : getTextOfNode(name); + return getFullWidth(name) === 0 ? unescapeLeadingUnderscores(name.escapedText) : getTextOfNode(name); case SyntaxKind.QualifiedName: return entityNameToString(name.left) + "." + entityNameToString(name.right); case SyntaxKind.PropertyAccessExpression: @@ -906,8 +912,8 @@ namespace ts { return predicate && predicate.kind === TypePredicateKind.This; } - export function getPropertyAssignment(objectLiteral: ObjectLiteralExpression, key: string, key2?: string) { - return filter(objectLiteral.properties, property => { + export function getPropertyAssignment(objectLiteral: ObjectLiteralExpression, key: string, key2?: string): ReadonlyArray { + return filter(objectLiteral.properties, (property): property is PropertyAssignment => { if (property.kind === SyntaxKind.PropertyAssignment) { const propName = getTextOfPropertyName(property.name); return key === propName || (key2 && key2 === propName); @@ -916,21 +922,11 @@ namespace ts { } export function getContainingFunction(node: Node): FunctionLike { - while (true) { - node = node.parent; - if (!node || isFunctionLike(node)) { - return node; - } - } + return findAncestor(node.parent, isFunctionLike); } export function getContainingClass(node: Node): ClassLikeDeclaration { - while (true) { - node = node.parent; - if (!node || isClassLike(node)) { - return node; - } - } + return findAncestor(node.parent, isClassLike); } export function getThisContainer(node: Node, includeArrowFunctions: boolean): Node { @@ -1308,7 +1304,7 @@ namespace ts { } const { expression, arguments: args } = callExpression as CallExpression; - if (expression.kind !== SyntaxKind.Identifier || (expression as Identifier).text !== "require") { + if (expression.kind !== SyntaxKind.Identifier || (expression as Identifier).escapedText !== "require") { return false; } @@ -1343,11 +1339,11 @@ namespace ts { } export function isExportsIdentifier(node: Node) { - return isIdentifier(node) && node.text === "exports"; + return isIdentifier(node) && node.escapedText === "exports"; } export function isModuleExportsPropertyAccessExpression(node: Node) { - return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === "module" && node.name.text === "exports"; + return isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.escapedText === "module" && node.name.escapedText === "exports"; } /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property @@ -1363,11 +1359,11 @@ namespace ts { const lhs = expr.left; if (lhs.expression.kind === SyntaxKind.Identifier) { const lhsId = lhs.expression; - if (lhsId.text === "exports") { + if (lhsId.escapedText === "exports") { // exports.name = expr return SpecialPropertyAssignmentKind.ExportsProperty; } - else if (lhsId.text === "module" && lhs.name.text === "exports") { + else if (lhsId.escapedText === "module" && lhs.name.escapedText === "exports") { // module.exports = expr return SpecialPropertyAssignmentKind.ModuleExports; } @@ -1385,10 +1381,10 @@ namespace ts { if (innerPropertyAccess.expression.kind === SyntaxKind.Identifier) { // module.exports.name = expr const innerPropertyAccessIdentifier = innerPropertyAccess.expression; - if (innerPropertyAccessIdentifier.text === "module" && innerPropertyAccess.name.text === "exports") { + if (innerPropertyAccessIdentifier.escapedText === "module" && innerPropertyAccess.name.escapedText === "exports") { return SpecialPropertyAssignmentKind.ExportsProperty; } - if (innerPropertyAccess.name.text === "prototype") { + if (innerPropertyAccess.name.escapedText === "prototype") { return SpecialPropertyAssignmentKind.PrototypeProperty; } } @@ -1454,7 +1450,7 @@ namespace ts { return node.kind === SyntaxKind.JSDocFunctionType && (node as JSDocFunctionType).parameters.length > 0 && (node as JSDocFunctionType).parameters[0].name && - ((node as JSDocFunctionType).parameters[0].name as Identifier).text === "new"; + ((node as JSDocFunctionType).parameters[0].name as Identifier).escapedText === "new"; } export function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean { @@ -1473,7 +1469,7 @@ namespace ts { return getJSDocCommentsAndTags(node); } - export function getJSDocTags(node: Node): JSDocTag[] | undefined { + export function getJSDocTags(node: Node): ReadonlyArray | undefined { let tags = node.jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { @@ -1541,32 +1537,36 @@ namespace ts { export function getJSDocParameterTags(param: ParameterDeclaration): JSDocParameterTag[] | undefined { if (param.name && isIdentifier(param.name)) { - const name = param.name.text; - return getJSDocTags(param.parent).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && tag.name.text === name) as JSDocParameterTag[]; - } - else { - // TODO: it's a destructured parameter, so it should look up an "object type" series of multiple lines - // But multi-line object types aren't supported yet either - return undefined; + const name = param.name.escapedText; + return getJSDocTags(param.parent).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name) as JSDocParameterTag[]; } + // a binding pattern doesn't have a name, so it's not possible to match it a jsdoc parameter, which is identified by name + return undefined; } /** 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.name.text; - const grandParent = node.parent!.parent!; - Debug.assert(node.parent!.kind === SyntaxKind.JSDocComment); - if (!isFunctionLike(grandParent)) { + export function getParameterSymbolFromJSDoc(node: JSDocParameterTag): Symbol | undefined { + if (node.symbol) { + return node.symbol; + } + if (!isIdentifier(node.name)) { return undefined; } - return find(grandParent.parameters, p => - p.name.kind === SyntaxKind.Identifier && p.name.text === name); + const name = node.name.escapedText; + Debug.assert(node.parent!.kind === SyntaxKind.JSDocComment); + const func = node.parent!.parent!; + if (!isFunctionLike(func)) { + return undefined; + } + const parameter = find(func.parameters, p => + p.name.kind === SyntaxKind.Identifier && p.name.escapedText === name); + return parameter && parameter.symbol; } export function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { parent: JSDocTemplateTag }): TypeParameterDeclaration | undefined { - const name = node.name.text; + const name = node.name.escapedText; const { typeParameters } = (node.parent.parent.parent as ts.SignatureDeclaration | ts.InterfaceDeclaration | ts.ClassDeclaration); - return find(typeParameters, p => p.name.text === name); + return find(typeParameters, p => p.name.escapedText === name); } export function getJSDocType(node: Node): TypeNode { @@ -1771,7 +1771,8 @@ namespace ts { // Property name in binding element or import specifier return (parent).propertyName === node; case SyntaxKind.ExportSpecifier: - // Any name in an export specifier + case SyntaxKind.JsxAttribute: + // Any name in an export specifier or JSX Attribute return true; } return false; @@ -1969,7 +1970,7 @@ namespace ts { export function getPropertyNameForPropertyNameNode(name: DeclarationName): __String { if (name.kind === SyntaxKind.Identifier) { - return name.text; + return name.escapedText; } if (name.kind === SyntaxKind.StringLiteral || name.kind === SyntaxKind.NumericLiteral) { return escapeLeadingUnderscores(name.text); @@ -1977,7 +1978,7 @@ namespace ts { if (name.kind === SyntaxKind.ComputedPropertyName) { const nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - const rightHandSideName = (nameExpression).name.text; + const rightHandSideName = (nameExpression).name.escapedText; return getPropertyNameForKnownSymbolName(unescapeLeadingUnderscores(rightHandSideName)); } else if (nameExpression.kind === SyntaxKind.StringLiteral || nameExpression.kind === SyntaxKind.NumericLiteral) { @@ -1991,7 +1992,7 @@ namespace ts { export function getTextOfIdentifierOrLiteral(node: Identifier | LiteralLikeNode) { if (node) { if (node.kind === SyntaxKind.Identifier) { - return unescapeLeadingUnderscores((node as Identifier).text); + return unescapeLeadingUnderscores((node as Identifier).escapedText); } if (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) { @@ -2006,7 +2007,7 @@ namespace ts { export function getEscapedTextOfIdentifierOrLiteral(node: Identifier | LiteralLikeNode) { if (node) { if (node.kind === SyntaxKind.Identifier) { - return (node as Identifier).text; + return (node as Identifier).escapedText; } if (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) { @@ -2026,11 +2027,11 @@ namespace ts { * Includes the word "Symbol" with unicode escapes */ export function isESSymbolIdentifier(node: Node): boolean { - return node.kind === SyntaxKind.Identifier && (node).text === "Symbol"; + return node.kind === SyntaxKind.Identifier && (node).escapedText === "Symbol"; } export function isPushOrUnshiftIdentifier(node: Identifier) { - return node.text === "push" || node.text === "unshift"; + return node.escapedText === "push" || node.escapedText === "unshift"; } export function isParameterDeclaration(node: VariableLikeDeclaration) { @@ -2067,7 +2068,7 @@ namespace ts { return getParseTreeNode(sourceFile, isSourceFile) || sourceFile; } - export function getOriginalSourceFiles(sourceFiles: SourceFile[]) { + export function getOriginalSourceFiles(sourceFiles: ReadonlyArray) { return sameMap(sourceFiles, getOriginalSourceFile); } @@ -2588,7 +2589,7 @@ namespace ts { return combinePaths(newDirPath, sourceFilePath); } - export function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]) { + export function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: ReadonlyArray) { host.writeFile(fileName, data, writeByteOrderMark, hostErrorMessage => { diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); }, sourceFiles); @@ -2598,7 +2599,7 @@ namespace ts { return getLineAndCharacterOfPosition(currentSourceFile, pos).line; } - export function getLineOfLocalPositionFromLineMap(lineMap: number[], pos: number) { + export function getLineOfLocalPositionFromLineMap(lineMap: ReadonlyArray, pos: number) { return computeLineAndCharacterOfPosition(lineMap, pos).line; } @@ -2750,11 +2751,11 @@ namespace ts { return parameter && getEffectiveTypeAnnotationNode(parameter); } - export function emitNewLineBeforeLeadingComments(lineMap: number[], writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]) { + export function emitNewLineBeforeLeadingComments(lineMap: ReadonlyArray, writer: EmitTextWriter, node: TextRange, leadingComments: ReadonlyArray) { emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); } - export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: number[], writer: EmitTextWriter, pos: number, leadingComments: CommentRange[]) { + export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: ReadonlyArray, writer: EmitTextWriter, pos: number, leadingComments: ReadonlyArray) { // If the leading comments start on different line than the start of node, write new line if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) { @@ -2762,7 +2763,7 @@ namespace ts { } } - export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: number[], writer: EmitTextWriter, pos: number, commentPos: number) { + export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: ReadonlyArray, writer: EmitTextWriter, pos: number, commentPos: number) { // If the leading comments start on different line than the start of node, write new line if (pos !== commentPos && getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) { @@ -2770,8 +2771,15 @@ namespace ts { } } - export function emitComments(text: string, lineMap: number[], writer: EmitTextWriter, comments: CommentRange[], leadingSeparator: boolean, trailingSeparator: boolean, newLine: string, - writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void) { + export function emitComments( + text: string, + lineMap: ReadonlyArray, + writer: EmitTextWriter, + comments: ReadonlyArray, + leadingSeparator: boolean, + trailingSeparator: boolean, + newLine: string, + writeComment: (text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void) { if (comments && comments.length > 0) { if (leadingSeparator) { writer.write(" "); @@ -2803,8 +2811,8 @@ namespace ts { * Detached comment is a comment at the top of file or function body that is separated from * the next statement by space. */ - export function emitDetachedComments(text: string, lineMap: number[], writer: EmitTextWriter, - writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, + export function emitDetachedComments(text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, + writeComment: (text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean) { let leadingComments: CommentRange[]; let currentDetachedCommentInfo: { nodePos: number, detachedCommentEndPos: number }; @@ -2868,7 +2876,7 @@ namespace ts { } - export function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { + export function writeCommentRange(text: string, lineMap: ReadonlyArray, writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { if (text.charCodeAt(commentPos + 1) === CharacterCodes.asterisk) { const firstCommentLineAndCharacter = computeLineAndCharacterOfPosition(lineMap, commentPos); const lineCount = lineMap.length; @@ -3718,7 +3726,7 @@ namespace ts { * This function will then merge those changes into a single change range valid between V1 and * Vn. */ - export function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange { + export function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange { if (changes.length === 0) { return unchangedTextChangeRange; } @@ -3909,7 +3917,7 @@ namespace ts { export function validateLocaleAndSetLanguage( locale: string, sys: { getExecutingFilePath(): string, resolvePath(path: string): string, fileExists(fileName: string): boolean, readFile(fileName: string): string | undefined }, - errors?: Diagnostic[]) { + errors?: Push) { const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { @@ -3928,7 +3936,7 @@ namespace ts { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } - function trySetLanguageAndTerritory(language: string, territory: string, errors?: Diagnostic[]): boolean { + function trySetLanguageAndTerritory(language: string, territory: string, errors?: Push): boolean { const compilerFilePath = normalizePath(sys.getExecutingFilePath()); const containingDirectoryPath = getDirectoryPath(compilerFilePath); @@ -4033,18 +4041,21 @@ namespace ts { /** * Remove extra underscore from escaped identifier text content. - * @deprecated + * @deprecated Use `id.text` for the unescaped text. * @param identifier The escaped identifier text. * @returns The unescaped identifier text. */ export function unescapeIdentifier(id: string): string { - return unescapeLeadingUnderscores(id as __String); + return id; } export function getNameOfDeclaration(declaration: Declaration): DeclarationName | undefined { if (!declaration) { return undefined; } + if (isJSDocPropertyLikeTag(declaration) && declaration.name.kind === SyntaxKind.QualifiedName) { + return declaration.name.right; + } if (declaration.kind === SyntaxKind.BinaryExpression) { const expr = declaration as BinaryExpression; switch (getSpecialPropertyAssignmentKind(expr)) { @@ -4703,6 +4714,10 @@ namespace ts { return node.kind === SyntaxKind.JSDocPropertyTag; } + export function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag { + return node.kind === SyntaxKind.JSDocPropertyTag || node.kind === SyntaxKind.JSDocParameterTag; + } + export function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral { return node.kind === SyntaxKind.JSDocTypeLiteral; } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index d32bf92b007..c6ec0f257b6 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -2405,7 +2405,7 @@ namespace FourSlash { const sortedActualArray = actualTextArray.sort(); if (!ts.arrayIsEqualTo(sortedExpectedArray, sortedActualArray)) { this.raiseError( - `Actual text array doesn't match expected text array. \nActual: \n"${sortedActualArray.join("\n\n")}"\n---\nExpected: \n'${sortedExpectedArray.join("\n\n")}'`); + `Actual text array doesn't match expected text array. \nActual: \n'${sortedActualArray.join("\n\n")}'\n---\nExpected: \n'${sortedExpectedArray.join("\n\n")}'`); } } diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts index a25a0181511..98663863a93 100644 --- a/src/harness/rwcRunner.ts +++ b/src/harness/rwcRunner.ts @@ -54,7 +54,8 @@ namespace RWC { useCustomLibraryFile = undefined; }); - it("can compile", () => { + it("can compile", function(this: Mocha.ITestCallbackContext) { + this.timeout(800000); // Allow long timeouts for RWC compilations let opts: ts.ParsedCommandLine; const ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath)); diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index 8d52791f539..66ca2fc3f48 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -74,11 +74,6 @@ "../services/formatting/tokenRange.ts", "../services/codeFixProvider.ts", "../services/codefixes/fixes.ts", - "../services/codefixes/fixExtendsInterfaceBecomesImplements.ts", - "../services/codefixes/fixClassIncorrectlyImplementsInterface.ts", - "../services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts", - "../services/codefixes/fixClassSuperMustPrecedeThisAccess.ts", - "../services/codefixes/fixConstructorForDerivedNeedSuperCall.ts", "../services/codefixes/helpers.ts", "../services/codefixes/importFixes.ts", "../services/codefixes/fixUnusedIdentifier.ts", diff --git a/src/harness/unittests/textChanges.ts b/src/harness/unittests/textChanges.ts index 3c9ebff68f9..34944c41bd6 100644 --- a/src/harness/unittests/textChanges.ts +++ b/src/harness/unittests/textChanges.ts @@ -11,7 +11,7 @@ namespace ts { return find(n); function find(node: Node): Node { - if (isDeclaration(node) && node.name && isIdentifier(node.name) && node.name.text === name) { + if (isDeclaration(node) && node.name && isIdentifier(node.name) && node.name.escapedText === name) { return node; } else { diff --git a/src/harness/unittests/transform.ts b/src/harness/unittests/transform.ts index deee352ebf1..537235f2f67 100644 --- a/src/harness/unittests/transform.ts +++ b/src/harness/unittests/transform.ts @@ -8,7 +8,7 @@ namespace ts { context.enableSubstitution(SyntaxKind.Identifier); context.onSubstituteNode = (hint, node) => { node = previousOnSubstituteNode(hint, node); - if (hint === EmitHint.Expression && node.kind === SyntaxKind.Identifier && (node).text === "undefined") { + if (hint === EmitHint.Expression && isIdentifier(node) && node.escapedText === "undefined") { node = createPartiallyEmittedExpression( addSyntheticTrailingComment( setTextRange( @@ -26,7 +26,7 @@ namespace ts { context.enableSubstitution(SyntaxKind.Identifier); context.onSubstituteNode = (hint, node) => { node = previousOnSubstituteNode(hint, node); - if (node.kind === SyntaxKind.Identifier && (node).text === "oldName") { + if (isIdentifier(node) && node.escapedText === "oldName") { node = setTextRange(createIdentifier("newName"), node); } return node; diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 14d174bf6af..fa6ffc74e65 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -2509,6 +2509,50 @@ namespace ts.projectSystem { const navbar = projectService.externalProjects[0].getLanguageService(/*ensureSynchronized*/ false).getNavigationBarItems(f1.path); assert.equal(navbar[0].spans[0].length, f1.content.length); }); + + it("deleting config file opened from the external project works", () => { + const site = { + path: "/user/someuser/project/js/site.js", + content: "" + }; + const configFile = { + path: "/user/someuser/project/tsconfig.json", + content: "{}" + }; + const projectFileName = "/user/someuser/project/WebApplication6.csproj"; + const host = createServerHost([libFile, site, configFile]); + const projectService = createProjectService(host); + + const externalProject: protocol.ExternalProject = { + projectFileName, + rootFiles: [toExternalFile(site.path), toExternalFile(configFile.path)], + options: { allowJs: false }, + typeAcquisition: { "include": [] } + }; + + projectService.openExternalProjects([externalProject]); + + let knownProjects = projectService.synchronizeProjectList([]); + checkNumberOfProjects(projectService, { configuredProjects: 1, externalProjects: 0, inferredProjects: 0 }); + + const configProject = configuredProjectAt(projectService, 0); + checkProjectActualFiles(configProject, [libFile.path, configFile.path]); + + const diagnostics = configProject.getAllProjectErrors(); + assert.equal(diagnostics[0].code, Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code); + + host.reloadFS([libFile, site]); + host.checkTimeoutQueueLengthAndRun(1); + + knownProjects = projectService.synchronizeProjectList(map(knownProjects, proj => proj.info)); + checkNumberOfProjects(projectService, { configuredProjects: 0, externalProjects: 0, inferredProjects: 0 }); + + externalProject.rootFiles.length = 1; + projectService.openExternalProjects([externalProject]); + + checkNumberOfProjects(projectService, { configuredProjects: 0, externalProjects: 1, inferredProjects: 0 }); + checkProjectActualFiles(projectService.externalProjects[0], [site.path, libFile.path]); + }); }); describe("Proper errors", () => { diff --git a/src/harness/unittests/typingsInstaller.ts b/src/harness/unittests/typingsInstaller.ts index c9617625cc7..0654a357d70 100644 --- a/src/harness/unittests/typingsInstaller.ts +++ b/src/harness/unittests/typingsInstaller.ts @@ -1034,6 +1034,8 @@ namespace ts.projectSystem { }); describe("discover typings", () => { + const emptySafeList = emptyMap; + it("should use mappings from safe list", () => { const app = { path: "/a/b/app.js", @@ -1047,13 +1049,15 @@ namespace ts.projectSystem { path: "/a/b/chroma.min.js", content: "" }; - const cache = createMap(); + + const safeList = createMapFromTemplate({ jquery: "jquery", chroma: "chroma-js" }); const host = createServerHost([app, jquery, chroma]); const logger = trackingLogger(); - const result = JsTyping.discoverTypings(host, logger.log, [app.path, jquery.path, chroma.path], getDirectoryPath(app.path), /*safeListPath*/ undefined, cache, { enable: true }, []); + const result = JsTyping.discoverTypings(host, logger.log, [app.path, jquery.path, chroma.path], getDirectoryPath(app.path), safeList, emptyMap, { enable: true }, emptyArray); assert.deepEqual(logger.finish(), [ 'Inferred typings from file names: ["jquery","chroma-js"]', + "Inferred typings from unresolved imports: []", 'Result: {"cachedTypingPaths":[],"newTypingNames":["jquery","chroma-js"],"filesToWatch":["/a/b/bower_components","/a/b/node_modules"]}', ]); assert.deepEqual(result.newTypingNames, ["jquery", "chroma-js"]); @@ -1069,7 +1073,7 @@ namespace ts.projectSystem { for (const name of JsTyping.nodeCoreModuleList) { const logger = trackingLogger(); - const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), /*safeListPath*/ undefined, cache, { enable: true }, [name, "somename"]); + const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), emptySafeList, cache, { enable: true }, [name, "somename"]); assert.deepEqual(logger.finish(), [ 'Inferred typings from unresolved imports: ["node","somename"]', 'Result: {"cachedTypingPaths":[],"newTypingNames":["node","somename"],"filesToWatch":["/a/b/bower_components","/a/b/node_modules"]}', @@ -1090,7 +1094,7 @@ namespace ts.projectSystem { const host = createServerHost([f, node]); const cache = createMapFromTemplate({ "node": node.path }); const logger = trackingLogger(); - const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), /*safeListPath*/ undefined, cache, { enable: true }, ["fs", "bar"]); + const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), emptySafeList, cache, { enable: true }, ["fs", "bar"]); assert.deepEqual(logger.finish(), [ 'Inferred typings from unresolved imports: ["node","bar"]', 'Result: {"cachedTypingPaths":["/a/b/node.d.ts"],"newTypingNames":["bar"],"filesToWatch":["/a/b/bower_components","/a/b/node_modules"]}', @@ -1115,9 +1119,11 @@ namespace ts.projectSystem { const host = createServerHost([app, a, b]); const cache = createMap(); const logger = trackingLogger(); - const result = JsTyping.discoverTypings(host, logger.log, [app.path], getDirectoryPath(app.path), /*safeListPath*/ undefined, cache, { enable: true }, /*unresolvedImports*/ []); + const result = JsTyping.discoverTypings(host, logger.log, [app.path], getDirectoryPath(app.path), emptySafeList, cache, { enable: true }, /*unresolvedImports*/ []); assert.deepEqual(logger.finish(), [ 'Searching for typing names in /node_modules; all files: ["/node_modules/a/package.json"]', + ' Found package names: ["a"]', + "Inferred typings from unresolved imports: []", 'Result: {"cachedTypingPaths":[],"newTypingNames":["a"],"filesToWatch":["/bower_components","/node_modules"]}', ]); assert.deepEqual(result, { diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 446a46692ed..003bb87f6a9 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -349,7 +349,7 @@ namespace ts.server { private readonly throttledOperations: ThrottledOperations; private readonly hostConfiguration: HostConfiguration; - private static safelist: SafeList = defaultTypeSafeList; + private safelist: SafeList = defaultTypeSafeList; private changedFiles: ScriptInfo[]; private pendingProjectUpdates = createMap(); @@ -1148,7 +1148,7 @@ namespace ts.server { this.logger.info("Open files: "); for (const rootFile of this.openFiles) { - this.logger.info(rootFile.fileName); + this.logger.info(`\t${rootFile.fileName}`); } this.logger.endGroup(); @@ -1899,7 +1899,7 @@ namespace ts.server { } resetSafeList(): void { - ProjectService.safelist = defaultTypeSafeList; + this.safelist = defaultTypeSafeList; } loadSafeList(fileName: string): void { @@ -1909,7 +1909,7 @@ namespace ts.server { raw[k].match = new RegExp(raw[k].match as {} as string, "i"); } // raw is now fixed and ready - ProjectService.safelist = raw; + this.safelist = raw; } applySafeList(proj: protocol.ExternalProject): void { @@ -1920,8 +1920,8 @@ namespace ts.server { const normalizedNames = rootFiles.map(f => normalizeSlashes(f.fileName)); - for (const name of Object.keys(ProjectService.safelist)) { - const rule = ProjectService.safelist[name]; + for (const name of Object.keys(this.safelist)) { + const rule = this.safelist[name]; for (const root of normalizedNames) { if (rule.match.test(root)) { this.logger.info(`Excluding files based on rule ${name}`); diff --git a/src/server/project.ts b/src/server/project.ts index 6a8e46486ab..62c450f9f4f 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -981,8 +981,8 @@ namespace ts.server { private typeAcquisition: TypeAcquisition; /* @internal */ configFileWatcher: FileWatcher; - private directoriesWatchedForWildcards: Map; - private typeRootsWatchers: Map; + private directoriesWatchedForWildcards: Map | undefined; + private typeRootsWatchers: Map | undefined; readonly canonicalConfigFilePath: NormalizedPath; /* @internal */ diff --git a/src/server/server.ts b/src/server/server.ts index f672ec31e1e..b72cc2f5a81 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -200,7 +200,7 @@ namespace ts.server { msg(s: string, type: Msg.Types = Msg.Err) { if (this.fd >= 0 || this.traceToConsole) { - s = s + "\n"; + s = `[${nowString()}] ${s}\n`; const prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); if (this.firstInGroup) { s = prefix + s; @@ -222,6 +222,12 @@ namespace ts.server { } } + // E.g. "12:34:56.789" + function nowString() { + const d = new Date(); + return `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}.${d.getMilliseconds()}`; + } + class NodeTypingsInstaller implements ITypingsInstaller { private installer: NodeChildProcess; private installerPidReported = false; @@ -751,6 +757,8 @@ namespace ts.server { validateLocaleAndSetLanguage(localeStr, sys); } + setStackTraceLimit(); + const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation); const npmLocation = findArgument(Arguments.NpmLocation); diff --git a/src/server/typingsInstaller/typingsInstaller.ts b/src/server/typingsInstaller/typingsInstaller.ts index b1fddfb4129..8a3840fd984 100644 --- a/src/server/typingsInstaller/typingsInstaller.ts +++ b/src/server/typingsInstaller/typingsInstaller.ts @@ -85,6 +85,7 @@ namespace ts.server.typingsInstaller { private readonly missingTypingsSet: Map = createMap(); private readonly knownCachesSet: Map = createMap(); private readonly projectWatchers: Map = createMap(); + private safeList: JsTyping.SafeList | undefined; readonly pendingRunRequests: PendingRequest[] = []; private installRunCount = 1; @@ -143,12 +144,15 @@ namespace ts.server.typingsInstaller { this.processCacheLocation(req.cachePath); } + if (this.safeList === undefined) { + this.safeList = JsTyping.loadSafeList(this.installTypingHost, this.safeListPath); + } const discoverTypingsResult = JsTyping.discoverTypings( this.installTypingHost, this.log.isEnabled() ? this.log.writeLine : undefined, req.fileNames, req.projectRootPath, - this.safeListPath, + this.safeList, this.packageNameToTypingLocation, req.typeAcquisition, req.unresolvedImports); diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 15a9fbb8035..6c884cebf59 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -176,6 +176,85 @@ namespace ts.server { return [] as SortedArray; } + export class ThrottledOperations { + private pendingTimeouts: Map = createMap(); + constructor(private readonly host: ServerHost) { + } + + public schedule(operationId: string, delay: number, cb: () => void) { + const pendingTimeout = this.pendingTimeouts.get(operationId); + if (pendingTimeout) { + // another operation was already scheduled for this id - cancel it + this.host.clearTimeout(pendingTimeout); + } + // schedule new operation, pass arguments + this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb)); + } + + private static run(self: ThrottledOperations, operationId: string, cb: () => void) { + self.pendingTimeouts.delete(operationId); + cb(); + } + } + + export class GcTimer { + private timerId: any; + constructor(private readonly host: ServerHost, private readonly delay: number, private readonly logger: Logger) { + } + + public scheduleCollect() { + if (!this.host.gc || this.timerId !== undefined) { + // no global.gc or collection was already scheduled - skip this request + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + } + + private static run(self: GcTimer) { + self.timerId = undefined; + + const log = self.logger.hasLevel(LogLevel.requestTime); + const before = log && self.host.getMemoryUsage(); + + self.host.gc(); + if (log) { + const after = self.host.getMemoryUsage(); + self.logger.perftrc(`GC::before ${before}, after ${after}`); + } + } + } +} + +/* @internal */ +namespace ts.server { + export function insertSorted(array: SortedArray, insert: T, compare: Comparer): void { + if (array.length === 0) { + array.push(insert); + return; + } + + const insertIndex = binarySearch(array, insert, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + + export function removeSorted(array: SortedArray, remove: T, compare: Comparer): void { + if (!array || array.length === 0) { + return; + } + + if (array[0] === remove) { + array.splice(0, 1); + return; + } + + const removeIndex = binarySearch(array, remove, compare); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + } + export function toSortedArray(arr: string[]): SortedArray; export function toSortedArray(arr: T[], comparer: Comparer): SortedArray; export function toSortedArray(arr: T[], comparer?: Comparer): SortedArray { @@ -286,80 +365,4 @@ namespace ts.server { cleanExistingMap(existingMap, onDeleteExistingValue); return undefined; } - - export class ThrottledOperations { - private pendingTimeouts: Map = createMap(); - constructor(private readonly host: ServerHost) { - } - - public schedule(operationId: string, delay: number, cb: () => void) { - const pendingTimeout = this.pendingTimeouts.get(operationId); - if (pendingTimeout) { - // another operation was already scheduled for this id - cancel it - this.host.clearTimeout(pendingTimeout); - } - // schedule new operation, pass arguments - this.pendingTimeouts.set(operationId, this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb)); - } - - private static run(self: ThrottledOperations, operationId: string, cb: () => void) { - self.pendingTimeouts.delete(operationId); - cb(); - } - } - - export class GcTimer { - private timerId: any; - constructor(private readonly host: ServerHost, private readonly delay: number, private readonly logger: Logger) { - } - - public scheduleCollect() { - if (!this.host.gc || this.timerId !== undefined) { - // no global.gc or collection was already scheduled - skip this request - return; - } - this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); - } - - private static run(self: GcTimer) { - self.timerId = undefined; - - const log = self.logger.hasLevel(LogLevel.requestTime); - const before = log && self.host.getMemoryUsage(); - - self.host.gc(); - if (log) { - const after = self.host.getMemoryUsage(); - self.logger.perftrc(`GC::before ${before}, after ${after}`); - } - } - } - - export function insertSorted(array: SortedArray, insert: T, compare: Comparer): void { - if (array.length === 0) { - array.push(insert); - return; - } - - const insertIndex = binarySearch(array, insert, compare); - if (insertIndex < 0) { - array.splice(~insertIndex, 0, insert); - } - } - - export function removeSorted(array: SortedArray, remove: T, compare: Comparer): void { - if (!array || array.length === 0) { - return; - } - - if (array[0] === remove) { - array.splice(0, 1); - return; - } - - const removeIndex = binarySearch(array, remove, compare); - if (removeIndex >= 0) { - array.splice(removeIndex, 1); - } - } } diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 146a513ffc5..dc5d99bc490 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -557,7 +557,7 @@ namespace ts { // Only bother calling into the typechecker if this is an identifier that // could possibly resolve to a type name. This makes classification run // in a third of the time it would normally take. - if (classifiableNames.has(identifier.text)) { + if (classifiableNames.has(identifier.escapedText)) { const symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { const type = classifySymbol(symbol, getMeaningFromLocation(node)); @@ -755,10 +755,10 @@ namespace ts { return; function processJSDocParameterTag(tag: JSDocParameterTag) { - if (tag.preParameterName) { - pushCommentRange(pos, tag.preParameterName.pos - pos); - pushClassification(tag.preParameterName.pos, tag.preParameterName.end - tag.preParameterName.pos, ClassificationType.parameterName); - pos = tag.preParameterName.end; + if (tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, ClassificationType.parameterName); + pos = tag.name.end; } if (tag.typeExpression) { @@ -767,10 +767,10 @@ namespace ts { pos = tag.typeExpression.end; } - if (tag.postParameterName) { - pushCommentRange(pos, tag.postParameterName.pos - pos); - pushClassification(tag.postParameterName.pos, tag.postParameterName.end - tag.postParameterName.pos, ClassificationType.parameterName); - pos = tag.postParameterName.end; + if (!tag.isNameFirst) { + pushCommentRange(pos, tag.name.pos - pos); + pushClassification(tag.name.pos, tag.name.end - tag.name.pos, ClassificationType.parameterName); + pos = tag.name.end; } } } diff --git a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts new file mode 100644 index 00000000000..3087d73276d --- /dev/null +++ b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts @@ -0,0 +1,27 @@ +/* @internal */ +namespace ts.codefix { + registerCodeFix({ + errorCodes: [Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code], + getCodeActions: (context: CodeFixContext) => { + const sourceFile = context.sourceFile; + const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); + const qualifiedName = getAncestor(token, SyntaxKind.QualifiedName) as QualifiedName; + Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); + if (!isIdentifier(qualifiedName.left)) { + return undefined; + } + const leftText = qualifiedName.left.getText(sourceFile); + const rightText = qualifiedName.right.getText(sourceFile); + const replacement = createIndexedAccessTypeNode( + createTypeReferenceNode(qualifiedName.left, /*typeArguments*/ undefined), + createLiteralTypeNode(createLiteral(rightText))); + const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context); + changeTracker.replaceNode(sourceFile, qualifiedName, replacement); + + return [{ + description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Rewrite_as_the_indexed_access_type_0), [`${leftText}["${rightText}"]`]), + changes: changeTracker.getChanges() + }]; + } + }); +} diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts index c8f539e8d34..ff3bd455291 100644 --- a/src/services/codefixes/fixSpelling.ts +++ b/src/services/codefixes/fixSpelling.ts @@ -15,7 +15,8 @@ namespace ts.codefix { 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)) { + if (isPropertyAccessExpression(node.parent) && node.parent.name === node) { + Debug.assert(node.kind === SyntaxKind.Identifier); const containingType = checker.getTypeAtLocation(node.parent.expression); suggestion = checker.getSuggestionForNonexistentProperty(node as Identifier, containingType); } diff --git a/src/services/codefixes/fixes.ts b/src/services/codefixes/fixes.ts index ef670c81ba9..9bc80cad691 100644 --- a/src/services/codefixes/fixes.ts +++ b/src/services/codefixes/fixes.ts @@ -1,3 +1,4 @@ +/// /// /// /// diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index d1599dc4cac..7b69e12a19a 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -35,7 +35,7 @@ namespace ts.codefix { */ export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: Symbol[], checker: TypeChecker): Node[] { const classMembers = classDeclaration.symbol.members; - const missingMembers = possiblyMissingSymbols.filter(symbol => !classMembers.has(symbol.name)); + const missingMembers = possiblyMissingSymbols.filter(symbol => !classMembers.has(symbol.escapedName)); let newNodes: Node[] = []; for (const symbol of missingMembers) { @@ -205,7 +205,7 @@ namespace ts.codefix { } } const maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); - const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(symbol => symbol.getUnescapedName()); + const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(symbol => symbol.name); const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*addAnyType*/ true); diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 2be20f35c16..d6fb8de9259 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -148,7 +148,7 @@ namespace ts.codefix { else if (isJsxOpeningLikeElement(token.parent) && token.parent.tagName === token) { // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. symbol = checker.getAliasedSymbol(checker.resolveNameAtLocation(token, checker.getJsxNamespace(), SymbolFlags.Value)); - symbolName = symbol.getUnescapedName(); + symbolName = symbol.name; } else { Debug.fail("Either the symbol or the JSX namespace should be a UMD global if we got here"); @@ -171,15 +171,18 @@ namespace ts.codefix { const defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { const localSymbol = getLocalSymbolForExportDefault(defaultExport); - if (localSymbol && localSymbol.name === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { + if (localSymbol && localSymbol.escapedName === name && checkSymbolHasMeaning(localSymbol, currentTokenMeaning)) { // check if this symbol is already used const symbolId = getUniqueSymbolId(localSymbol); - symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isDefault*/ true)); + symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name, /*isNamespaceImport*/ true)); } } + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + Debug.assert(name !== "default"); + // check exports with the same name - const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExports(name, moduleSymbol); + const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(name, moduleSymbol); if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { const symbolId = getUniqueSymbolId(exportSymbolWithIdenticalName); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, name)); @@ -501,45 +504,120 @@ namespace ts.codefix { return undefined; } - const indexOfNodeModules = moduleFileName.indexOf("node_modules"); - if (indexOfNodeModules < 0) { + const parts = getNodeModulePathParts(moduleFileName); + + if (!parts) { return undefined; } - let relativeFileName: string; - 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); - } + // Simplify the full file path to something that can be resolved by Node. - relativeFileName = removeFileExtension(relativeFileName); - if (endsWith(relativeFileName, "/index")) { - relativeFileName = getDirectoryPath(relativeFileName); - } - else { - try { - const moduleDirectory = getDirectoryPath(moduleFileName); - const packageJsonContent = JSON.parse(context.host.readFile(combinePaths(moduleDirectory, "package.json"))); + // If the module could be imported by a directory name, use that directory's name + let moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + moduleSpecifier = getNodeResolvablePath(moduleSpecifier); + // If the module was found in @types, get the actual Node package name + return getPackageNameFromAtTypesDirectory(moduleSpecifier); + + function getDirectoryOrExtensionlessFileName(path: string): string { + // If the file is the main module, it can be imported by the package name + const packageRootPath = path.substring(0, parts.packageRootIndex); + const packageJsonPath = combinePaths(packageRootPath, "package.json"); + if (context.host.fileExists(packageJsonPath)) { + const packageJsonContent = JSON.parse(context.host.readFile(packageJsonPath)); if (packageJsonContent) { - const mainFile = packageJsonContent.main || packageJsonContent.typings; - if (mainFile) { - const mainExportFile = toPath(mainFile, moduleDirectory, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(moduleFileName)) { - relativeFileName = getDirectoryPath(relativeFileName); + const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (mainExportFile === getCanonicalFileName(path)) { + return packageRootPath; } } } } - catch (e) { } + + // We still have a file name - remove the extension + const fullModulePathWithoutExtension = removeFileExtension(path); + + // If the file is /index, it can be imported by its directory name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + + return fullModulePathWithoutExtension; } - return getPackageNameFromAtTypesDirectory(relativeFileName); + function getNodeResolvablePath(path: string): string { + const basePath = path.substring(0, parts.topLevelNodeModulesIndex); + if (sourceDirectory.indexOf(basePath) === 0) { + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + return path.substring(parts.topLevelPackageNameIndex + 1); + } + else { + return getRelativePath(path, sourceDirectory); + } + } } } + function getNodeModulePathParts(fullPath: string) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + + let topLevelNodeModulesIndex = 0; + let topLevelPackageNameIndex = 0; + let packageRootIndex = 0; + let fileNameIndex = 0; + + const enum States { + BeforeNodeModules, + NodeModules, + Scope, + PackageContent + } + + let partStart = 0; + let partEnd = 0; + let state = States.BeforeNodeModules; + + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case States.BeforeNodeModules: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = States.NodeModules; + } + break; + case States.NodeModules: + case States.Scope: + if (state === States.NodeModules && fullPath.charAt(partStart + 1) === "@") { + state = States.Scope; + } + else { + packageRootIndex = partEnd; + state = States.PackageContent; + } + break; + case States.PackageContent: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = States.NodeModules; + } + else { + state = States.PackageContent; + } + break; + } + } + + fileNameIndex = partStart; + + return state > States.NodeModules ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path: string, rootDirs: string[]) { for (const rootDir of rootDirs) { const relativeName = getRelativePathIfInDirectory(path, rootDir); diff --git a/src/services/completions.ts b/src/services/completions.ts index d7f0701caf2..b49567ef217 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -420,7 +420,7 @@ namespace ts.Completions { if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression) { + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === SyntaxKind.JSDocTypeExpression) { currentToken = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); if (!currentToken || (!isDeclarationName(currentToken) && @@ -606,7 +606,7 @@ namespace ts.Completions { if (symbol.flags & (SymbolFlags.Module | SymbolFlags.Enum)) { // Extract module or enum members const exportedSymbols = typeChecker.getExportsOfModule(symbol); - const isValidValueAccess = (symbol: Symbol) => typeChecker.isValidPropertyAccess((node.parent), symbol.getUnescapedName()); + const isValidValueAccess = (symbol: Symbol) => typeChecker.isValidPropertyAccess((node.parent), symbol.name); const isValidTypeAccess = (symbol: Symbol) => symbolCanBeReferencedAtTypeLocation(symbol); const isValidAccess = isRhsOfImportDeclaration ? // Any kind is allowed when dotting off namespace in internal import equals declaration @@ -636,7 +636,7 @@ namespace ts.Completions { function addTypeProperties(type: Type) { // Filter private properties for (const symbol of type.getApparentProperties()) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.getUnescapedName())) { + if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { symbols.push(symbol); } } @@ -1453,14 +1453,14 @@ namespace ts.Completions { } const name = element.propertyName || element.name; - existingImportsOrExports.set(name.text, true); + existingImportsOrExports.set(name.escapedText, true); } if (existingImportsOrExports.size === 0) { - return filter(exportsOfModule, e => e.name !== "default"); + return filter(exportsOfModule, e => e.escapedName !== "default"); } - return filter(exportsOfModule, e => e.name !== "default" && !existingImportsOrExports.get(e.name)); + return filter(exportsOfModule, e => e.escapedName !== "default" && !existingImportsOrExports.get(e.escapedName)); } /** @@ -1496,7 +1496,7 @@ namespace ts.Completions { if (m.kind === SyntaxKind.BindingElement && (m).propertyName) { // include only identifiers in completion list if ((m).propertyName.kind === SyntaxKind.Identifier) { - existingName = ((m).propertyName).text; + existingName = ((m).propertyName).escapedText; } } else { @@ -1510,7 +1510,7 @@ namespace ts.Completions { existingMemberNames.set(existingName, true); } - return filter(contextualMemberSymbols, m => !existingMemberNames.get(m.name)); + return filter(contextualMemberSymbols, m => !existingMemberNames.get(m.escapedName)); } /** @@ -1571,7 +1571,7 @@ namespace ts.Completions { } function isValidProperty(propertySymbol: Symbol, inValidModifierFlags: ModifierFlags) { - return !existingMemberNames.get(propertySymbol.name) && + return !existingMemberNames.get(propertySymbol.escapedName) && propertySymbol.getDeclarations() && !(getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); } @@ -1592,11 +1592,11 @@ namespace ts.Completions { } if (attr.kind === SyntaxKind.JsxAttribute) { - seenNames.set((attr).name.text, true); + seenNames.set((attr).name.escapedText, true); } } - return filter(symbols, a => !seenNames.get(a.name)); + return filter(symbols, a => !seenNames.get(a.escapedName)); } function isCurrentlyEditingNode(node: Node): boolean { @@ -1610,7 +1610,7 @@ namespace ts.Completions { * @return undefined if the name is of external module */ function getCompletionEntryDisplayNameForSymbol(symbol: Symbol, target: ScriptTarget, performCharacterChecks: boolean): string | undefined { - const name = symbol.getUnescapedName(); + const name = symbol.name; if (!name) return undefined; // First check of the displayName is not external module; if it is an external module, it is not valid entry diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index eb1e2531143..ca4bb861c7d 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -248,7 +248,7 @@ namespace ts.DocumentHighlights { case SyntaxKind.ForOfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: - if (!statement.label || isLabeledBy(node, unescapeLeadingUnderscores(statement.label.text))) { + if (!statement.label || isLabeledBy(node, statement.label.text)) { return node; } break; @@ -606,7 +606,7 @@ namespace ts.DocumentHighlights { */ function isLabeledBy(node: Node, labelName: string) { for (let owner = node.parent; owner.kind === SyntaxKind.LabeledStatement; owner = owner.parent) { - if ((owner).label.text === labelName) { + if ((owner).label.escapedText === labelName) { return true; } } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 9fc3588ddb9..204de12a10c 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -122,7 +122,7 @@ namespace ts.FindAllReferences { } case "label": { const { node } = def; - return { node, name: unescapeLeadingUnderscores(node.text), kind: ScriptElementKind.label, displayParts: [displayPart(unescapeLeadingUnderscores(node.text), SymbolDisplayPartKind.text)] }; + return { node, name: node.text, kind: ScriptElementKind.label, displayParts: [displayPart(node.text, SymbolDisplayPartKind.text)] }; } case "keyword": { const { node } = def; @@ -357,7 +357,7 @@ namespace ts.FindAllReferences.Core { // Labels if (isLabelName(node)) { if (isJumpStatementTarget(node)) { - const labelDefinition = getTargetLabel((node.parent), unescapeLeadingUnderscores((node).text)); + const labelDefinition = getTargetLabel((node.parent), (node).text); // if we have a label definition, look within its statement for references, if not, then // the label is undefined and we have no results.. return labelDefinition && getLabelReferencesInNode(labelDefinition.parent, labelDefinition); @@ -604,11 +604,16 @@ namespace ts.FindAllReferences.Core { function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol, checker: TypeChecker): Symbol | undefined { const bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (bindingElement) { - const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - return typeOfPattern && checker.getPropertyOfType(typeOfPattern, unescapeLeadingUnderscores((bindingElement.name).text)); + if (!bindingElement) return undefined; + + const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + const propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, (bindingElement.name).text); + if (propSymbol && propSymbol.flags & SymbolFlags.Accessor) { + // See GH#16922 + Debug.assert(!!(propSymbol.flags & SymbolFlags.Transient)); + return (propSymbol as TransientSymbol).target; } - return undefined; + return propSymbol; } /** @@ -718,7 +723,7 @@ namespace ts.FindAllReferences.Core { function getLabelReferencesInNode(container: Node, targetLabel: Identifier): SymbolAndEntries[] { const references: Entry[] = []; const sourceFile = container.getSourceFile(); - const labelName = unescapeLeadingUnderscores(targetLabel.text); + const labelName = targetLabel.text; const possiblePositions = getPossibleSymbolReferencePositions(sourceFile, labelName, container); for (const position of possiblePositions) { const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); @@ -735,7 +740,7 @@ 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 unescapeLeadingUnderscores((node as Identifier).text).length === searchSymbolName.length; + return (node as Identifier).text.length === searchSymbolName.length; case SyntaxKind.StringLiteral: return (isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && @@ -1417,7 +1422,7 @@ namespace ts.FindAllReferences.Core { // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members if (symbol.valueDeclaration && symbol.valueDeclaration.kind === SyntaxKind.Parameter && isParameterPropertyDeclaration(symbol.valueDeclaration)) { - addRange(result, checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.getUnescapedName())); + addRange(result, checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name)); } // If this is symbol of binding element without propertyName declaration in Object binding pattern @@ -1436,7 +1441,7 @@ namespace ts.FindAllReferences.Core { // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (SymbolFlags.Class | SymbolFlags.Interface)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getUnescapedName(), result, /*previousIterationSymbolsCache*/ createSymbolTable(), checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ createSymbolTable(), checker); } } @@ -1467,7 +1472,7 @@ namespace ts.FindAllReferences.Core { // the function will add any found symbol of the property-name, then its sub-routine will call // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. - if (previousIterationSymbolsCache.has(symbol.name)) { + if (previousIterationSymbolsCache.has(symbol.escapedName)) { return; } @@ -1494,7 +1499,7 @@ namespace ts.FindAllReferences.Core { } // Visit the typeReference as well to see if it directly or indirectly use that property - previousIterationSymbolsCache.set(symbol.name, symbol); + previousIterationSymbolsCache.set(symbol.escapedName, symbol); getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); } } @@ -1554,7 +1559,7 @@ namespace ts.FindAllReferences.Core { } const result: Symbol[] = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.getUnescapedName(), result, /*previousIterationSymbolsCache*/ createSymbolTable(), state.checker); + getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ createSymbolTable(), state.checker); return find(result, search.includes); } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index b388a8551d2..3c4adcb68df 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -26,7 +26,7 @@ namespace ts.GoToDefinition { // Labels if (isJumpStatementTarget(node)) { - const labelName = unescapeLeadingUnderscores((node).text); + const labelName = (node).text; const label = getTargetLabel((node.parent), labelName); return label ? [createDefinitionInfoFromName(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; } diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 417c16909df..1bbf175c7fe 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -180,7 +180,7 @@ namespace ts.FindAllReferences { * But re-exports will be placed in 'singleReferences' since they cannot be locally referenced. */ function getSearchesFromDirectImports(directImports: Importer[], exportSymbol: Symbol, exportKind: ExportKind, checker: TypeChecker, isForRename: boolean): Pick { - const exportName = exportSymbol.name; + const exportName = exportSymbol.escapedName; const importSearches: Array<[Identifier, Symbol]> = []; const singleReferences: Identifier[] = []; function addSearch(location: Identifier, symbol: Symbol): void { @@ -238,7 +238,7 @@ namespace ts.FindAllReferences { const { name } = importClause; // If a default import has the same name as the default export, allow to rename it. // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.text === symbolName(exportSymbol))) { + if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { const defaultImportAlias = checker.getSymbolAtLocation(name); addSearch(name, defaultImportAlias); } @@ -258,7 +258,7 @@ namespace ts.FindAllReferences { */ function handleNamespaceImportLike(importName: Identifier): void { // Don't rename an import that already has a different name than the export. - if (exportKind === ExportKind.ExportEquals && (!isForRename || importName.text === exportName)) { + if (exportKind === ExportKind.ExportEquals && (!isForRename || importName.escapedText === exportName)) { addSearch(importName, checker.getSymbolAtLocation(importName)); } } @@ -267,7 +267,7 @@ namespace ts.FindAllReferences { if (namedBindings) { for (const element of namedBindings.elements) { const { name, propertyName } = element; - if ((propertyName || name).text !== exportName) { + if ((propertyName || name).escapedText !== exportName) { continue; } @@ -521,11 +521,11 @@ namespace ts.FindAllReferences { // Search on the local symbol in the exporting module, not the exported symbol. importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); // Similarly, skip past the symbol for 'export =' - if (importedSymbol.name === "export=") { + if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); } - if (symbolName(importedSymbol) === symbol.name) { // If this is a rename import, do not continue searching. + if (symbolName(importedSymbol) === symbol.escapedName) { // If this is a rename import, do not continue searching. return { kind: ImportExport.Import, symbol: importedSymbol, ...isImport }; } } @@ -595,16 +595,16 @@ namespace ts.FindAllReferences { } function symbolName(symbol: Symbol): __String | undefined { - if (symbol.name !== "default") { - return symbol.getName(); + if (symbol.escapedName !== "default") { + return symbol.escapedName; } return forEach(symbol.declarations, decl => { if (isExportAssignment(decl)) { - return isIdentifier(decl.expression) ? decl.expression.text : undefined; + return isIdentifier(decl.expression) ? decl.expression.escapedText : undefined; } const name = getNameOfDeclaration(decl); - return name && name.kind === SyntaxKind.Identifier && name.text; + return name && name.kind === SyntaxKind.Identifier && name.escapedText; }); } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 070b96101e2..ee3ae7c868f 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -71,7 +71,7 @@ namespace ts.JsDoc { forEachUnique(declarations, declaration => { for (const tag of getJSDocTags(declaration)) { if (tag.kind === SyntaxKind.JSDocTag) { - tags.push({ name: unescapeLeadingUnderscores(tag.tagName.text), text: tag.comment }); + tags.push({ name: tag.tagName.text, text: tag.comment }); } } }); @@ -120,7 +120,10 @@ namespace ts.JsDoc { } export function getJSDocParameterNameCompletions(tag: JSDocParameterTag): CompletionEntry[] { - const nameThusFar = unescapeLeadingUnderscores(tag.name.text); + if (!isIdentifier(tag.name)) { + return emptyArray; + } + const nameThusFar = tag.name.text; const jsdoc = tag.parent; const fn = jsdoc.parent; if (!ts.isFunctionLike(fn)) return []; @@ -128,8 +131,8 @@ namespace ts.JsDoc { return mapDefined(fn.parameters, param => { if (!isIdentifier(param.name)) return undefined; - const name = unescapeLeadingUnderscores(param.name.text); - if (jsdoc.tags.some(t => t !== tag && isJSDocParameterTag(t) && t.name.text === name) + const name = param.name.text; + if (jsdoc.tags.some(t => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== undefined && !startsWith(name, nameThusFar)) { return undefined; } @@ -213,7 +216,7 @@ namespace ts.JsDoc { for (let i = 0; i < parameters.length; i++) { const currentName = parameters[i].name; const paramName = currentName.kind === SyntaxKind.Identifier ? - (currentName).text : + (currentName).escapedText : "param" + i; if (isJavaScriptFile) { docParams += `${indentationStr} * @param {any} ${paramName}${newLine}`; diff --git a/src/services/jsTyping.ts b/src/services/jsTyping.ts index 670633eb44b..4de7bb3191d 100644 --- a/src/services/jsTyping.ts +++ b/src/services/jsTyping.ts @@ -22,13 +22,10 @@ namespace ts.JsTyping { name?: string; optionalDependencies?: MapLike; peerDependencies?: MapLike; + types?: string; typings?: string; } - // A map of loose file names to library names - // that we are confident require typings - let safeList: Map; - /* @internal */ export const nodeCoreModuleList: ReadonlyArray = [ "buffer", "querystring", "events", "http", "cluster", @@ -40,6 +37,16 @@ namespace ts.JsTyping { const nodeCoreModules = arrayToMap(nodeCoreModuleList, x => x); + /** + * A map of loose file names to library names that we are confident require typings + */ + export type SafeList = ReadonlyMap; + + export function loadSafeList(host: TypingResolutionHost, safeListPath: Path): SafeList { + const result = readConfigFile(safeListPath, path => host.readFile(path)); + return createMapFromTemplate(result.config); + } + /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -54,8 +61,8 @@ namespace ts.JsTyping { log: ((message: string) => void) | undefined, fileNames: string[], projectRootPath: Path, - safeListPath: Path, - packageNameToTypingLocation: Map, + safeList: SafeList, + packageNameToTypingLocation: ReadonlyMap, typeAcquisition: TypeAcquisition, unresolvedImports: ReadonlyArray): { cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } { @@ -75,21 +82,13 @@ namespace ts.JsTyping { } }); - if (!safeList) { - const result = readConfigFile(safeListPath, (path: string) => host.readFile(path)); - safeList = createMapFromTemplate(result.config); - } - const filesToWatch: string[] = []; - forEach(typeAcquisition.include, addInferredTyping); + if (typeAcquisition.include) addInferredTypings(typeAcquisition.include, "Explicitly included types"); const exclude = typeAcquisition.exclude || []; // Directories to search for package.json, bower.json and other typing information - const possibleSearchDirs = createMap(); - for (const f of fileNames) { - possibleSearchDirs.set(getDirectoryPath(f), true); - } + const possibleSearchDirs = arrayToSet(fileNames, getDirectoryPath); possibleSearchDirs.set(projectRootPath, true); possibleSearchDirs.forEach((_true, searchDir) => { const packageJsonPath = combinePaths(searchDir, "package.json"); @@ -108,13 +107,8 @@ namespace ts.JsTyping { // add typings for unresolved imports if (unresolvedImports) { - const x = unresolvedImports.map(moduleId => nodeCoreModules.has(moduleId) ? "node" : moduleId); - if (x.length && log) log(`Inferred typings from unresolved imports: ${JSON.stringify(x)}`); - for (const typingName of x) { - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } + const module = deduplicate(unresolvedImports.map(moduleId => nodeCoreModules.has(moduleId) ? "node" : moduleId)); + addInferredTypings(module, "Inferred typings from unresolved imports"); } // Add the cached typing locations for inferred typings that are already installed packageNameToTypingLocation.forEach((typingLocation, name) => { @@ -125,7 +119,8 @@ namespace ts.JsTyping { // Remove typings that the user has added to the exclude list for (const excludeTypingName of exclude) { - inferredTypings.delete(excludeTypingName); + const didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) log(`Typing for ${excludeTypingName} is in exclude list, will be ignored.`); } const newTypingNames: string[] = []; @@ -147,6 +142,10 @@ namespace ts.JsTyping { inferredTypings.set(typingName, undefined); } } + function addInferredTypings(typingNames: ReadonlyArray, message: string) { + if (log) log(`${message}: ${JSON.stringify(typingNames)}`); + forEach(typingNames, addInferredTyping); + } /** * Get the typing info from common package manager json files like package.json or bower.json @@ -157,20 +156,9 @@ namespace ts.JsTyping { } filesToWatch.push(jsonPath); - if (log) log(`Searching for typing names in '${jsonPath}' dependencies`); - const jsonConfig: PackageJson = readConfigFile(jsonPath, (path: string) => host.readFile(path)).config; - addInferredTypingsFromKeys(jsonConfig.dependencies); - addInferredTypingsFromKeys(jsonConfig.devDependencies); - addInferredTypingsFromKeys(jsonConfig.optionalDependencies); - addInferredTypingsFromKeys(jsonConfig.peerDependencies); - - function addInferredTypingsFromKeys(map: MapLike | undefined): void { - for (const key in map) { - if (ts.hasProperty(map, key)) { - addInferredTyping(key); - } - } - } + const jsonConfig: PackageJson = readConfigFile(jsonPath, path => host.readFile(path)).config; + const jsonTypingNames = flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], getOwnKeys); + addInferredTypings(jsonTypingNames, `Typing names in '${jsonPath}' dependencies`); } /** @@ -188,10 +176,7 @@ namespace ts.JsTyping { return safeList.get(cleanedTypingName); }); if (fromFileNames.length) { - if (log) log(`Inferred typings from file names: ${JSON.stringify(fromFileNames)}`); - for (const safe of fromFileNames) { - addInferredTyping(safe); - } + addInferredTypings(fromFileNames, "Inferred typings from file names"); } const hasJsxFile = some(fileNames, f => fileExtensionIs(f, Extension.Jsx)); @@ -216,6 +201,7 @@ namespace ts.JsTyping { // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` const fileNames = host.readDirectory(packagesFolderPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); if (log) log(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(fileNames)}`); + const packageNames: string[] = []; for (const fileName of fileNames) { const normalizedFileName = normalizePath(fileName); const baseFileName = getBaseFileName(normalizedFileName); @@ -238,14 +224,17 @@ namespace ts.JsTyping { if (!packageJson.name) { continue; } - if (packageJson.typings) { - const absolutePath = getNormalizedAbsolutePath(packageJson.typings, getDirectoryPath(normalizedFileName)); + const ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + const absolutePath = getNormalizedAbsolutePath(ownTypes, getDirectoryPath(normalizedFileName)); + if (log) log(` Package '${packageJson.name}' provides its own types.`); inferredTypings.set(packageJson.name, absolutePath); } else { - addInferredTyping(packageJson.name); + packageNames.push(packageJson.name); } } + addInferredTypings(packageNames, " Found package names"); } } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index f8a0d96806e..122ada09019 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -54,7 +54,7 @@ namespace ts.NavigateTo { if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) { const importer = checker.getSymbolAtLocation((decl as NamedDeclaration).name); const imported = checker.getAliasedSymbol(importer); - return importer.name !== imported.name; + return importer.escapedName !== imported.escapedName; } else { return true; @@ -119,7 +119,7 @@ namespace ts.NavigateTo { if (expression.kind === SyntaxKind.PropertyAccessExpression) { const propertyAccess = expression; if (includeLastPortion) { - containers.unshift(unescapeLeadingUnderscores(propertyAccess.name.text)); + containers.unshift(propertyAccess.name.text); } return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); @@ -191,7 +191,7 @@ namespace ts.NavigateTo { fileName: rawItem.fileName, textSpan: createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: containerName ? unescapeLeadingUnderscores((containerName).text) : "", + containerName: containerName ? (containerName).text : "", containerKind: containerName ? getNodeKind(container) : ScriptElementKind.unknown }; } diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 6720225f125..35357b9331a 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -442,7 +442,7 @@ namespace ts.NavigationBar { function getJSDocTypedefTagName(node: JSDocTypedefTag): string { if (node.name) { - return unescapeLeadingUnderscores(node.name.text); + return node.name.text; } else { const parentNode = node.parent && node.parent.parent; @@ -450,7 +450,7 @@ namespace ts.NavigationBar { if ((parentNode).declarationList.declarations.length > 0) { const nameIdentifier = (parentNode).declarationList.declarations[0].name; if (nameIdentifier.kind === SyntaxKind.Identifier) { - return unescapeLeadingUnderscores((nameIdentifier).text); + return nameIdentifier.text; } } } diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 9b645280a1e..c41ed798b1d 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -239,7 +239,7 @@ namespace ts.Completions.PathCompletions { const moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(directorySeparator)) : undefined; // Get modules that the type checker picked up - const ambientModules = map(typeChecker.getAmbientModules(), sym => stripQuotes(unescapeLeadingUnderscores(sym.name))); + const ambientModules = map(typeChecker.getAmbientModules(), sym => stripQuotes(sym.name)); 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 diff --git a/src/services/refactors/convertFunctionToEs6Class.ts b/src/services/refactors/convertFunctionToEs6Class.ts index 2fb67ea98e8..45adfb4b039 100644 --- a/src/services/refactors/convertFunctionToEs6Class.ts +++ b/src/services/refactors/convertFunctionToEs6Class.ts @@ -163,7 +163,7 @@ namespace ts.refactor { deleteNode(nodeToDelete); if (!assignmentBinaryExpression.right) { - return createProperty([], modifiers, symbol.getUnescapedName(), /*questionToken*/ undefined, + return createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } diff --git a/src/services/services.ts b/src/services/services.ts index a444bd808d9..2e031f3cad2 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -304,7 +304,7 @@ namespace ts { class SymbolObject implements Symbol { flags: SymbolFlags; - name: __String; + escapedName: __String; declarations?: Declaration[]; // Undefined is used to indicate the value has not been computed. If, after computing, the @@ -317,19 +317,23 @@ namespace ts { constructor(flags: SymbolFlags, name: __String) { this.flags = flags; - this.name = name; + this.escapedName = name; } getFlags(): SymbolFlags { return this.flags; } - getName(): __String { - return this.name; + get name(): string { + return unescapeLeadingUnderscores(this.escapedName); } - getUnescapedName(): string { - return unescapeLeadingUnderscores(this.name); + getEscapedName(): __String { + return this.escapedName; + } + + getName(): string { + return this.name; } getDeclarations(): Declaration[] | undefined { @@ -364,7 +368,7 @@ namespace ts { class IdentifierObject extends TokenOrIdentifierObject implements Identifier { public kind: SyntaxKind.Identifier; - public text: __String; + public escapedText: __String; _primaryExpressionBrand: any; _memberExpressionBrand: any; _leftHandSideExpressionBrand: any; @@ -375,6 +379,10 @@ namespace ts { constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) { super(pos, end); } + + get text(): string { + return unescapeLeadingUnderscores(this.escapedText); + } } IdentifierObject.prototype.kind = SyntaxKind.Identifier; @@ -601,7 +609,7 @@ namespace ts { if (name.kind === SyntaxKind.ComputedPropertyName) { const expr = (name).expression; if (expr.kind === SyntaxKind.PropertyAccessExpression) { - return unescapeLeadingUnderscores((expr).name.text); + return (expr).name.text; } return getTextOfIdentifierOrLiteral(expr as (Identifier | LiteralExpression)); @@ -1826,7 +1834,8 @@ namespace ts { const fileContents = sourceFile.text; const result: TodoComment[] = []; - if (descriptors.length > 0) { + // Exclude node_modules files as we don't want to show the todos of external libraries. + if (descriptors.length > 0 && !isNodeModulesFile(sourceFile.fileName)) { const regExp = getTodoCommentsRegExp(); let matchArray: RegExpExecArray; @@ -1950,6 +1959,12 @@ namespace ts { (char >= CharacterCodes.A && char <= CharacterCodes.Z) || (char >= CharacterCodes._0 && char <= CharacterCodes._9); } + + function isNodeModulesFile(path: string): boolean { + const node_modulesFolderName = "/node_modules/"; + + return path.indexOf(node_modulesFolderName) !== -1; + } } function getRenameInfo(fileName: string, position: number): RenameInfo { @@ -2050,7 +2065,7 @@ namespace ts { function initializeNameTable(sourceFile: SourceFile): void { const nameTable = sourceFile.nameTable = createUnderscoreEscapedMap(); sourceFile.forEachChild(function walk(node) { - if ((isIdentifier(node) || isStringOrNumericLiteral(node) && literalIsName(node)) && node.text) { + if (isIdentifier(node) && node.escapedText || isStringOrNumericLiteral(node) && literalIsName(node)) { const text = getEscapedTextOfIdentifierOrLiteral(node); nameTable.set(text, nameTable.get(text) === undefined ? node.pos : -1); } diff --git a/src/services/shims.ts b/src/services/shims.ts index e86e9053e57..b7c85d2ce82 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -1005,6 +1005,7 @@ namespace ts { class CoreServicesShimObject extends ShimBase implements CoreServicesShim { private logPerformance = false; + private safeList: JsTyping.SafeList | undefined; constructor(factory: ShimFactory, public readonly logger: Logger, private readonly host: CoreServicesShimHostAdapter) { super(factory); @@ -1114,12 +1115,15 @@ namespace ts { const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); return this.forwardJSONCall("discoverTypings()", () => { const info = JSON.parse(discoverTypingsJson); - return ts.JsTyping.discoverTypings( + if (this.safeList === undefined) { + this.safeList = JsTyping.loadSafeList(this.host, toPath(info.safeListPath, info.safeListPath, getCanonicalFileName)); + } + return JsTyping.discoverTypings( this.host, msg => this.logger.log(msg), info.fileNames, toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), - toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), + this.safeList, info.packageNameToTypingLocation, info.typeAcquisition, info.unresolvedImports); diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 71e6bc00b00..f008c829116 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -65,14 +65,14 @@ namespace ts.SignatureHelp { ? (expression).name : undefined; - if (!name || !name.text) { + if (!name || !name.escapedText) { return undefined; } const typeChecker = program.getTypeChecker(); for (const sourceFile of program.getSourceFiles()) { const nameToDeclarations = sourceFile.getNamedDeclarations(); - const declarations = nameToDeclarations.get(unescapeLeadingUnderscores(name.text)); + const declarations = nameToDeclarations.get(name.text); if (declarations) { for (const declaration of declarations) { @@ -414,7 +414,7 @@ namespace ts.SignatureHelp { typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation)); return { - name: parameter.getUnescapedName(), + name: parameter.name, documentation: parameter.getDocumentationComment(), displayParts, isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) @@ -426,7 +426,7 @@ namespace ts.SignatureHelp { typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation)); return { - name: typeParameter.symbol.getUnescapedName(), + name: typeParameter.symbol.name, documentation: emptyArray, displayParts, isOptional: false diff --git a/src/services/types.ts b/src/services/types.ts index 19d2345d968..6ff7402f3ad 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -22,10 +22,15 @@ namespace ts { forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; } + export interface Identifier { + readonly text: string; + } + export interface Symbol { + readonly name: string; getFlags(): SymbolFlags; - getName(): __String; - getUnescapedName(): string; + getEscapedName(): __String; + getName(): string; getDeclarations(): Declaration[] | undefined; getDocumentationComment(): SymbolDisplayPart[]; getJsDocTags(): JSDocTagInfo[]; diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 0e92884d502..a5b035154be 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -203,7 +203,7 @@ namespace ts { export function getTargetLabel(referenceNode: Node, labelName: string): Identifier { while (referenceNode) { - if (referenceNode.kind === SyntaxKind.LabeledStatement && (referenceNode).label.text === labelName) { + if (referenceNode.kind === SyntaxKind.LabeledStatement && (referenceNode).label.escapedText === labelName) { return (referenceNode).label; } referenceNode = referenceNode.parent; @@ -1090,7 +1090,7 @@ namespace ts { /** True if the symbol is for an external module, as opposed to a namespace. */ export function isExternalModuleSymbol(moduleSymbol: Symbol): boolean { Debug.assert(!!(moduleSymbol.flags & SymbolFlags.Module)); - return moduleSymbol.getUnescapedName().charCodeAt(0) === CharacterCodes.doubleQuote; + return moduleSymbol.name.charCodeAt(0) === CharacterCodes.doubleQuote; } /** Returns `true` the first time it encounters a node and `false` afterwards. */ diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json index b47a07e8487..1a49c026e4c 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 12, - "text": "arg" + "escapedText": "arg" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 20 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 22, - "end": 27, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 22, "end": 27, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": false, "comment": "Description" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json index cf86fda872e..4b463061bb5 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 17, - "text": "argument" + "escapedText": "argument" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 25 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 27, - "end": 32, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 27, "end": 32, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": false, "comment": "Description" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json index 4ce75d8c3f9..934de3d8faf 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 13, - "text": "type" + "escapedText": "type" }, "typeExpression": { "kind": "JSDocTypeExpression", diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json index 4ce75d8c3f9..934de3d8faf 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 13, - "text": "type" + "escapedText": "type" }, "typeExpression": { "kind": "JSDocTypeExpression", diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json index b37b887624a..62228eac4af 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 15, - "text": "return" + "escapedText": "return" }, "comment": "" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noType.json index 53c73cdf7c1..06e50488025 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noType.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 13, - "text": "type" + "escapedText": "type" }, "comment": "" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json index 506487232e0..15e8b4a5cfb 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 22 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 24, - "end": 29, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 24, "end": 29, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": false, "comment": "" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json index abc116d7452..21d94f52e6a 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 22 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 24, - "end": 29, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 24, "end": 29, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": false, "comment": "Description text follows" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json index 1df54fadcd7..18649dcb321 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 22 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 25, - "end": 30, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 25, "end": 30, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": true, "comment": "Description text follows" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json index 5347b99be7a..6bddf6235d5 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 22 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 26, - "end": 31, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 26, "end": 31, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": true, "comment": "Description text follows" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json index 9d66ca3dd55..93f47686e8f 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json @@ -16,13 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" - }, - "preParameterName": { - "kind": "Identifier", - "pos": 15, - "end": 20, - "text": "name1" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -38,8 +32,9 @@ "kind": "Identifier", "pos": 15, "end": 20, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": true, "isBracketed": false, "comment": "" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json index 01d08a103c1..e6c48a3f759 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json @@ -16,13 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" - }, - "preParameterName": { - "kind": "Identifier", - "pos": 15, - "end": 20, - "text": "name1" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -38,8 +32,9 @@ "kind": "Identifier", "pos": 15, "end": 20, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": true, "isBracketed": false, "comment": "Description" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json index ab15d24f618..926344175d7 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json @@ -16,20 +16,15 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" - }, - "preParameterName": { - "kind": "Identifier", - "pos": 15, - "end": 18, - "text": "foo" + "escapedText": "param" }, "name": { "kind": "Identifier", "pos": 15, "end": 18, - "text": "foo" + "escapedText": "foo" }, + "isNameFirst": true, "isBracketed": false, "comment": "" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json index 59288030068..0668e7d6324 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 15, - "text": "return" + "escapedText": "return" }, "typeExpression": { "kind": "JSDocTypeExpression", diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json index 48c72efad36..fdc4d523104 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 15, - "text": "return" + "escapedText": "return" }, "typeExpression": { "kind": "JSDocTypeExpression", diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json index 12111466f9e..e108287c52a 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 16, - "text": "returns" + "escapedText": "returns" }, "typeExpression": { "kind": "JSDocTypeExpression", diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json index 8dd2963713e..b39b16497e6 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 17, - "text": "template" + "escapedText": "template" }, "typeParameters": { "0": { @@ -27,7 +27,7 @@ "kind": "Identifier", "pos": 18, "end": 19, - "text": "T" + "escapedText": "T" } }, "length": 1, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json index 2f66159c249..5eeb97af119 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 17, - "text": "template" + "escapedText": "template" }, "typeParameters": { "0": { @@ -27,7 +27,7 @@ "kind": "Identifier", "pos": 18, "end": 19, - "text": "K" + "escapedText": "K" } }, "1": { @@ -38,7 +38,7 @@ "kind": "Identifier", "pos": 20, "end": 21, - "text": "V" + "escapedText": "V" } }, "length": 2, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json index e5814c387bb..96645551c5c 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 17, - "text": "template" + "escapedText": "template" }, "typeParameters": { "0": { @@ -27,7 +27,7 @@ "kind": "Identifier", "pos": 18, "end": 19, - "text": "K" + "escapedText": "K" } }, "1": { @@ -38,7 +38,7 @@ "kind": "Identifier", "pos": 21, "end": 22, - "text": "V" + "escapedText": "V" } }, "length": 2, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json index f29fed31e4c..0b2719f59ba 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 17, - "text": "template" + "escapedText": "template" }, "typeParameters": { "0": { @@ -27,7 +27,7 @@ "kind": "Identifier", "pos": 18, "end": 19, - "text": "K" + "escapedText": "K" } }, "1": { @@ -38,7 +38,7 @@ "kind": "Identifier", "pos": 21, "end": 22, - "text": "V" + "escapedText": "V" } }, "length": 2, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json index d3ee964df7a..8b6118e9b19 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 17, - "text": "template" + "escapedText": "template" }, "typeParameters": { "0": { @@ -27,7 +27,7 @@ "kind": "Identifier", "pos": 18, "end": 19, - "text": "K" + "escapedText": "K" } }, "1": { @@ -38,7 +38,7 @@ "kind": "Identifier", "pos": 22, "end": 23, - "text": "V" + "escapedText": "V" } }, "length": 2, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json index 98f0de70848..d097b42a0b0 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 17, - "text": "template" + "escapedText": "template" }, "typeParameters": { "0": { @@ -27,7 +27,7 @@ "kind": "Identifier", "pos": 18, "end": 19, - "text": "K" + "escapedText": "K" } }, "1": { @@ -38,7 +38,7 @@ "kind": "Identifier", "pos": 22, "end": 23, - "text": "V" + "escapedText": "V" } }, "length": 2, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json index 5ba60030f1b..391ee1aac2f 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 22 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 24, - "end": 29, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 24, "end": 29, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": false, "comment": "" }, @@ -56,7 +51,7 @@ "kind": "Identifier", "pos": 35, "end": 40, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -68,18 +63,13 @@ "end": 48 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 50, - "end": 55, - "text": "name2" - }, "name": { "kind": "Identifier", "pos": 50, "end": 55, - "text": "name2" + "escapedText": "name2" }, + "isNameFirst": false, "isBracketed": false, "comment": "" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json index 7d26097bb34..628d54d162d 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 14, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -28,18 +28,13 @@ "end": 22 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 24, - "end": 29, - "text": "name1" - }, "name": { "kind": "Identifier", "pos": 24, "end": 29, - "text": "name1" + "escapedText": "name1" }, + "isNameFirst": false, "isBracketed": false, "comment": "" }, @@ -56,7 +51,7 @@ "kind": "Identifier", "pos": 31, "end": 36, - "text": "param" + "escapedText": "param" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -68,18 +63,13 @@ "end": 44 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 46, - "end": 51, - "text": "name2" - }, "name": { "kind": "Identifier", "pos": 46, "end": 51, - "text": "name2" + "escapedText": "name2" }, + "isNameFirst": false, "isBracketed": false, "comment": "" }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json index 4ce75d8c3f9..934de3d8faf 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json @@ -16,7 +16,7 @@ "kind": "Identifier", "pos": 9, "end": 13, - "text": "type" + "escapedText": "type" }, "typeExpression": { "kind": "JSDocTypeExpression", diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json index 370e139b512..f0e42ae6325 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json @@ -16,21 +16,21 @@ "kind": "Identifier", "pos": 9, "end": 16, - "text": "typedef" + "escapedText": "typedef" }, "fullName": { "kind": "Identifier", "pos": 17, "end": 23, - "text": "People" + "escapedText": "People" }, "name": { "kind": "Identifier", "pos": 17, "end": 23, - "text": "People" + "escapedText": "People" }, - "jsDocTypeLiteral": { + "typeExpression": { "kind": "JSDocTypeLiteral", "pos": 26, "end": 98, @@ -47,7 +47,7 @@ "kind": "Identifier", "pos": 29, "end": 33, - "text": "type" + "escapedText": "type" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -61,7 +61,7 @@ "kind": "Identifier", "pos": 35, "end": 41, - "text": "Object" + "escapedText": "Object" } } } @@ -80,7 +80,7 @@ "kind": "Identifier", "pos": 48, "end": 56, - "text": "property" + "escapedText": "property" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -92,18 +92,13 @@ "end": 64 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 66, - "end": 69, - "text": "age" - }, "name": { "kind": "Identifier", "pos": 66, "end": 69, - "text": "age" + "escapedText": "age" }, + "isNameFirst": false, "isBracketed": false }, { @@ -119,7 +114,7 @@ "kind": "Identifier", "pos": 75, "end": 83, - "text": "property" + "escapedText": "property" }, "typeExpression": { "kind": "JSDocTypeExpression", @@ -131,18 +126,13 @@ "end": 91 } }, - "postParameterName": { - "kind": "Identifier", - "pos": 93, - "end": 97, - "text": "name" - }, "name": { "kind": "Identifier", "pos": 93, "end": 97, - "text": "name" + "escapedText": "name" }, + "isNameFirst": false, "isBracketed": false } ] diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType1.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType1.json index b1e7fa13dc9..a634587d23a 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType1.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType1.json @@ -13,7 +13,7 @@ "pos": 1, "end": 2, "flags": "JSDoc", - "text": "a" + "escapedText": "a" } } } \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType2.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType2.json index 125c706510d..8db394910fb 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType2.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType2.json @@ -18,7 +18,7 @@ "pos": 1, "end": 2, "flags": "JSDoc", - "text": "a" + "escapedText": "a" } } } diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType3.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType3.json index 49ecaf53d4c..65eba602cce 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType3.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.arrayType3.json @@ -28,7 +28,7 @@ "pos": 2, "end": 3, "flags": "JSDoc", - "text": "a" + "escapedText": "a" } } } diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.functionTypeWithTrailingComma.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.functionTypeWithTrailingComma.json index a3d7fd40267..d686922eecf 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.functionTypeWithTrailingComma.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.functionTypeWithTrailingComma.json @@ -19,7 +19,7 @@ "pos": 10, "end": 11, "flags": "JSDoc", - "text": "a" + "escapedText": "a" } } }, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.keyword1.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.keyword1.json index b37c372a30c..4cac38e9e37 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.keyword1.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.keyword1.json @@ -9,6 +9,6 @@ "end": 4, "flags": "JSDoc", "originalKeywordKind": "VarKeyword", - "text": "var" + "escapedText": "var" } } \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.methodInRecordType.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.methodInRecordType.json index 296a5b0cc31..3d94654aa19 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.methodInRecordType.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.methodInRecordType.json @@ -14,7 +14,7 @@ "pos": 2, "end": 5, "flags": "JSDoc", - "text": "foo" + "escapedText": "foo" }, "parameters": { "length": 0, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.newType1.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.newType1.json index 4458100a3c1..7c134915cf2 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.newType1.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.newType1.json @@ -15,7 +15,7 @@ "end": 13, "flags": "JSDoc", "originalKeywordKind": "NewKeyword", - "text": "new" + "escapedText": "new" }, "type": { "kind": "TypeReference", @@ -32,14 +32,14 @@ "pos": 14, "end": 15, "flags": "JSDoc", - "text": "a" + "escapedText": "a" }, "right": { "kind": "Identifier", "pos": 16, "end": 17, "flags": "JSDoc", - "text": "b" + "escapedText": "b" } } } diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType2.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType2.json index 274a1abd531..c1a48a6c385 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType2.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType2.json @@ -14,7 +14,7 @@ "pos": 2, "end": 5, "flags": "JSDoc", - "text": "foo" + "escapedText": "foo" } }, "length": 1, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType3.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType3.json index 6451edee68b..b21dae3e77c 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType3.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType3.json @@ -14,7 +14,7 @@ "pos": 2, "end": 5, "flags": "JSDoc", - "text": "foo" + "escapedText": "foo" }, "type": { "kind": "NumberKeyword", diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType4.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType4.json index 2fb902cc7d3..a3c37d1efab 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType4.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType4.json @@ -14,7 +14,7 @@ "pos": 2, "end": 5, "flags": "JSDoc", - "text": "foo" + "escapedText": "foo" } }, "1": { @@ -27,7 +27,7 @@ "pos": 6, "end": 10, "flags": "JSDoc", - "text": "bar" + "escapedText": "bar" } }, "length": 2, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType5.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType5.json index 083d498df5f..30949ee9ab4 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType5.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType5.json @@ -14,7 +14,7 @@ "pos": 2, "end": 5, "flags": "JSDoc", - "text": "foo" + "escapedText": "foo" }, "type": { "kind": "NumberKeyword", @@ -33,7 +33,7 @@ "pos": 14, "end": 18, "flags": "JSDoc", - "text": "bar" + "escapedText": "bar" } }, "length": 2, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType6.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType6.json index 7c3e7898528..396645856a8 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType6.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType6.json @@ -14,7 +14,7 @@ "pos": 2, "end": 5, "flags": "JSDoc", - "text": "foo" + "escapedText": "foo" } }, "1": { @@ -27,7 +27,7 @@ "pos": 6, "end": 10, "flags": "JSDoc", - "text": "bar" + "escapedText": "bar" }, "type": { "kind": "NumberKeyword", diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType7.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType7.json index 484c8eab770..c8eba7da464 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType7.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType7.json @@ -14,7 +14,7 @@ "pos": 2, "end": 5, "flags": "JSDoc", - "text": "foo" + "escapedText": "foo" }, "type": { "kind": "NumberKeyword", @@ -33,7 +33,7 @@ "pos": 14, "end": 18, "flags": "JSDoc", - "text": "bar" + "escapedText": "bar" }, "type": { "kind": "NumberKeyword", diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType8.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType8.json index 661a02217aa..c851d76a6fe 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType8.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.recordType8.json @@ -15,7 +15,7 @@ "end": 10, "flags": "JSDoc", "originalKeywordKind": "FunctionKeyword", - "text": "function" + "escapedText": "function" } }, "length": 1, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.thisType1.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.thisType1.json index 276a3bc4ee9..68e4ab1e83c 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.thisType1.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.thisType1.json @@ -15,7 +15,7 @@ "end": 14, "flags": "JSDoc", "originalKeywordKind": "ThisKeyword", - "text": "this" + "escapedText": "this" }, "type": { "kind": "TypeReference", @@ -32,14 +32,14 @@ "pos": 15, "end": 16, "flags": "JSDoc", - "text": "a" + "escapedText": "a" }, "right": { "kind": "Identifier", "pos": 17, "end": 18, "flags": "JSDoc", - "text": "b" + "escapedText": "b" } } } diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.trailingCommaInRecordType.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.trailingCommaInRecordType.json index 899fcc6a649..70aff3b7298 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.trailingCommaInRecordType.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.trailingCommaInRecordType.json @@ -14,7 +14,7 @@ "pos": 2, "end": 3, "flags": "JSDoc", - "text": "a" + "escapedText": "a" } }, "length": 1, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeArgumentsNotFollowingDot.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeArgumentsNotFollowingDot.json index a7a7ffbdf50..1ac2aec383a 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeArgumentsNotFollowingDot.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeArgumentsNotFollowingDot.json @@ -8,7 +8,7 @@ "pos": 1, "end": 2, "flags": "JSDoc", - "text": "a" + "escapedText": "a" }, "typeArguments": { "length": 0, diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeOfType.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeOfType.json index a889c3ef3a1..7efe99ca991 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeOfType.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeOfType.json @@ -8,6 +8,6 @@ "pos": 7, "end": 9, "flags": "JSDoc", - "text": "M" + "escapedText": "M" } } \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference1.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference1.json index 9c22db0c64d..dc59fdf9ae1 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference1.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference1.json @@ -8,7 +8,7 @@ "pos": 1, "end": 2, "flags": "JSDoc", - "text": "a", + "escapedText": "a", "jsdocDotPos": 2 }, "typeArguments": { diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference2.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference2.json index 38e2616fc04..8890aad35eb 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference2.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference2.json @@ -8,7 +8,7 @@ "pos": 1, "end": 2, "flags": "JSDoc", - "text": "a", + "escapedText": "a", "jsdocDotPos": 2 }, "typeArguments": { diff --git a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference3.json b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference3.json index 632c7ba87e9..3fadecba2d5 100644 --- a/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference3.json +++ b/tests/baselines/reference/JSDocParsing/TypeExpressions.parsesCorrectly.typeReference3.json @@ -13,7 +13,7 @@ "pos": 1, "end": 2, "flags": "JSDoc", - "text": "a" + "escapedText": "a" }, "right": { "kind": "Identifier", @@ -21,7 +21,7 @@ "end": 11, "flags": "JSDoc", "originalKeywordKind": "FunctionKeyword", - "text": "function" + "escapedText": "function" } } } \ No newline at end of file diff --git a/tests/baselines/reference/anyIndexedAccessArrayNoException.errors.txt b/tests/baselines/reference/anyIndexedAccessArrayNoException.errors.txt new file mode 100644 index 00000000000..01c5bd6b2e2 --- /dev/null +++ b/tests/baselines/reference/anyIndexedAccessArrayNoException.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/anyIndexedAccessArrayNoException.ts(1,12): error TS1122: A tuple type element list cannot be empty. +tests/cases/compiler/anyIndexedAccessArrayNoException.ts(1,12): error TS2538: Type '[]' cannot be used as an index type. + + +==== tests/cases/compiler/anyIndexedAccessArrayNoException.ts (2 errors) ==== + var x: any[[]]; + ~~ +!!! error TS1122: A tuple type element list cannot be empty. + ~~ +!!! error TS2538: Type '[]' cannot be used as an index type. + \ No newline at end of file diff --git a/tests/baselines/reference/anyIndexedAccessArrayNoException.js b/tests/baselines/reference/anyIndexedAccessArrayNoException.js new file mode 100644 index 00000000000..d42bc54deb4 --- /dev/null +++ b/tests/baselines/reference/anyIndexedAccessArrayNoException.js @@ -0,0 +1,6 @@ +//// [anyIndexedAccessArrayNoException.ts] +var x: any[[]]; + + +//// [anyIndexedAccessArrayNoException.js] +var x; diff --git a/tests/baselines/reference/commentOnBinaryOperator1.js b/tests/baselines/reference/commentOnBinaryOperator1.js new file mode 100644 index 00000000000..daad6f5bdde --- /dev/null +++ b/tests/baselines/reference/commentOnBinaryOperator1.js @@ -0,0 +1,25 @@ +//// [commentOnBinaryOperator1.ts] +var a = 'some' + // comment + + 'text'; + +var b = 'some' + /* comment */ + + 'text'; + +var c = 'some' + /* comment */ + + /*comment1*/ + 'text'; + +//// [commentOnBinaryOperator1.js] +var a = 'some' + // comment + + 'text'; +var b = 'some' + /* comment */ + + 'text'; +var c = 'some' + /* comment */ + +/*comment1*/ + 'text'; diff --git a/tests/baselines/reference/commentOnBinaryOperator1.symbols b/tests/baselines/reference/commentOnBinaryOperator1.symbols new file mode 100644 index 00000000000..db92e4e4fc5 --- /dev/null +++ b/tests/baselines/reference/commentOnBinaryOperator1.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/commentOnBinaryOperator1.ts === +var a = 'some' +>a : Symbol(a, Decl(commentOnBinaryOperator1.ts, 0, 3)) + + // comment + + 'text'; + +var b = 'some' +>b : Symbol(b, Decl(commentOnBinaryOperator1.ts, 4, 3)) + + /* comment */ + + 'text'; + +var c = 'some' +>c : Symbol(c, Decl(commentOnBinaryOperator1.ts, 8, 3)) + + /* comment */ + + /*comment1*/ + 'text'; diff --git a/tests/baselines/reference/commentOnBinaryOperator1.types b/tests/baselines/reference/commentOnBinaryOperator1.types new file mode 100644 index 00000000000..59724d42f51 --- /dev/null +++ b/tests/baselines/reference/commentOnBinaryOperator1.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/commentOnBinaryOperator1.ts === +var a = 'some' +>a : string +>'some' // comment + 'text' : string +>'some' : "some" + + // comment + + 'text'; +>'text' : "text" + +var b = 'some' +>b : string +>'some' /* comment */ + 'text' : string +>'some' : "some" + + /* comment */ + + 'text'; +>'text' : "text" + +var c = 'some' +>c : string +>'some' /* comment */ + /*comment1*/ 'text' : string +>'some' : "some" + + /* comment */ + + /*comment1*/ + 'text'; +>'text' : "text" + diff --git a/tests/baselines/reference/commentOnBinaryOperator2.js b/tests/baselines/reference/commentOnBinaryOperator2.js new file mode 100644 index 00000000000..5d87ddccbef --- /dev/null +++ b/tests/baselines/reference/commentOnBinaryOperator2.js @@ -0,0 +1,22 @@ +//// [commentOnBinaryOperator2.ts] +var a = 'some' + // comment + + 'text'; + +var b = 'some' + /* comment */ + + 'text'; + +var c = 'some' + /* comment */ + + /*comment1*/ + 'text'; + +//// [commentOnBinaryOperator2.js] +var a = 'some' + + 'text'; +var b = 'some' + + 'text'; +var c = 'some' + + + 'text'; diff --git a/tests/baselines/reference/commentOnBinaryOperator2.symbols b/tests/baselines/reference/commentOnBinaryOperator2.symbols new file mode 100644 index 00000000000..10a0e94dd36 --- /dev/null +++ b/tests/baselines/reference/commentOnBinaryOperator2.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/commentOnBinaryOperator2.ts === +var a = 'some' +>a : Symbol(a, Decl(commentOnBinaryOperator2.ts, 0, 3)) + + // comment + + 'text'; + +var b = 'some' +>b : Symbol(b, Decl(commentOnBinaryOperator2.ts, 4, 3)) + + /* comment */ + + 'text'; + +var c = 'some' +>c : Symbol(c, Decl(commentOnBinaryOperator2.ts, 8, 3)) + + /* comment */ + + /*comment1*/ + 'text'; diff --git a/tests/baselines/reference/commentOnBinaryOperator2.types b/tests/baselines/reference/commentOnBinaryOperator2.types new file mode 100644 index 00000000000..411c8c69b8a --- /dev/null +++ b/tests/baselines/reference/commentOnBinaryOperator2.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/commentOnBinaryOperator2.ts === +var a = 'some' +>a : string +>'some' // comment + 'text' : string +>'some' : "some" + + // comment + + 'text'; +>'text' : "text" + +var b = 'some' +>b : string +>'some' /* comment */ + 'text' : string +>'some' : "some" + + /* comment */ + + 'text'; +>'text' : "text" + +var c = 'some' +>c : string +>'some' /* comment */ + /*comment1*/ 'text' : string +>'some' : "some" + + /* comment */ + + /*comment1*/ + 'text'; +>'text' : "text" + diff --git a/tests/baselines/reference/commentsArgumentsOfCallExpression2.js b/tests/baselines/reference/commentsArgumentsOfCallExpression2.js index a7065410ff4..e05256b86b6 100644 --- a/tests/baselines/reference/commentsArgumentsOfCallExpression2.js +++ b/tests/baselines/reference/commentsArgumentsOfCallExpression2.js @@ -14,7 +14,7 @@ foo( function foo(/*c1*/ x, /*d1*/ y, /*e1*/ w) { } var a, b; foo(/*c2*/ 1, /*d2*/ 1 + 2, /*e1*/ a + b); -foo(/*c3*/ function () { }, /*d2*/ function () { }, /*e2*/ a + b); +foo(/*c3*/ function () { }, /*d2*/ function () { }, /*e2*/ a +/*e3*/ b); foo(/*c3*/ function () { }, /*d3*/ function () { }, /*e3*/ (a + b)); foo( /*c4*/ function () { }, diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType.symbols b/tests/baselines/reference/declarationEmitInferedDefaultExportType.symbols deleted file mode 100644 index 5d49c84e8f8..00000000000 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType.symbols +++ /dev/null @@ -1,13 +0,0 @@ -=== tests/cases/compiler/declarationEmitInferedDefaultExportType.ts === -// test.ts -export default { - foo: [], ->foo : Symbol(foo, Decl(declarationEmitInferedDefaultExportType.ts, 1, 16)) - - bar: undefined, ->bar : Symbol(bar, Decl(declarationEmitInferedDefaultExportType.ts, 2, 10)) ->undefined : Symbol(undefined) - - baz: null ->baz : Symbol(baz, Decl(declarationEmitInferedDefaultExportType.ts, 3, 17)) -} diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.symbols b/tests/baselines/reference/declarationEmitInferedDefaultExportType2.symbols deleted file mode 100644 index 8a617715bf4..00000000000 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.symbols +++ /dev/null @@ -1,13 +0,0 @@ -=== tests/cases/compiler/declarationEmitInferedDefaultExportType2.ts === -// test.ts -export = { - foo: [], ->foo : Symbol(foo, Decl(declarationEmitInferedDefaultExportType2.ts, 1, 10)) - - bar: undefined, ->bar : Symbol(bar, Decl(declarationEmitInferedDefaultExportType2.ts, 2, 10)) ->undefined : Symbol(undefined) - - baz: null ->baz : Symbol(baz, Decl(declarationEmitInferedDefaultExportType2.ts, 3, 17)) -} diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias4.symbols b/tests/baselines/reference/declarationEmitInferedTypeAlias4.symbols deleted file mode 100644 index 6108e2326d0..00000000000 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias4.symbols +++ /dev/null @@ -1,21 +0,0 @@ -=== tests/cases/compiler/declarationEmitInferedTypeAlias4.ts === -function f() { ->f : Symbol(f, Decl(declarationEmitInferedTypeAlias4.ts, 0, 0)) ->A : Symbol(A, Decl(declarationEmitInferedTypeAlias4.ts, 0, 11)) - - type Foo = T | { x: Foo }; ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias4.ts, 0, 17)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias4.ts, 1, 13)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias4.ts, 1, 13)) ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias4.ts, 1, 23)) ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias4.ts, 0, 17)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias4.ts, 1, 13)) - - var x: Foo; ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias4.ts, 2, 7)) ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias4.ts, 0, 17)) ->A : Symbol(A, Decl(declarationEmitInferedTypeAlias4.ts, 0, 11)) - - return x; ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias4.ts, 2, 7)) -} diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias8.symbols b/tests/baselines/reference/declarationEmitInferedTypeAlias8.symbols deleted file mode 100644 index 3e4b21c4a06..00000000000 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias8.symbols +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/compiler/declarationEmitInferedTypeAlias8.ts === -type Foo = T | { x: Foo }; ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias8.ts, 0, 0)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias8.ts, 0, 9)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias8.ts, 0, 9)) ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias8.ts, 0, 19)) ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias8.ts, 0, 0)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias8.ts, 0, 9)) - -var x: Foo; ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias8.ts, 1, 3)) ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias8.ts, 0, 0)) - -function returnSomeGlobalValue() { ->returnSomeGlobalValue : Symbol(returnSomeGlobalValue, Decl(declarationEmitInferedTypeAlias8.ts, 1, 21)) - - return x; ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias8.ts, 1, 3)) -} diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias9.symbols b/tests/baselines/reference/declarationEmitInferedTypeAlias9.symbols deleted file mode 100644 index 3a147cd63a2..00000000000 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias9.symbols +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/compiler/declarationEmitInferedTypeAlias9.ts === -type Foo = T | { x: Foo }; ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias9.ts, 0, 0)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias9.ts, 0, 9)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias9.ts, 0, 9)) ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias9.ts, 0, 19)) ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias9.ts, 0, 0)) ->T : Symbol(T, Decl(declarationEmitInferedTypeAlias9.ts, 0, 9)) - -var x: Foo; ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias9.ts, 1, 3)) ->Foo : Symbol(Foo, Decl(declarationEmitInferedTypeAlias9.ts, 0, 0)) - -export function returnSomeGlobalValue() { ->returnSomeGlobalValue : Symbol(returnSomeGlobalValue, Decl(declarationEmitInferedTypeAlias9.ts, 1, 21)) - - return x; ->x : Symbol(x, Decl(declarationEmitInferedTypeAlias9.ts, 1, 3)) -} diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType.js b/tests/baselines/reference/declarationEmitInferredDefaultExportType.js similarity index 62% rename from tests/baselines/reference/declarationEmitInferedDefaultExportType.js rename to tests/baselines/reference/declarationEmitInferredDefaultExportType.js index a9eca8d1161..3d0cd0312ed 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType.js +++ b/tests/baselines/reference/declarationEmitInferredDefaultExportType.js @@ -1,4 +1,4 @@ -//// [declarationEmitInferedDefaultExportType.ts] +//// [declarationEmitInferredDefaultExportType.ts] // test.ts export default { foo: [], @@ -6,7 +6,7 @@ export default { baz: null } -//// [declarationEmitInferedDefaultExportType.js] +//// [declarationEmitInferredDefaultExportType.js] "use strict"; exports.__esModule = true; // test.ts @@ -17,7 +17,7 @@ exports["default"] = { }; -//// [declarationEmitInferedDefaultExportType.d.ts] +//// [declarationEmitInferredDefaultExportType.d.ts] declare const _default: { foo: any[]; bar: any; diff --git a/tests/baselines/reference/declarationEmitInferredDefaultExportType.symbols b/tests/baselines/reference/declarationEmitInferredDefaultExportType.symbols new file mode 100644 index 00000000000..21e38428558 --- /dev/null +++ b/tests/baselines/reference/declarationEmitInferredDefaultExportType.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/declarationEmitInferredDefaultExportType.ts === +// test.ts +export default { + foo: [], +>foo : Symbol(foo, Decl(declarationEmitInferredDefaultExportType.ts, 1, 16)) + + bar: undefined, +>bar : Symbol(bar, Decl(declarationEmitInferredDefaultExportType.ts, 2, 10)) +>undefined : Symbol(undefined) + + baz: null +>baz : Symbol(baz, Decl(declarationEmitInferredDefaultExportType.ts, 3, 17)) +} diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType.types b/tests/baselines/reference/declarationEmitInferredDefaultExportType.types similarity index 74% rename from tests/baselines/reference/declarationEmitInferedDefaultExportType.types rename to tests/baselines/reference/declarationEmitInferredDefaultExportType.types index 4ccb520b606..99585dbab93 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType.types +++ b/tests/baselines/reference/declarationEmitInferredDefaultExportType.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/declarationEmitInferedDefaultExportType.ts === +=== tests/cases/compiler/declarationEmitInferredDefaultExportType.ts === // test.ts export default { >{ foo: [], bar: undefined, baz: null} : { foo: undefined[]; bar: undefined; baz: null; } diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js b/tests/baselines/reference/declarationEmitInferredDefaultExportType2.js similarity index 57% rename from tests/baselines/reference/declarationEmitInferedDefaultExportType2.js rename to tests/baselines/reference/declarationEmitInferredDefaultExportType2.js index fde31605659..31b6c6a13b5 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.js +++ b/tests/baselines/reference/declarationEmitInferredDefaultExportType2.js @@ -1,4 +1,4 @@ -//// [declarationEmitInferedDefaultExportType2.ts] +//// [declarationEmitInferredDefaultExportType2.ts] // test.ts export = { foo: [], @@ -6,7 +6,7 @@ export = { baz: null } -//// [declarationEmitInferedDefaultExportType2.js] +//// [declarationEmitInferredDefaultExportType2.js] "use strict"; module.exports = { foo: [], @@ -15,7 +15,7 @@ module.exports = { }; -//// [declarationEmitInferedDefaultExportType2.d.ts] +//// [declarationEmitInferredDefaultExportType2.d.ts] declare const _default: { foo: any[]; bar: any; diff --git a/tests/baselines/reference/declarationEmitInferredDefaultExportType2.symbols b/tests/baselines/reference/declarationEmitInferredDefaultExportType2.symbols new file mode 100644 index 00000000000..a1261ef4e55 --- /dev/null +++ b/tests/baselines/reference/declarationEmitInferredDefaultExportType2.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/declarationEmitInferredDefaultExportType2.ts === +// test.ts +export = { + foo: [], +>foo : Symbol(foo, Decl(declarationEmitInferredDefaultExportType2.ts, 1, 10)) + + bar: undefined, +>bar : Symbol(bar, Decl(declarationEmitInferredDefaultExportType2.ts, 2, 10)) +>undefined : Symbol(undefined) + + baz: null +>baz : Symbol(baz, Decl(declarationEmitInferredDefaultExportType2.ts, 3, 17)) +} diff --git a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.types b/tests/baselines/reference/declarationEmitInferredDefaultExportType2.types similarity index 74% rename from tests/baselines/reference/declarationEmitInferedDefaultExportType2.types rename to tests/baselines/reference/declarationEmitInferredDefaultExportType2.types index 808a0cf1e85..d98a377b9ed 100644 --- a/tests/baselines/reference/declarationEmitInferedDefaultExportType2.types +++ b/tests/baselines/reference/declarationEmitInferredDefaultExportType2.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/declarationEmitInferedDefaultExportType2.ts === +=== tests/cases/compiler/declarationEmitInferredDefaultExportType2.ts === // test.ts export = { >{ foo: [], bar: undefined, baz: null} : { foo: undefined[]; bar: undefined; baz: null; } diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias6.js b/tests/baselines/reference/declarationEmitInferredTypeAlias1.js similarity index 80% rename from tests/baselines/reference/declarationEmitInferedTypeAlias6.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias1.js index 0b98e0bdeb0..9c0fe631b12 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias6.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias1.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/declarationEmitInferedTypeAlias6.ts] //// +//// [tests/cases/compiler/declarationEmitInferredTypeAlias1.ts] //// //// [0.ts] { diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias1.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias1.symbols similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias1.symbols rename to tests/baselines/reference/declarationEmitInferredTypeAlias1.symbols diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias1.types b/tests/baselines/reference/declarationEmitInferredTypeAlias1.types similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias1.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias1.types diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias2.js b/tests/baselines/reference/declarationEmitInferredTypeAlias2.js similarity index 84% rename from tests/baselines/reference/declarationEmitInferedTypeAlias2.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias2.js index d99a1abc346..73aae9d8a40 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias2.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias2.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/declarationEmitInferedTypeAlias2.ts] //// +//// [tests/cases/compiler/declarationEmitInferredTypeAlias2.ts] //// //// [0.ts] { diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias2.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias2.symbols similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias2.symbols rename to tests/baselines/reference/declarationEmitInferredTypeAlias2.symbols diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias2.types b/tests/baselines/reference/declarationEmitInferredTypeAlias2.types similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias2.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias2.types diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias3.js b/tests/baselines/reference/declarationEmitInferredTypeAlias3.js similarity index 81% rename from tests/baselines/reference/declarationEmitInferedTypeAlias3.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias3.js index 4621aa8db2f..665cab9f9be 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias3.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias3.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/declarationEmitInferedTypeAlias3.ts] //// +//// [tests/cases/compiler/declarationEmitInferredTypeAlias3.ts] //// //// [0.ts] { diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias3.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias3.symbols similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias3.symbols rename to tests/baselines/reference/declarationEmitInferredTypeAlias3.symbols diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias3.types b/tests/baselines/reference/declarationEmitInferredTypeAlias3.types similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias3.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias3.types diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias4.js b/tests/baselines/reference/declarationEmitInferredTypeAlias4.js similarity index 56% rename from tests/baselines/reference/declarationEmitInferedTypeAlias4.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias4.js index c29dbb517d9..3200c6b8b25 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias4.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias4.js @@ -1,18 +1,18 @@ -//// [declarationEmitInferedTypeAlias4.ts] +//// [declarationEmitInferredTypeAlias4.ts] function f() { type Foo = T | { x: Foo }; var x: Foo; return x; } -//// [declarationEmitInferedTypeAlias4.js] +//// [declarationEmitInferredTypeAlias4.js] function f() { var x; return x; } -//// [declarationEmitInferedTypeAlias4.d.ts] +//// [declarationEmitInferredTypeAlias4.d.ts] declare function f(): A[] | { x: A[] | any; }; diff --git a/tests/baselines/reference/declarationEmitInferredTypeAlias4.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias4.symbols new file mode 100644 index 00000000000..7207d0b9f15 --- /dev/null +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias4.symbols @@ -0,0 +1,21 @@ +=== tests/cases/compiler/declarationEmitInferredTypeAlias4.ts === +function f() { +>f : Symbol(f, Decl(declarationEmitInferredTypeAlias4.ts, 0, 0)) +>A : Symbol(A, Decl(declarationEmitInferredTypeAlias4.ts, 0, 11)) + + type Foo = T | { x: Foo }; +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias4.ts, 0, 17)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias4.ts, 1, 13)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias4.ts, 1, 13)) +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias4.ts, 1, 23)) +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias4.ts, 0, 17)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias4.ts, 1, 13)) + + var x: Foo; +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias4.ts, 2, 7)) +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias4.ts, 0, 17)) +>A : Symbol(A, Decl(declarationEmitInferredTypeAlias4.ts, 0, 11)) + + return x; +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias4.ts, 2, 7)) +} diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias4.types b/tests/baselines/reference/declarationEmitInferredTypeAlias4.types similarity index 79% rename from tests/baselines/reference/declarationEmitInferedTypeAlias4.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias4.types index b4e5428e82a..71ba87f9428 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias4.types +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias4.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/declarationEmitInferedTypeAlias4.ts === +=== tests/cases/compiler/declarationEmitInferredTypeAlias4.ts === function f() { >f : () => A[] | { x: A[] | any; } >A : A diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias5.js b/tests/baselines/reference/declarationEmitInferredTypeAlias5.js similarity index 83% rename from tests/baselines/reference/declarationEmitInferedTypeAlias5.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias5.js index a20c4da52e0..918e2898d2e 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias5.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias5.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/declarationEmitInferedTypeAlias5.ts] //// +//// [tests/cases/compiler/declarationEmitInferredTypeAlias5.ts] //// //// [0.ts] export type Data = string | boolean; diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias5.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias5.symbols similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias5.symbols rename to tests/baselines/reference/declarationEmitInferredTypeAlias5.symbols diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias5.types b/tests/baselines/reference/declarationEmitInferredTypeAlias5.types similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias5.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias5.types diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias1.js b/tests/baselines/reference/declarationEmitInferredTypeAlias6.js similarity index 80% rename from tests/baselines/reference/declarationEmitInferedTypeAlias1.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias6.js index 091e7f97a0e..d0709cc5962 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias1.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias6.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/declarationEmitInferedTypeAlias1.ts] //// +//// [tests/cases/compiler/declarationEmitInferredTypeAlias6.ts] //// //// [0.ts] { diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias6.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias6.symbols similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias6.symbols rename to tests/baselines/reference/declarationEmitInferredTypeAlias6.symbols diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias6.types b/tests/baselines/reference/declarationEmitInferredTypeAlias6.types similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias6.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias6.types diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias7.js b/tests/baselines/reference/declarationEmitInferredTypeAlias7.js similarity index 81% rename from tests/baselines/reference/declarationEmitInferedTypeAlias7.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias7.js index 187913b0fd8..ff44c18f918 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias7.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias7.js @@ -1,4 +1,4 @@ -//// [tests/cases/compiler/declarationEmitInferedTypeAlias7.ts] //// +//// [tests/cases/compiler/declarationEmitInferredTypeAlias7.ts] //// //// [0.ts] export type Data = string | boolean; diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias7.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias7.symbols similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias7.symbols rename to tests/baselines/reference/declarationEmitInferredTypeAlias7.symbols diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias7.types b/tests/baselines/reference/declarationEmitInferredTypeAlias7.types similarity index 100% rename from tests/baselines/reference/declarationEmitInferedTypeAlias7.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias7.types diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias8.js b/tests/baselines/reference/declarationEmitInferredTypeAlias8.js similarity index 66% rename from tests/baselines/reference/declarationEmitInferedTypeAlias8.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias8.js index d6e3c6bb7c2..0919c9a2282 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias8.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias8.js @@ -1,4 +1,4 @@ -//// [declarationEmitInferedTypeAlias8.ts] +//// [declarationEmitInferredTypeAlias8.ts] type Foo = T | { x: Foo }; var x: Foo; @@ -6,14 +6,14 @@ function returnSomeGlobalValue() { return x; } -//// [declarationEmitInferedTypeAlias8.js] +//// [declarationEmitInferredTypeAlias8.js] var x; function returnSomeGlobalValue() { return x; } -//// [declarationEmitInferedTypeAlias8.d.ts] +//// [declarationEmitInferredTypeAlias8.d.ts] declare type Foo = T | { x: Foo; }; diff --git a/tests/baselines/reference/declarationEmitInferredTypeAlias8.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias8.symbols new file mode 100644 index 00000000000..b97c2cea4e0 --- /dev/null +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias8.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/declarationEmitInferredTypeAlias8.ts === +type Foo = T | { x: Foo }; +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias8.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias8.ts, 0, 9)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias8.ts, 0, 9)) +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias8.ts, 0, 19)) +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias8.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias8.ts, 0, 9)) + +var x: Foo; +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias8.ts, 1, 3)) +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias8.ts, 0, 0)) + +function returnSomeGlobalValue() { +>returnSomeGlobalValue : Symbol(returnSomeGlobalValue, Decl(declarationEmitInferredTypeAlias8.ts, 1, 21)) + + return x; +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias8.ts, 1, 3)) +} diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias8.types b/tests/baselines/reference/declarationEmitInferredTypeAlias8.types similarity index 75% rename from tests/baselines/reference/declarationEmitInferedTypeAlias8.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias8.types index c58624aad56..62f23b60488 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias8.types +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias8.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/declarationEmitInferedTypeAlias8.ts === +=== tests/cases/compiler/declarationEmitInferredTypeAlias8.ts === type Foo = T | { x: Foo }; >Foo : Foo >T : T diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias9.js b/tests/baselines/reference/declarationEmitInferredTypeAlias9.js similarity index 70% rename from tests/baselines/reference/declarationEmitInferedTypeAlias9.js rename to tests/baselines/reference/declarationEmitInferredTypeAlias9.js index 3f237f2dc44..8d03c6b70d2 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias9.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias9.js @@ -1,4 +1,4 @@ -//// [declarationEmitInferedTypeAlias9.ts] +//// [declarationEmitInferredTypeAlias9.ts] type Foo = T | { x: Foo }; var x: Foo; @@ -6,7 +6,7 @@ export function returnSomeGlobalValue() { return x; } -//// [declarationEmitInferedTypeAlias9.js] +//// [declarationEmitInferredTypeAlias9.js] "use strict"; exports.__esModule = true; var x; @@ -16,7 +16,7 @@ function returnSomeGlobalValue() { exports.returnSomeGlobalValue = returnSomeGlobalValue; -//// [declarationEmitInferedTypeAlias9.d.ts] +//// [declarationEmitInferredTypeAlias9.d.ts] export declare function returnSomeGlobalValue(): number[] | { x: number[] | any; }; diff --git a/tests/baselines/reference/declarationEmitInferredTypeAlias9.symbols b/tests/baselines/reference/declarationEmitInferredTypeAlias9.symbols new file mode 100644 index 00000000000..619a36af7a8 --- /dev/null +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias9.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/declarationEmitInferredTypeAlias9.ts === +type Foo = T | { x: Foo }; +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias9.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias9.ts, 0, 9)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias9.ts, 0, 9)) +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias9.ts, 0, 19)) +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias9.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitInferredTypeAlias9.ts, 0, 9)) + +var x: Foo; +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias9.ts, 1, 3)) +>Foo : Symbol(Foo, Decl(declarationEmitInferredTypeAlias9.ts, 0, 0)) + +export function returnSomeGlobalValue() { +>returnSomeGlobalValue : Symbol(returnSomeGlobalValue, Decl(declarationEmitInferredTypeAlias9.ts, 1, 21)) + + return x; +>x : Symbol(x, Decl(declarationEmitInferredTypeAlias9.ts, 1, 3)) +} diff --git a/tests/baselines/reference/declarationEmitInferedTypeAlias9.types b/tests/baselines/reference/declarationEmitInferredTypeAlias9.types similarity index 81% rename from tests/baselines/reference/declarationEmitInferedTypeAlias9.types rename to tests/baselines/reference/declarationEmitInferredTypeAlias9.types index b49c5c49887..30a15aff6fb 100644 --- a/tests/baselines/reference/declarationEmitInferedTypeAlias9.types +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias9.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/declarationEmitInferedTypeAlias9.ts === +=== tests/cases/compiler/declarationEmitInferredTypeAlias9.ts === type Foo = T | { x: Foo }; >Foo : T | { x: T | any; } >T : T diff --git a/tests/baselines/reference/deferredLookupTypeResolution.js b/tests/baselines/reference/deferredLookupTypeResolution.js new file mode 100644 index 00000000000..5f8edd63e57 --- /dev/null +++ b/tests/baselines/reference/deferredLookupTypeResolution.js @@ -0,0 +1,64 @@ +//// [deferredLookupTypeResolution.ts] +// Repro from #17456 + +type StringContains = ( + { [K in S]: 'true' } & + { [key: string]: 'false' } + )[L] + +type ObjectHasKey = StringContains + +type First = ObjectHasKey; // Should be deferred + +type T1 = ObjectHasKey<{ a: string }, 'a'>; // 'true' +type T2 = ObjectHasKey<{ a: string }, 'b'>; // 'false' + +// Verify that mapped type isn't eagerly resolved in type-to-string operation + +declare function f1(a: A, b: B): { [P in A | B]: any }; + +function f2(a: A) { + return f1(a, 'x'); +} + +function f3(x: 'a' | 'b') { + return f2(x); +} + + +//// [deferredLookupTypeResolution.js] +"use strict"; +// Repro from #17456 +function f2(a) { + return f1(a, 'x'); +} +function f3(x) { + return f2(x); +} + + +//// [deferredLookupTypeResolution.d.ts] +declare type StringContains = ({ + [K in S]: 'true'; +} & { + [key: string]: 'false'; +})[L]; +declare type ObjectHasKey = StringContains; +declare type First = ObjectHasKey; +declare type T1 = ObjectHasKey<{ + a: string; +}, 'a'>; +declare type T2 = ObjectHasKey<{ + a: string; +}, 'b'>; +declare function f1(a: A, b: B): { + [P in A | B]: any; +}; +declare function f2(a: A): { + [P in A | "x"]: any; +}; +declare function f3(x: 'a' | 'b'): { + a: any; + b: any; + x: any; +}; diff --git a/tests/baselines/reference/deferredLookupTypeResolution.symbols b/tests/baselines/reference/deferredLookupTypeResolution.symbols new file mode 100644 index 00000000000..022dc3cc2f4 --- /dev/null +++ b/tests/baselines/reference/deferredLookupTypeResolution.symbols @@ -0,0 +1,76 @@ +=== tests/cases/compiler/deferredLookupTypeResolution.ts === +// Repro from #17456 + +type StringContains = ( +>StringContains : Symbol(StringContains, Decl(deferredLookupTypeResolution.ts, 0, 0)) +>S : Symbol(S, Decl(deferredLookupTypeResolution.ts, 2, 20)) +>L : Symbol(L, Decl(deferredLookupTypeResolution.ts, 2, 37)) + + { [K in S]: 'true' } & +>K : Symbol(K, Decl(deferredLookupTypeResolution.ts, 3, 7)) +>S : Symbol(S, Decl(deferredLookupTypeResolution.ts, 2, 20)) + + { [key: string]: 'false' } +>key : Symbol(key, Decl(deferredLookupTypeResolution.ts, 4, 7)) + + )[L] +>L : Symbol(L, Decl(deferredLookupTypeResolution.ts, 2, 37)) + +type ObjectHasKey = StringContains +>ObjectHasKey : Symbol(ObjectHasKey, Decl(deferredLookupTypeResolution.ts, 5, 6)) +>O : Symbol(O, Decl(deferredLookupTypeResolution.ts, 7, 18)) +>L : Symbol(L, Decl(deferredLookupTypeResolution.ts, 7, 20)) +>StringContains : Symbol(StringContains, Decl(deferredLookupTypeResolution.ts, 0, 0)) +>O : Symbol(O, Decl(deferredLookupTypeResolution.ts, 7, 18)) +>L : Symbol(L, Decl(deferredLookupTypeResolution.ts, 7, 20)) + +type First = ObjectHasKey; // Should be deferred +>First : Symbol(First, Decl(deferredLookupTypeResolution.ts, 7, 67)) +>T : Symbol(T, Decl(deferredLookupTypeResolution.ts, 9, 11)) +>ObjectHasKey : Symbol(ObjectHasKey, Decl(deferredLookupTypeResolution.ts, 5, 6)) +>T : Symbol(T, Decl(deferredLookupTypeResolution.ts, 9, 11)) + +type T1 = ObjectHasKey<{ a: string }, 'a'>; // 'true' +>T1 : Symbol(T1, Decl(deferredLookupTypeResolution.ts, 9, 37)) +>ObjectHasKey : Symbol(ObjectHasKey, Decl(deferredLookupTypeResolution.ts, 5, 6)) +>a : Symbol(a, Decl(deferredLookupTypeResolution.ts, 11, 24)) + +type T2 = ObjectHasKey<{ a: string }, 'b'>; // 'false' +>T2 : Symbol(T2, Decl(deferredLookupTypeResolution.ts, 11, 43)) +>ObjectHasKey : Symbol(ObjectHasKey, Decl(deferredLookupTypeResolution.ts, 5, 6)) +>a : Symbol(a, Decl(deferredLookupTypeResolution.ts, 12, 24)) + +// Verify that mapped type isn't eagerly resolved in type-to-string operation + +declare function f1(a: A, b: B): { [P in A | B]: any }; +>f1 : Symbol(f1, Decl(deferredLookupTypeResolution.ts, 12, 43)) +>A : Symbol(A, Decl(deferredLookupTypeResolution.ts, 16, 20)) +>B : Symbol(B, Decl(deferredLookupTypeResolution.ts, 16, 37)) +>a : Symbol(a, Decl(deferredLookupTypeResolution.ts, 16, 56)) +>A : Symbol(A, Decl(deferredLookupTypeResolution.ts, 16, 20)) +>b : Symbol(b, Decl(deferredLookupTypeResolution.ts, 16, 61)) +>B : Symbol(B, Decl(deferredLookupTypeResolution.ts, 16, 37)) +>P : Symbol(P, Decl(deferredLookupTypeResolution.ts, 16, 72)) +>A : Symbol(A, Decl(deferredLookupTypeResolution.ts, 16, 20)) +>B : Symbol(B, Decl(deferredLookupTypeResolution.ts, 16, 37)) + +function f2(a: A) { +>f2 : Symbol(f2, Decl(deferredLookupTypeResolution.ts, 16, 91)) +>A : Symbol(A, Decl(deferredLookupTypeResolution.ts, 18, 12)) +>a : Symbol(a, Decl(deferredLookupTypeResolution.ts, 18, 30)) +>A : Symbol(A, Decl(deferredLookupTypeResolution.ts, 18, 12)) + + return f1(a, 'x'); +>f1 : Symbol(f1, Decl(deferredLookupTypeResolution.ts, 12, 43)) +>a : Symbol(a, Decl(deferredLookupTypeResolution.ts, 18, 30)) +} + +function f3(x: 'a' | 'b') { +>f3 : Symbol(f3, Decl(deferredLookupTypeResolution.ts, 20, 1)) +>x : Symbol(x, Decl(deferredLookupTypeResolution.ts, 22, 12)) + + return f2(x); +>f2 : Symbol(f2, Decl(deferredLookupTypeResolution.ts, 16, 91)) +>x : Symbol(x, Decl(deferredLookupTypeResolution.ts, 22, 12)) +} + diff --git a/tests/baselines/reference/deferredLookupTypeResolution.types b/tests/baselines/reference/deferredLookupTypeResolution.types new file mode 100644 index 00000000000..d9486d30b07 --- /dev/null +++ b/tests/baselines/reference/deferredLookupTypeResolution.types @@ -0,0 +1,79 @@ +=== tests/cases/compiler/deferredLookupTypeResolution.ts === +// Repro from #17456 + +type StringContains = ( +>StringContains : ({ [K in S]: "true"; } & { [key: string]: "false"; })[L] +>S : S +>L : L + + { [K in S]: 'true' } & +>K : K +>S : S + + { [key: string]: 'false' } +>key : string + + )[L] +>L : L + +type ObjectHasKey = StringContains +>ObjectHasKey : ({ [K in S]: "true"; } & { [key: string]: "false"; })[L] +>O : O +>L : L +>StringContains : ({ [K in S]: "true"; } & { [key: string]: "false"; })[L] +>O : O +>L : L + +type First = ObjectHasKey; // Should be deferred +>First : ({ [K in S]: "true"; } & { [key: string]: "false"; })["0"] +>T : T +>ObjectHasKey : ({ [K in S]: "true"; } & { [key: string]: "false"; })[L] +>T : T + +type T1 = ObjectHasKey<{ a: string }, 'a'>; // 'true' +>T1 : "true" +>ObjectHasKey : ({ [K in S]: "true"; } & { [key: string]: "false"; })[L] +>a : string + +type T2 = ObjectHasKey<{ a: string }, 'b'>; // 'false' +>T2 : "false" +>ObjectHasKey : ({ [K in S]: "true"; } & { [key: string]: "false"; })[L] +>a : string + +// Verify that mapped type isn't eagerly resolved in type-to-string operation + +declare function f1(a: A, b: B): { [P in A | B]: any }; +>f1 : (a: A, b: B) => { [P in A | B]: any; } +>A : A +>B : B +>a : A +>A : A +>b : B +>B : B +>P : P +>A : A +>B : B + +function f2(a: A) { +>f2 : (a: A) => { [P in A | B]: any; } +>A : A +>a : A +>A : A + + return f1(a, 'x'); +>f1(a, 'x') : { [P in A | B]: any; } +>f1 : (a: A, b: B) => { [P in A | B]: any; } +>a : A +>'x' : "x" +} + +function f3(x: 'a' | 'b') { +>f3 : (x: "a" | "b") => { a: any; b: any; x: any; } +>x : "a" | "b" + + return f2(x); +>f2(x) : { a: any; b: any; x: any; } +>f2 : (a: A) => { [P in A | B]: any; } +>x : "a" | "b" +} + diff --git a/tests/baselines/reference/deferredLookupTypeResolution2.errors.txt b/tests/baselines/reference/deferredLookupTypeResolution2.errors.txt new file mode 100644 index 00000000000..f6bbe72f1a6 --- /dev/null +++ b/tests/baselines/reference/deferredLookupTypeResolution2.errors.txt @@ -0,0 +1,31 @@ +tests/cases/compiler/deferredLookupTypeResolution2.ts(14,13): error TS2536: Type '({ [K in S]: "true"; } & { [key: string]: "false"; })["1"]' cannot be used to index type '{ true: "true"; }'. +tests/cases/compiler/deferredLookupTypeResolution2.ts(19,21): error TS2536: Type '({ true: "otherwise"; } & { [k: string]: "true"; })[({ [K in S]: "true"; } & { [key: string]: "false"; })["1"]]' cannot be used to index type '{ true: "true"; }'. + + +==== tests/cases/compiler/deferredLookupTypeResolution2.ts (2 errors) ==== + // Repro from #17456 + + type StringContains = ({ [K in S]: 'true' } & { [key: string]: 'false'})[L]; + + type ObjectHasKey = StringContains; + + type A = ObjectHasKey; + + type B = ObjectHasKey<[string, number], '1'>; // "true" + type C = ObjectHasKey<[string, number], '2'>; // "false" + type D = A<[string]>; // "true" + + // Error, "false" not handled + type E = { true: 'true' }[ObjectHasKey]; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2536: Type '({ [K in S]: "true"; } & { [key: string]: "false"; })["1"]' cannot be used to index type '{ true: "true"; }'. + + type Juxtapose = ({ true: 'otherwise' } & { [k: string]: 'true' })[ObjectHasKey]; + + // Error, "otherwise" is missing + type DeepError = { true: 'true' }[Juxtapose]; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2536: Type '({ true: "otherwise"; } & { [k: string]: "true"; })[({ [K in S]: "true"; } & { [key: string]: "false"; })["1"]]' cannot be used to index type '{ true: "true"; }'. + + type DeepOK = { true: 'true', otherwise: 'false' }[Juxtapose]; + \ No newline at end of file diff --git a/tests/baselines/reference/deferredLookupTypeResolution2.js b/tests/baselines/reference/deferredLookupTypeResolution2.js new file mode 100644 index 00000000000..97289f47f9c --- /dev/null +++ b/tests/baselines/reference/deferredLookupTypeResolution2.js @@ -0,0 +1,55 @@ +//// [deferredLookupTypeResolution2.ts] +// Repro from #17456 + +type StringContains = ({ [K in S]: 'true' } & { [key: string]: 'false'})[L]; + +type ObjectHasKey = StringContains; + +type A = ObjectHasKey; + +type B = ObjectHasKey<[string, number], '1'>; // "true" +type C = ObjectHasKey<[string, number], '2'>; // "false" +type D = A<[string]>; // "true" + +// Error, "false" not handled +type E = { true: 'true' }[ObjectHasKey]; + +type Juxtapose = ({ true: 'otherwise' } & { [k: string]: 'true' })[ObjectHasKey]; + +// Error, "otherwise" is missing +type DeepError = { true: 'true' }[Juxtapose]; + +type DeepOK = { true: 'true', otherwise: 'false' }[Juxtapose]; + + +//// [deferredLookupTypeResolution2.js] +"use strict"; +// Repro from #17456 + + +//// [deferredLookupTypeResolution2.d.ts] +declare type StringContains = ({ + [K in S]: 'true'; +} & { + [key: string]: 'false'; +})[L]; +declare type ObjectHasKey = StringContains; +declare type A = ObjectHasKey; +declare type B = ObjectHasKey<[string, number], '1'>; +declare type C = ObjectHasKey<[string, number], '2'>; +declare type D = A<[string]>; +declare type E = { + true: 'true'; +}[ObjectHasKey]; +declare type Juxtapose = ({ + true: 'otherwise'; +} & { + [k: string]: 'true'; +})[ObjectHasKey]; +declare type DeepError = { + true: 'true'; +}[Juxtapose]; +declare type DeepOK = { + true: 'true'; + otherwise: 'false'; +}[Juxtapose]; diff --git a/tests/baselines/reference/doNotInferUnrelatedTypes.js b/tests/baselines/reference/doNotInferUnrelatedTypes.js new file mode 100644 index 00000000000..cff708cec89 --- /dev/null +++ b/tests/baselines/reference/doNotInferUnrelatedTypes.js @@ -0,0 +1,11 @@ +//// [doNotInferUnrelatedTypes.ts] +// #16709 +declare function dearray(ara: ReadonlyArray): T; +type LiteralType = "foo" | "bar"; +declare var alt: Array; + +let foo: LiteralType = dearray(alt); + + +//// [doNotInferUnrelatedTypes.js] +var foo = dearray(alt); diff --git a/tests/baselines/reference/doNotInferUnrelatedTypes.symbols b/tests/baselines/reference/doNotInferUnrelatedTypes.symbols new file mode 100644 index 00000000000..ce7351cf78f --- /dev/null +++ b/tests/baselines/reference/doNotInferUnrelatedTypes.symbols @@ -0,0 +1,24 @@ +=== tests/cases/compiler/doNotInferUnrelatedTypes.ts === +// #16709 +declare function dearray(ara: ReadonlyArray): T; +>dearray : Symbol(dearray, Decl(doNotInferUnrelatedTypes.ts, 0, 0)) +>T : Symbol(T, Decl(doNotInferUnrelatedTypes.ts, 1, 25)) +>ara : Symbol(ara, Decl(doNotInferUnrelatedTypes.ts, 1, 28)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(doNotInferUnrelatedTypes.ts, 1, 25)) +>T : Symbol(T, Decl(doNotInferUnrelatedTypes.ts, 1, 25)) + +type LiteralType = "foo" | "bar"; +>LiteralType : Symbol(LiteralType, Decl(doNotInferUnrelatedTypes.ts, 1, 54)) + +declare var alt: Array; +>alt : Symbol(alt, Decl(doNotInferUnrelatedTypes.ts, 3, 11)) +>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>LiteralType : Symbol(LiteralType, Decl(doNotInferUnrelatedTypes.ts, 1, 54)) + +let foo: LiteralType = dearray(alt); +>foo : Symbol(foo, Decl(doNotInferUnrelatedTypes.ts, 5, 3)) +>LiteralType : Symbol(LiteralType, Decl(doNotInferUnrelatedTypes.ts, 1, 54)) +>dearray : Symbol(dearray, Decl(doNotInferUnrelatedTypes.ts, 0, 0)) +>alt : Symbol(alt, Decl(doNotInferUnrelatedTypes.ts, 3, 11)) + diff --git a/tests/baselines/reference/doNotInferUnrelatedTypes.types b/tests/baselines/reference/doNotInferUnrelatedTypes.types new file mode 100644 index 00000000000..5068c04ab1b --- /dev/null +++ b/tests/baselines/reference/doNotInferUnrelatedTypes.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/doNotInferUnrelatedTypes.ts === +// #16709 +declare function dearray(ara: ReadonlyArray): T; +>dearray : (ara: ReadonlyArray) => T +>T : T +>ara : ReadonlyArray +>ReadonlyArray : ReadonlyArray +>T : T +>T : T + +type LiteralType = "foo" | "bar"; +>LiteralType : LiteralType + +declare var alt: Array; +>alt : LiteralType[] +>Array : T[] +>LiteralType : LiteralType + +let foo: LiteralType = dearray(alt); +>foo : LiteralType +>LiteralType : LiteralType +>dearray(alt) : LiteralType +>dearray : (ara: ReadonlyArray) => T +>alt : LiteralType[] + diff --git a/tests/baselines/reference/emitExponentiationOperator3.types b/tests/baselines/reference/emitExponentiationOperator3.types index 2fe95d4db8f..666d46dca39 100644 --- a/tests/baselines/reference/emitExponentiationOperator3.types +++ b/tests/baselines/reference/emitExponentiationOperator3.types @@ -113,32 +113,32 @@ var temp = 10; (+3) ** temp++; >(+3) ** temp++ : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >temp++ : number >temp : number (+3) ** temp--; >(+3) ** temp-- : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >temp-- : number >temp : number (+3) ** ++temp; >(+3) ** ++temp : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >++temp : number >temp : number (+3) ** --temp; >(+3) ** --temp : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >--temp : number >temp : number @@ -185,8 +185,8 @@ var temp = 10; (+3) ** temp++ ** 2; >(+3) ** temp++ ** 2 : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >temp++ ** 2 : number >temp++ : number @@ -195,8 +195,8 @@ var temp = 10; (+3) ** temp-- ** 2; >(+3) ** temp-- ** 2 : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >temp-- ** 2 : number >temp-- : number @@ -205,8 +205,8 @@ var temp = 10; (+3) ** ++temp ** 2; >(+3) ** ++temp ** 2 : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >++temp ** 2 : number >++temp : number @@ -215,8 +215,8 @@ var temp = 10; (+3) ** --temp ** 2; >(+3) ** --temp ** 2 : number ->(+3) : number ->+3 : number +>(+3) : 3 +>+3 : 3 >3 : 3 >--temp ** 2 : number >--temp : number diff --git a/tests/baselines/reference/enumClassification.types b/tests/baselines/reference/enumClassification.types index d0581c7fcae..73c8041a6b7 100644 --- a/tests/baselines/reference/enumClassification.types +++ b/tests/baselines/reference/enumClassification.types @@ -131,7 +131,7 @@ enum E11 { A = +0, >A : E11 ->+0 : number +>+0 : 0 >0 : 0 B, diff --git a/tests/baselines/reference/errorForUsingPropertyOfTypeAsType01.errors.txt b/tests/baselines/reference/errorForUsingPropertyOfTypeAsType01.errors.txt new file mode 100644 index 00000000000..0c55ba75f13 --- /dev/null +++ b/tests/baselines/reference/errorForUsingPropertyOfTypeAsType01.errors.txt @@ -0,0 +1,83 @@ +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(6,12): error TS2713: Cannot access 'Foo.bar' because 'Foo' is a type, but not a namespace. Did you mean to retrieve the type of the property 'bar' in 'Foo' with 'Foo["bar"]'? +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(7,18): error TS2694: Namespace 'Test1' has no exported member 'Foo'. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(15,12): error TS2503: Cannot find namespace 'Foo'. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(16,18): error TS2694: Namespace 'Test2' has no exported member 'Foo'. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(24,12): error TS2713: Cannot access 'Foo.bar' because 'Foo' is a type, but not a namespace. Did you mean to retrieve the type of the property 'bar' in 'Foo' with 'Foo["bar"]'? +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(25,18): error TS2694: Namespace 'Test3' has no exported member 'Foo'. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(32,12): error TS2713: Cannot access 'Foo.bar' because 'Foo' is a type, but not a namespace. Did you mean to retrieve the type of the property 'bar' in 'Foo' with 'Foo["bar"]'? +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(33,18): error TS2694: Namespace 'Test4' has no exported member 'Foo'. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(40,12): error TS2702: 'Foo' only refers to a type, but is being used as a namespace here. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(41,18): error TS2694: Namespace 'Test5' has no exported member 'Foo'. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(44,20): error TS2694: Namespace 'Test5' has no exported member 'Foo'. +tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts(44,24): error TS1003: Identifier expected. + + +==== tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts (12 errors) ==== + namespace Test1 { + export interface Foo { + bar: string; + } + + var x: Foo.bar = ""; + ~~~~~~~ +!!! error TS2713: Cannot access 'Foo.bar' because 'Foo' is a type, but not a namespace. Did you mean to retrieve the type of the property 'bar' in 'Foo' with 'Foo["bar"]'? + var y: Test1.Foo.bar = ""; + ~~~ +!!! error TS2694: Namespace 'Test1' has no exported member 'Foo'. + } + + namespace Test2 { + export class Foo { + bar: string; + } + + var x: Foo.bar = ""; + ~~~ +!!! error TS2503: Cannot find namespace 'Foo'. + var y: Test2.Foo.bar = ""; + ~~~ +!!! error TS2694: Namespace 'Test2' has no exported member 'Foo'. + } + + namespace Test3 { + export type Foo = { + bar: string; + } + + var x: Foo.bar = ""; + ~~~~~~~ +!!! error TS2713: Cannot access 'Foo.bar' because 'Foo' is a type, but not a namespace. Did you mean to retrieve the type of the property 'bar' in 'Foo' with 'Foo["bar"]'? + var y: Test3.Foo.bar = ""; + ~~~ +!!! error TS2694: Namespace 'Test3' has no exported member 'Foo'. + } + + namespace Test4 { + export type Foo = { bar: number } + | { bar: string } + + var x: Foo.bar = ""; + ~~~~~~~ +!!! error TS2713: Cannot access 'Foo.bar' because 'Foo' is a type, but not a namespace. Did you mean to retrieve the type of the property 'bar' in 'Foo' with 'Foo["bar"]'? + var y: Test4.Foo.bar = ""; + ~~~ +!!! error TS2694: Namespace 'Test4' has no exported member 'Foo'. + } + + namespace Test5 { + export type Foo = { bar: number } + | { wat: string } + + var x: Foo.bar = ""; + ~~~ +!!! error TS2702: 'Foo' only refers to a type, but is being used as a namespace here. + var y: Test5.Foo.bar = ""; + ~~~ +!!! error TS2694: Namespace 'Test5' has no exported member 'Foo'. + } + + import lol = Test5.Foo. + ~~~ +!!! error TS2694: Namespace 'Test5' has no exported member 'Foo'. + +!!! error TS1003: Identifier expected. \ No newline at end of file diff --git a/tests/baselines/reference/errorForUsingPropertyOfTypeAsType01.js b/tests/baselines/reference/errorForUsingPropertyOfTypeAsType01.js new file mode 100644 index 00000000000..26903a97989 --- /dev/null +++ b/tests/baselines/reference/errorForUsingPropertyOfTypeAsType01.js @@ -0,0 +1,79 @@ +//// [errorForUsingPropertyOfTypeAsType01.ts] +namespace Test1 { + export interface Foo { + bar: string; + } + + var x: Foo.bar = ""; + var y: Test1.Foo.bar = ""; +} + +namespace Test2 { + export class Foo { + bar: string; + } + + var x: Foo.bar = ""; + var y: Test2.Foo.bar = ""; +} + +namespace Test3 { + export type Foo = { + bar: string; + } + + var x: Foo.bar = ""; + var y: Test3.Foo.bar = ""; +} + +namespace Test4 { + export type Foo = { bar: number } + | { bar: string } + + var x: Foo.bar = ""; + var y: Test4.Foo.bar = ""; +} + +namespace Test5 { + export type Foo = { bar: number } + | { wat: string } + + var x: Foo.bar = ""; + var y: Test5.Foo.bar = ""; +} + +import lol = Test5.Foo. + +//// [errorForUsingPropertyOfTypeAsType01.js] +var Test1; +(function (Test1) { + var x = ""; + var y = ""; +})(Test1 || (Test1 = {})); +var Test2; +(function (Test2) { + var Foo = (function () { + function Foo() { + } + return Foo; + }()); + Test2.Foo = Foo; + var x = ""; + var y = ""; +})(Test2 || (Test2 = {})); +var Test3; +(function (Test3) { + var x = ""; + var y = ""; +})(Test3 || (Test3 = {})); +var Test4; +(function (Test4) { + var x = ""; + var y = ""; +})(Test4 || (Test4 = {})); +var Test5; +(function (Test5) { + var x = ""; + var y = ""; +})(Test5 || (Test5 = {})); +var lol = Test5.Foo.; diff --git a/tests/baselines/reference/expressionTypeNodeShouldError.errors.txt b/tests/baselines/reference/expressionTypeNodeShouldError.errors.txt new file mode 100644 index 00000000000..86a592779ca --- /dev/null +++ b/tests/baselines/reference/expressionTypeNodeShouldError.errors.txt @@ -0,0 +1,90 @@ +tests/cases/compiler/base.d.ts(1,23): error TS1005: ',' expected. +tests/cases/compiler/base.d.ts(1,34): error TS1005: '=' expected. +tests/cases/compiler/boolean.ts(7,23): error TS1005: ',' expected. +tests/cases/compiler/boolean.ts(7,24): error TS1134: Variable declaration expected. +tests/cases/compiler/boolean.ts(11,16): error TS2304: Cannot find name 'document'. +tests/cases/compiler/boolean.ts(12,22): error TS1005: ';' expected. +tests/cases/compiler/number.ts(7,26): error TS1005: ',' expected. +tests/cases/compiler/number.ts(7,27): error TS1134: Variable declaration expected. +tests/cases/compiler/number.ts(11,16): error TS2304: Cannot find name 'document'. +tests/cases/compiler/number.ts(12,20): error TS1005: ';' expected. +tests/cases/compiler/string.ts(7,20): error TS1005: ',' expected. +tests/cases/compiler/string.ts(7,21): error TS1134: Variable declaration expected. +tests/cases/compiler/string.ts(11,15): error TS2304: Cannot find name 'document'. +tests/cases/compiler/string.ts(12,19): error TS1005: ';' expected. + + +==== tests/cases/compiler/base.d.ts (2 errors) ==== + declare const x: "foo".charCodeAt(0); + ~ +!!! error TS1005: ',' expected. + ~ +!!! error TS1005: '=' expected. + +==== tests/cases/compiler/string.ts (4 errors) ==== + interface String { + typeof(x: T): T; + } + + class C { + foo() { + const x: "".typeof(this.foo); + ~ +!!! error TS1005: ',' expected. + ~~~~~~ +!!! error TS1134: Variable declaration expected. + } + } + + const nodes = document.getElementsByTagName("li"); + ~~~~~~~~ +!!! error TS2304: Cannot find name 'document'. + type ItemType = "".typeof(nodes.item(0)); + ~ +!!! error TS1005: ';' expected. + +==== tests/cases/compiler/number.ts (4 errors) ==== + interface Number { + typeof(x: T): T; + } + + class C2 { + foo() { + const x: 3.141592.typeof(this.foo); + ~ +!!! error TS1005: ',' expected. + ~~~~~~ +!!! error TS1134: Variable declaration expected. + } + } + + const nodes2 = document.getElementsByTagName("li"); + ~~~~~~~~ +!!! error TS2304: Cannot find name 'document'. + type ItemType2 = 4..typeof(nodes.item(0)); + ~ +!!! error TS1005: ';' expected. + +==== tests/cases/compiler/boolean.ts (4 errors) ==== + interface Boolean { + typeof(x: T): T; + } + + class C3 { + foo() { + const x: false.typeof(this.foo); + ~ +!!! error TS1005: ',' expected. + ~~~~~~ +!!! error TS1134: Variable declaration expected. + } + } + + const nodes3 = document.getElementsByTagName("li"); + ~~~~~~~~ +!!! error TS2304: Cannot find name 'document'. + type ItemType3 = true.typeof(nodes.item(0)); + ~ +!!! error TS1005: ';' expected. + + \ No newline at end of file diff --git a/tests/baselines/reference/expressionTypeNodeShouldError.js b/tests/baselines/reference/expressionTypeNodeShouldError.js new file mode 100644 index 00000000000..80f9f82145a --- /dev/null +++ b/tests/baselines/reference/expressionTypeNodeShouldError.js @@ -0,0 +1,85 @@ +//// [tests/cases/compiler/expressionTypeNodeShouldError.ts] //// + +//// [base.d.ts] +declare const x: "foo".charCodeAt(0); + +//// [string.ts] +interface String { + typeof(x: T): T; +} + +class C { + foo() { + const x: "".typeof(this.foo); + } +} + +const nodes = document.getElementsByTagName("li"); +type ItemType = "".typeof(nodes.item(0)); + +//// [number.ts] +interface Number { + typeof(x: T): T; +} + +class C2 { + foo() { + const x: 3.141592.typeof(this.foo); + } +} + +const nodes2 = document.getElementsByTagName("li"); +type ItemType2 = 4..typeof(nodes.item(0)); + +//// [boolean.ts] +interface Boolean { + typeof(x: T): T; +} + +class C3 { + foo() { + const x: false.typeof(this.foo); + } +} + +const nodes3 = document.getElementsByTagName("li"); +type ItemType3 = true.typeof(nodes.item(0)); + + + +//// [string.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + var x; + typeof (this.foo); + }; + return C; +}()); +var nodes = document.getElementsByTagName("li"); +typeof (nodes.item(0)); +//// [number.js] +var C2 = (function () { + function C2() { + } + C2.prototype.foo = function () { + var x; + typeof (this.foo); + }; + return C2; +}()); +var nodes2 = document.getElementsByTagName("li"); +typeof (nodes.item(0)); +//// [boolean.js] +var C3 = (function () { + function C3() { + } + C3.prototype.foo = function () { + var x; + typeof (this.foo); + }; + return C3; +}()); +var nodes3 = document.getElementsByTagName("li"); +typeof (nodes.item(0)); diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.errors.txt b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.errors.txt index b435e7773f5..51db9c7391e 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.errors.txt +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.errors.txt @@ -1,10 +1,7 @@ -tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,12): error TS2304: Cannot find name 'a'. -tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,12): error TS2695: Left side of comma operator is unused and has no side effects. +tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,15): error TS1003: Identifier expected. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,16): error TS2304: Cannot find name 'b'. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,16): error TS2695: Left side of comma operator is unused and has no side effects. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,19): error TS2304: Cannot find name 'c'. -tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,23): error TS1005: ';' expected. -tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,26): error TS2304: Cannot find name 'a'. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,28): error TS2304: Cannot find name 'b'. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(1,30): error TS2304: Cannot find name 'c'. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(2,12): error TS2695: Left side of comma operator is unused and has no side effects. @@ -21,22 +18,16 @@ tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(4,17): error TS1005 tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts(4,20): error TS2304: Cannot find name 'a'. -==== tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts (21 errors) ==== +==== tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors2.ts (18 errors) ==== var tt1 = (a, (b, c)) => a+b+c; - ~ -!!! error TS2304: Cannot find name 'a'. - ~ -!!! error TS2695: Left side of comma operator is unused and has no side effects. + ~ +!!! error TS1003: Identifier expected. ~ !!! error TS2304: Cannot find name 'b'. ~ !!! error TS2695: Left side of comma operator is unused and has no side effects. ~ !!! error TS2304: Cannot find name 'c'. - ~~ -!!! error TS1005: ';' expected. - ~ -!!! error TS2304: Cannot find name 'a'. ~ !!! error TS2304: Cannot find name 'b'. ~ diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.js index b51003b62df..a1c68ea4476 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.js +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.js @@ -5,8 +5,10 @@ var tt2 = ((a), b, c) => a+b+c; var tt3 = ((a)) => a; //// [fatarrowfunctionsOptionalArgsErrors2.js] -var tt1 = (a, (b, c)); -a + b + c; +var tt1 = function (a, ) { + if ( === void 0) { = (b, c); } + return a + b + c; +}; var tt2 = ((a), b, c); a + b + c; var tt3 = ((a)); diff --git a/tests/baselines/reference/flowControlTypeGuardThenSwitch.js b/tests/baselines/reference/flowControlTypeGuardThenSwitch.js new file mode 100644 index 00000000000..381cdad58e1 --- /dev/null +++ b/tests/baselines/reference/flowControlTypeGuardThenSwitch.js @@ -0,0 +1,58 @@ +//// [flowControlTypeGuardThenSwitch.ts] +enum Kind { + A, + B, +} + +interface Base { + kind: Kind; +} + +interface A extends Base { + kind: Kind.A; + yar: any; +} + +interface B extends Base { + kind: Kind.B; + gar: any; +} + +type Both = A | B; +function isBoth(x: Base): x is Both { + return true; +} + +let foo: Base = undefined; +if (isBoth(foo)) { + switch (foo.kind) { + case Kind.A: + const myA: A = foo; // Should not be an error + break; + case Kind.B: + const myB: B = foo; + break; + } +} + + +//// [flowControlTypeGuardThenSwitch.js] +var Kind; +(function (Kind) { + Kind[Kind["A"] = 0] = "A"; + Kind[Kind["B"] = 1] = "B"; +})(Kind || (Kind = {})); +function isBoth(x) { + return true; +} +var foo = undefined; +if (isBoth(foo)) { + switch (foo.kind) { + case Kind.A: + var myA = foo; // Should not be an error + break; + case Kind.B: + var myB = foo; + break; + } +} diff --git a/tests/baselines/reference/flowControlTypeGuardThenSwitch.symbols b/tests/baselines/reference/flowControlTypeGuardThenSwitch.symbols new file mode 100644 index 00000000000..98d876402d4 --- /dev/null +++ b/tests/baselines/reference/flowControlTypeGuardThenSwitch.symbols @@ -0,0 +1,99 @@ +=== tests/cases/compiler/flowControlTypeGuardThenSwitch.ts === +enum Kind { +>Kind : Symbol(Kind, Decl(flowControlTypeGuardThenSwitch.ts, 0, 0)) + + A, +>A : Symbol(Kind.A, Decl(flowControlTypeGuardThenSwitch.ts, 0, 11)) + + B, +>B : Symbol(Kind.B, Decl(flowControlTypeGuardThenSwitch.ts, 1, 6)) +} + +interface Base { +>Base : Symbol(Base, Decl(flowControlTypeGuardThenSwitch.ts, 3, 1)) + + kind: Kind; +>kind : Symbol(Base.kind, Decl(flowControlTypeGuardThenSwitch.ts, 5, 16)) +>Kind : Symbol(Kind, Decl(flowControlTypeGuardThenSwitch.ts, 0, 0)) +} + +interface A extends Base { +>A : Symbol(A, Decl(flowControlTypeGuardThenSwitch.ts, 7, 1)) +>Base : Symbol(Base, Decl(flowControlTypeGuardThenSwitch.ts, 3, 1)) + + kind: Kind.A; +>kind : Symbol(A.kind, Decl(flowControlTypeGuardThenSwitch.ts, 9, 26)) +>Kind : Symbol(Kind, Decl(flowControlTypeGuardThenSwitch.ts, 0, 0)) +>A : Symbol(Kind.A, Decl(flowControlTypeGuardThenSwitch.ts, 0, 11)) + + yar: any; +>yar : Symbol(A.yar, Decl(flowControlTypeGuardThenSwitch.ts, 10, 17)) +} + +interface B extends Base { +>B : Symbol(B, Decl(flowControlTypeGuardThenSwitch.ts, 12, 1)) +>Base : Symbol(Base, Decl(flowControlTypeGuardThenSwitch.ts, 3, 1)) + + kind: Kind.B; +>kind : Symbol(B.kind, Decl(flowControlTypeGuardThenSwitch.ts, 14, 26)) +>Kind : Symbol(Kind, Decl(flowControlTypeGuardThenSwitch.ts, 0, 0)) +>B : Symbol(Kind.B, Decl(flowControlTypeGuardThenSwitch.ts, 1, 6)) + + gar: any; +>gar : Symbol(B.gar, Decl(flowControlTypeGuardThenSwitch.ts, 15, 17)) +} + +type Both = A | B; +>Both : Symbol(Both, Decl(flowControlTypeGuardThenSwitch.ts, 17, 1)) +>A : Symbol(A, Decl(flowControlTypeGuardThenSwitch.ts, 7, 1)) +>B : Symbol(B, Decl(flowControlTypeGuardThenSwitch.ts, 12, 1)) + +function isBoth(x: Base): x is Both { +>isBoth : Symbol(isBoth, Decl(flowControlTypeGuardThenSwitch.ts, 19, 18)) +>x : Symbol(x, Decl(flowControlTypeGuardThenSwitch.ts, 20, 16)) +>Base : Symbol(Base, Decl(flowControlTypeGuardThenSwitch.ts, 3, 1)) +>x : Symbol(x, Decl(flowControlTypeGuardThenSwitch.ts, 20, 16)) +>Both : Symbol(Both, Decl(flowControlTypeGuardThenSwitch.ts, 17, 1)) + + return true; +} + +let foo: Base = undefined; +>foo : Symbol(foo, Decl(flowControlTypeGuardThenSwitch.ts, 24, 3)) +>Base : Symbol(Base, Decl(flowControlTypeGuardThenSwitch.ts, 3, 1)) +>undefined : Symbol(undefined) + +if (isBoth(foo)) { +>isBoth : Symbol(isBoth, Decl(flowControlTypeGuardThenSwitch.ts, 19, 18)) +>foo : Symbol(foo, Decl(flowControlTypeGuardThenSwitch.ts, 24, 3)) + + switch (foo.kind) { +>foo.kind : Symbol(kind, Decl(flowControlTypeGuardThenSwitch.ts, 9, 26), Decl(flowControlTypeGuardThenSwitch.ts, 14, 26)) +>foo : Symbol(foo, Decl(flowControlTypeGuardThenSwitch.ts, 24, 3)) +>kind : Symbol(kind, Decl(flowControlTypeGuardThenSwitch.ts, 9, 26), Decl(flowControlTypeGuardThenSwitch.ts, 14, 26)) + + case Kind.A: +>Kind.A : Symbol(Kind.A, Decl(flowControlTypeGuardThenSwitch.ts, 0, 11)) +>Kind : Symbol(Kind, Decl(flowControlTypeGuardThenSwitch.ts, 0, 0)) +>A : Symbol(Kind.A, Decl(flowControlTypeGuardThenSwitch.ts, 0, 11)) + + const myA: A = foo; // Should not be an error +>myA : Symbol(myA, Decl(flowControlTypeGuardThenSwitch.ts, 28, 17)) +>A : Symbol(A, Decl(flowControlTypeGuardThenSwitch.ts, 7, 1)) +>foo : Symbol(foo, Decl(flowControlTypeGuardThenSwitch.ts, 24, 3)) + + break; + case Kind.B: +>Kind.B : Symbol(Kind.B, Decl(flowControlTypeGuardThenSwitch.ts, 1, 6)) +>Kind : Symbol(Kind, Decl(flowControlTypeGuardThenSwitch.ts, 0, 0)) +>B : Symbol(Kind.B, Decl(flowControlTypeGuardThenSwitch.ts, 1, 6)) + + const myB: B = foo; +>myB : Symbol(myB, Decl(flowControlTypeGuardThenSwitch.ts, 31, 17)) +>B : Symbol(B, Decl(flowControlTypeGuardThenSwitch.ts, 12, 1)) +>foo : Symbol(foo, Decl(flowControlTypeGuardThenSwitch.ts, 24, 3)) + + break; + } +} + diff --git a/tests/baselines/reference/flowControlTypeGuardThenSwitch.types b/tests/baselines/reference/flowControlTypeGuardThenSwitch.types new file mode 100644 index 00000000000..faa5dd64252 --- /dev/null +++ b/tests/baselines/reference/flowControlTypeGuardThenSwitch.types @@ -0,0 +1,101 @@ +=== tests/cases/compiler/flowControlTypeGuardThenSwitch.ts === +enum Kind { +>Kind : Kind + + A, +>A : Kind.A + + B, +>B : Kind.B +} + +interface Base { +>Base : Base + + kind: Kind; +>kind : Kind +>Kind : Kind +} + +interface A extends Base { +>A : A +>Base : Base + + kind: Kind.A; +>kind : Kind.A +>Kind : any +>A : Kind.A + + yar: any; +>yar : any +} + +interface B extends Base { +>B : B +>Base : Base + + kind: Kind.B; +>kind : Kind.B +>Kind : any +>B : Kind.B + + gar: any; +>gar : any +} + +type Both = A | B; +>Both : Both +>A : A +>B : B + +function isBoth(x: Base): x is Both { +>isBoth : (x: Base) => x is Both +>x : Base +>Base : Base +>x : any +>Both : Both + + return true; +>true : true +} + +let foo: Base = undefined; +>foo : Base +>Base : Base +>undefined : undefined + +if (isBoth(foo)) { +>isBoth(foo) : boolean +>isBoth : (x: Base) => x is Both +>foo : Base + + switch (foo.kind) { +>foo.kind : Kind +>foo : Both +>kind : Kind + + case Kind.A: +>Kind.A : Kind.A +>Kind : typeof Kind +>A : Kind.A + + const myA: A = foo; // Should not be an error +>myA : A +>A : A +>foo : A + + break; + case Kind.B: +>Kind.B : Kind.B +>Kind : typeof Kind +>B : Kind.B + + const myB: B = foo; +>myB : B +>B : B +>foo : B + + break; + } +} + diff --git a/tests/baselines/reference/importCallExpression1ESNext.js b/tests/baselines/reference/importCallExpression1ESNext.js index 39b779c921f..32d45aaf628 100644 --- a/tests/baselines/reference/importCallExpression1ESNext.js +++ b/tests/baselines/reference/importCallExpression1ESNext.js @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }) +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } @@ -22,6 +24,7 @@ var p1 = import("./0"); p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); function foo() { const p2 = import("./0"); } diff --git a/tests/baselines/reference/importCallExpression1ESNext.symbols b/tests/baselines/reference/importCallExpression1ESNext.symbols index 564943aca54..33cf3c23420 100644 --- a/tests/baselines/reference/importCallExpression1ESNext.symbols +++ b/tests/baselines/reference/importCallExpression1ESNext.symbols @@ -23,10 +23,14 @@ p1.then(zero => { }) +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 2)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } diff --git a/tests/baselines/reference/importCallExpression1ESNext.types b/tests/baselines/reference/importCallExpression1ESNext.types index 53a1b3d08fa..29e2c3d261b 100644 --- a/tests/baselines/reference/importCallExpression1ESNext.types +++ b/tests/baselines/reference/importCallExpression1ESNext.types @@ -29,6 +29,11 @@ p1.then(zero => { }) +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void diff --git a/tests/baselines/reference/importCallExpression4ESNext.js b/tests/baselines/reference/importCallExpression4ESNext.js index e148d5c1e51..d5d4a51d69f 100644 --- a/tests/baselines/reference/importCallExpression4ESNext.js +++ b/tests/baselines/reference/importCallExpression4ESNext.js @@ -15,6 +15,7 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import ("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { @@ -38,6 +39,7 @@ class C { this.myModule = import("./0"); } method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async (err) => { diff --git a/tests/baselines/reference/importCallExpression4ESNext.symbols b/tests/baselines/reference/importCallExpression4ESNext.symbols index b02646d5e3d..ef8d6e9c509 100644 --- a/tests/baselines/reference/importCallExpression4ESNext.symbols +++ b/tests/baselines/reference/importCallExpression4ESNext.symbols @@ -27,35 +27,39 @@ class C { method() { >method : Symbol(C.method, Decl(2.ts, 2, 37)) + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 4, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + this.myModule.then(Zero => { >this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) >this.myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >this : Symbol(C, Decl(2.ts, 0, 25)) >myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) console.log(Zero.foo()); >console : Symbol(console, Decl(2.ts, 0, 11)) >Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) >foo : Symbol(foo, Decl(0.ts, 2, 1)) }, async err => { ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) console.log(err); >console : Symbol(console, Decl(2.ts, 0, 11)) ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) let one = await import("./1"); ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) >"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) console.log(one.backup()); >console : Symbol(console, Decl(2.ts, 0, 11)) >one.backup : Symbol(backup, Decl(1.ts, 0, 0)) ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) >backup : Symbol(backup, Decl(1.ts, 0, 0)) }); diff --git a/tests/baselines/reference/importCallExpression4ESNext.types b/tests/baselines/reference/importCallExpression4ESNext.types index 2ea666ba672..74cc6ff8b28 100644 --- a/tests/baselines/reference/importCallExpression4ESNext.types +++ b/tests/baselines/reference/importCallExpression4ESNext.types @@ -31,6 +31,11 @@ class C { method() { >method : () => void + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + this.myModule.then(Zero => { >this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise >this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise diff --git a/tests/baselines/reference/importCallExpressionAsyncES3AMD.js b/tests/baselines/reference/importCallExpressionAsyncES3AMD.js new file mode 100644 index 00000000000..f0246f4ce5e --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3AMD.js @@ -0,0 +1,153 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +define(["require", "exports"], function (require, exports) { + "use strict"; + var _this = this; + exports.__esModule = true; + function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_1, reject_1) { require(['./test'], resolve_1, reject_1); })]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); + } + exports.fn = fn; + var cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_2, reject_2) { require(['./test'], resolve_2, reject_2); })]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; + }()); + exports.cl1 = cl1; + exports.obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_3, reject_3) { require(['./test'], resolve_3, reject_3); })]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } + }; + var cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_4, reject_4) { require(['./test'], resolve_4, reject_4); })]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; + }()); + exports.cl2 = cl2; + exports.l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_5, reject_5) { require(['./test'], resolve_5, reject_5); })]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); + }); }; +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES3AMD.symbols b/tests/baselines/reference/importCallExpressionAsyncES3AMD.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3AMD.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES3AMD.types b/tests/baselines/reference/importCallExpressionAsyncES3AMD.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3AMD.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES3CJS.js b/tests/baselines/reference/importCallExpressionAsyncES3CJS.js new file mode 100644 index 00000000000..6b4006e05be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3CJS.js @@ -0,0 +1,151 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var _this = this; +exports.__esModule = true; +function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); +} +exports.fn = fn; +var cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; +}()); +exports.cl1 = cl1; +exports.obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } +}; +var cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; +}()); +exports.cl2 = cl2; +exports.l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); +}); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES3CJS.symbols b/tests/baselines/reference/importCallExpressionAsyncES3CJS.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3CJS.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES3CJS.types b/tests/baselines/reference/importCallExpressionAsyncES3CJS.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3CJS.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES3System.js b/tests/baselines/reference/importCallExpressionAsyncES3System.js new file mode 100644 index 00000000000..542ce108039 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3System.js @@ -0,0 +1,159 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +System.register([], function (exports_1, context_1) { + "use strict"; + var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + _this = this; + var __moduleName = context_1 && context_1.id; + function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1["import"]('./test')]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); + } + exports_1("fn", fn); + var _this, cl1, obj, cl2, l; + return { + setters: [], + execute: function () { + cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1["import"]('./test')]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; + }()); + exports_1("cl1", cl1); + exports_1("obj", obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1["import"]('./test')]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } + }); + cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1["import"]('./test')]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; + }()); + exports_1("cl2", cl2); + exports_1("l", l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1["import"]('./test')]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); + }); }); + } + }; +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES3System.symbols b/tests/baselines/reference/importCallExpressionAsyncES3System.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3System.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES3System.types b/tests/baselines/reference/importCallExpressionAsyncES3System.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3System.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES3UMD.js b/tests/baselines/reference/importCallExpressionAsyncES3UMD.js new file mode 100644 index 00000000000..4404cad5937 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3UMD.js @@ -0,0 +1,162 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + var _this = this; + exports.__esModule = true; + function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_1, reject_1) { require(['./test'], resolve_1, reject_1); })]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); + } + exports.fn = fn; + var cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_2, reject_2) { require(['./test'], resolve_2, reject_2); })]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; + }()); + exports.cl1 = cl1; + exports.obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_3, reject_3) { require(['./test'], resolve_3, reject_3); })]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } + }; + var cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_4, reject_4) { require(['./test'], resolve_4, reject_4); })]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; + }()); + exports.cl2 = cl2; + exports.l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_5, reject_5) { require(['./test'], resolve_5, reject_5); })]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); + }); }; +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES3UMD.symbols b/tests/baselines/reference/importCallExpressionAsyncES3UMD.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3UMD.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES3UMD.types b/tests/baselines/reference/importCallExpressionAsyncES3UMD.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES3UMD.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5AMD.js b/tests/baselines/reference/importCallExpressionAsyncES5AMD.js new file mode 100644 index 00000000000..8e7b2005e78 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5AMD.js @@ -0,0 +1,153 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +define(["require", "exports"], function (require, exports) { + "use strict"; + var _this = this; + Object.defineProperty(exports, "__esModule", { value: true }); + function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_1, reject_1) { require(['./test'], resolve_1, reject_1); })]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); + } + exports.fn = fn; + var cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_2, reject_2) { require(['./test'], resolve_2, reject_2); })]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; + }()); + exports.cl1 = cl1; + exports.obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_3, reject_3) { require(['./test'], resolve_3, reject_3); })]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } + }; + var cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_4, reject_4) { require(['./test'], resolve_4, reject_4); })]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; + }()); + exports.cl2 = cl2; + exports.l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, new Promise(function (resolve_5, reject_5) { require(['./test'], resolve_5, reject_5); })]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); + }); }; +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES5AMD.symbols b/tests/baselines/reference/importCallExpressionAsyncES5AMD.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5AMD.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5AMD.types b/tests/baselines/reference/importCallExpressionAsyncES5AMD.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5AMD.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5CJS.js b/tests/baselines/reference/importCallExpressionAsyncES5CJS.js new file mode 100644 index 00000000000..2e04783fa89 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5CJS.js @@ -0,0 +1,151 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +var _this = this; +Object.defineProperty(exports, "__esModule", { value: true }); +function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); +} +exports.fn = fn; +var cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; +}()); +exports.cl1 = cl1; +exports.obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } +}; +var cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; +}()); +exports.cl2 = cl2; +exports.l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./test'); })]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); +}); }; diff --git a/tests/baselines/reference/importCallExpressionAsyncES5CJS.symbols b/tests/baselines/reference/importCallExpressionAsyncES5CJS.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5CJS.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5CJS.types b/tests/baselines/reference/importCallExpressionAsyncES5CJS.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5CJS.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5System.js b/tests/baselines/reference/importCallExpressionAsyncES5System.js new file mode 100644 index 00000000000..b7d89d158b1 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5System.js @@ -0,0 +1,159 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +System.register([], function (exports_1, context_1) { + "use strict"; + var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + _this = this; + var __moduleName = context_1 && context_1.id; + function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1.import('./test')]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); + } + exports_1("fn", fn); + var _this, cl1, obj, cl2, l; + return { + setters: [], + execute: function () { + cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1.import('./test')]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; + }()); + exports_1("cl1", cl1); + exports_1("obj", obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1.import('./test')]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } + }); + cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1.import('./test')]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; + }()); + exports_1("cl2", cl2); + exports_1("l", l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, context_1.import('./test')]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); + }); }); + } + }; +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES5System.symbols b/tests/baselines/reference/importCallExpressionAsyncES5System.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5System.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5System.types b/tests/baselines/reference/importCallExpressionAsyncES5System.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5System.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5UMD.js b/tests/baselines/reference/importCallExpressionAsyncES5UMD.js new file mode 100644 index 00000000000..102d78cfa05 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5UMD.js @@ -0,0 +1,162 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + var _this = this; + Object.defineProperty(exports, "__esModule", { value: true }); + function fn() { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_1, reject_1) { require(['./test'], resolve_1, reject_1); })]; // ONE + case 1: + req = _a.sent() // ONE + ; + return [2 /*return*/]; + } + }); + }); + } + exports.fn = fn; + var cl1 = (function () { + function cl1() { + } + cl1.prototype.m = function () { + return __awaiter(this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_2, reject_2) { require(['./test'], resolve_2, reject_2); })]; // TWO + case 1: + req = _a.sent() // TWO + ; + return [2 /*return*/]; + } + }); + }); + }; + return cl1; + }()); + exports.cl1 = cl1; + exports.obj = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_3, reject_3) { require(['./test'], resolve_3, reject_3); })]; // THREE + case 1: + req = _a.sent() // THREE + ; + return [2 /*return*/]; + } + }); + }); } + }; + var cl2 = (function () { + function cl2() { + var _this = this; + this.p = { + m: function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_4, reject_4) { require(['./test'], resolve_4, reject_4); })]; // FOUR + case 1: + req = _a.sent() // FOUR + ; + return [2 /*return*/]; + } + }); + }); } + }; + } + return cl2; + }()); + exports.cl2 = cl2; + exports.l = function () { return __awaiter(_this, void 0, void 0, function () { + var req; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_5, reject_5) { require(['./test'], resolve_5, reject_5); })]; // FIVE + case 1: + req = _a.sent() // FIVE + ; + return [2 /*return*/]; + } + }); + }); }; +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES5UMD.symbols b/tests/baselines/reference/importCallExpressionAsyncES5UMD.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5UMD.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES5UMD.types b/tests/baselines/reference/importCallExpressionAsyncES5UMD.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES5UMD.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6AMD.js b/tests/baselines/reference/importCallExpressionAsyncES6AMD.js new file mode 100644 index 00000000000..9819da8369b --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6AMD.js @@ -0,0 +1,75 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +define(["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function fn() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield new Promise(function (resolve_1, reject_1) { require(['./test'], resolve_1, reject_1); }); // ONE + }); + } + exports.fn = fn; + class cl1 { + m() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield new Promise(function (resolve_2, reject_2) { require(['./test'], resolve_2, reject_2); }); // TWO + }); + } + } + exports.cl1 = cl1; + exports.obj = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield new Promise(function (resolve_3, reject_3) { require(['./test'], resolve_3, reject_3); }); // THREE + }) + }; + class cl2 { + constructor() { + this.p = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield new Promise(function (resolve_4, reject_4) { require(['./test'], resolve_4, reject_4); }); // FOUR + }) + }; + } + } + exports.cl2 = cl2; + exports.l = () => __awaiter(this, void 0, void 0, function* () { + const req = yield new Promise(function (resolve_5, reject_5) { require(['./test'], resolve_5, reject_5); }); // FIVE + }); +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES6AMD.symbols b/tests/baselines/reference/importCallExpressionAsyncES6AMD.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6AMD.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6AMD.types b/tests/baselines/reference/importCallExpressionAsyncES6AMD.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6AMD.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6CJS.js b/tests/baselines/reference/importCallExpressionAsyncES6CJS.js new file mode 100644 index 00000000000..b512ae94b48 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6CJS.js @@ -0,0 +1,73 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +function fn() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield Promise.resolve().then(function () { return require('./test'); }); // ONE + }); +} +exports.fn = fn; +class cl1 { + m() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield Promise.resolve().then(function () { return require('./test'); }); // TWO + }); + } +} +exports.cl1 = cl1; +exports.obj = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield Promise.resolve().then(function () { return require('./test'); }); // THREE + }) +}; +class cl2 { + constructor() { + this.p = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield Promise.resolve().then(function () { return require('./test'); }); // FOUR + }) + }; + } +} +exports.cl2 = cl2; +exports.l = () => __awaiter(this, void 0, void 0, function* () { + const req = yield Promise.resolve().then(function () { return require('./test'); }); // FIVE +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES6CJS.symbols b/tests/baselines/reference/importCallExpressionAsyncES6CJS.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6CJS.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6CJS.types b/tests/baselines/reference/importCallExpressionAsyncES6CJS.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6CJS.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6System.js b/tests/baselines/reference/importCallExpressionAsyncES6System.js new file mode 100644 index 00000000000..32a9b9028e5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6System.js @@ -0,0 +1,81 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +System.register([], function (exports_1, context_1) { + "use strict"; + var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __moduleName = context_1 && context_1.id; + function fn() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield context_1.import('./test'); // ONE + }); + } + exports_1("fn", fn); + var cl1, obj, cl2, l; + return { + setters: [], + execute: function () { + cl1 = class cl1 { + m() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield context_1.import('./test'); // TWO + }); + } + }; + exports_1("cl1", cl1); + exports_1("obj", obj = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield context_1.import('./test'); // THREE + }) + }); + cl2 = class cl2 { + constructor() { + this.p = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield context_1.import('./test'); // FOUR + }) + }; + } + }; + exports_1("cl2", cl2); + exports_1("l", l = () => __awaiter(this, void 0, void 0, function* () { + const req = yield context_1.import('./test'); // FIVE + })); + } + }; +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES6System.symbols b/tests/baselines/reference/importCallExpressionAsyncES6System.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6System.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6System.types b/tests/baselines/reference/importCallExpressionAsyncES6System.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6System.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6UMD.js b/tests/baselines/reference/importCallExpressionAsyncES6UMD.js new file mode 100644 index 00000000000..f77d5150118 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6UMD.js @@ -0,0 +1,84 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + Object.defineProperty(exports, "__esModule", { value: true }); + function fn() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_1, reject_1) { require(['./test'], resolve_1, reject_1); }); // ONE + }); + } + exports.fn = fn; + class cl1 { + m() { + return __awaiter(this, void 0, void 0, function* () { + const req = yield __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_2, reject_2) { require(['./test'], resolve_2, reject_2); }); // TWO + }); + } + } + exports.cl1 = cl1; + exports.obj = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_3, reject_3) { require(['./test'], resolve_3, reject_3); }); // THREE + }) + }; + class cl2 { + constructor() { + this.p = { + m: () => __awaiter(this, void 0, void 0, function* () { + const req = yield __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_4, reject_4) { require(['./test'], resolve_4, reject_4); }); // FOUR + }) + }; + } + } + exports.cl2 = cl2; + exports.l = () => __awaiter(this, void 0, void 0, function* () { + const req = yield __syncRequire ? Promise.resolve().then(function () { return require('./test'); }) : new Promise(function (resolve_5, reject_5) { require(['./test'], resolve_5, reject_5); }); // FIVE + }); +}); diff --git a/tests/baselines/reference/importCallExpressionAsyncES6UMD.symbols b/tests/baselines/reference/importCallExpressionAsyncES6UMD.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6UMD.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncES6UMD.types b/tests/baselines/reference/importCallExpressionAsyncES6UMD.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncES6UMD.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncESNext.js b/tests/baselines/reference/importCallExpressionAsyncESNext.js new file mode 100644 index 00000000000..7d5f2b0ed25 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncESNext.js @@ -0,0 +1,56 @@ +//// [test.ts] +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} + + +//// [test.js] +export async function fn() { + const req = await import('./test'); // ONE +} +export class cl1 { + async m() { + const req = await import('./test'); // TWO + } +} +export const obj = { + m: async () => { + const req = await import('./test'); // THREE + } +}; +export class cl2 { + constructor() { + this.p = { + m: async () => { + const req = await import('./test'); // FOUR + } + }; + } +} +export const l = async () => { + const req = await import('./test'); // FIVE +}; diff --git a/tests/baselines/reference/importCallExpressionAsyncESNext.symbols b/tests/baselines/reference/importCallExpressionAsyncESNext.symbols new file mode 100644 index 00000000000..48aad998fc5 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncESNext.symbols @@ -0,0 +1,57 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : Symbol(fn, Decl(test.ts, 0, 0)) + + const req = await import('./test') // ONE +>req : Symbol(req, Decl(test.ts, 1, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + +export class cl1 { +>cl1 : Symbol(cl1, Decl(test.ts, 2, 1)) + + public async m() { +>m : Symbol(cl1.m, Decl(test.ts, 4, 18)) + + const req = await import('./test') // TWO +>req : Symbol(req, Decl(test.ts, 6, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export const obj = { +>obj : Symbol(obj, Decl(test.ts, 10, 12)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 10, 20)) + + const req = await import('./test') // THREE +>req : Symbol(req, Decl(test.ts, 12, 13)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } +} + +export class cl2 { +>cl2 : Symbol(cl2, Decl(test.ts, 14, 1)) + + public p = { +>p : Symbol(cl2.p, Decl(test.ts, 16, 18)) + + m: async () => { +>m : Symbol(m, Decl(test.ts, 17, 16)) + + const req = await import('./test') // FOUR +>req : Symbol(req, Decl(test.ts, 19, 17)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) + } + } +} + +export const l = async () => { +>l : Symbol(l, Decl(test.ts, 24, 12)) + + const req = await import('./test') // FIVE +>req : Symbol(req, Decl(test.ts, 25, 9)) +>'./test' : Symbol("tests/cases/conformance/dynamicImport/test", Decl(test.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/importCallExpressionAsyncESNext.types b/tests/baselines/reference/importCallExpressionAsyncESNext.types new file mode 100644 index 00000000000..4f6a2bb31be --- /dev/null +++ b/tests/baselines/reference/importCallExpressionAsyncESNext.types @@ -0,0 +1,72 @@ +=== tests/cases/conformance/dynamicImport/test.ts === +export async function fn() { +>fn : () => Promise + + const req = await import('./test') // ONE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + +export class cl1 { +>cl1 : cl1 + + public async m() { +>m : () => Promise + + const req = await import('./test') // TWO +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export const obj = { +>obj : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // THREE }} : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // THREE } : () => Promise + + const req = await import('./test') // THREE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } +} + +export class cl2 { +>cl2 : cl2 + + public p = { +>p : { m: () => Promise; } +>{ m: async () => { const req = await import('./test') // FOUR } } : { m: () => Promise; } + + m: async () => { +>m : () => Promise +>async () => { const req = await import('./test') // FOUR } : () => Promise + + const req = await import('./test') // FOUR +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" + } + } +} + +export const l = async () => { +>l : () => Promise +>async () => { const req = await import('./test') // FIVE} : () => Promise + + const req = await import('./test') // FIVE +>req : typeof "tests/cases/conformance/dynamicImport/test" +>await import('./test') : typeof "tests/cases/conformance/dynamicImport/test" +>import('./test') : Promise +>'./test' : "./test" +} + diff --git a/tests/baselines/reference/importCallExpressionES5AMD.js b/tests/baselines/reference/importCallExpressionES5AMD.js index cce61a5a3f9..8fa22d81dc9 100644 --- a/tests/baselines/reference/importCallExpressionES5AMD.js +++ b/tests/baselines/reference/importCallExpressionES5AMD.js @@ -10,8 +10,22 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } //// [0.js] @@ -24,12 +38,31 @@ define(["require", "exports"], function (require, exports) { //// [1.js] define(["require", "exports"], function (require, exports) { "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); var p1 = new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); p1.then(function (zero) { return zero.foo(); }); + exports.p2 = new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); function foo() { - var p2 = new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); + var p2 = new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); } + var C = (function () { + function C() { + } + C.prototype.method = function () { + var loadAsync = new Promise(function (resolve_5, reject_5) { require(["./0"], resolve_5, reject_5); }); + }; + return C; + }()); + var D = (function () { + function D() { + } + D.prototype.method = function () { + var loadAsync = new Promise(function (resolve_6, reject_6) { require(["./0"], resolve_6, reject_6); }); + }; + return D; + }()); + exports.D = D; }); diff --git a/tests/baselines/reference/importCallExpressionES5AMD.symbols b/tests/baselines/reference/importCallExpressionES5AMD.symbols index a1a506e7005..2f8bd23758d 100644 --- a/tests/baselines/reference/importCallExpressionES5AMD.symbols +++ b/tests/baselines/reference/importCallExpressionES5AMD.symbols @@ -23,10 +23,38 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES5AMD.types b/tests/baselines/reference/importCallExpressionES5AMD.types index 59da055ee01..e97f722b14f 100644 --- a/tests/baselines/reference/importCallExpressionES5AMD.types +++ b/tests/baselines/reference/importCallExpressionES5AMD.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void @@ -37,3 +42,29 @@ function foo() { >import("./0") : Promise >"./0" : "./0" } + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionES5CJS.js b/tests/baselines/reference/importCallExpressionES5CJS.js index 11d1bf46319..2cf5d3157e2 100644 --- a/tests/baselines/reference/importCallExpressionES5CJS.js +++ b/tests/baselines/reference/importCallExpressionES5CJS.js @@ -10,8 +10,22 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } //// [0.js] @@ -20,11 +34,31 @@ Object.defineProperty(exports, "__esModule", { value: true }); function foo() { return "foo"; } exports.foo = foo; //// [1.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); Promise.resolve().then(function () { return require("./0"); }); var p1 = Promise.resolve().then(function () { return require("./0"); }); p1.then(function (zero) { return zero.foo(); }); +exports.p2 = Promise.resolve().then(function () { return require("./0"); }); function foo() { var p2 = Promise.resolve().then(function () { return require("./0"); }); } +var C = (function () { + function C() { + } + C.prototype.method = function () { + var loadAsync = Promise.resolve().then(function () { return require("./0"); }); + }; + return C; +}()); +var D = (function () { + function D() { + } + D.prototype.method = function () { + var loadAsync = Promise.resolve().then(function () { return require("./0"); }); + }; + return D; +}()); +exports.D = D; diff --git a/tests/baselines/reference/importCallExpressionES5CJS.symbols b/tests/baselines/reference/importCallExpressionES5CJS.symbols index a1a506e7005..2f8bd23758d 100644 --- a/tests/baselines/reference/importCallExpressionES5CJS.symbols +++ b/tests/baselines/reference/importCallExpressionES5CJS.symbols @@ -23,10 +23,38 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES5CJS.types b/tests/baselines/reference/importCallExpressionES5CJS.types index 59da055ee01..e97f722b14f 100644 --- a/tests/baselines/reference/importCallExpressionES5CJS.types +++ b/tests/baselines/reference/importCallExpressionES5CJS.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void @@ -37,3 +42,29 @@ function foo() { >import("./0") : Promise >"./0" : "./0" } + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionES5System.js b/tests/baselines/reference/importCallExpressionES5System.js index 1842fc6e60a..3dabfce80c9 100644 --- a/tests/baselines/reference/importCallExpressionES5System.js +++ b/tests/baselines/reference/importCallExpressionES5System.js @@ -10,8 +10,22 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } //// [0.js] @@ -28,11 +42,12 @@ System.register([], function (exports_1, context_1) { }); //// [1.js] System.register([], function (exports_1, context_1) { + "use strict"; var __moduleName = context_1 && context_1.id; function foo() { var p2 = context_1.import("./0"); } - var p1; + var p1, p2, C, D; return { setters: [], execute: function () { @@ -41,6 +56,24 @@ System.register([], function (exports_1, context_1) { p1.then(function (zero) { return zero.foo(); }); + exports_1("p2", p2 = context_1.import("./0")); + C = (function () { + function C() { + } + C.prototype.method = function () { + var loadAsync = context_1.import("./0"); + }; + return C; + }()); + D = (function () { + function D() { + } + D.prototype.method = function () { + var loadAsync = context_1.import("./0"); + }; + return D; + }()); + exports_1("D", D); } }; }); diff --git a/tests/baselines/reference/importCallExpressionES5System.symbols b/tests/baselines/reference/importCallExpressionES5System.symbols index a1a506e7005..2f8bd23758d 100644 --- a/tests/baselines/reference/importCallExpressionES5System.symbols +++ b/tests/baselines/reference/importCallExpressionES5System.symbols @@ -23,10 +23,38 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES5System.types b/tests/baselines/reference/importCallExpressionES5System.types index 59da055ee01..e97f722b14f 100644 --- a/tests/baselines/reference/importCallExpressionES5System.types +++ b/tests/baselines/reference/importCallExpressionES5System.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void @@ -37,3 +42,29 @@ function foo() { >import("./0") : Promise >"./0" : "./0" } + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionES5UMD.js b/tests/baselines/reference/importCallExpressionES5UMD.js index dfe6813839c..5727744aa71 100644 --- a/tests/baselines/reference/importCallExpressionES5UMD.js +++ b/tests/baselines/reference/importCallExpressionES5UMD.js @@ -10,8 +10,22 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } //// [0.js] @@ -41,12 +55,31 @@ function foo() { })(function (require, exports) { "use strict"; var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + Object.defineProperty(exports, "__esModule", { value: true }); __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); var p1 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); p1.then(function (zero) { return zero.foo(); }); + exports.p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); function foo() { - var p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); + var p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); } + var C = (function () { + function C() { + } + C.prototype.method = function () { + var loadAsync = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_5, reject_5) { require(["./0"], resolve_5, reject_5); }); + }; + return C; + }()); + var D = (function () { + function D() { + } + D.prototype.method = function () { + var loadAsync = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_6, reject_6) { require(["./0"], resolve_6, reject_6); }); + }; + return D; + }()); + exports.D = D; }); diff --git a/tests/baselines/reference/importCallExpressionES5UMD.symbols b/tests/baselines/reference/importCallExpressionES5UMD.symbols index a1a506e7005..2f8bd23758d 100644 --- a/tests/baselines/reference/importCallExpressionES5UMD.symbols +++ b/tests/baselines/reference/importCallExpressionES5UMD.symbols @@ -23,10 +23,38 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES5UMD.types b/tests/baselines/reference/importCallExpressionES5UMD.types index 59da055ee01..e97f722b14f 100644 --- a/tests/baselines/reference/importCallExpressionES5UMD.types +++ b/tests/baselines/reference/importCallExpressionES5UMD.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void @@ -37,3 +42,29 @@ function foo() { >import("./0") : Promise >"./0" : "./0" } + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionES6AMD.js b/tests/baselines/reference/importCallExpressionES6AMD.js new file mode 100644 index 00000000000..08fec3b27fd --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6AMD.js @@ -0,0 +1,62 @@ +//// [tests/cases/conformance/dynamicImport/importCallExpressionES6AMD.ts] //// + +//// [0.ts] +export function foo() { return "foo"; } + +//// [1.ts] +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} + +//// [0.js] +define(["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function foo() { return "foo"; } + exports.foo = foo; +}); +//// [1.js] +define(["require", "exports"], function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); + var p1 = new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); + p1.then(zero => { + return zero.foo(); + }); + exports.p2 = new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); + function foo() { + const p2 = new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); + } + class C { + method() { + const loadAsync = new Promise(function (resolve_5, reject_5) { require(["./0"], resolve_5, reject_5); }); + } + } + class D { + method() { + const loadAsync = new Promise(function (resolve_6, reject_6) { require(["./0"], resolve_6, reject_6); }); + } + } + exports.D = D; +}); diff --git a/tests/baselines/reference/importCallExpressionES6AMD.symbols b/tests/baselines/reference/importCallExpressionES6AMD.symbols new file mode 100644 index 00000000000..2f8bd23758d --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6AMD.symbols @@ -0,0 +1,60 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +var p1 = import("./0"); +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +p1.then(zero => { +>p1.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) + + return zero.foo(); +>zero.foo : Symbol(foo, Decl(0.ts, 0, 0)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +}); + +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +function foo() { +>foo : Symbol(foo, Decl(1.ts, 6, 30)) + + const p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) +} + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES6AMD.types b/tests/baselines/reference/importCallExpressionES6AMD.types new file mode 100644 index 00000000000..e97f722b14f --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6AMD.types @@ -0,0 +1,70 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : () => string +>"foo" : "foo" + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>import("./0") : Promise +>"./0" : "./0" + +var p1 = import("./0"); +>p1 : Promise +>import("./0") : Promise +>"./0" : "./0" + +p1.then(zero => { +>p1.then(zero => { return zero.foo();}) : Promise +>p1.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>p1 : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>zero => { return zero.foo();} : (zero: typeof "tests/cases/conformance/dynamicImport/0") => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" + + return zero.foo(); +>zero.foo() : string +>zero.foo : () => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + +}); + +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + +function foo() { +>foo : () => void + + const p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" +} + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionES6CJS.js b/tests/baselines/reference/importCallExpressionES6CJS.js new file mode 100644 index 00000000000..28833e17479 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6CJS.js @@ -0,0 +1,58 @@ +//// [tests/cases/conformance/dynamicImport/importCallExpressionES6CJS.ts] //// + +//// [0.ts] +export function foo() { return "foo"; } + +//// [1.ts] +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} + +//// [0.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function foo() { return "foo"; } +exports.foo = foo; +//// [1.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +Promise.resolve().then(function () { return require("./0"); }); +var p1 = Promise.resolve().then(function () { return require("./0"); }); +p1.then(zero => { + return zero.foo(); +}); +exports.p2 = Promise.resolve().then(function () { return require("./0"); }); +function foo() { + const p2 = Promise.resolve().then(function () { return require("./0"); }); +} +class C { + method() { + const loadAsync = Promise.resolve().then(function () { return require("./0"); }); + } +} +class D { + method() { + const loadAsync = Promise.resolve().then(function () { return require("./0"); }); + } +} +exports.D = D; diff --git a/tests/baselines/reference/importCallExpressionES6CJS.symbols b/tests/baselines/reference/importCallExpressionES6CJS.symbols new file mode 100644 index 00000000000..2f8bd23758d --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6CJS.symbols @@ -0,0 +1,60 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +var p1 = import("./0"); +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +p1.then(zero => { +>p1.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) + + return zero.foo(); +>zero.foo : Symbol(foo, Decl(0.ts, 0, 0)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +}); + +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +function foo() { +>foo : Symbol(foo, Decl(1.ts, 6, 30)) + + const p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) +} + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES6CJS.types b/tests/baselines/reference/importCallExpressionES6CJS.types new file mode 100644 index 00000000000..e97f722b14f --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6CJS.types @@ -0,0 +1,70 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : () => string +>"foo" : "foo" + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>import("./0") : Promise +>"./0" : "./0" + +var p1 = import("./0"); +>p1 : Promise +>import("./0") : Promise +>"./0" : "./0" + +p1.then(zero => { +>p1.then(zero => { return zero.foo();}) : Promise +>p1.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>p1 : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>zero => { return zero.foo();} : (zero: typeof "tests/cases/conformance/dynamicImport/0") => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" + + return zero.foo(); +>zero.foo() : string +>zero.foo : () => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + +}); + +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + +function foo() { +>foo : () => void + + const p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" +} + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionES6System.js b/tests/baselines/reference/importCallExpressionES6System.js new file mode 100644 index 00000000000..0676e4cd559 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6System.js @@ -0,0 +1,73 @@ +//// [tests/cases/conformance/dynamicImport/importCallExpressionES6System.ts] //// + +//// [0.ts] +export function foo() { return "foo"; } + +//// [1.ts] +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} + +//// [0.js] +System.register([], function (exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; + function foo() { return "foo"; } + exports_1("foo", foo); + return { + setters: [], + execute: function () { + } + }; +}); +//// [1.js] +System.register([], function (exports_1, context_1) { + "use strict"; + var __moduleName = context_1 && context_1.id; + function foo() { + const p2 = context_1.import("./0"); + } + var p1, p2, C, D; + return { + setters: [], + execute: function () { + context_1.import("./0"); + p1 = context_1.import("./0"); + p1.then(zero => { + return zero.foo(); + }); + exports_1("p2", p2 = context_1.import("./0")); + C = class C { + method() { + const loadAsync = context_1.import("./0"); + } + }; + D = class D { + method() { + const loadAsync = context_1.import("./0"); + } + }; + exports_1("D", D); + } + }; +}); diff --git a/tests/baselines/reference/importCallExpressionES6System.symbols b/tests/baselines/reference/importCallExpressionES6System.symbols new file mode 100644 index 00000000000..2f8bd23758d --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6System.symbols @@ -0,0 +1,60 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +var p1 = import("./0"); +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +p1.then(zero => { +>p1.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) + + return zero.foo(); +>zero.foo : Symbol(foo, Decl(0.ts, 0, 0)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +}); + +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +function foo() { +>foo : Symbol(foo, Decl(1.ts, 6, 30)) + + const p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) +} + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES6System.types b/tests/baselines/reference/importCallExpressionES6System.types new file mode 100644 index 00000000000..e97f722b14f --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6System.types @@ -0,0 +1,70 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : () => string +>"foo" : "foo" + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>import("./0") : Promise +>"./0" : "./0" + +var p1 = import("./0"); +>p1 : Promise +>import("./0") : Promise +>"./0" : "./0" + +p1.then(zero => { +>p1.then(zero => { return zero.foo();}) : Promise +>p1.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>p1 : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>zero => { return zero.foo();} : (zero: typeof "tests/cases/conformance/dynamicImport/0") => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" + + return zero.foo(); +>zero.foo() : string +>zero.foo : () => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + +}); + +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + +function foo() { +>foo : () => void + + const p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" +} + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionES6UMD.js b/tests/baselines/reference/importCallExpressionES6UMD.js new file mode 100644 index 00000000000..cc7dfef0074 --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6UMD.js @@ -0,0 +1,79 @@ +//// [tests/cases/conformance/dynamicImport/importCallExpressionES6UMD.ts] //// + +//// [0.ts] +export function foo() { return "foo"; } + +//// [1.ts] +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} + +//// [0.js] +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function foo() { return "foo"; } + exports.foo = foo; +}); +//// [1.js] +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports"], factory); + } +})(function (require, exports) { + "use strict"; + var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + Object.defineProperty(exports, "__esModule", { value: true }); + __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); + var p1 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); + p1.then(zero => { + return zero.foo(); + }); + exports.p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); + function foo() { + const p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); + } + class C { + method() { + const loadAsync = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_5, reject_5) { require(["./0"], resolve_5, reject_5); }); + } + } + class D { + method() { + const loadAsync = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_6, reject_6) { require(["./0"], resolve_6, reject_6); }); + } + } + exports.D = D; +}); diff --git a/tests/baselines/reference/importCallExpressionES6UMD.symbols b/tests/baselines/reference/importCallExpressionES6UMD.symbols new file mode 100644 index 00000000000..2f8bd23758d --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6UMD.symbols @@ -0,0 +1,60 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +var p1 = import("./0"); +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +p1.then(zero => { +>p1.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>p1 : Symbol(p1, Decl(1.ts, 1, 3)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) + + return zero.foo(); +>zero.foo : Symbol(foo, Decl(0.ts, 0, 0)) +>zero : Symbol(zero, Decl(1.ts, 2, 8)) +>foo : Symbol(foo, Decl(0.ts, 0, 0)) + +}); + +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + +function foo() { +>foo : Symbol(foo, Decl(1.ts, 6, 30)) + + const p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) +} + +class C { +>C : Symbol(C, Decl(1.ts, 10, 1)) + + method() { +>method : Symbol(C.method, Decl(1.ts, 12, 9)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 14, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} + +export class D { +>D : Symbol(D, Decl(1.ts, 16, 1)) + + method() { +>method : Symbol(D.method, Decl(1.ts, 18, 16)) + + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(1.ts, 20, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + } +} diff --git a/tests/baselines/reference/importCallExpressionES6UMD.types b/tests/baselines/reference/importCallExpressionES6UMD.types new file mode 100644 index 00000000000..e97f722b14f --- /dev/null +++ b/tests/baselines/reference/importCallExpressionES6UMD.types @@ -0,0 +1,70 @@ +=== tests/cases/conformance/dynamicImport/0.ts === +export function foo() { return "foo"; } +>foo : () => string +>"foo" : "foo" + +=== tests/cases/conformance/dynamicImport/1.ts === +import("./0"); +>import("./0") : Promise +>"./0" : "./0" + +var p1 = import("./0"); +>p1 : Promise +>import("./0") : Promise +>"./0" : "./0" + +p1.then(zero => { +>p1.then(zero => { return zero.foo();}) : Promise +>p1.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>p1 : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>zero => { return zero.foo();} : (zero: typeof "tests/cases/conformance/dynamicImport/0") => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" + + return zero.foo(); +>zero.foo() : string +>zero.foo : () => string +>zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + +}); + +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + +function foo() { +>foo : () => void + + const p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" +} + +class C { +>C : C + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} + +export class D { +>D : D + + method() { +>method : () => void + + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + } +} diff --git a/tests/baselines/reference/importCallExpressionInAMD1.js b/tests/baselines/reference/importCallExpressionInAMD1.js index e1758173646..5c858160353 100644 --- a/tests/baselines/reference/importCallExpressionInAMD1.js +++ b/tests/baselines/reference/importCallExpressionInAMD1.js @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } @@ -24,12 +26,14 @@ define(["require", "exports"], function (require, exports) { //// [1.js] define(["require", "exports"], function (require, exports) { "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); var p1 = new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); p1.then(zero => { return zero.foo(); }); + exports.p2 = new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); function foo() { - const p2 = new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); + const p2 = new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); } }); diff --git a/tests/baselines/reference/importCallExpressionInAMD1.symbols b/tests/baselines/reference/importCallExpressionInAMD1.symbols index a1a506e7005..839f7d0d6da 100644 --- a/tests/baselines/reference/importCallExpressionInAMD1.symbols +++ b/tests/baselines/reference/importCallExpressionInAMD1.symbols @@ -23,10 +23,14 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } diff --git a/tests/baselines/reference/importCallExpressionInAMD1.types b/tests/baselines/reference/importCallExpressionInAMD1.types index 59da055ee01..661d27d1469 100644 --- a/tests/baselines/reference/importCallExpressionInAMD1.types +++ b/tests/baselines/reference/importCallExpressionInAMD1.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void diff --git a/tests/baselines/reference/importCallExpressionInAMD4.js b/tests/baselines/reference/importCallExpressionInAMD4.js index 6e50e139116..43ba5afcd30 100644 --- a/tests/baselines/reference/importCallExpressionInAMD4.js +++ b/tests/baselines/reference/importCallExpressionInAMD4.js @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { @@ -46,18 +61,36 @@ define(["require", "exports"], function (require, exports) { //// [2.js] define(["require", "exports"], function (require, exports) { "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); class C { constructor() { this.myModule = new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); } method() { + const loadAsync = new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); this.myModule.then(Zero => { console.log(Zero.foo()); }, async (err) => { console.log(err); - let one = await new Promise(function (resolve_2, reject_2) { require(["./1"], resolve_2, reject_2); }); + let one = await new Promise(function (resolve_3, reject_3) { require(["./1"], resolve_3, reject_3); }); console.log(one.backup()); }); } } + class D { + constructor() { + this.myModule = new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); + } + method() { + const loadAsync = new Promise(function (resolve_5, reject_5) { require(["./0"], resolve_5, reject_5); }); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async (err) => { + console.log(err); + let one = await new Promise(function (resolve_6, reject_6) { require(["./1"], resolve_6, reject_6); }); + console.log(one.backup()); + }); + } + } + exports.D = D; }); diff --git a/tests/baselines/reference/importCallExpressionInAMD4.symbols b/tests/baselines/reference/importCallExpressionInAMD4.symbols index b02646d5e3d..c4de50e5bc4 100644 --- a/tests/baselines/reference/importCallExpressionInAMD4.symbols +++ b/tests/baselines/reference/importCallExpressionInAMD4.symbols @@ -27,35 +27,88 @@ class C { method() { >method : Symbol(C.method, Decl(2.ts, 2, 37)) + const loadAsync = import("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 4, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + this.myModule.then(Zero => { >this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) >this.myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >this : Symbol(C, Decl(2.ts, 0, 25)) >myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) console.log(Zero.foo()); >console : Symbol(console, Decl(2.ts, 0, 11)) >Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) >foo : Symbol(foo, Decl(0.ts, 2, 1)) }, async err => { ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) console.log(err); >console : Symbol(console, Decl(2.ts, 0, 11)) ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) let one = await import("./1"); ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) >"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) console.log(one.backup()); >console : Symbol(console, Decl(2.ts, 0, 11)) >one.backup : Symbol(backup, Decl(1.ts, 0, 0)) ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) +>backup : Symbol(backup, Decl(1.ts, 0, 0)) + + }); + } +} + +export class D { +>D : Symbol(D, Decl(2.ts, 13, 1)) + + private myModule = import("./0"); +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + method() { +>method : Symbol(D.method, Decl(2.ts, 16, 37)) + + const loadAsync = import("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 18, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + this.myModule.then(Zero => { +>this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>this.myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>this : Symbol(D, Decl(2.ts, 13, 1)) +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) + + console.log(Zero.foo()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) +>foo : Symbol(foo, Decl(0.ts, 2, 1)) + + }, async err => { +>err : Symbol(err, Decl(2.ts, 21, 16)) + + console.log(err); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>err : Symbol(err, Decl(2.ts, 21, 16)) + + let one = await import("./1"); +>one : Symbol(one, Decl(2.ts, 23, 15)) +>"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) + + console.log(one.backup()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>one.backup : Symbol(backup, Decl(1.ts, 0, 0)) +>one : Symbol(one, Decl(2.ts, 23, 15)) >backup : Symbol(backup, Decl(1.ts, 0, 0)) }); diff --git a/tests/baselines/reference/importCallExpressionInAMD4.types b/tests/baselines/reference/importCallExpressionInAMD4.types index 2ea666ba672..156247851c9 100644 --- a/tests/baselines/reference/importCallExpressionInAMD4.types +++ b/tests/baselines/reference/importCallExpressionInAMD4.types @@ -31,6 +31,78 @@ class C { method() { >method : () => void + const loadAsync = import("./0"); +>loadAsync : Promise +>import("./0") : Promise +>"./0" : "./0" + + this.myModule.then(Zero => { +>this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise +>this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>this.myModule : Promise +>this : this +>myModule : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>Zero => { console.log(Zero.foo()); } : (Zero: typeof "tests/cases/conformance/dynamicImport/0") => void +>Zero : typeof "tests/cases/conformance/dynamicImport/0" + + console.log(Zero.foo()); +>console.log(Zero.foo()) : any +>console.log : any +>console : any +>log : any +>Zero.foo() : string +>Zero.foo : () => string +>Zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + + }, async err => { +>async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); } : (err: any) => Promise +>err : any + + console.log(err); +>console.log(err) : any +>console.log : any +>console : any +>log : any +>err : any + + let one = await import("./1"); +>one : typeof "tests/cases/conformance/dynamicImport/1" +>await import("./1") : typeof "tests/cases/conformance/dynamicImport/1" +>import("./1") : Promise +>"./1" : "./1" + + console.log(one.backup()); +>console.log(one.backup()) : any +>console.log : any +>console : any +>log : any +>one.backup() : string +>one.backup : () => string +>one : typeof "tests/cases/conformance/dynamicImport/1" +>backup : () => string + + }); + } +} + +export class D { +>D : D + + private myModule = import("./0"); +>myModule : Promise +>import("./0") : Promise +>"./0" : "./0" + + method() { +>method : () => void + + const loadAsync = import("./0"); +>loadAsync : Promise +>import("./0") : Promise +>"./0" : "./0" + this.myModule.then(Zero => { >this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise >this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise diff --git a/tests/baselines/reference/importCallExpressionInCJS1.js b/tests/baselines/reference/importCallExpressionInCJS1.js index 3fb298b5bde..359e743144b 100644 --- a/tests/baselines/reference/importCallExpressionInCJS1.js +++ b/tests/baselines/reference/importCallExpressionInCJS1.js @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } @@ -20,11 +22,14 @@ Object.defineProperty(exports, "__esModule", { value: true }); function foo() { return "foo"; } exports.foo = foo; //// [1.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); Promise.resolve().then(function () { return require("./0"); }); var p1 = Promise.resolve().then(function () { return require("./0"); }); p1.then(zero => { return zero.foo(); }); +exports.p2 = Promise.resolve().then(function () { return require("./0"); }); function foo() { const p2 = Promise.resolve().then(function () { return require("./0"); }); } diff --git a/tests/baselines/reference/importCallExpressionInCJS1.symbols b/tests/baselines/reference/importCallExpressionInCJS1.symbols index a1a506e7005..839f7d0d6da 100644 --- a/tests/baselines/reference/importCallExpressionInCJS1.symbols +++ b/tests/baselines/reference/importCallExpressionInCJS1.symbols @@ -23,10 +23,14 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } diff --git a/tests/baselines/reference/importCallExpressionInCJS1.types b/tests/baselines/reference/importCallExpressionInCJS1.types index 59da055ee01..661d27d1469 100644 --- a/tests/baselines/reference/importCallExpressionInCJS1.types +++ b/tests/baselines/reference/importCallExpressionInCJS1.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void diff --git a/tests/baselines/reference/importCallExpressionInCJS5.js b/tests/baselines/reference/importCallExpressionInCJS5.js index 762da592827..eeb4db275fa 100644 --- a/tests/baselines/reference/importCallExpressionInCJS5.js +++ b/tests/baselines/reference/importCallExpressionInCJS5.js @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import ("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { @@ -40,11 +55,14 @@ Object.defineProperty(exports, "__esModule", { value: true }); function backup() { return "backup"; } exports.backup = backup; //// [2.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); class C { constructor() { this.myModule = Promise.resolve().then(function () { return require("./0"); }); } method() { + const loadAsync = Promise.resolve().then(function () { return require("./0"); }); this.myModule.then(Zero => { console.log(Zero.foo()); }, async (err) => { @@ -54,3 +72,19 @@ class C { }); } } +class D { + constructor() { + this.myModule = Promise.resolve().then(function () { return require("./0"); }); + } + method() { + const loadAsync = Promise.resolve().then(function () { return require("./0"); }); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async (err) => { + console.log(err); + let one = await Promise.resolve().then(function () { return require("./1"); }); + console.log(one.backup()); + }); + } +} +exports.D = D; diff --git a/tests/baselines/reference/importCallExpressionInCJS5.symbols b/tests/baselines/reference/importCallExpressionInCJS5.symbols index b02646d5e3d..ed4baf00fe8 100644 --- a/tests/baselines/reference/importCallExpressionInCJS5.symbols +++ b/tests/baselines/reference/importCallExpressionInCJS5.symbols @@ -27,35 +27,88 @@ class C { method() { >method : Symbol(C.method, Decl(2.ts, 2, 37)) + const loadAsync = import ("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 4, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + this.myModule.then(Zero => { >this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) >this.myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >this : Symbol(C, Decl(2.ts, 0, 25)) >myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) console.log(Zero.foo()); >console : Symbol(console, Decl(2.ts, 0, 11)) >Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) >foo : Symbol(foo, Decl(0.ts, 2, 1)) }, async err => { ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) console.log(err); >console : Symbol(console, Decl(2.ts, 0, 11)) ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) let one = await import("./1"); ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) >"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) console.log(one.backup()); >console : Symbol(console, Decl(2.ts, 0, 11)) >one.backup : Symbol(backup, Decl(1.ts, 0, 0)) ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) +>backup : Symbol(backup, Decl(1.ts, 0, 0)) + + }); + } +} + +export class D { +>D : Symbol(D, Decl(2.ts, 13, 1)) + + private myModule = import("./0"); +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + method() { +>method : Symbol(D.method, Decl(2.ts, 16, 37)) + + const loadAsync = import("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 18, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + this.myModule.then(Zero => { +>this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>this.myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>this : Symbol(D, Decl(2.ts, 13, 1)) +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) + + console.log(Zero.foo()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) +>foo : Symbol(foo, Decl(0.ts, 2, 1)) + + }, async err => { +>err : Symbol(err, Decl(2.ts, 21, 16)) + + console.log(err); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>err : Symbol(err, Decl(2.ts, 21, 16)) + + let one = await import("./1"); +>one : Symbol(one, Decl(2.ts, 23, 15)) +>"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) + + console.log(one.backup()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>one.backup : Symbol(backup, Decl(1.ts, 0, 0)) +>one : Symbol(one, Decl(2.ts, 23, 15)) >backup : Symbol(backup, Decl(1.ts, 0, 0)) }); diff --git a/tests/baselines/reference/importCallExpressionInCJS5.types b/tests/baselines/reference/importCallExpressionInCJS5.types index 2ea666ba672..7d0c6f01cac 100644 --- a/tests/baselines/reference/importCallExpressionInCJS5.types +++ b/tests/baselines/reference/importCallExpressionInCJS5.types @@ -31,6 +31,78 @@ class C { method() { >method : () => void + const loadAsync = import ("./0"); +>loadAsync : Promise +>import ("./0") : Promise +>"./0" : "./0" + + this.myModule.then(Zero => { +>this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise +>this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>this.myModule : Promise +>this : this +>myModule : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>Zero => { console.log(Zero.foo()); } : (Zero: typeof "tests/cases/conformance/dynamicImport/0") => void +>Zero : typeof "tests/cases/conformance/dynamicImport/0" + + console.log(Zero.foo()); +>console.log(Zero.foo()) : any +>console.log : any +>console : any +>log : any +>Zero.foo() : string +>Zero.foo : () => string +>Zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + + }, async err => { +>async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); } : (err: any) => Promise +>err : any + + console.log(err); +>console.log(err) : any +>console.log : any +>console : any +>log : any +>err : any + + let one = await import("./1"); +>one : typeof "tests/cases/conformance/dynamicImport/1" +>await import("./1") : typeof "tests/cases/conformance/dynamicImport/1" +>import("./1") : Promise +>"./1" : "./1" + + console.log(one.backup()); +>console.log(one.backup()) : any +>console.log : any +>console : any +>log : any +>one.backup() : string +>one.backup : () => string +>one : typeof "tests/cases/conformance/dynamicImport/1" +>backup : () => string + + }); + } +} + +export class D { +>D : D + + private myModule = import("./0"); +>myModule : Promise +>import("./0") : Promise +>"./0" : "./0" + + method() { +>method : () => void + + const loadAsync = import("./0"); +>loadAsync : Promise +>import("./0") : Promise +>"./0" : "./0" + this.myModule.then(Zero => { >this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise >this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise diff --git a/tests/baselines/reference/importCallExpressionInSystem1.js b/tests/baselines/reference/importCallExpressionInSystem1.js index d74eb6ffc76..74df68fc9a1 100644 --- a/tests/baselines/reference/importCallExpressionInSystem1.js +++ b/tests/baselines/reference/importCallExpressionInSystem1.js @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } @@ -28,11 +30,12 @@ System.register([], function (exports_1, context_1) { }); //// [1.js] System.register([], function (exports_1, context_1) { + "use strict"; var __moduleName = context_1 && context_1.id; function foo() { const p2 = context_1.import("./0"); } - var p1; + var p1, p2; return { setters: [], execute: function () { @@ -41,6 +44,7 @@ System.register([], function (exports_1, context_1) { p1.then(zero => { return zero.foo(); }); + exports_1("p2", p2 = context_1.import("./0")); } }; }); diff --git a/tests/baselines/reference/importCallExpressionInSystem1.symbols b/tests/baselines/reference/importCallExpressionInSystem1.symbols index a1a506e7005..839f7d0d6da 100644 --- a/tests/baselines/reference/importCallExpressionInSystem1.symbols +++ b/tests/baselines/reference/importCallExpressionInSystem1.symbols @@ -23,10 +23,14 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } diff --git a/tests/baselines/reference/importCallExpressionInSystem1.types b/tests/baselines/reference/importCallExpressionInSystem1.types index 59da055ee01..661d27d1469 100644 --- a/tests/baselines/reference/importCallExpressionInSystem1.types +++ b/tests/baselines/reference/importCallExpressionInSystem1.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void diff --git a/tests/baselines/reference/importCallExpressionInSystem4.js b/tests/baselines/reference/importCallExpressionInSystem4.js index ac01a0439e8..b7bc1f51fe5 100644 --- a/tests/baselines/reference/importCallExpressionInSystem4.js +++ b/tests/baselines/reference/importCallExpressionInSystem4.js @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { @@ -56,8 +71,9 @@ System.register([], function (exports_1, context_1) { }); //// [2.js] System.register([], function (exports_1, context_1) { + "use strict"; var __moduleName = context_1 && context_1.id; - var C; + var C, D; return { setters: [], execute: function () { @@ -66,6 +82,7 @@ System.register([], function (exports_1, context_1) { this.myModule = context_1.import("./0"); } method() { + const loadAsync = context_1.import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async (err) => { @@ -75,6 +92,22 @@ System.register([], function (exports_1, context_1) { }); } }; + D = class D { + constructor() { + this.myModule = context_1.import("./0"); + } + method() { + const loadAsync = context_1.import("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async (err) => { + console.log(err); + let one = await context_1.import("./1"); + console.log(one.backup()); + }); + } + }; + exports_1("D", D); } }; }); diff --git a/tests/baselines/reference/importCallExpressionInSystem4.symbols b/tests/baselines/reference/importCallExpressionInSystem4.symbols index b02646d5e3d..c4de50e5bc4 100644 --- a/tests/baselines/reference/importCallExpressionInSystem4.symbols +++ b/tests/baselines/reference/importCallExpressionInSystem4.symbols @@ -27,35 +27,88 @@ class C { method() { >method : Symbol(C.method, Decl(2.ts, 2, 37)) + const loadAsync = import("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 4, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + this.myModule.then(Zero => { >this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) >this.myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >this : Symbol(C, Decl(2.ts, 0, 25)) >myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) console.log(Zero.foo()); >console : Symbol(console, Decl(2.ts, 0, 11)) >Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) >foo : Symbol(foo, Decl(0.ts, 2, 1)) }, async err => { ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) console.log(err); >console : Symbol(console, Decl(2.ts, 0, 11)) ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) let one = await import("./1"); ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) >"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) console.log(one.backup()); >console : Symbol(console, Decl(2.ts, 0, 11)) >one.backup : Symbol(backup, Decl(1.ts, 0, 0)) ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) +>backup : Symbol(backup, Decl(1.ts, 0, 0)) + + }); + } +} + +export class D { +>D : Symbol(D, Decl(2.ts, 13, 1)) + + private myModule = import("./0"); +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + method() { +>method : Symbol(D.method, Decl(2.ts, 16, 37)) + + const loadAsync = import("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 18, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + this.myModule.then(Zero => { +>this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>this.myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>this : Symbol(D, Decl(2.ts, 13, 1)) +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) + + console.log(Zero.foo()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) +>foo : Symbol(foo, Decl(0.ts, 2, 1)) + + }, async err => { +>err : Symbol(err, Decl(2.ts, 21, 16)) + + console.log(err); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>err : Symbol(err, Decl(2.ts, 21, 16)) + + let one = await import("./1"); +>one : Symbol(one, Decl(2.ts, 23, 15)) +>"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) + + console.log(one.backup()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>one.backup : Symbol(backup, Decl(1.ts, 0, 0)) +>one : Symbol(one, Decl(2.ts, 23, 15)) >backup : Symbol(backup, Decl(1.ts, 0, 0)) }); diff --git a/tests/baselines/reference/importCallExpressionInSystem4.types b/tests/baselines/reference/importCallExpressionInSystem4.types index 2ea666ba672..156247851c9 100644 --- a/tests/baselines/reference/importCallExpressionInSystem4.types +++ b/tests/baselines/reference/importCallExpressionInSystem4.types @@ -31,6 +31,78 @@ class C { method() { >method : () => void + const loadAsync = import("./0"); +>loadAsync : Promise +>import("./0") : Promise +>"./0" : "./0" + + this.myModule.then(Zero => { +>this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise +>this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>this.myModule : Promise +>this : this +>myModule : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>Zero => { console.log(Zero.foo()); } : (Zero: typeof "tests/cases/conformance/dynamicImport/0") => void +>Zero : typeof "tests/cases/conformance/dynamicImport/0" + + console.log(Zero.foo()); +>console.log(Zero.foo()) : any +>console.log : any +>console : any +>log : any +>Zero.foo() : string +>Zero.foo : () => string +>Zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + + }, async err => { +>async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); } : (err: any) => Promise +>err : any + + console.log(err); +>console.log(err) : any +>console.log : any +>console : any +>log : any +>err : any + + let one = await import("./1"); +>one : typeof "tests/cases/conformance/dynamicImport/1" +>await import("./1") : typeof "tests/cases/conformance/dynamicImport/1" +>import("./1") : Promise +>"./1" : "./1" + + console.log(one.backup()); +>console.log(one.backup()) : any +>console.log : any +>console : any +>log : any +>one.backup() : string +>one.backup : () => string +>one : typeof "tests/cases/conformance/dynamicImport/1" +>backup : () => string + + }); + } +} + +export class D { +>D : D + + private myModule = import("./0"); +>myModule : Promise +>import("./0") : Promise +>"./0" : "./0" + + method() { +>method : () => void + + const loadAsync = import("./0"); +>loadAsync : Promise +>import("./0") : Promise +>"./0" : "./0" + this.myModule.then(Zero => { >this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise >this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise diff --git a/tests/baselines/reference/importCallExpressionInUMD1.js b/tests/baselines/reference/importCallExpressionInUMD1.js index f1bfcd3cc71..ee99468f7f3 100644 --- a/tests/baselines/reference/importCallExpressionInUMD1.js +++ b/tests/baselines/reference/importCallExpressionInUMD1.js @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } @@ -41,12 +43,14 @@ function foo() { })(function (require, exports) { "use strict"; var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + Object.defineProperty(exports, "__esModule", { value: true }); __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); var p1 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); p1.then(zero => { return zero.foo(); }); + exports.p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); function foo() { - const p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_3, reject_3) { require(["./0"], resolve_3, reject_3); }); + const p2 = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); } }); diff --git a/tests/baselines/reference/importCallExpressionInUMD1.symbols b/tests/baselines/reference/importCallExpressionInUMD1.symbols index a1a506e7005..839f7d0d6da 100644 --- a/tests/baselines/reference/importCallExpressionInUMD1.symbols +++ b/tests/baselines/reference/importCallExpressionInUMD1.symbols @@ -23,10 +23,14 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Symbol(p2, Decl(1.ts, 6, 10)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + function foo() { ->foo : Symbol(foo, Decl(1.ts, 4, 3)) +>foo : Symbol(foo, Decl(1.ts, 6, 30)) const p2 = import("./0"); ->p2 : Symbol(p2, Decl(1.ts, 7, 9)) +>p2 : Symbol(p2, Decl(1.ts, 9, 9)) >"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) } diff --git a/tests/baselines/reference/importCallExpressionInUMD1.types b/tests/baselines/reference/importCallExpressionInUMD1.types index 59da055ee01..661d27d1469 100644 --- a/tests/baselines/reference/importCallExpressionInUMD1.types +++ b/tests/baselines/reference/importCallExpressionInUMD1.types @@ -29,6 +29,11 @@ p1.then(zero => { }); +export var p2 = import("./0"); +>p2 : Promise +>import("./0") : Promise +>"./0" : "./0" + function foo() { >foo : () => void diff --git a/tests/baselines/reference/importCallExpressionInUMD4.js b/tests/baselines/reference/importCallExpressionInUMD4.js index 47ba83b1718..477a7826bc0 100644 --- a/tests/baselines/reference/importCallExpressionInUMD4.js +++ b/tests/baselines/reference/importCallExpressionInUMD4.js @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { @@ -71,18 +86,36 @@ class C { })(function (require, exports) { "use strict"; var __syncRequire = typeof module === "object" && typeof module.exports === "object"; + Object.defineProperty(exports, "__esModule", { value: true }); class C { constructor() { this.myModule = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_1, reject_1) { require(["./0"], resolve_1, reject_1); }); } method() { + const loadAsync = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_2, reject_2) { require(["./0"], resolve_2, reject_2); }); this.myModule.then(Zero => { console.log(Zero.foo()); }, async (err) => { console.log(err); - let one = await (__syncRequire ? Promise.resolve().then(function () { return require("./1"); }) : new Promise(function (resolve_2, reject_2) { require(["./1"], resolve_2, reject_2); })); + let one = await (__syncRequire ? Promise.resolve().then(function () { return require("./1"); }) : new Promise(function (resolve_3, reject_3) { require(["./1"], resolve_3, reject_3); })); console.log(one.backup()); }); } } + class D { + constructor() { + this.myModule = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_4, reject_4) { require(["./0"], resolve_4, reject_4); }); + } + method() { + const loadAsync = __syncRequire ? Promise.resolve().then(function () { return require("./0"); }) : new Promise(function (resolve_5, reject_5) { require(["./0"], resolve_5, reject_5); }); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async (err) => { + console.log(err); + let one = await (__syncRequire ? Promise.resolve().then(function () { return require("./1"); }) : new Promise(function (resolve_6, reject_6) { require(["./1"], resolve_6, reject_6); })); + console.log(one.backup()); + }); + } + } + exports.D = D; }); diff --git a/tests/baselines/reference/importCallExpressionInUMD4.symbols b/tests/baselines/reference/importCallExpressionInUMD4.symbols index b02646d5e3d..c4de50e5bc4 100644 --- a/tests/baselines/reference/importCallExpressionInUMD4.symbols +++ b/tests/baselines/reference/importCallExpressionInUMD4.symbols @@ -27,35 +27,88 @@ class C { method() { >method : Symbol(C.method, Decl(2.ts, 2, 37)) + const loadAsync = import("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 4, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + this.myModule.then(Zero => { >this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) >this.myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >this : Symbol(C, Decl(2.ts, 0, 25)) >myModule : Symbol(C.myModule, Decl(2.ts, 1, 9)) >then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) console.log(Zero.foo()); >console : Symbol(console, Decl(2.ts, 0, 11)) >Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) ->Zero : Symbol(Zero, Decl(2.ts, 4, 27)) +>Zero : Symbol(Zero, Decl(2.ts, 5, 27)) >foo : Symbol(foo, Decl(0.ts, 2, 1)) }, async err => { ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) console.log(err); >console : Symbol(console, Decl(2.ts, 0, 11)) ->err : Symbol(err, Decl(2.ts, 6, 16)) +>err : Symbol(err, Decl(2.ts, 7, 16)) let one = await import("./1"); ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) >"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) console.log(one.backup()); >console : Symbol(console, Decl(2.ts, 0, 11)) >one.backup : Symbol(backup, Decl(1.ts, 0, 0)) ->one : Symbol(one, Decl(2.ts, 8, 15)) +>one : Symbol(one, Decl(2.ts, 9, 15)) +>backup : Symbol(backup, Decl(1.ts, 0, 0)) + + }); + } +} + +export class D { +>D : Symbol(D, Decl(2.ts, 13, 1)) + + private myModule = import("./0"); +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + method() { +>method : Symbol(D.method, Decl(2.ts, 16, 37)) + + const loadAsync = import("./0"); +>loadAsync : Symbol(loadAsync, Decl(2.ts, 18, 13)) +>"./0" : Symbol("tests/cases/conformance/dynamicImport/0", Decl(0.ts, 0, 0)) + + this.myModule.then(Zero => { +>this.myModule.then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>this.myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>this : Symbol(D, Decl(2.ts, 13, 1)) +>myModule : Symbol(D.myModule, Decl(2.ts, 15, 16)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) + + console.log(Zero.foo()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>Zero.foo : Symbol(foo, Decl(0.ts, 2, 1)) +>Zero : Symbol(Zero, Decl(2.ts, 19, 27)) +>foo : Symbol(foo, Decl(0.ts, 2, 1)) + + }, async err => { +>err : Symbol(err, Decl(2.ts, 21, 16)) + + console.log(err); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>err : Symbol(err, Decl(2.ts, 21, 16)) + + let one = await import("./1"); +>one : Symbol(one, Decl(2.ts, 23, 15)) +>"./1" : Symbol("tests/cases/conformance/dynamicImport/1", Decl(1.ts, 0, 0)) + + console.log(one.backup()); +>console : Symbol(console, Decl(2.ts, 0, 11)) +>one.backup : Symbol(backup, Decl(1.ts, 0, 0)) +>one : Symbol(one, Decl(2.ts, 23, 15)) >backup : Symbol(backup, Decl(1.ts, 0, 0)) }); diff --git a/tests/baselines/reference/importCallExpressionInUMD4.types b/tests/baselines/reference/importCallExpressionInUMD4.types index 2ea666ba672..156247851c9 100644 --- a/tests/baselines/reference/importCallExpressionInUMD4.types +++ b/tests/baselines/reference/importCallExpressionInUMD4.types @@ -31,6 +31,78 @@ class C { method() { >method : () => void + const loadAsync = import("./0"); +>loadAsync : Promise +>import("./0") : Promise +>"./0" : "./0" + + this.myModule.then(Zero => { +>this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise +>this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>this.myModule : Promise +>this : this +>myModule : Promise +>then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>Zero => { console.log(Zero.foo()); } : (Zero: typeof "tests/cases/conformance/dynamicImport/0") => void +>Zero : typeof "tests/cases/conformance/dynamicImport/0" + + console.log(Zero.foo()); +>console.log(Zero.foo()) : any +>console.log : any +>console : any +>log : any +>Zero.foo() : string +>Zero.foo : () => string +>Zero : typeof "tests/cases/conformance/dynamicImport/0" +>foo : () => string + + }, async err => { +>async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); } : (err: any) => Promise +>err : any + + console.log(err); +>console.log(err) : any +>console.log : any +>console : any +>log : any +>err : any + + let one = await import("./1"); +>one : typeof "tests/cases/conformance/dynamicImport/1" +>await import("./1") : typeof "tests/cases/conformance/dynamicImport/1" +>import("./1") : Promise +>"./1" : "./1" + + console.log(one.backup()); +>console.log(one.backup()) : any +>console.log : any +>console : any +>log : any +>one.backup() : string +>one.backup : () => string +>one : typeof "tests/cases/conformance/dynamicImport/1" +>backup : () => string + + }); + } +} + +export class D { +>D : D + + private myModule = import("./0"); +>myModule : Promise +>import("./0") : Promise +>"./0" : "./0" + + method() { +>method : () => void + + const loadAsync = import("./0"); +>loadAsync : Promise +>import("./0") : Promise +>"./0" : "./0" + this.myModule.then(Zero => { >this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { console.log(err); let one = await import("./1"); console.log(one.backup()); }) : Promise >this.myModule.then : (onfulfilled?: (value: typeof "tests/cases/conformance/dynamicImport/0") => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise diff --git a/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.errors.txt b/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.errors.txt index cf665dda049..b422869ff21 100644 --- a/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.errors.txt +++ b/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.errors.txt @@ -1,7 +1,8 @@ error TS2468: Cannot find global value 'Promise'. tests/cases/conformance/dynamicImport/2.ts(3,24): error TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. -tests/cases/conformance/dynamicImport/2.ts(7,12): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. -tests/cases/conformance/dynamicImport/2.ts(9,29): error TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. +tests/cases/conformance/dynamicImport/2.ts(5,27): error TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. +tests/cases/conformance/dynamicImport/2.ts(8,12): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. +tests/cases/conformance/dynamicImport/2.ts(10,29): error TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. !!! error TS2468: Cannot find global value 'Promise'. @@ -15,13 +16,16 @@ tests/cases/conformance/dynamicImport/2.ts(9,29): error TS2712: A dynamic import ==== tests/cases/conformance/dynamicImport/1.ts (0 errors) ==== export function backup() { return "backup"; } -==== tests/cases/conformance/dynamicImport/2.ts (3 errors) ==== +==== tests/cases/conformance/dynamicImport/2.ts (4 errors) ==== declare var console: any; class C { private myModule = import("./0"); ~~~~~~~~~~~~~ !!! error TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. method() { + const loadAsync = import("./0"); + ~~~~~~~~~~~~~ +!!! error TS2712: A dynamic import call in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option. this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { diff --git a/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js b/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js index 487d4e03a6c..598056a32c6 100644 --- a/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js +++ b/tests/baselines/reference/importCallExpressionNoModuleKindSpecified.js @@ -15,6 +15,7 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { @@ -84,6 +85,7 @@ var C = (function () { } C.prototype.method = function () { var _this = this; + var loadAsync = Promise.resolve().then(function () { return require("./0"); }); this.myModule.then(function (Zero) { console.log(Zero.foo()); }, function (err) { return __awaiter(_this, void 0, void 0, function () { diff --git a/tests/baselines/reference/importCallExpressionWithTypeArgument.errors.txt b/tests/baselines/reference/importCallExpressionWithTypeArgument.errors.txt index 8adf2789585..34c423a0d2f 100644 --- a/tests/baselines/reference/importCallExpressionWithTypeArgument.errors.txt +++ b/tests/baselines/reference/importCallExpressionWithTypeArgument.errors.txt @@ -12,7 +12,4 @@ tests/cases/conformance/dynamicImport/1.ts(3,10): error TS1326: Dynamic import c !!! error TS1326: Dynamic import cannot have type arguments var p2 = import<>("./0"); // error ~~~~~~~~~~~~~~~ -!!! error TS1326: Dynamic import cannot have type arguments - // p1.then(value => { - // value.anyFunction(); - // }) \ No newline at end of file +!!! error TS1326: Dynamic import cannot have type arguments \ No newline at end of file diff --git a/tests/baselines/reference/importCallExpressionWithTypeArgument.js b/tests/baselines/reference/importCallExpressionWithTypeArgument.js index cdea13b2fac..2915669eae5 100644 --- a/tests/baselines/reference/importCallExpressionWithTypeArgument.js +++ b/tests/baselines/reference/importCallExpressionWithTypeArgument.js @@ -6,10 +6,7 @@ export function foo() { return "foo"; } //// [1.ts] "use strict" var p1 = import>("./0"); // error -var p2 = import<>("./0"); // error -// p1.then(value => { -// value.anyFunction(); -// }) +var p2 = import<>("./0"); // error //// [0.js] "use strict"; diff --git a/tests/baselines/reference/jsFileCompilationNonNullAssertion.errors.txt b/tests/baselines/reference/jsFileCompilationNonNullAssertion.errors.txt new file mode 100644 index 00000000000..13670601f70 --- /dev/null +++ b/tests/baselines/reference/jsFileCompilationNonNullAssertion.errors.txt @@ -0,0 +1,8 @@ +/src/a.js(1,1): error TS8013: 'non-null assertions' can only be used in a .ts file. + + +==== /src/a.js (1 errors) ==== + 0! + ~~ +!!! error TS8013: 'non-null assertions' can only be used in a .ts file. + \ No newline at end of file diff --git a/tests/baselines/reference/jsFileCompilationNonNullAssertion.js b/tests/baselines/reference/jsFileCompilationNonNullAssertion.js new file mode 100644 index 00000000000..3790ff66c17 --- /dev/null +++ b/tests/baselines/reference/jsFileCompilationNonNullAssertion.js @@ -0,0 +1,6 @@ +//// [a.js] +0! + + +//// [a.js] +0; diff --git a/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt b/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt index 3ec792c79fe..13fbe712dba 100644 --- a/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt +++ b/tests/baselines/reference/jsFileCompilationTypeAssertions.errors.txt @@ -1,14 +1,15 @@ -error TS5055: Cannot write file 'tests/cases/compiler/a.js' because it would overwrite input file. - Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig. -tests/cases/compiler/a.js(1,10): error TS17008: JSX element 'string' has no corresponding closing tag. -tests/cases/compiler/a.js(1,27): error TS1005: 'undefined; ~~~~~~ !!! error TS17008: JSX element 'string' has no corresponding closing tag. - + + !!! error TS1005: 'undefined; + + +//// [a.js] +0; +var v = undefined; +; diff --git a/tests/baselines/reference/jsdocParamTagTypeLiteral.symbols b/tests/baselines/reference/jsdocParamTagTypeLiteral.symbols new file mode 100644 index 00000000000..8005be7cec7 --- /dev/null +++ b/tests/baselines/reference/jsdocParamTagTypeLiteral.symbols @@ -0,0 +1,132 @@ +=== tests/cases/conformance/jsdoc/0.js === +/** + * @param {Object} notSpecial + * @param {string} unrelated - not actually related because it's not notSpecial.unrelated + */ +function normal(notSpecial) { +>normal : Symbol(normal, Decl(0.js, 0, 0)) +>notSpecial : Symbol(notSpecial, Decl(0.js, 4, 16)) + + notSpecial; // should just be 'any' +>notSpecial : Symbol(notSpecial, Decl(0.js, 4, 16)) +} +normal(12); +>normal : Symbol(normal, Decl(0.js, 0, 0)) + +/** + * @param {Object} opts1 doc1 + * @param {string} opts1.x doc2 + * @param {string=} opts1.y doc3 + * @param {string} [opts1.z] doc4 + * @param {string} [opts1.w="hi"] doc5 + */ +function foo1(opts1) { +>foo1 : Symbol(foo1, Decl(0.js, 7, 11)) +>opts1 : Symbol(opts1, Decl(0.js, 16, 14)) + + opts1.x; +>opts1.x : Symbol(x, Decl(0.js, 11, 3)) +>opts1 : Symbol(opts1, Decl(0.js, 16, 14)) +>x : Symbol(x, Decl(0.js, 11, 3)) +} + +foo1({x: 'abc'}); +>foo1 : Symbol(foo1, Decl(0.js, 7, 11)) +>x : Symbol(x, Decl(0.js, 20, 6)) + +/** + * @param {Object[]} opts2 + * @param {string} opts2[].anotherX + * @param {string=} opts2[].anotherY + */ +function foo2(/** @param opts2 bad idea theatre! */opts2) { +>foo2 : Symbol(foo2, Decl(0.js, 20, 17)) +>opts2 : Symbol(opts2, Decl(0.js, 27, 14)) + + opts2[0].anotherX; +>opts2[0].anotherX : Symbol(anotherX, Decl(0.js, 24, 3)) +>opts2 : Symbol(opts2, Decl(0.js, 27, 14)) +>anotherX : Symbol(anotherX, Decl(0.js, 24, 3)) +} + +foo2([{anotherX: "world"}]); +>foo2 : Symbol(foo2, Decl(0.js, 20, 17)) +>anotherX : Symbol(anotherX, Decl(0.js, 31, 7)) + +/** + * @param {object} opts3 + * @param {string} opts3.x + */ +function foo3(opts3) { +>foo3 : Symbol(foo3, Decl(0.js, 31, 28)) +>opts3 : Symbol(opts3, Decl(0.js, 37, 14)) + + opts3.x; +>opts3.x : Symbol(x, Decl(0.js, 35, 3)) +>opts3 : Symbol(opts3, Decl(0.js, 37, 14)) +>x : Symbol(x, Decl(0.js, 35, 3)) +} +foo3({x: 'abc'}); +>foo3 : Symbol(foo3, Decl(0.js, 31, 28)) +>x : Symbol(x, Decl(0.js, 40, 6)) + +/** + * @param {object[]} opts4 + * @param {string} opts4[].x + * @param {string=} opts4[].y + * @param {string} [opts4[].z] + * @param {string} [opts4[].w="hi"] + */ +function foo4(opts4) { +>foo4 : Symbol(foo4, Decl(0.js, 40, 17)) +>opts4 : Symbol(opts4, Decl(0.js, 49, 14)) + + opts4[0].x; +>opts4[0].x : Symbol(x, Decl(0.js, 44, 3)) +>opts4 : Symbol(opts4, Decl(0.js, 49, 14)) +>x : Symbol(x, Decl(0.js, 44, 3)) +} + +foo4([{ x: 'hi' }]); +>foo4 : Symbol(foo4, Decl(0.js, 40, 17)) +>x : Symbol(x, Decl(0.js, 53, 7)) + +/** + * @param {object[]} opts5 - Let's test out some multiple nesting levels + * @param {string} opts5[].help - (This one is just normal) + * @param {object} opts5[].what - Look at us go! Here's the first nest! + * @param {string} opts5[].what.a - (Another normal one) + * @param {Object[]} opts5[].what.bad - Now we're nesting inside a nested type + * @param {string} opts5[].what.bad[].idea - I don't think you can get back out of this level... + * @param {boolean} opts5[].what.bad[].oh - Oh ... that's how you do it. + * @param {number} opts5[].unnest - Here we are almost all the way back at the beginning. + */ +function foo5(opts5) { +>foo5 : Symbol(foo5, Decl(0.js, 53, 20)) +>opts5 : Symbol(opts5, Decl(0.js, 65, 14)) + + opts5[0].what.bad[0].idea; +>opts5[0].what.bad[0].idea : Symbol(idea, Decl(0.js, 61, 3)) +>opts5[0].what.bad : Symbol(bad, Decl(0.js, 60, 3)) +>opts5[0].what : Symbol(what, Decl(0.js, 58, 3)) +>opts5 : Symbol(opts5, Decl(0.js, 65, 14)) +>what : Symbol(what, Decl(0.js, 58, 3)) +>bad : Symbol(bad, Decl(0.js, 60, 3)) +>idea : Symbol(idea, Decl(0.js, 61, 3)) + + opts5[0].unnest; +>opts5[0].unnest : Symbol(unnest, Decl(0.js, 63, 3)) +>opts5 : Symbol(opts5, Decl(0.js, 65, 14)) +>unnest : Symbol(unnest, Decl(0.js, 63, 3)) +} + +foo5([{ help: "help", what: { a: 'a', bad: [{ idea: 'idea', oh: false }] }, unnest: 1 }]); +>foo5 : Symbol(foo5, Decl(0.js, 53, 20)) +>help : Symbol(help, Decl(0.js, 70, 7)) +>what : Symbol(what, Decl(0.js, 70, 21)) +>a : Symbol(a, Decl(0.js, 70, 29)) +>bad : Symbol(bad, Decl(0.js, 70, 37)) +>idea : Symbol(idea, Decl(0.js, 70, 45)) +>oh : Symbol(oh, Decl(0.js, 70, 59)) +>unnest : Symbol(unnest, Decl(0.js, 70, 75)) + diff --git a/tests/baselines/reference/jsdocParamTagTypeLiteral.types b/tests/baselines/reference/jsdocParamTagTypeLiteral.types new file mode 100644 index 00000000000..95adecafc83 --- /dev/null +++ b/tests/baselines/reference/jsdocParamTagTypeLiteral.types @@ -0,0 +1,169 @@ +=== tests/cases/conformance/jsdoc/0.js === +/** + * @param {Object} notSpecial + * @param {string} unrelated - not actually related because it's not notSpecial.unrelated + */ +function normal(notSpecial) { +>normal : (notSpecial: any) => void +>notSpecial : any + + notSpecial; // should just be 'any' +>notSpecial : any +} +normal(12); +>normal(12) : void +>normal : (notSpecial: any) => void +>12 : 12 + +/** + * @param {Object} opts1 doc1 + * @param {string} opts1.x doc2 + * @param {string=} opts1.y doc3 + * @param {string} [opts1.z] doc4 + * @param {string} [opts1.w="hi"] doc5 + */ +function foo1(opts1) { +>foo1 : (opts1: { x: string; y?: string; z?: string; w?: string; }) => void +>opts1 : { x: string; y?: string; z?: string; w?: string; } + + opts1.x; +>opts1.x : string +>opts1 : { x: string; y?: string; z?: string; w?: string; } +>x : string +} + +foo1({x: 'abc'}); +>foo1({x: 'abc'}) : void +>foo1 : (opts1: { x: string; y?: string; z?: string; w?: string; }) => void +>{x: 'abc'} : { x: string; } +>x : string +>'abc' : "abc" + +/** + * @param {Object[]} opts2 + * @param {string} opts2[].anotherX + * @param {string=} opts2[].anotherY + */ +function foo2(/** @param opts2 bad idea theatre! */opts2) { +>foo2 : (opts2: { anotherX: string; anotherY?: string; }[]) => void +>opts2 : { anotherX: string; anotherY?: string; }[] + + opts2[0].anotherX; +>opts2[0].anotherX : string +>opts2[0] : { anotherX: string; anotherY?: string; } +>opts2 : { anotherX: string; anotherY?: string; }[] +>0 : 0 +>anotherX : string +} + +foo2([{anotherX: "world"}]); +>foo2([{anotherX: "world"}]) : void +>foo2 : (opts2: { anotherX: string; anotherY?: string; }[]) => void +>[{anotherX: "world"}] : { anotherX: string; }[] +>{anotherX: "world"} : { anotherX: string; } +>anotherX : string +>"world" : "world" + +/** + * @param {object} opts3 + * @param {string} opts3.x + */ +function foo3(opts3) { +>foo3 : (opts3: { x: string; }) => void +>opts3 : { x: string; } + + opts3.x; +>opts3.x : string +>opts3 : { x: string; } +>x : string +} +foo3({x: 'abc'}); +>foo3({x: 'abc'}) : void +>foo3 : (opts3: { x: string; }) => void +>{x: 'abc'} : { x: string; } +>x : string +>'abc' : "abc" + +/** + * @param {object[]} opts4 + * @param {string} opts4[].x + * @param {string=} opts4[].y + * @param {string} [opts4[].z] + * @param {string} [opts4[].w="hi"] + */ +function foo4(opts4) { +>foo4 : (opts4: { x: string; y?: string; z?: string; w?: string; }[]) => void +>opts4 : { x: string; y?: string; z?: string; w?: string; }[] + + opts4[0].x; +>opts4[0].x : string +>opts4[0] : { x: string; y?: string; z?: string; w?: string; } +>opts4 : { x: string; y?: string; z?: string; w?: string; }[] +>0 : 0 +>x : string +} + +foo4([{ x: 'hi' }]); +>foo4([{ x: 'hi' }]) : void +>foo4 : (opts4: { x: string; y?: string; z?: string; w?: string; }[]) => void +>[{ x: 'hi' }] : { x: string; }[] +>{ x: 'hi' } : { x: string; } +>x : string +>'hi' : "hi" + +/** + * @param {object[]} opts5 - Let's test out some multiple nesting levels + * @param {string} opts5[].help - (This one is just normal) + * @param {object} opts5[].what - Look at us go! Here's the first nest! + * @param {string} opts5[].what.a - (Another normal one) + * @param {Object[]} opts5[].what.bad - Now we're nesting inside a nested type + * @param {string} opts5[].what.bad[].idea - I don't think you can get back out of this level... + * @param {boolean} opts5[].what.bad[].oh - Oh ... that's how you do it. + * @param {number} opts5[].unnest - Here we are almost all the way back at the beginning. + */ +function foo5(opts5) { +>foo5 : (opts5: { help: string; what: { a: string; bad: { idea: string; oh: boolean; }[]; }; unnest: number; }[]) => void +>opts5 : { help: string; what: { a: string; bad: { idea: string; oh: boolean; }[]; }; unnest: number; }[] + + opts5[0].what.bad[0].idea; +>opts5[0].what.bad[0].idea : string +>opts5[0].what.bad[0] : { idea: string; oh: boolean; } +>opts5[0].what.bad : { idea: string; oh: boolean; }[] +>opts5[0].what : { a: string; bad: { idea: string; oh: boolean; }[]; } +>opts5[0] : { help: string; what: { a: string; bad: { idea: string; oh: boolean; }[]; }; unnest: number; } +>opts5 : { help: string; what: { a: string; bad: { idea: string; oh: boolean; }[]; }; unnest: number; }[] +>0 : 0 +>what : { a: string; bad: { idea: string; oh: boolean; }[]; } +>bad : { idea: string; oh: boolean; }[] +>0 : 0 +>idea : string + + opts5[0].unnest; +>opts5[0].unnest : number +>opts5[0] : { help: string; what: { a: string; bad: { idea: string; oh: boolean; }[]; }; unnest: number; } +>opts5 : { help: string; what: { a: string; bad: { idea: string; oh: boolean; }[]; }; unnest: number; }[] +>0 : 0 +>unnest : number +} + +foo5([{ help: "help", what: { a: 'a', bad: [{ idea: 'idea', oh: false }] }, unnest: 1 }]); +>foo5([{ help: "help", what: { a: 'a', bad: [{ idea: 'idea', oh: false }] }, unnest: 1 }]) : void +>foo5 : (opts5: { help: string; what: { a: string; bad: { idea: string; oh: boolean; }[]; }; unnest: number; }[]) => void +>[{ help: "help", what: { a: 'a', bad: [{ idea: 'idea', oh: false }] }, unnest: 1 }] : { help: string; what: { a: string; bad: { idea: string; oh: false; }[]; }; unnest: number; }[] +>{ help: "help", what: { a: 'a', bad: [{ idea: 'idea', oh: false }] }, unnest: 1 } : { help: string; what: { a: string; bad: { idea: string; oh: false; }[]; }; unnest: number; } +>help : string +>"help" : "help" +>what : { a: string; bad: { idea: string; oh: false; }[]; } +>{ a: 'a', bad: [{ idea: 'idea', oh: false }] } : { a: string; bad: { idea: string; oh: false; }[]; } +>a : string +>'a' : "a" +>bad : { idea: string; oh: false; }[] +>[{ idea: 'idea', oh: false }] : { idea: string; oh: false; }[] +>{ idea: 'idea', oh: false } : { idea: string; oh: false; } +>idea : string +>'idea' : "idea" +>oh : boolean +>false : false +>unnest : number +>1 : 1 + diff --git a/tests/baselines/reference/jsdocParameterParsingInfiniteLoop.errors.txt b/tests/baselines/reference/jsdocParameterParsingInfiniteLoop.errors.txt new file mode 100644 index 00000000000..e42d67a62c1 --- /dev/null +++ b/tests/baselines/reference/jsdocParameterParsingInfiniteLoop.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/example.js(3,20): error TS1003: Identifier expected. + + +==== tests/cases/compiler/example.js (1 errors) ==== + // @ts-check + /** + * @type {function(@foo)} + ~ +!!! error TS1003: Identifier expected. + */ + let x; \ No newline at end of file diff --git a/tests/baselines/reference/jsdocTypeGenericInstantiationAttempt.symbols b/tests/baselines/reference/jsdocTypeGenericInstantiationAttempt.symbols new file mode 100644 index 00000000000..1b17b09fce2 --- /dev/null +++ b/tests/baselines/reference/jsdocTypeGenericInstantiationAttempt.symbols @@ -0,0 +1,12 @@ +=== tests/cases/compiler/index.js === +/** + * @param {Array<*>} list + */ +function thing(list) { +>thing : Symbol(thing, Decl(index.js, 0, 0)) +>list : Symbol(list, Decl(index.js, 3, 15)) + + return list; +>list : Symbol(list, Decl(index.js, 3, 15)) +} + diff --git a/tests/baselines/reference/jsdocTypeGenericInstantiationAttempt.types b/tests/baselines/reference/jsdocTypeGenericInstantiationAttempt.types new file mode 100644 index 00000000000..50231c9d868 --- /dev/null +++ b/tests/baselines/reference/jsdocTypeGenericInstantiationAttempt.types @@ -0,0 +1,12 @@ +=== tests/cases/compiler/index.js === +/** + * @param {Array<*>} list + */ +function thing(list) { +>thing : (list: any[]) => any[] +>list : any[] + + return list; +>list : any[] +} + diff --git a/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt b/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt new file mode 100644 index 00000000000..645eca539f4 --- /dev/null +++ b/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt @@ -0,0 +1,97 @@ +tests/cases/compiler/index.js(2,19): error TS2315: Type 'boolean' is not generic. +tests/cases/compiler/index2.js(2,19): error TS2315: Type 'void' is not generic. +tests/cases/compiler/index3.js(2,19): error TS2315: Type 'undefined' is not generic. +tests/cases/compiler/index4.js(2,19): error TS2315: Type 'Function' is not generic. +tests/cases/compiler/index5.js(2,19): error TS2315: Type 'string' is not generic. +tests/cases/compiler/index6.js(2,19): error TS2315: Type 'number' is not generic. +tests/cases/compiler/index7.js(2,19): error TS2315: Type 'any' is not generic. +tests/cases/compiler/index8.js(4,12): error TS2304: Cannot find name 'fn'. +tests/cases/compiler/index8.js(4,15): error TS2304: Cannot find name 'T'. + + +==== tests/cases/compiler/index.js (1 errors) ==== + /** + * @param {(m: Boolean) => string} somebody + ~~~~~~~~~~ +!!! error TS2315: Type 'boolean' is not generic. + */ + function sayHello(somebody) { + return 'Hello ' + somebody; + } + +==== tests/cases/compiler/index2.js (1 errors) ==== + /** + * @param {(m: Void) => string} somebody + ~~~~~~~ +!!! error TS2315: Type 'void' is not generic. + */ + function sayHello2(somebody) { + return 'Hello ' + somebody; + } + + +==== tests/cases/compiler/index3.js (1 errors) ==== + /** + * @param {(m: Undefined) => string} somebody + ~~~~~~~~~~~~ +!!! error TS2315: Type 'undefined' is not generic. + */ + function sayHello3(somebody) { + return 'Hello ' + somebody; + } + + +==== tests/cases/compiler/index4.js (1 errors) ==== + /** + * @param {(m: Function) => string} somebody + ~~~~~~~~~~~ +!!! error TS2315: Type 'Function' is not generic. + */ + function sayHello4(somebody) { + return 'Hello ' + somebody; + } + + +==== tests/cases/compiler/index5.js (1 errors) ==== + /** + * @param {(m: String) => string} somebody + ~~~~~~~~~ +!!! error TS2315: Type 'string' is not generic. + */ + function sayHello5(somebody) { + return 'Hello ' + somebody; + } + + +==== tests/cases/compiler/index6.js (1 errors) ==== + /** + * @param {(m: Number) => string} somebody + ~~~~~~~~~ +!!! error TS2315: Type 'number' is not generic. + */ + function sayHello6(somebody) { + return 'Hello ' + somebody; + } + + +==== tests/cases/compiler/index7.js (1 errors) ==== + /** + * @param {(m: Object) => string} somebody + ~~~~~~~~~ +!!! error TS2315: Type 'any' is not generic. + */ + function sayHello7(somebody) { + return 'Hello ' + somebody; + } + +==== tests/cases/compiler/index8.js (2 errors) ==== + function fn() {} + + /** + * @param {fn} somebody + ~~ +!!! error TS2304: Cannot find name 'fn'. + ~ +!!! error TS2304: Cannot find name 'T'. + */ + function sayHello8(somebody) { } \ No newline at end of file diff --git a/tests/baselines/reference/jsdocTypeTagCast.js b/tests/baselines/reference/jsdocTypeTagCast.js index c2df50cd6dd..ffe59d0138d 100644 --- a/tests/baselines/reference/jsdocTypeTagCast.js +++ b/tests/baselines/reference/jsdocTypeTagCast.js @@ -97,7 +97,7 @@ var a; /** @type {string} */ var s; var a = ("" + 4); -var s = "" + (4); +var s = "" +/** @type {*} */ (4); var SomeBase = (function () { function SomeBase() { this.p = 42; @@ -128,19 +128,19 @@ var someBase = new SomeBase(); var someDerived = new SomeDerived(); var someOther = new SomeOther(); var someFakeClass = new SomeFakeClass(); -someBase = (someDerived); -someBase = (someBase); -someBase = (someOther); // Error -someDerived = (someDerived); -someDerived = (someBase); -someDerived = (someOther); // Error -someOther = (someDerived); // Error -someOther = (someBase); // Error -someOther = (someOther); +someBase =/** @type {SomeBase} */ (someDerived); +someBase =/** @type {SomeBase} */ (someBase); +someBase =/** @type {SomeBase} */ (someOther); // Error +someDerived =/** @type {SomeDerived} */ (someDerived); +someDerived =/** @type {SomeDerived} */ (someBase); +someDerived =/** @type {SomeDerived} */ (someOther); // Error +someOther =/** @type {SomeOther} */ (someDerived); // Error +someOther =/** @type {SomeOther} */ (someBase); // Error +someOther =/** @type {SomeOther} */ (someOther); someFakeClass = someBase; someFakeClass = someDerived; someBase = someFakeClass; // Error -someBase = (someFakeClass); +someBase =/** @type {SomeBase} */ (someFakeClass); // Type assertion cannot be a type-predicate type /** @type {number | string} */ var numOrStr; diff --git a/tests/baselines/reference/jsxPropsAsIdentifierNames.js b/tests/baselines/reference/jsxPropsAsIdentifierNames.js new file mode 100644 index 00000000000..ef9d360b1dd --- /dev/null +++ b/tests/baselines/reference/jsxPropsAsIdentifierNames.js @@ -0,0 +1,16 @@ +//// [index.tsx] +declare namespace JSX { + interface Element { } + interface IntrinsicElements { + div: { + static?: boolean; + }; + } +} +export default
; + + +//// [index.jsx] +"use strict"; +exports.__esModule = true; +exports["default"] =
; diff --git a/tests/baselines/reference/jsxPropsAsIdentifierNames.symbols b/tests/baselines/reference/jsxPropsAsIdentifierNames.symbols new file mode 100644 index 00000000000..15df2efa0c9 --- /dev/null +++ b/tests/baselines/reference/jsxPropsAsIdentifierNames.symbols @@ -0,0 +1,23 @@ +=== tests/cases/compiler/index.tsx === +declare namespace JSX { +>JSX : Symbol(JSX, Decl(index.tsx, 0, 0)) + + interface Element { } +>Element : Symbol(Element, Decl(index.tsx, 0, 23)) + + interface IntrinsicElements { +>IntrinsicElements : Symbol(IntrinsicElements, Decl(index.tsx, 1, 25)) + + div: { +>div : Symbol(IntrinsicElements.div, Decl(index.tsx, 2, 33)) + + static?: boolean; +>static : Symbol(static, Decl(index.tsx, 3, 14)) + + }; + } +} +export default
; +>div : Symbol(unknown) +>static : Symbol(static, Decl(index.tsx, 8, 19)) + diff --git a/tests/baselines/reference/jsxPropsAsIdentifierNames.types b/tests/baselines/reference/jsxPropsAsIdentifierNames.types new file mode 100644 index 00000000000..1d52871b419 --- /dev/null +++ b/tests/baselines/reference/jsxPropsAsIdentifierNames.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/index.tsx === +declare namespace JSX { +>JSX : any + + interface Element { } +>Element : Element + + interface IntrinsicElements { +>IntrinsicElements : IntrinsicElements + + div: { +>div : { static?: boolean; } + + static?: boolean; +>static : boolean + + }; + } +} +export default
; +>
: any +>div : any +>static : boolean +>true : true + diff --git a/tests/baselines/reference/keyofAndIndexedAccessErrors.errors.txt b/tests/baselines/reference/keyofAndIndexedAccessErrors.errors.txt index 1e88e2abc43..0634c3419e0 100644 --- a/tests/baselines/reference/keyofAndIndexedAccessErrors.errors.txt +++ b/tests/baselines/reference/keyofAndIndexedAccessErrors.errors.txt @@ -15,6 +15,7 @@ tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(35,21): error tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(36,21): error TS2538: Type 'boolean' cannot be used as an index type. tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(41,31): error TS2538: Type 'boolean' cannot be used as an index type. tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(46,16): error TS2538: Type 'boolean' cannot be used as an index type. +tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(49,12): error TS1122: A tuple type element list cannot be empty. tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(63,33): error TS2345: Argument of type '"size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(64,33): error TS2345: Argument of type '"name" | "size"' is not assignable to parameter of type '"name" | "width" | "height" | "visible"'. Type '"size"' is not assignable to type '"name" | "width" | "height" | "visible"'. @@ -28,7 +29,7 @@ tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(76,5): error tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(77,5): error TS2322: Type 'keyof (T & U)' is not assignable to type 'keyof (T | U)'. -==== tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts (24 errors) ==== +==== tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts (25 errors) ==== class Shape { name: string; width: number; @@ -112,6 +113,8 @@ tests/cases/conformance/types/keyof/keyofAndIndexedAccessErrors.ts(77,5): error type T60 = {}["toString"]; type T61 = []["toString"]; + ~~ +!!! error TS1122: A tuple type element list cannot be empty. declare let cond: boolean; diff --git a/tests/baselines/reference/mappedTypeErrors2.errors.txt b/tests/baselines/reference/mappedTypeErrors2.errors.txt new file mode 100644 index 00000000000..18bc7cc7239 --- /dev/null +++ b/tests/baselines/reference/mappedTypeErrors2.errors.txt @@ -0,0 +1,35 @@ +tests/cases/conformance/types/mapped/mappedTypeErrors2.ts(9,30): error TS2536: Type 'K' cannot be used to index type 'T1'. +tests/cases/conformance/types/mapped/mappedTypeErrors2.ts(13,30): error TS2536: Type 'K' cannot be used to index type 'T3'. +tests/cases/conformance/types/mapped/mappedTypeErrors2.ts(15,47): error TS2536: Type 'S' cannot be used to index type 'AB'. +tests/cases/conformance/types/mapped/mappedTypeErrors2.ts(17,49): error TS2536: Type 'L' cannot be used to index type '{ [key in AB[S]]: true; }'. + + +==== tests/cases/conformance/types/mapped/mappedTypeErrors2.ts (4 errors) ==== + // Repros from #17238 + + type AB = { + a: 'a' + b: 'a' + }; + + type T1 = { [key in AB[K]]: true }; + type T2 = T1[K]; // Error + ~~~~~~~~ +!!! error TS2536: Type 'K' cannot be used to index type 'T1'. + + type R = AB[keyof AB]; // "a" + type T3 = { [key in R]: true }; + type T4 = T3[K] // Error + ~~~~~ +!!! error TS2536: Type 'K' cannot be used to index type 'T3'. + + type T5 = {[key in AB[S]]: true}[S]; // Error + ~~~~~ +!!! error TS2536: Type 'S' cannot be used to index type 'AB'. + + type T6 = {[key in AB[S]]: true}[L]; // Error + ~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2536: Type 'L' cannot be used to index type '{ [key in AB[S]]: true; }'. + + type T7 = {[key in AB[S]]: true}[L]; + \ No newline at end of file diff --git a/tests/baselines/reference/mappedTypeErrors2.js b/tests/baselines/reference/mappedTypeErrors2.js new file mode 100644 index 00000000000..d9fc6b0bc72 --- /dev/null +++ b/tests/baselines/reference/mappedTypeErrors2.js @@ -0,0 +1,49 @@ +//// [mappedTypeErrors2.ts] +// Repros from #17238 + +type AB = { + a: 'a' + b: 'a' +}; + +type T1 = { [key in AB[K]]: true }; +type T2 = T1[K]; // Error + +type R = AB[keyof AB]; // "a" +type T3 = { [key in R]: true }; +type T4 = T3[K] // Error + +type T5 = {[key in AB[S]]: true}[S]; // Error + +type T6 = {[key in AB[S]]: true}[L]; // Error + +type T7 = {[key in AB[S]]: true}[L]; + + +//// [mappedTypeErrors2.js] +// Repros from #17238 + + +//// [mappedTypeErrors2.d.ts] +declare type AB = { + a: 'a'; + b: 'a'; +}; +declare type T1 = { + [key in AB[K]]: true; +}; +declare type T2 = T1[K]; +declare type R = AB[keyof AB]; +declare type T3 = { + [key in R]: true; +}; +declare type T4 = T3[K]; +declare type T5 = { + [key in AB[S]]: true; +}[S]; +declare type T6 = { + [key in AB[S]]: true; +}[L]; +declare type T7 = { + [key in AB[S]]: true; +}[L]; diff --git a/tests/baselines/reference/mappedTypePartialConstraints.js b/tests/baselines/reference/mappedTypePartialConstraints.js new file mode 100644 index 00000000000..1c83e2506dd --- /dev/null +++ b/tests/baselines/reference/mappedTypePartialConstraints.js @@ -0,0 +1,46 @@ +//// [mappedTypePartialConstraints.ts] +// Repro from #16985 + +interface MyInterface { + something: number; +} + +class MyClass { + doIt(data : Partial) {} +} + +class MySubClass extends MyClass {} + +function fn(arg: typeof MyClass) {}; + +fn(MySubClass); + + +//// [mappedTypePartialConstraints.js] +// Repro from #16985 +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 MyClass = (function () { + function MyClass() { + } + MyClass.prototype.doIt = function (data) { }; + return MyClass; +}()); +var MySubClass = (function (_super) { + __extends(MySubClass, _super); + function MySubClass() { + return _super !== null && _super.apply(this, arguments) || this; + } + return MySubClass; +}(MyClass)); +function fn(arg) { } +; +fn(MySubClass); diff --git a/tests/baselines/reference/mappedTypePartialConstraints.symbols b/tests/baselines/reference/mappedTypePartialConstraints.symbols new file mode 100644 index 00000000000..7601cd68d69 --- /dev/null +++ b/tests/baselines/reference/mappedTypePartialConstraints.symbols @@ -0,0 +1,36 @@ +=== tests/cases/compiler/mappedTypePartialConstraints.ts === +// Repro from #16985 + +interface MyInterface { +>MyInterface : Symbol(MyInterface, Decl(mappedTypePartialConstraints.ts, 0, 0)) + + something: number; +>something : Symbol(MyInterface.something, Decl(mappedTypePartialConstraints.ts, 2, 23)) +} + +class MyClass { +>MyClass : Symbol(MyClass, Decl(mappedTypePartialConstraints.ts, 4, 1)) +>T : Symbol(T, Decl(mappedTypePartialConstraints.ts, 6, 14)) +>MyInterface : Symbol(MyInterface, Decl(mappedTypePartialConstraints.ts, 0, 0)) + + doIt(data : Partial) {} +>doIt : Symbol(MyClass.doIt, Decl(mappedTypePartialConstraints.ts, 6, 38)) +>data : Symbol(data, Decl(mappedTypePartialConstraints.ts, 7, 7)) +>Partial : Symbol(Partial, Decl(lib.d.ts, --, --)) +>T : Symbol(T, Decl(mappedTypePartialConstraints.ts, 6, 14)) +} + +class MySubClass extends MyClass {} +>MySubClass : Symbol(MySubClass, Decl(mappedTypePartialConstraints.ts, 8, 1)) +>MyClass : Symbol(MyClass, Decl(mappedTypePartialConstraints.ts, 4, 1)) +>MyInterface : Symbol(MyInterface, Decl(mappedTypePartialConstraints.ts, 0, 0)) + +function fn(arg: typeof MyClass) {}; +>fn : Symbol(fn, Decl(mappedTypePartialConstraints.ts, 10, 48)) +>arg : Symbol(arg, Decl(mappedTypePartialConstraints.ts, 12, 12)) +>MyClass : Symbol(MyClass, Decl(mappedTypePartialConstraints.ts, 4, 1)) + +fn(MySubClass); +>fn : Symbol(fn, Decl(mappedTypePartialConstraints.ts, 10, 48)) +>MySubClass : Symbol(MySubClass, Decl(mappedTypePartialConstraints.ts, 8, 1)) + diff --git a/tests/baselines/reference/mappedTypePartialConstraints.types b/tests/baselines/reference/mappedTypePartialConstraints.types new file mode 100644 index 00000000000..a0543774692 --- /dev/null +++ b/tests/baselines/reference/mappedTypePartialConstraints.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/mappedTypePartialConstraints.ts === +// Repro from #16985 + +interface MyInterface { +>MyInterface : MyInterface + + something: number; +>something : number +} + +class MyClass { +>MyClass : MyClass +>T : T +>MyInterface : MyInterface + + doIt(data : Partial) {} +>doIt : (data: Partial) => void +>data : Partial +>Partial : Partial +>T : T +} + +class MySubClass extends MyClass {} +>MySubClass : MySubClass +>MyClass : MyClass +>MyInterface : MyInterface + +function fn(arg: typeof MyClass) {}; +>fn : (arg: typeof MyClass) => void +>arg : typeof MyClass +>MyClass : typeof MyClass + +fn(MySubClass); +>fn(MySubClass) : void +>fn : (arg: typeof MyClass) => void +>MySubClass : typeof MySubClass + diff --git a/tests/baselines/reference/mappedTypeRelationships.errors.txt b/tests/baselines/reference/mappedTypeRelationships.errors.txt index c54330e9b16..bc0aa32b149 100644 --- a/tests/baselines/reference/mappedTypeRelationships.errors.txt +++ b/tests/baselines/reference/mappedTypeRelationships.errors.txt @@ -60,25 +60,26 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(51,5): error TS2 tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(56,5): error TS2542: Index signature in type 'Readonly' only permits reading. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(61,5): error TS2542: Index signature in type 'Readonly' only permits reading. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(66,5): error TS2542: Index signature in type 'Readonly' only permits reading. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(70,5): error TS2322: Type 'Partial' is not assignable to type 'T'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(75,5): error TS2322: Type 'Partial' is not assignable to type 'T'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(125,5): error TS2322: Type 'Partial' is not assignable to type 'Identity'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(141,5): error TS2322: Type '{ [P in keyof T]: T[P]; }' is not assignable to type '{ [P in keyof T]: U[P]; }'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(72,5): error TS2322: Type 'Partial' is not assignable to type 'T'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(78,5): error TS2322: Type 'Partial' is not assignable to type 'Partial'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(88,5): error TS2322: Type 'Readonly' is not assignable to type 'Readonly'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(127,5): error TS2322: Type 'Partial' is not assignable to type 'Identity'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(143,5): error TS2322: Type '{ [P in keyof T]: T[P]; }' is not assignable to type '{ [P in keyof T]: U[P]; }'. Type 'T[P]' is not assignable to type 'U[P]'. Type 'T[string]' is not assignable to type 'U[P]'. Type 'T[string]' is not assignable to type 'U[string]'. Type 'T[P]' is not assignable to type 'U[string]'. Type 'T[string]' is not assignable to type 'U[string]'. Type 'T' is not assignable to type 'U'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(146,5): error TS2322: Type '{ [P in keyof T]: T[P]; }' is not assignable to type '{ [P in keyof U]: U[P]; }'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(148,5): error TS2322: Type '{ [P in keyof T]: T[P]; }' is not assignable to type '{ [P in keyof U]: U[P]; }'. Type 'keyof U' is not assignable to type 'keyof T'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(151,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in keyof T]: T[P]; }'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(153,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in keyof T]: T[P]; }'. Type 'keyof T' is not assignable to type 'K'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(156,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in keyof U]: U[P]; }'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(158,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in keyof U]: U[P]; }'. Type 'keyof U' is not assignable to type 'K'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(161,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in keyof T]: U[P]; }'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(163,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in keyof T]: U[P]; }'. Type 'keyof T' is not assignable to type 'K'. -tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(166,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in K]: U[P]; }'. +tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(168,5): error TS2322: Type '{ [P in K]: T[P]; }' is not assignable to type '{ [P in K]: U[P]; }'. Type 'T[P]' is not assignable to type 'U[P]'. Type 'T[string]' is not assignable to type 'U[P]'. Type 'T[string]' is not assignable to type 'U[string]'. @@ -87,7 +88,7 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(166,5): error TS Type 'T' is not assignable to type 'U'. -==== tests/cases/conformance/types/mapped/mappedTypeRelationships.ts (27 errors) ==== +==== tests/cases/conformance/types/mapped/mappedTypeRelationships.ts (28 errors) ==== function f1(x: T, k: keyof T) { return x[k]; } @@ -236,6 +237,8 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(166,5): error TS !!! error TS2542: Index signature in type 'Readonly' only permits reading. } + type Thing = { a: string, b: string }; + function f30(x: T, y: Partial) { x = y; // Error ~ @@ -243,11 +246,11 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(166,5): error TS y = x; } - function f31(x: T, y: Partial) { - x = y; // Error + function f31(x: Partial, y: Partial) { + x = y; + y = x; // Error ~ -!!! error TS2322: Type 'Partial' is not assignable to type 'T'. - y = x; +!!! error TS2322: Type 'Partial' is not assignable to type 'Partial'. } function f40(x: T, y: Readonly) { @@ -255,9 +258,11 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(166,5): error TS y = x; } - function f41(x: T, y: Readonly) { + function f41(x: Readonly, y: Readonly) { x = y; - y = x; + y = x; // Error + ~ +!!! error TS2322: Type 'Readonly' is not assignable to type 'Readonly'. } type Item = { diff --git a/tests/baselines/reference/mappedTypeRelationships.js b/tests/baselines/reference/mappedTypeRelationships.js index 3580007137e..180c293b6c1 100644 --- a/tests/baselines/reference/mappedTypeRelationships.js +++ b/tests/baselines/reference/mappedTypeRelationships.js @@ -67,14 +67,16 @@ function f23(x: T, y: Readonly, k: K) { y[k] = x[k]; // Error } +type Thing = { a: string, b: string }; + function f30(x: T, y: Partial) { x = y; // Error y = x; } -function f31(x: T, y: Partial) { - x = y; // Error - y = x; +function f31(x: Partial, y: Partial) { + x = y; + y = x; // Error } function f40(x: T, y: Readonly) { @@ -82,9 +84,9 @@ function f40(x: T, y: Readonly) { y = x; } -function f41(x: T, y: Readonly) { +function f41(x: Readonly, y: Readonly) { x = y; - y = x; + y = x; // Error } type Item = { @@ -228,8 +230,8 @@ function f30(x, y) { y = x; } function f31(x, y) { - x = y; // Error - y = x; + x = y; + y = x; // Error } function f40(x, y) { x = y; @@ -237,7 +239,7 @@ function f40(x, y) { } function f41(x, y) { x = y; - y = x; + y = x; // Error } function f50(obj, key) { var item = obj[key]; @@ -304,10 +306,14 @@ declare function f20(x: T, y: Readonly, k: keyof T): void; declare function f21(x: T, y: Readonly, k: K): void; declare function f22(x: T, y: Readonly, k: keyof T): void; declare function f23(x: T, y: Readonly, k: K): void; +declare type Thing = { + a: string; + b: string; +}; declare function f30(x: T, y: Partial): void; -declare function f31(x: T, y: Partial): void; +declare function f31(x: Partial, y: Partial): void; declare function f40(x: T, y: Readonly): void; -declare function f41(x: T, y: Readonly): void; +declare function f41(x: Readonly, y: Readonly): void; declare type Item = { name: string; }; diff --git a/tests/baselines/reference/parseCommaSeperatedNewlineNew.errors.txt b/tests/baselines/reference/parseCommaSeperatedNewlineNew.errors.txt new file mode 100644 index 00000000000..ff3ff1a033d --- /dev/null +++ b/tests/baselines/reference/parseCommaSeperatedNewlineNew.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/parseCommaSeperatedNewlineNew.ts(1,2): error TS2304: Cannot find name 'a'. +tests/cases/compiler/parseCommaSeperatedNewlineNew.ts(1,2): error TS2695: Left side of comma operator is unused and has no side effects. +tests/cases/compiler/parseCommaSeperatedNewlineNew.ts(2,4): error TS1109: Expression expected. + + +==== tests/cases/compiler/parseCommaSeperatedNewlineNew.ts (3 errors) ==== + (a, + ~ +!!! error TS2304: Cannot find name 'a'. + ~ +!!! error TS2695: Left side of comma operator is unused and has no side effects. + new) + ~ +!!! error TS1109: Expression expected. \ No newline at end of file diff --git a/tests/baselines/reference/parseCommaSeperatedNewlineNew.js b/tests/baselines/reference/parseCommaSeperatedNewlineNew.js new file mode 100644 index 00000000000..c1326c47802 --- /dev/null +++ b/tests/baselines/reference/parseCommaSeperatedNewlineNew.js @@ -0,0 +1,7 @@ +//// [parseCommaSeperatedNewlineNew.ts] +(a, +new) + +//// [parseCommaSeperatedNewlineNew.js] +(a, + new ); diff --git a/tests/baselines/reference/parseCommaSeperatedNewlineNumber.errors.txt b/tests/baselines/reference/parseCommaSeperatedNewlineNumber.errors.txt new file mode 100644 index 00000000000..73f087cc1e6 --- /dev/null +++ b/tests/baselines/reference/parseCommaSeperatedNewlineNumber.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/parseCommaSeperatedNewlineNumber.ts(1,2): error TS2304: Cannot find name 'a'. +tests/cases/compiler/parseCommaSeperatedNewlineNumber.ts(1,2): error TS2695: Left side of comma operator is unused and has no side effects. + + +==== tests/cases/compiler/parseCommaSeperatedNewlineNumber.ts (2 errors) ==== + (a, + ~ +!!! error TS2304: Cannot find name 'a'. + ~ +!!! error TS2695: Left side of comma operator is unused and has no side effects. + 1) \ No newline at end of file diff --git a/tests/baselines/reference/parseCommaSeperatedNewlineNumber.js b/tests/baselines/reference/parseCommaSeperatedNewlineNumber.js new file mode 100644 index 00000000000..167e604665a --- /dev/null +++ b/tests/baselines/reference/parseCommaSeperatedNewlineNumber.js @@ -0,0 +1,7 @@ +//// [parseCommaSeperatedNewlineNumber.ts] +(a, +1) + +//// [parseCommaSeperatedNewlineNumber.js] +(a, + 1); diff --git a/tests/baselines/reference/parseCommaSeperatedNewlineString.errors.txt b/tests/baselines/reference/parseCommaSeperatedNewlineString.errors.txt new file mode 100644 index 00000000000..2c70bfbfc30 --- /dev/null +++ b/tests/baselines/reference/parseCommaSeperatedNewlineString.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/parseCommaSeperatedNewlineString.ts(1,2): error TS2304: Cannot find name 'a'. +tests/cases/compiler/parseCommaSeperatedNewlineString.ts(1,2): error TS2695: Left side of comma operator is unused and has no side effects. + + +==== tests/cases/compiler/parseCommaSeperatedNewlineString.ts (2 errors) ==== + (a, + ~ +!!! error TS2304: Cannot find name 'a'. + ~ +!!! error TS2695: Left side of comma operator is unused and has no side effects. + '') \ No newline at end of file diff --git a/tests/baselines/reference/parseCommaSeperatedNewlineString.js b/tests/baselines/reference/parseCommaSeperatedNewlineString.js new file mode 100644 index 00000000000..f7f96541c77 --- /dev/null +++ b/tests/baselines/reference/parseCommaSeperatedNewlineString.js @@ -0,0 +1,7 @@ +//// [parseCommaSeperatedNewlineString.ts] +(a, +'') + +//// [parseCommaSeperatedNewlineString.js] +(a, + ''); diff --git a/tests/baselines/reference/parser15.4.4.14-9-2.js b/tests/baselines/reference/parser15.4.4.14-9-2.js index 0f533cd9a26..e24da870d3e 100644 --- a/tests/baselines/reference/parser15.4.4.14-9-2.js +++ b/tests/baselines/reference/parser15.4.4.14-9-2.js @@ -41,9 +41,9 @@ function testcase() { var one = 1; var _float = -(4 / 3); var a = new Array(false, undefined, null, "0", obj, -1.3333333333333, "str", -0, true, +0, one, 1, 0, false, _float, -(4 / 3)); - if (a.indexOf(-(4 / 3)) === 14 && - a.indexOf(0) === 7 && - a.indexOf(-0) === 7 && + if (a.indexOf(-(4 / 3)) === 14 &&// a[14]=_float===-(4/3) + a.indexOf(0) === 7 &&// a[7] = +0, 0===+0 + a.indexOf(-0) === 7 &&// a[7] = +0, -0===+0 a.indexOf(1) === 10) { return true; } diff --git a/tests/baselines/reference/parser512325.errors.txt b/tests/baselines/reference/parser512325.errors.txt index e6a47fbf226..f54d9f2110a 100644 --- a/tests/baselines/reference/parser512325.errors.txt +++ b/tests/baselines/reference/parser512325.errors.txt @@ -1,30 +1,21 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,11): error TS2304: Cannot find name 'a'. -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,11): error TS2695: Left side of comma operator is unused and has no side effects. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,14): error TS1003: Identifier expected. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,15): error TS2304: Cannot find name 'b'. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,15): error TS2695: Left side of comma operator is unused and has no side effects. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,18): error TS2304: Cannot find name 'c'. -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,22): error TS1005: ';' expected. -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,25): error TS2304: Cannot find name 'a'. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,27): error TS2304: Cannot find name 'b'. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts(1,29): error TS2304: Cannot find name 'c'. -==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts (9 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser512325.ts (6 errors) ==== var tt = (a, (b, c)) => a+b+c; - ~ -!!! error TS2304: Cannot find name 'a'. - ~ -!!! error TS2695: Left side of comma operator is unused and has no side effects. + ~ +!!! error TS1003: Identifier expected. ~ !!! error TS2304: Cannot find name 'b'. ~ !!! error TS2695: Left side of comma operator is unused and has no side effects. ~ !!! error TS2304: Cannot find name 'c'. - ~~ -!!! error TS1005: ';' expected. - ~ -!!! error TS2304: Cannot find name 'a'. ~ !!! error TS2304: Cannot find name 'b'. ~ diff --git a/tests/baselines/reference/parser512325.js b/tests/baselines/reference/parser512325.js index 14cbcddd86b..75af6b9f39a 100644 --- a/tests/baselines/reference/parser512325.js +++ b/tests/baselines/reference/parser512325.js @@ -2,5 +2,7 @@ var tt = (a, (b, c)) => a+b+c; //// [parser512325.js] -var tt = (a, (b, c)); -a + b + c; +var tt = function (a, ) { + if ( === void 0) { = (b, c); } + return a + b + c; +}; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity10.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity10.js index 862722b1a73..7ff9e380dcf 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity10.js +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity10.js @@ -6,5 +6,6 @@ //// [parserGreaterThanTokenAmbiguity10.js] 1 - >>> + // before + >>>// after 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.js index b6f905e12e7..03e6211ae15 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.js +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity15.js @@ -6,5 +6,6 @@ //// [parserGreaterThanTokenAmbiguity15.js] 1 - >>= + // before + >>=// after 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.js index 01d1d6401f2..ba5e380043d 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.js +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity20.js @@ -6,5 +6,6 @@ //// [parserGreaterThanTokenAmbiguity20.js] 1 - >>>= + // Before + >>>=// after 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity5.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity5.js index c65b76f504a..e240746caa4 100644 --- a/tests/baselines/reference/parserGreaterThanTokenAmbiguity5.js +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity5.js @@ -6,5 +6,6 @@ //// [parserGreaterThanTokenAmbiguity5.js] 1 - >> + // before + >>// after 2; diff --git a/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.js b/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.js new file mode 100644 index 00000000000..63f1f42d101 --- /dev/null +++ b/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.js @@ -0,0 +1,8 @@ +//// [prefixedNumberLiteralAssignToNumberLiteralType.ts] +let x: 1 = +1; + +let y: -1 = -1; + +//// [prefixedNumberLiteralAssignToNumberLiteralType.js] +var x = +1; +var y = -1; diff --git a/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.symbols b/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.symbols new file mode 100644 index 00000000000..4ab5d371e8a --- /dev/null +++ b/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.symbols @@ -0,0 +1,7 @@ +=== tests/cases/compiler/prefixedNumberLiteralAssignToNumberLiteralType.ts === +let x: 1 = +1; +>x : Symbol(x, Decl(prefixedNumberLiteralAssignToNumberLiteralType.ts, 0, 3)) + +let y: -1 = -1; +>y : Symbol(y, Decl(prefixedNumberLiteralAssignToNumberLiteralType.ts, 2, 3)) + diff --git a/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.types b/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.types new file mode 100644 index 00000000000..93bd5cc6274 --- /dev/null +++ b/tests/baselines/reference/prefixedNumberLiteralAssignToNumberLiteralType.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/prefixedNumberLiteralAssignToNumberLiteralType.ts === +let x: 1 = +1; +>x : 1 +>+1 : 1 +>1 : 1 + +let y: -1 = -1; +>y : -1 +>-1 : -1 +>1 : 1 +>-1 : -1 +>1 : 1 + diff --git a/tests/baselines/reference/promiseEmptyTupleNoException.errors.txt b/tests/baselines/reference/promiseEmptyTupleNoException.errors.txt new file mode 100644 index 00000000000..0237d658da5 --- /dev/null +++ b/tests/baselines/reference/promiseEmptyTupleNoException.errors.txt @@ -0,0 +1,20 @@ +tests/cases/compiler/promiseEmptyTupleNoException.ts(1,38): error TS1122: A tuple type element list cannot be empty. +tests/cases/compiler/promiseEmptyTupleNoException.ts(3,3): error TS2322: Type 'any[]' is not assignable to type '[]'. + Types of property 'pop' are incompatible. + Type '() => any' is not assignable to type '() => never'. + Type 'any' is not assignable to type 'never'. + + +==== tests/cases/compiler/promiseEmptyTupleNoException.ts (2 errors) ==== + export async function get(): Promise<[]> { + ~~ +!!! error TS1122: A tuple type element list cannot be empty. + let emails = []; + return emails; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type 'any[]' is not assignable to type '[]'. +!!! error TS2322: Types of property 'pop' are incompatible. +!!! error TS2322: Type '() => any' is not assignable to type '() => never'. +!!! error TS2322: Type 'any' is not assignable to type 'never'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/promiseEmptyTupleNoException.js b/tests/baselines/reference/promiseEmptyTupleNoException.js new file mode 100644 index 00000000000..4498cc3b4cf --- /dev/null +++ b/tests/baselines/reference/promiseEmptyTupleNoException.js @@ -0,0 +1,12 @@ +//// [promiseEmptyTupleNoException.ts] +export async function get(): Promise<[]> { + let emails = []; + return emails; +} + + +//// [promiseEmptyTupleNoException.js] +export async function get() { + let emails = []; + return emails; +} diff --git a/tests/baselines/reference/typeGuardsInConditionalExpression.js b/tests/baselines/reference/typeGuardsInConditionalExpression.js index 9aade91612a..8be83a887b1 100644 --- a/tests/baselines/reference/typeGuardsInConditionalExpression.js +++ b/tests/baselines/reference/typeGuardsInConditionalExpression.js @@ -138,7 +138,7 @@ function foo8(x) { var b; return typeof x === "string" ? x === "hello" - : ((b = x) && + : ((b = x) &&// number | boolean (typeof x === "boolean" ? x // boolean : x == 10)); // boolean diff --git a/tests/baselines/reference/typeInferenceWithExcessProperties.js b/tests/baselines/reference/typeInferenceWithExcessProperties.js new file mode 100644 index 00000000000..0630f1c8977 --- /dev/null +++ b/tests/baselines/reference/typeInferenceWithExcessProperties.js @@ -0,0 +1,54 @@ +//// [typeInferenceWithExcessProperties.ts] +// Repro from #17041 + +interface Named { + name: string; +} + +function parrot(obj: T): T { + return obj; +} + + +parrot({ + name: "TypeScript", +}); + +parrot({ + name: "TypeScript", + age: 5, +}); + +parrot({ + name: "TypeScript", + age: function () { }, +}); + +parrot({ + name: "TypeScript", + sayHello() { + }, +}); + + +//// [typeInferenceWithExcessProperties.js] +// Repro from #17041 +function parrot(obj) { + return obj; +} +parrot({ + name: "TypeScript" +}); +parrot({ + name: "TypeScript", + age: 5 +}); +parrot({ + name: "TypeScript", + age: function () { } +}); +parrot({ + name: "TypeScript", + sayHello: function () { + } +}); diff --git a/tests/baselines/reference/typeInferenceWithExcessProperties.symbols b/tests/baselines/reference/typeInferenceWithExcessProperties.symbols new file mode 100644 index 00000000000..1c4d79cda48 --- /dev/null +++ b/tests/baselines/reference/typeInferenceWithExcessProperties.symbols @@ -0,0 +1,65 @@ +=== tests/cases/compiler/typeInferenceWithExcessProperties.ts === +// Repro from #17041 + +interface Named { +>Named : Symbol(Named, Decl(typeInferenceWithExcessProperties.ts, 0, 0)) + + name: string; +>name : Symbol(Named.name, Decl(typeInferenceWithExcessProperties.ts, 2, 17)) +} + +function parrot(obj: T): T { +>parrot : Symbol(parrot, Decl(typeInferenceWithExcessProperties.ts, 4, 1)) +>T : Symbol(T, Decl(typeInferenceWithExcessProperties.ts, 6, 16)) +>Named : Symbol(Named, Decl(typeInferenceWithExcessProperties.ts, 0, 0)) +>obj : Symbol(obj, Decl(typeInferenceWithExcessProperties.ts, 6, 33)) +>T : Symbol(T, Decl(typeInferenceWithExcessProperties.ts, 6, 16)) +>T : Symbol(T, Decl(typeInferenceWithExcessProperties.ts, 6, 16)) + + return obj; +>obj : Symbol(obj, Decl(typeInferenceWithExcessProperties.ts, 6, 33)) +} + + +parrot({ +>parrot : Symbol(parrot, Decl(typeInferenceWithExcessProperties.ts, 4, 1)) + + name: "TypeScript", +>name : Symbol(name, Decl(typeInferenceWithExcessProperties.ts, 11, 8)) + +}); + +parrot({ +>parrot : Symbol(parrot, Decl(typeInferenceWithExcessProperties.ts, 4, 1)) + + name: "TypeScript", +>name : Symbol(name, Decl(typeInferenceWithExcessProperties.ts, 15, 8)) + + age: 5, +>age : Symbol(age, Decl(typeInferenceWithExcessProperties.ts, 16, 23)) + +}); + +parrot({ +>parrot : Symbol(parrot, Decl(typeInferenceWithExcessProperties.ts, 4, 1)) + + name: "TypeScript", +>name : Symbol(name, Decl(typeInferenceWithExcessProperties.ts, 20, 8)) + + age: function () { }, +>age : Symbol(age, Decl(typeInferenceWithExcessProperties.ts, 21, 23)) + +}); + +parrot({ +>parrot : Symbol(parrot, Decl(typeInferenceWithExcessProperties.ts, 4, 1)) + + name: "TypeScript", +>name : Symbol(name, Decl(typeInferenceWithExcessProperties.ts, 25, 8)) + + sayHello() { +>sayHello : Symbol(sayHello, Decl(typeInferenceWithExcessProperties.ts, 26, 23)) + + }, +}); + diff --git a/tests/baselines/reference/typeInferenceWithExcessProperties.types b/tests/baselines/reference/typeInferenceWithExcessProperties.types new file mode 100644 index 00000000000..af3e1baae90 --- /dev/null +++ b/tests/baselines/reference/typeInferenceWithExcessProperties.types @@ -0,0 +1,79 @@ +=== tests/cases/compiler/typeInferenceWithExcessProperties.ts === +// Repro from #17041 + +interface Named { +>Named : Named + + name: string; +>name : string +} + +function parrot(obj: T): T { +>parrot : (obj: T) => T +>T : T +>Named : Named +>obj : T +>T : T +>T : T + + return obj; +>obj : T +} + + +parrot({ +>parrot({ name: "TypeScript",}) : { name: string; } +>parrot : (obj: T) => T +>{ name: "TypeScript",} : { name: string; } + + name: "TypeScript", +>name : string +>"TypeScript" : "TypeScript" + +}); + +parrot({ +>parrot({ name: "TypeScript", age: 5,}) : { name: string; age: number; } +>parrot : (obj: T) => T +>{ name: "TypeScript", age: 5,} : { name: string; age: number; } + + name: "TypeScript", +>name : string +>"TypeScript" : "TypeScript" + + age: 5, +>age : number +>5 : 5 + +}); + +parrot({ +>parrot({ name: "TypeScript", age: function () { },}) : { name: string; age: () => void; } +>parrot : (obj: T) => T +>{ name: "TypeScript", age: function () { },} : { name: string; age: () => void; } + + name: "TypeScript", +>name : string +>"TypeScript" : "TypeScript" + + age: function () { }, +>age : () => void +>function () { } : () => void + +}); + +parrot({ +>parrot({ name: "TypeScript", sayHello() { },}) : { name: string; sayHello(): void; } +>parrot : (obj: T) => T +>{ name: "TypeScript", sayHello() { },} : { name: string; sayHello(): void; } + + name: "TypeScript", +>name : string +>"TypeScript" : "TypeScript" + + sayHello() { +>sayHello : () => void + + }, +}); + diff --git a/tests/baselines/reference/unaryPlus.types b/tests/baselines/reference/unaryPlus.types index 8f92b51a159..9bd741f2ad1 100644 --- a/tests/baselines/reference/unaryPlus.types +++ b/tests/baselines/reference/unaryPlus.types @@ -2,7 +2,7 @@ // allowed per spec var a = +1; >a : number ->+1 : number +>+1 : 1 >1 : 1 var b = +(""); diff --git a/tests/baselines/reference/underscoreEscapedNameInEnum.js b/tests/baselines/reference/underscoreEscapedNameInEnum.js new file mode 100644 index 00000000000..db40f126739 --- /dev/null +++ b/tests/baselines/reference/underscoreEscapedNameInEnum.js @@ -0,0 +1,13 @@ +//// [underscoreEscapedNameInEnum.ts] +enum E { + "__foo" = 1, + bar = E["__foo"] + 1 +} + + +//// [underscoreEscapedNameInEnum.js] +var E; +(function (E) { + E[E["__foo"] = 1] = "__foo"; + E[E["bar"] = 2] = "bar"; +})(E || (E = {})); diff --git a/tests/baselines/reference/underscoreEscapedNameInEnum.symbols b/tests/baselines/reference/underscoreEscapedNameInEnum.symbols new file mode 100644 index 00000000000..4546d844cd2 --- /dev/null +++ b/tests/baselines/reference/underscoreEscapedNameInEnum.symbols @@ -0,0 +1,10 @@ +=== tests/cases/compiler/underscoreEscapedNameInEnum.ts === +enum E { +>E : Symbol(E, Decl(underscoreEscapedNameInEnum.ts, 0, 0)) + + "__foo" = 1, + bar = E["__foo"] + 1 +>bar : Symbol(E.bar, Decl(underscoreEscapedNameInEnum.ts, 1, 16)) +>E : Symbol(E, Decl(underscoreEscapedNameInEnum.ts, 0, 0)) +} + diff --git a/tests/baselines/reference/underscoreEscapedNameInEnum.types b/tests/baselines/reference/underscoreEscapedNameInEnum.types new file mode 100644 index 00000000000..02fc9a5493c --- /dev/null +++ b/tests/baselines/reference/underscoreEscapedNameInEnum.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/underscoreEscapedNameInEnum.ts === +enum E { +>E : E + + "__foo" = 1, +>1 : 1 + + bar = E["__foo"] + 1 +>bar : E +>E["__foo"] + 1 : number +>E["__foo"] : E +>E : typeof E +>"__foo" : "__foo" +>1 : 1 +} + diff --git a/tests/cases/compiler/anyIndexedAccessArrayNoException.ts b/tests/cases/compiler/anyIndexedAccessArrayNoException.ts new file mode 100644 index 00000000000..83f9e301d07 --- /dev/null +++ b/tests/cases/compiler/anyIndexedAccessArrayNoException.ts @@ -0,0 +1 @@ +var x: any[[]]; diff --git a/tests/cases/compiler/commentOnBinaryOperator1.ts b/tests/cases/compiler/commentOnBinaryOperator1.ts new file mode 100644 index 00000000000..29de3410c32 --- /dev/null +++ b/tests/cases/compiler/commentOnBinaryOperator1.ts @@ -0,0 +1,12 @@ +var a = 'some' + // comment + + 'text'; + +var b = 'some' + /* comment */ + + 'text'; + +var c = 'some' + /* comment */ + + /*comment1*/ + 'text'; \ No newline at end of file diff --git a/tests/cases/compiler/commentOnBinaryOperator2.ts b/tests/cases/compiler/commentOnBinaryOperator2.ts new file mode 100644 index 00000000000..023655e16c0 --- /dev/null +++ b/tests/cases/compiler/commentOnBinaryOperator2.ts @@ -0,0 +1,13 @@ +// @removeComments: true +var a = 'some' + // comment + + 'text'; + +var b = 'some' + /* comment */ + + 'text'; + +var c = 'some' + /* comment */ + + /*comment1*/ + 'text'; \ No newline at end of file diff --git a/tests/cases/compiler/declarationEmitInferedDefaultExportType.ts b/tests/cases/compiler/declarationEmitInferredDefaultExportType.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedDefaultExportType.ts rename to tests/cases/compiler/declarationEmitInferredDefaultExportType.ts diff --git a/tests/cases/compiler/declarationEmitInferedDefaultExportType2.ts b/tests/cases/compiler/declarationEmitInferredDefaultExportType2.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedDefaultExportType2.ts rename to tests/cases/compiler/declarationEmitInferredDefaultExportType2.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias1.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias1.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias1.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias1.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias2.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias2.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias2.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias2.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias3.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias3.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias3.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias3.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias4.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias4.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias4.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias4.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias5.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias5.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias5.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias5.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias6.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias6.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias6.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias6.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias7.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias7.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias7.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias7.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias8.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias8.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias8.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias8.ts diff --git a/tests/cases/compiler/declarationEmitInferedTypeAlias9.ts b/tests/cases/compiler/declarationEmitInferredTypeAlias9.ts similarity index 100% rename from tests/cases/compiler/declarationEmitInferedTypeAlias9.ts rename to tests/cases/compiler/declarationEmitInferredTypeAlias9.ts diff --git a/tests/cases/compiler/deferredLookupTypeResolution.ts b/tests/cases/compiler/deferredLookupTypeResolution.ts new file mode 100644 index 00000000000..6c9853266ad --- /dev/null +++ b/tests/cases/compiler/deferredLookupTypeResolution.ts @@ -0,0 +1,28 @@ +// @strict: true +// @declaration: true + +// Repro from #17456 + +type StringContains = ( + { [K in S]: 'true' } & + { [key: string]: 'false' } + )[L] + +type ObjectHasKey = StringContains + +type First = ObjectHasKey; // Should be deferred + +type T1 = ObjectHasKey<{ a: string }, 'a'>; // 'true' +type T2 = ObjectHasKey<{ a: string }, 'b'>; // 'false' + +// Verify that mapped type isn't eagerly resolved in type-to-string operation + +declare function f1(a: A, b: B): { [P in A | B]: any }; + +function f2(a: A) { + return f1(a, 'x'); +} + +function f3(x: 'a' | 'b') { + return f2(x); +} diff --git a/tests/cases/compiler/deferredLookupTypeResolution2.ts b/tests/cases/compiler/deferredLookupTypeResolution2.ts new file mode 100644 index 00000000000..4aa18c092ba --- /dev/null +++ b/tests/cases/compiler/deferredLookupTypeResolution2.ts @@ -0,0 +1,24 @@ +// @strict: true +// @declaration: true + +// Repro from #17456 + +type StringContains = ({ [K in S]: 'true' } & { [key: string]: 'false'})[L]; + +type ObjectHasKey = StringContains; + +type A = ObjectHasKey; + +type B = ObjectHasKey<[string, number], '1'>; // "true" +type C = ObjectHasKey<[string, number], '2'>; // "false" +type D = A<[string]>; // "true" + +// Error, "false" not handled +type E = { true: 'true' }[ObjectHasKey]; + +type Juxtapose = ({ true: 'otherwise' } & { [k: string]: 'true' })[ObjectHasKey]; + +// Error, "otherwise" is missing +type DeepError = { true: 'true' }[Juxtapose]; + +type DeepOK = { true: 'true', otherwise: 'false' }[Juxtapose]; diff --git a/tests/cases/compiler/doNotInferUnrelatedTypes.ts b/tests/cases/compiler/doNotInferUnrelatedTypes.ts new file mode 100644 index 00000000000..08a7d793430 --- /dev/null +++ b/tests/cases/compiler/doNotInferUnrelatedTypes.ts @@ -0,0 +1,6 @@ +// #16709 +declare function dearray(ara: ReadonlyArray): T; +type LiteralType = "foo" | "bar"; +declare var alt: Array; + +let foo: LiteralType = dearray(alt); diff --git a/tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts b/tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts new file mode 100644 index 00000000000..8ce16b6fcd7 --- /dev/null +++ b/tests/cases/compiler/errorForUsingPropertyOfTypeAsType01.ts @@ -0,0 +1,44 @@ +namespace Test1 { + export interface Foo { + bar: string; + } + + var x: Foo.bar = ""; + var y: Test1.Foo.bar = ""; +} + +namespace Test2 { + export class Foo { + bar: string; + } + + var x: Foo.bar = ""; + var y: Test2.Foo.bar = ""; +} + +namespace Test3 { + export type Foo = { + bar: string; + } + + var x: Foo.bar = ""; + var y: Test3.Foo.bar = ""; +} + +namespace Test4 { + export type Foo = { bar: number } + | { bar: string } + + var x: Foo.bar = ""; + var y: Test4.Foo.bar = ""; +} + +namespace Test5 { + export type Foo = { bar: number } + | { wat: string } + + var x: Foo.bar = ""; + var y: Test5.Foo.bar = ""; +} + +import lol = Test5.Foo. \ No newline at end of file diff --git a/tests/cases/compiler/expressionTypeNodeShouldError.ts b/tests/cases/compiler/expressionTypeNodeShouldError.ts new file mode 100644 index 00000000000..0f6463f454b --- /dev/null +++ b/tests/cases/compiler/expressionTypeNodeShouldError.ts @@ -0,0 +1,45 @@ +// @Filename: base.d.ts +declare const x: "foo".charCodeAt(0); + +// @filename: string.ts +interface String { + typeof(x: T): T; +} + +class C { + foo() { + const x: "".typeof(this.foo); + } +} + +const nodes = document.getElementsByTagName("li"); +type ItemType = "".typeof(nodes.item(0)); + +// @filename: number.ts +interface Number { + typeof(x: T): T; +} + +class C2 { + foo() { + const x: 3.141592.typeof(this.foo); + } +} + +const nodes2 = document.getElementsByTagName("li"); +type ItemType2 = 4..typeof(nodes.item(0)); + +// @filename: boolean.ts +interface Boolean { + typeof(x: T): T; +} + +class C3 { + foo() { + const x: false.typeof(this.foo); + } +} + +const nodes3 = document.getElementsByTagName("li"); +type ItemType3 = true.typeof(nodes.item(0)); + diff --git a/tests/cases/compiler/flowControlTypeGuardThenSwitch.ts b/tests/cases/compiler/flowControlTypeGuardThenSwitch.ts new file mode 100644 index 00000000000..537e3ca66ff --- /dev/null +++ b/tests/cases/compiler/flowControlTypeGuardThenSwitch.ts @@ -0,0 +1,35 @@ +enum Kind { + A, + B, +} + +interface Base { + kind: Kind; +} + +interface A extends Base { + kind: Kind.A; + yar: any; +} + +interface B extends Base { + kind: Kind.B; + gar: any; +} + +type Both = A | B; +function isBoth(x: Base): x is Both { + return true; +} + +let foo: Base = undefined; +if (isBoth(foo)) { + switch (foo.kind) { + case Kind.A: + const myA: A = foo; // Should not be an error + break; + case Kind.B: + const myB: B = foo; + break; + } +} diff --git a/tests/cases/compiler/jsFileCompilationNonNullAssertion.ts b/tests/cases/compiler/jsFileCompilationNonNullAssertion.ts new file mode 100644 index 00000000000..5f34b132ed5 --- /dev/null +++ b/tests/cases/compiler/jsFileCompilationNonNullAssertion.ts @@ -0,0 +1,4 @@ +// @allowJs: true +// @filename: /src/a.js +// @out: /bin/a.js +0! diff --git a/tests/cases/compiler/jsFileCompilationTypeAssertions.ts b/tests/cases/compiler/jsFileCompilationTypeAssertions.ts index 15f39b36d01..6eebf93ca77 100644 --- a/tests/cases/compiler/jsFileCompilationTypeAssertions.ts +++ b/tests/cases/compiler/jsFileCompilationTypeAssertions.ts @@ -1,3 +1,5 @@ // @allowJs: true -// @filename: a.js -var v = undefined; \ No newline at end of file +// @filename: /src/a.js +// @out: /lib/a.js +0 as number; +var v = undefined; diff --git a/tests/cases/compiler/jsdocParameterParsingInfiniteLoop.ts b/tests/cases/compiler/jsdocParameterParsingInfiniteLoop.ts new file mode 100644 index 00000000000..581a485bf0b --- /dev/null +++ b/tests/cases/compiler/jsdocParameterParsingInfiniteLoop.ts @@ -0,0 +1,9 @@ +// @filename: example.js +// @checkJs: true +// @allowJs: true +// @noEmit: true +// @ts-check +/** + * @type {function(@foo)} + */ +let x; \ No newline at end of file diff --git a/tests/cases/compiler/jsdocTypeGenericInstantiationAttempt.ts b/tests/cases/compiler/jsdocTypeGenericInstantiationAttempt.ts new file mode 100644 index 00000000000..f7a694f6124 --- /dev/null +++ b/tests/cases/compiler/jsdocTypeGenericInstantiationAttempt.ts @@ -0,0 +1,10 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @filename: index.js +/** + * @param {Array<*>} list + */ +function thing(list) { + return list; +} diff --git a/tests/cases/compiler/jsdocTypeNongenericInstantiationAttempt.ts b/tests/cases/compiler/jsdocTypeNongenericInstantiationAttempt.ts new file mode 100644 index 00000000000..bf05c7f6de7 --- /dev/null +++ b/tests/cases/compiler/jsdocTypeNongenericInstantiationAttempt.ts @@ -0,0 +1,71 @@ +// @allowJs: true +// @noEmit: true +// @checkJs: true +// @filename: index.js +/** + * @param {(m: Boolean) => string} somebody + */ +function sayHello(somebody) { + return 'Hello ' + somebody; +} + +// @filename: index2.js +/** + * @param {(m: Void) => string} somebody + */ +function sayHello2(somebody) { + return 'Hello ' + somebody; +} + + +// @filename: index3.js +/** + * @param {(m: Undefined) => string} somebody + */ +function sayHello3(somebody) { + return 'Hello ' + somebody; +} + + +// @filename: index4.js +/** + * @param {(m: Function) => string} somebody + */ +function sayHello4(somebody) { + return 'Hello ' + somebody; +} + + +// @filename: index5.js +/** + * @param {(m: String) => string} somebody + */ +function sayHello5(somebody) { + return 'Hello ' + somebody; +} + + +// @filename: index6.js +/** + * @param {(m: Number) => string} somebody + */ +function sayHello6(somebody) { + return 'Hello ' + somebody; +} + + +// @filename: index7.js +/** + * @param {(m: Object) => string} somebody + */ +function sayHello7(somebody) { + return 'Hello ' + somebody; +} + +// @filename: index8.js +function fn() {} + +/** + * @param {fn} somebody + */ +function sayHello8(somebody) { } \ No newline at end of file diff --git a/tests/cases/compiler/jsxPropsAsIdentifierNames.tsx b/tests/cases/compiler/jsxPropsAsIdentifierNames.tsx new file mode 100644 index 00000000000..7f19b3d457d --- /dev/null +++ b/tests/cases/compiler/jsxPropsAsIdentifierNames.tsx @@ -0,0 +1,12 @@ +// @jsx: preserve + +// @filename: index.tsx +declare namespace JSX { + interface Element { } + interface IntrinsicElements { + div: { + static?: boolean; + }; + } +} +export default
; diff --git a/tests/cases/compiler/mappedTypePartialConstraints.ts b/tests/cases/compiler/mappedTypePartialConstraints.ts new file mode 100644 index 00000000000..92fa3394034 --- /dev/null +++ b/tests/cases/compiler/mappedTypePartialConstraints.ts @@ -0,0 +1,15 @@ +// Repro from #16985 + +interface MyInterface { + something: number; +} + +class MyClass { + doIt(data : Partial) {} +} + +class MySubClass extends MyClass {} + +function fn(arg: typeof MyClass) {}; + +fn(MySubClass); diff --git a/tests/cases/compiler/parseCommaSeperatedNewlineNew.ts b/tests/cases/compiler/parseCommaSeperatedNewlineNew.ts new file mode 100644 index 00000000000..a0062db6cf1 --- /dev/null +++ b/tests/cases/compiler/parseCommaSeperatedNewlineNew.ts @@ -0,0 +1,2 @@ +(a, +new) \ No newline at end of file diff --git a/tests/cases/compiler/parseCommaSeperatedNewlineNumber.ts b/tests/cases/compiler/parseCommaSeperatedNewlineNumber.ts new file mode 100644 index 00000000000..cc07845674d --- /dev/null +++ b/tests/cases/compiler/parseCommaSeperatedNewlineNumber.ts @@ -0,0 +1,2 @@ +(a, +1) \ No newline at end of file diff --git a/tests/cases/compiler/parseCommaSeperatedNewlineString.ts b/tests/cases/compiler/parseCommaSeperatedNewlineString.ts new file mode 100644 index 00000000000..e6cff2438a5 --- /dev/null +++ b/tests/cases/compiler/parseCommaSeperatedNewlineString.ts @@ -0,0 +1,2 @@ +(a, +'') \ No newline at end of file diff --git a/tests/cases/compiler/prefixedNumberLiteralAssignToNumberLiteralType.ts b/tests/cases/compiler/prefixedNumberLiteralAssignToNumberLiteralType.ts new file mode 100644 index 00000000000..6c2afbba2bd --- /dev/null +++ b/tests/cases/compiler/prefixedNumberLiteralAssignToNumberLiteralType.ts @@ -0,0 +1,3 @@ +let x: 1 = +1; + +let y: -1 = -1; \ No newline at end of file diff --git a/tests/cases/compiler/promiseEmptyTupleNoException.ts b/tests/cases/compiler/promiseEmptyTupleNoException.ts new file mode 100644 index 00000000000..84ae24816e4 --- /dev/null +++ b/tests/cases/compiler/promiseEmptyTupleNoException.ts @@ -0,0 +1,5 @@ +// @target: es2017 +export async function get(): Promise<[]> { + let emails = []; + return emails; +} diff --git a/tests/cases/compiler/typeInferenceWithExcessProperties.ts b/tests/cases/compiler/typeInferenceWithExcessProperties.ts new file mode 100644 index 00000000000..3cf9f23a1ed --- /dev/null +++ b/tests/cases/compiler/typeInferenceWithExcessProperties.ts @@ -0,0 +1,30 @@ +// Repro from #17041 + +interface Named { + name: string; +} + +function parrot(obj: T): T { + return obj; +} + + +parrot({ + name: "TypeScript", +}); + +parrot({ + name: "TypeScript", + age: 5, +}); + +parrot({ + name: "TypeScript", + age: function () { }, +}); + +parrot({ + name: "TypeScript", + sayHello() { + }, +}); diff --git a/tests/cases/compiler/underscoreEscapedNameInEnum.ts b/tests/cases/compiler/underscoreEscapedNameInEnum.ts new file mode 100644 index 00000000000..ef16f253dd7 --- /dev/null +++ b/tests/cases/compiler/underscoreEscapedNameInEnum.ts @@ -0,0 +1,4 @@ +enum E { + "__foo" = 1, + bar = E["__foo"] + 1 +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpression1ESNext.ts b/tests/cases/conformance/dynamicImport/importCallExpression1ESNext.ts index 295b6470301..a499360f5dd 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpression1ESNext.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpression1ESNext.ts @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }) +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpression4ESNext.ts b/tests/cases/conformance/dynamicImport/importCallExpression4ESNext.ts index 91342770d7d..7bc540e1e2a 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpression4ESNext.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpression4ESNext.ts @@ -15,6 +15,7 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import ("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3AMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3AMD.ts new file mode 100644 index 00000000000..d92b5f27085 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3AMD.ts @@ -0,0 +1,31 @@ +// @module: amd +// @target: es3 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3CJS.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3CJS.ts new file mode 100644 index 00000000000..6807bff9ebc --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3CJS.ts @@ -0,0 +1,31 @@ +// @module: commonjs +// @target: es3 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3System.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3System.ts new file mode 100644 index 00000000000..e39e80b8fab --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3System.ts @@ -0,0 +1,31 @@ +// @module: system +// @target: es3 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3UMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3UMD.ts new file mode 100644 index 00000000000..7c5fb5da98e --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES3UMD.ts @@ -0,0 +1,31 @@ +// @module: umd +// @target: es3 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5AMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5AMD.ts new file mode 100644 index 00000000000..02a2feab574 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5AMD.ts @@ -0,0 +1,31 @@ +// @module: amd +// @target: es5 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5CJS.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5CJS.ts new file mode 100644 index 00000000000..0622e10a895 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5CJS.ts @@ -0,0 +1,31 @@ +// @module: commonjs +// @target: es5 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5System.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5System.ts new file mode 100644 index 00000000000..b18096d2446 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5System.ts @@ -0,0 +1,31 @@ +// @module: system +// @target: es5 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5UMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5UMD.ts new file mode 100644 index 00000000000..232211588a6 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES5UMD.ts @@ -0,0 +1,31 @@ +// @module: umd +// @target: es5 +// @lib: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6AMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6AMD.ts new file mode 100644 index 00000000000..a4b2997b8de --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6AMD.ts @@ -0,0 +1,30 @@ +// @module: amd +// @target: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6CJS.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6CJS.ts new file mode 100644 index 00000000000..906e2eb157b --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6CJS.ts @@ -0,0 +1,30 @@ +// @module: commonjs +// @target: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6System.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6System.ts new file mode 100644 index 00000000000..e974974cc63 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6System.ts @@ -0,0 +1,30 @@ +// @module: system +// @target: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6UMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6UMD.ts new file mode 100644 index 00000000000..b532771c9c7 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncES6UMD.ts @@ -0,0 +1,30 @@ +// @module: umd +// @target: es6 +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionAsyncESNext.ts b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncESNext.ts new file mode 100644 index 00000000000..8e56b2aa640 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionAsyncESNext.ts @@ -0,0 +1,30 @@ +// @module: esnext +// @target: esnext +// @filename: test.ts +export async function fn() { + const req = await import('./test') // ONE +} + +export class cl1 { + public async m() { + const req = await import('./test') // TWO + } +} + +export const obj = { + m: async () => { + const req = await import('./test') // THREE + } +} + +export class cl2 { + public p = { + m: async () => { + const req = await import('./test') // FOUR + } + } +} + +export const l = async () => { + const req = await import('./test') // FIVE +} diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES5AMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES5AMD.ts index 33c31283ea0..e218dd4758b 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionES5AMD.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES5AMD.ts @@ -11,6 +11,20 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES5CJS.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES5CJS.ts index 900ddbdba0c..2c45d42abbe 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionES5CJS.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES5CJS.ts @@ -11,6 +11,20 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES5System.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES5System.ts index c00ab6899c6..b9f8bac1920 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionES5System.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES5System.ts @@ -11,6 +11,20 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES5UMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES5UMD.ts index 699b0ffc342..66877c79ced 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionES5UMD.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES5UMD.ts @@ -11,6 +11,20 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES6AMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES6AMD.ts new file mode 100644 index 00000000000..7e45b081ba4 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES6AMD.ts @@ -0,0 +1,29 @@ +// @module: amd +// @target: es6 +// @filename: 0.ts +export function foo() { return "foo"; } + +// @filename: 1.ts +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES6CJS.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES6CJS.ts new file mode 100644 index 00000000000..0267c490712 --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES6CJS.ts @@ -0,0 +1,29 @@ +// @module: commonjs +// @target: es6 +// @filename: 0.ts +export function foo() { return "foo"; } + +// @filename: 1.ts +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES6System.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES6System.ts new file mode 100644 index 00000000000..cf78470c30b --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES6System.ts @@ -0,0 +1,29 @@ +// @module: system +// @target: es6 +// @filename: 0.ts +export function foo() { return "foo"; } + +// @filename: 1.ts +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionES6UMD.ts b/tests/cases/conformance/dynamicImport/importCallExpressionES6UMD.ts new file mode 100644 index 00000000000..060b6097d3d --- /dev/null +++ b/tests/cases/conformance/dynamicImport/importCallExpressionES6UMD.ts @@ -0,0 +1,29 @@ +// @module: umd +// @target: es6 +// @filename: 0.ts +export function foo() { return "foo"; } + +// @filename: 1.ts +import("./0"); +var p1 = import("./0"); +p1.then(zero => { + return zero.foo(); +}); + +export var p2 = import("./0"); + +function foo() { + const p2 = import("./0"); +} + +class C { + method() { + const loadAsync = import ("./0"); + } +} + +export class D { + method() { + const loadAsync = import ("./0"); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInAMD1.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInAMD1.ts index 63cfc54c732..7aafc5294ff 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInAMD1.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInAMD1.ts @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInAMD4.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInAMD4.ts index 10044ab674c..ae861ff6987 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInAMD4.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInAMD4.ts @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInCJS1.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInCJS1.ts index e1457017552..9827828a0a0 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInCJS1.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInCJS1.ts @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInCJS5.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInCJS5.ts index db86764802b..c7dfbc663d1 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInCJS5.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInCJS5.ts @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import ("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInSystem1.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInSystem1.ts index a69e844c7a7..bbc265bc13f 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInSystem1.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInSystem1.ts @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInSystem4.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInSystem4.ts index 1ab3040862c..d3f25ab1e35 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInSystem4.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInSystem4.ts @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInUMD1.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInUMD1.ts index 05c4d699104..b273d1594b3 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInUMD1.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInUMD1.ts @@ -10,6 +10,8 @@ p1.then(zero => { return zero.foo(); }); +export var p2 = import("./0"); + function foo() { const p2 = import("./0"); } \ No newline at end of file diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionInUMD4.ts b/tests/cases/conformance/dynamicImport/importCallExpressionInUMD4.ts index ef0f0999407..35750f30da8 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionInUMD4.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionInUMD4.ts @@ -15,6 +15,21 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); + this.myModule.then(Zero => { + console.log(Zero.foo()); + }, async err => { + console.log(err); + let one = await import("./1"); + console.log(one.backup()); + }); + } +} + +export class D { + private myModule = import("./0"); + method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionNoModuleKindSpecified.ts b/tests/cases/conformance/dynamicImport/importCallExpressionNoModuleKindSpecified.ts index 2d2f54e00b1..856f763eb56 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionNoModuleKindSpecified.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionNoModuleKindSpecified.ts @@ -13,6 +13,7 @@ declare var console: any; class C { private myModule = import("./0"); method() { + const loadAsync = import("./0"); this.myModule.then(Zero => { console.log(Zero.foo()); }, async err => { diff --git a/tests/cases/conformance/dynamicImport/importCallExpressionWithTypeArgument.ts b/tests/cases/conformance/dynamicImport/importCallExpressionWithTypeArgument.ts index 895b61af6ff..09f07d9f9c0 100644 --- a/tests/cases/conformance/dynamicImport/importCallExpressionWithTypeArgument.ts +++ b/tests/cases/conformance/dynamicImport/importCallExpressionWithTypeArgument.ts @@ -8,7 +8,4 @@ export function foo() { return "foo"; } // @filename: 1.ts "use strict" var p1 = import>("./0"); // error -var p2 = import<>("./0"); // error -// p1.then(value => { -// value.anyFunction(); -// }) \ No newline at end of file +var p2 = import<>("./0"); // error \ No newline at end of file diff --git a/tests/cases/conformance/jsdoc/jsdocParamTagTypeLiteral.ts b/tests/cases/conformance/jsdoc/jsdocParamTagTypeLiteral.ts new file mode 100644 index 00000000000..bf59ac5664d --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocParamTagTypeLiteral.ts @@ -0,0 +1,78 @@ +// @allowJS: true +// @checkJs: true +// @noEmit: true +// @strict: true +// @suppressOutputPathCheck: true + +// @Filename: 0.js +/** + * @param {Object} notSpecial + * @param {string} unrelated - not actually related because it's not notSpecial.unrelated + */ +function normal(notSpecial) { + notSpecial; // should just be 'any' +} +normal(12); + +/** + * @param {Object} opts1 doc1 + * @param {string} opts1.x doc2 + * @param {string=} opts1.y doc3 + * @param {string} [opts1.z] doc4 + * @param {string} [opts1.w="hi"] doc5 + */ +function foo1(opts1) { + opts1.x; +} + +foo1({x: 'abc'}); + +/** + * @param {Object[]} opts2 + * @param {string} opts2[].anotherX + * @param {string=} opts2[].anotherY + */ +function foo2(/** @param opts2 bad idea theatre! */opts2) { + opts2[0].anotherX; +} + +foo2([{anotherX: "world"}]); + +/** + * @param {object} opts3 + * @param {string} opts3.x + */ +function foo3(opts3) { + opts3.x; +} +foo3({x: 'abc'}); + +/** + * @param {object[]} opts4 + * @param {string} opts4[].x + * @param {string=} opts4[].y + * @param {string} [opts4[].z] + * @param {string} [opts4[].w="hi"] + */ +function foo4(opts4) { + opts4[0].x; +} + +foo4([{ x: 'hi' }]); + +/** + * @param {object[]} opts5 - Let's test out some multiple nesting levels + * @param {string} opts5[].help - (This one is just normal) + * @param {object} opts5[].what - Look at us go! Here's the first nest! + * @param {string} opts5[].what.a - (Another normal one) + * @param {Object[]} opts5[].what.bad - Now we're nesting inside a nested type + * @param {string} opts5[].what.bad[].idea - I don't think you can get back out of this level... + * @param {boolean} opts5[].what.bad[].oh - Oh ... that's how you do it. + * @param {number} opts5[].unnest - Here we are almost all the way back at the beginning. + */ +function foo5(opts5) { + opts5[0].what.bad[0].idea; + opts5[0].unnest; +} + +foo5([{ help: "help", what: { a: 'a', bad: [{ idea: 'idea', oh: false }] }, unnest: 1 }]); diff --git a/tests/cases/conformance/types/mapped/mappedTypeErrors2.ts b/tests/cases/conformance/types/mapped/mappedTypeErrors2.ts new file mode 100644 index 00000000000..100a93eb159 --- /dev/null +++ b/tests/cases/conformance/types/mapped/mappedTypeErrors2.ts @@ -0,0 +1,22 @@ +// @strictNullChecks: true +// @declaration: true + +// Repros from #17238 + +type AB = { + a: 'a' + b: 'a' +}; + +type T1 = { [key in AB[K]]: true }; +type T2 = T1[K]; // Error + +type R = AB[keyof AB]; // "a" +type T3 = { [key in R]: true }; +type T4 = T3[K] // Error + +type T5 = {[key in AB[S]]: true}[S]; // Error + +type T6 = {[key in AB[S]]: true}[L]; // Error + +type T7 = {[key in AB[S]]: true}[L]; diff --git a/tests/cases/conformance/types/mapped/mappedTypeRelationships.ts b/tests/cases/conformance/types/mapped/mappedTypeRelationships.ts index 587ec1c9d7e..7acacd6c1d7 100644 --- a/tests/cases/conformance/types/mapped/mappedTypeRelationships.ts +++ b/tests/cases/conformance/types/mapped/mappedTypeRelationships.ts @@ -69,14 +69,16 @@ function f23(x: T, y: Readonly, k: K) { y[k] = x[k]; // Error } +type Thing = { a: string, b: string }; + function f30(x: T, y: Partial) { x = y; // Error y = x; } -function f31(x: T, y: Partial) { - x = y; // Error - y = x; +function f31(x: Partial, y: Partial) { + x = y; + y = x; // Error } function f40(x: T, y: Readonly) { @@ -84,9 +86,9 @@ function f40(x: T, y: Readonly) { y = x; } -function f41(x: T, y: Readonly) { +function f41(x: Readonly, y: Readonly) { x = y; - y = x; + y = x; // Error } type Item = { diff --git a/tests/cases/fourslash/codeFixCorrectSpelling4.ts b/tests/cases/fourslash/codeFixCorrectSpelling4.ts new file mode 100644 index 00000000000..21dd3f03a1d --- /dev/null +++ b/tests/cases/fourslash/codeFixCorrectSpelling4.ts @@ -0,0 +1,7 @@ +/// + +//// export declare const despite: { the: any }; +//// +//// [|dispite.the|] + +verify.rangeAfterCodeFix(`despite.the`); diff --git a/tests/cases/fourslash/codeFixNegativeReplaceQualifiedNameWithIndexedAccessType01.ts b/tests/cases/fourslash/codeFixNegativeReplaceQualifiedNameWithIndexedAccessType01.ts new file mode 100644 index 00000000000..683e45f056a --- /dev/null +++ b/tests/cases/fourslash/codeFixNegativeReplaceQualifiedNameWithIndexedAccessType01.ts @@ -0,0 +1,11 @@ +/// + + +//// namespace Container { +//// export interface Foo { +//// bar: string; +//// } +//// } +//// const x: [|Container.Foo.bar|] = "" + +verify.not.codeFixAvailable(); diff --git a/tests/cases/fourslash/codeFixReplaceQualifiedNameWithIndexedAccessType01.ts b/tests/cases/fourslash/codeFixReplaceQualifiedNameWithIndexedAccessType01.ts new file mode 100644 index 00000000000..ffcc9ffeacc --- /dev/null +++ b/tests/cases/fourslash/codeFixReplaceQualifiedNameWithIndexedAccessType01.ts @@ -0,0 +1,8 @@ +/// + +//// export interface Foo { +//// bar: string; +//// } +//// const x: [|Foo.bar|] = "" + +verify.rangeAfterCodeFix(`Foo["bar"]`); diff --git a/tests/cases/fourslash/findAllReferencesJsDocTypeLiteral.ts b/tests/cases/fourslash/findAllReferencesJsDocTypeLiteral.ts new file mode 100644 index 00000000000..6d1b32b1515 --- /dev/null +++ b/tests/cases/fourslash/findAllReferencesJsDocTypeLiteral.ts @@ -0,0 +1,22 @@ +// @allowJs: true +// @checkJs: true +/// + +// @Filename: foo.js +/////** +//// * @param {object} o - very important! +//// * @param {string} o.x - a thing, its ok +//// * @param {number} o.y - another thing +//// * @param {Object} o.nested - very nested +//// * @param {boolean} o.nested.[|great|] - much greatness +//// * @param {number} o.nested.times - twice? probably!?? +//// */ +//// function f(o) { return o.nested.[|great|]; } + +verify.rangesReferenceEachOther(); + +///** +// * @param {object} [|o|] - very important! +// * @param {string} o.x - a thing, its ok +// */ +// function f([|o|]) { return [|o|].x; } diff --git a/tests/cases/fourslash/findAllRefsDestructureGetter.ts b/tests/cases/fourslash/findAllRefsDestructureGetter.ts new file mode 100644 index 00000000000..b21e6186eb2 --- /dev/null +++ b/tests/cases/fourslash/findAllRefsDestructureGetter.ts @@ -0,0 +1,22 @@ +/// + +////class Test { +//// get [|{| "isDefinition": true, "isWriteAccess": true |}x|]() { return 0; } +//// +//// set [|{| "isDefinition": true, "isWriteAccess": true |}y|](a: number) {} +////} +////const { [|{| "isDefinition": true, "isWriteAccess": true |}x|], [|{| "isDefinition": true, "isWriteAccess": true |}y|] } = new Test(); +////[|x|]; [|y|]; + +const [x0, y0, x1, y1, x2, y2] = test.ranges(); +verify.referenceGroups(x0, [{ definition: "(property) Test.x: number", ranges: [x0, x1, x2] }]); +verify.referenceGroups([x1, x2], [ + { definition: "(property) Test.x: number", ranges: [x0] }, + { definition: "const x: number", ranges: [x1, x2] }, +]); + +verify.referenceGroups(y0, [{ definition: "(property) Test.y: number", ranges: [y0, y1, y2] }]); +verify.referenceGroups([y1, y2], [ + { definition: "(property) Test.y: number", ranges: [y0] }, + { definition: "const y: number", ranges: [y1, y2] }, +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportFile5.ts b/tests/cases/fourslash/importNameCodeFixNewImportFile5.ts new file mode 100644 index 00000000000..28cf48d8a5f --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportFile5.ts @@ -0,0 +1,16 @@ +/// + +//// [|bar/*0*/();|] + +// @Filename: foo.ts +//// interface MyStatic { +//// bar(): void; +//// } +//// declare var x: MyStatic; +//// export = x; + +verify.importFixAtPosition([ +`import { bar } from "./foo"; + +bar();` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules4.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules4.ts new file mode 100644 index 00000000000..9969bdcf46a --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules4.ts @@ -0,0 +1,25 @@ +/// + +//// [|f1/*0*/('');|] + +// @Filename: package.json +//// { "dependencies": { "package-name": "latest" } } + +// @Filename: node_modules/package-name/bin/lib/libfile.d.ts +//// export function f1(text: string): string; + +// @Filename: node_modules/package-name/bin/lib/libfile.js +//// function f1(text) { } +//// exports.f1 = f1; + +// @Filename: node_modules/package-name/package.json +//// { +//// "main": "bin/lib/libfile.js", +//// "types": "bin/lib/libfile.d.ts" +//// } + +verify.importFixAtPosition([ +`import { f1 } from "package-name"; + +f1('');` +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules5.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules5.ts new file mode 100644 index 00000000000..24100362994 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules5.ts @@ -0,0 +1,25 @@ +/// + +//// [|f1/*0*/('');|] + +// @Filename: package.json +//// { "dependencies": { "package-name": "latest" } } + +// @Filename: node_modules/package-name/node_modules/package-name2/bin/lib/libfile.d.ts +//// export function f1(text: string): string; + +// @Filename: node_modules/package-name/node_modules/package-name2/bin/lib/libfile.js +//// function f1(text) { } +//// exports.f1 = f1; + +// @Filename: node_modules/package-name/node_modules/package-name2/package.json +//// { +//// "main": "bin/lib/libfile.js", +//// "types": "bin/lib/libfile.d.ts" +//// } + +verify.importFixAtPosition([ +`import { f1 } from "package-name/node_modules/package-name2"; + +f1('');` +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules6.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules6.ts new file mode 100644 index 00000000000..7a52e3f67fe --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules6.ts @@ -0,0 +1,25 @@ +/// + +//// [|f1/*0*/('');|] + +// @Filename: package.json +//// { "dependencies": { "package-name": "latest" } } + +// @Filename: node_modules/package-name/bin/lib/index.d.ts +//// export function f1(text: string): string; + +// @Filename: node_modules/package-name/bin/lib/index.js +//// function f1(text) { } +//// exports.f1 = f1; + +// @Filename: node_modules/package-name/package.json +//// { +//// "main": "bin/lib/index.js", +//// "types": "bin/lib/index.d.ts" +//// } + +verify.importFixAtPosition([ +`import { f1 } from "package-name"; + +f1('');` +]); diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules7.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules7.ts new file mode 100644 index 00000000000..9032018a7f5 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules7.ts @@ -0,0 +1,29 @@ +/// + +//// [|f1/*0*/('');|] + +// @Filename: package.json +//// { "dependencies": { "package-name": "0.0.1" } } + +// @Filename: node_modules/package-name/bin/lib/libfile.d.ts +//// export declare function f1(text: string): string; + +// @Filename: node_modules/package-name/bin/lib/libfile.js +//// function f1(text) {} +//// exports.f1 = f1; + +// @Filename: node_modules/package-name/package.json +//// { "main": "bin/lib/libfile.js" } + + +// In this case, importing the module by its package name: +// import { f1 } from 'package-name' +// could in theory work, however the resulting code compiles with a module resolution error +// since bin/lib/libfile.d.ts isn't declared under "typings" in package.json +// Therefore just import the module by its qualified path + +verify.importFixAtPosition([ +`import { f1 } from "package-name/bin/lib/libfile"; + +f1('');` +]); \ No newline at end of file diff --git a/tests/cases/fourslash/importNameCodeFixNewImportNodeModules8.ts b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules8.ts new file mode 100644 index 00000000000..f048f0d30d2 --- /dev/null +++ b/tests/cases/fourslash/importNameCodeFixNewImportNodeModules8.ts @@ -0,0 +1,25 @@ +/// + +//// [|f1/*0*/('');|] + +// @Filename: package.json +//// { "dependencies": { "package-name": "latest" } } + +// @Filename: node_modules/@scope/package-name/bin/lib/index.d.ts +//// export function f1(text: string): string; + +// @Filename: node_modules/@scope/package-name/bin/lib/index.js +//// function f1(text) { } +//// exports.f1 = f1; + +// @Filename: node_modules/@scope/package-name/package.json +//// { +//// "main": "bin/lib/index.js", +//// "types": "bin/lib/index.d.ts" +//// } + +verify.importFixAtPosition([ +`import { f1 } from "@scope/package-name"; + +f1('');` +]); diff --git a/tests/cases/fourslash/todoComments18.ts b/tests/cases/fourslash/todoComments18.ts new file mode 100644 index 00000000000..d591f98236f --- /dev/null +++ b/tests/cases/fourslash/todoComments18.ts @@ -0,0 +1,8 @@ +/// + +// Tests node_modules name in file still gets todos. + +// @Filename: /node_modules_todoTest0.ts +//// // [|TODO|] + +verify.todoCommentsInCurrentFile(["TODO"]); \ No newline at end of file diff --git a/tests/cases/fourslash/todoComments19.ts b/tests/cases/fourslash/todoComments19.ts new file mode 100644 index 00000000000..2f14ba69a57 --- /dev/null +++ b/tests/cases/fourslash/todoComments19.ts @@ -0,0 +1,11 @@ +/// + +// Tests that todos are not found in node_modules folder. + +// @Filename: todoTest0.ts +//// import * as foo1 from "fake-module"; + +// @Filename: node_modules/fake-module/ts.ts +//// // TODO + +verify.todoCommentsInCurrentFile(["TODO"]); diff --git a/tests/cases/fourslash/todoComments20.ts b/tests/cases/fourslash/todoComments20.ts new file mode 100644 index 00000000000..2284236714d --- /dev/null +++ b/tests/cases/fourslash/todoComments20.ts @@ -0,0 +1,6 @@ +/// + +// @Filename: dir1/node_modules/todoTest0.ts +//// // TODO + +verify.todoCommentsInCurrentFile(["TODO"]);